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

#include "base/string_util.h"
#include "base/values.h"
#include "chrome/browser/browser_process.h"
#include "chrome/browser/dom_ui/tips_handler.h"
#include "chrome/browser/profile.h"
#include "chrome/browser/web_resource/web_resource_service.h"
#include "chrome/common/pref_names.h"
#include "chrome/common/web_resource/web_resource_unpacker.h"
#include "chrome/common/url_constants.h"
#include "googleurl/src/gurl.h"

DOMMessageHandler* TipsHandler::Attach(DOMUI* dom_ui) {
  dom_ui_ = dom_ui;
  tips_cache_ = dom_ui_->GetProfile()->GetPrefs()->
      GetMutableDictionary(prefs::kNTPTipsCache);
  return DOMMessageHandler::Attach(dom_ui);
}

void TipsHandler::RegisterMessages() {
  dom_ui_->RegisterMessageCallback("getTips",
      NewCallback(this, &TipsHandler::HandleGetTips));
}

void TipsHandler::HandleGetTips(const Value* content) {
  // List containing the tips to be displayed.
  ListValue list_value;

  // Holds the web resource data found in the preferences cache.
  ListValue* wr_list;

  // These values hold the data for each web resource item.
  int current_tip_index;
  std::string current_tip;

  // If tips are not correct for our locale, do not send.  Wait for update.
  // We need to check here because the new tab page calls for tips before
  // the tip service starts up.
  PrefService* current_prefs = dom_ui_->GetProfile()->GetPrefs();
  if (current_prefs->HasPrefPath(prefs::kNTPTipsServer)) {
    std::wstring server = current_prefs->GetString(prefs::kNTPTipsServer);
    std::wstring locale = ASCIIToWide(
        g_browser_process->GetApplicationLocale());
    if (!EndsWith(server, locale, false)) {
      dom_ui_->CallJavascriptFunction(L"tips", list_value);
      return;
    }
  }

  if (tips_cache_ != NULL && tips_cache_->GetSize() >= 0) {
    if (tips_cache_->GetInteger(
        WebResourceService::kCurrentTipPrefName, &current_tip_index) &&
        tips_cache_->GetList(
        WebResourceService::kTipCachePrefName, &wr_list) &&
        wr_list && wr_list->GetSize() > 0) {
      if (wr_list->GetSize() <= static_cast<size_t>(current_tip_index))
        current_tip_index = 0;
      if (wr_list->GetString(current_tip_index, &current_tip)) {
        DictionaryValue* tip_dict = new DictionaryValue();
        tip_dict->SetString(L"tip_html_text", current_tip);
        list_value.Append(tip_dict);
        tips_cache_->SetInteger(WebResourceService::kCurrentTipPrefName,
                                current_tip_index + 1);
      }
    }
  }

  // Send list of web resource items back out to the DOM.
  dom_ui_->CallJavascriptFunction(L"tips", list_value);
}

// static
void TipsHandler::RegisterUserPrefs(PrefService* prefs) {
  prefs->RegisterDictionaryPref(prefs::kNTPTipsCache);
  prefs->RegisterStringPref(prefs::kNTPTipsServer,
                            WebResourceService::kDefaultResourceServer);
}

bool TipsHandler::IsValidURL(const std::wstring& url_string) {
  GURL url(WideToUTF8(url_string));
  return !url.is_empty() && (url.SchemeIs(chrome::kHttpScheme) ||
                             url.SchemeIs(chrome::kHttpsScheme));
}
<commit_msg>Coverity: tips_cache_->GetSize() returns an unsigned int so the comparison >= 0 is always true.  Change the check to != 0 to actually have an effect.<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 <string>

#include "base/string_util.h"
#include "base/values.h"
#include "chrome/browser/browser_process.h"
#include "chrome/browser/dom_ui/tips_handler.h"
#include "chrome/browser/profile.h"
#include "chrome/browser/web_resource/web_resource_service.h"
#include "chrome/common/pref_names.h"
#include "chrome/common/web_resource/web_resource_unpacker.h"
#include "chrome/common/url_constants.h"
#include "googleurl/src/gurl.h"

DOMMessageHandler* TipsHandler::Attach(DOMUI* dom_ui) {
  dom_ui_ = dom_ui;
  tips_cache_ = dom_ui_->GetProfile()->GetPrefs()->
      GetMutableDictionary(prefs::kNTPTipsCache);
  return DOMMessageHandler::Attach(dom_ui);
}

void TipsHandler::RegisterMessages() {
  dom_ui_->RegisterMessageCallback("getTips",
      NewCallback(this, &TipsHandler::HandleGetTips));
}

void TipsHandler::HandleGetTips(const Value* content) {
  // List containing the tips to be displayed.
  ListValue list_value;

  // Holds the web resource data found in the preferences cache.
  ListValue* wr_list;

  // These values hold the data for each web resource item.
  int current_tip_index;
  std::string current_tip;

  // If tips are not correct for our locale, do not send.  Wait for update.
  // We need to check here because the new tab page calls for tips before
  // the tip service starts up.
  PrefService* current_prefs = dom_ui_->GetProfile()->GetPrefs();
  if (current_prefs->HasPrefPath(prefs::kNTPTipsServer)) {
    std::wstring server = current_prefs->GetString(prefs::kNTPTipsServer);
    std::wstring locale = ASCIIToWide(
        g_browser_process->GetApplicationLocale());
    if (!EndsWith(server, locale, false)) {
      dom_ui_->CallJavascriptFunction(L"tips", list_value);
      return;
    }
  }

  if (tips_cache_ != NULL && tips_cache_->GetSize() != 0) {
    if (tips_cache_->GetInteger(
        WebResourceService::kCurrentTipPrefName, &current_tip_index) &&
        tips_cache_->GetList(
        WebResourceService::kTipCachePrefName, &wr_list) &&
        wr_list && wr_list->GetSize() > 0) {
      if (wr_list->GetSize() <= static_cast<size_t>(current_tip_index))
        current_tip_index = 0;
      if (wr_list->GetString(current_tip_index, &current_tip)) {
        DictionaryValue* tip_dict = new DictionaryValue();
        tip_dict->SetString(L"tip_html_text", current_tip);
        list_value.Append(tip_dict);
        tips_cache_->SetInteger(WebResourceService::kCurrentTipPrefName,
                                current_tip_index + 1);
      }
    }
  }

  // Send list of web resource items back out to the DOM.
  dom_ui_->CallJavascriptFunction(L"tips", list_value);
}

// static
void TipsHandler::RegisterUserPrefs(PrefService* prefs) {
  prefs->RegisterDictionaryPref(prefs::kNTPTipsCache);
  prefs->RegisterStringPref(prefs::kNTPTipsServer,
                            WebResourceService::kDefaultResourceServer);
}

bool TipsHandler::IsValidURL(const std::wstring& url_string) {
  GURL url(WideToUTF8(url_string));
  return !url.is_empty() && (url.SchemeIs(chrome::kHttpScheme) ||
                             url.SchemeIs(chrome::kHttpsScheme));
}
<|endoftext|>


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

#include "chrome/browser/greasemonkey_master.h"

#include <vector>

#include "base/file_util.h"
#include "base/logging.h"
#include "base/path_service.h"
#include "base/pickle.h"
#include "base/string_util.h"
#include "chrome/common/chrome_paths.h"
#include "net/base/net_util.h"

bool GreasemonkeyMaster::UpdateScripts() {
  std::vector<std::wstring> scripts;
  std::wstring path;

  PathService::Get(chrome::DIR_USER_SCRIPTS, &path);
  file_util::FileEnumerator enumerator(path, false,
                                       file_util::FileEnumerator::FILES,
                                       L"*.user.js");
  for (std::wstring file = enumerator.Next(); !file.empty();
       file = enumerator.Next()) {
    scripts.push_back(file);
  }

  // Pickle scripts data.
  Pickle pickle;
  pickle.WriteSize(scripts.size());
  for (std::vector<std::wstring>::iterator path = scripts.begin();
       path != scripts.end(); ++path) {
    std::string file_url = net::FilePathToFileURL(*path).spec();
    std::string contents;
    // TODO(aa): Support unicode script files.
    file_util::ReadFileToString(*path, &contents);

    // Write scripts as 'data' so that we can read it out in the slave without
    // allocating a new string.
    pickle.WriteData(file_url.c_str(), file_url.length());
    pickle.WriteData(contents.c_str(), contents.length());
  }

  // Create the shared memory object.
  scoped_ptr<SharedMemory> temp_shared_memory(new SharedMemory());
  if (!temp_shared_memory.get()) {
    return false;
  }

  shared_memory_serial_++;
  if (!temp_shared_memory->Create(std::wstring(), // anonymous
                                  false, // read-only
                                  false, // open existing
                                  pickle.size())) {
    return false;
  }

  // Map into our process.
  if (!temp_shared_memory->Map(pickle.size())) {
    return false;
  }

  // Copy the pickle to shared memory.
  memcpy(temp_shared_memory->memory(), pickle.data(), pickle.size());

  shared_memory_.reset(temp_shared_memory.release());
  return true;
}

bool GreasemonkeyMaster::ShareToProcess(ProcessHandle process,
                                        SharedMemoryHandle* new_handle) {
  if (shared_memory_.get())
    return shared_memory_->ShareToProcess(process, new_handle);

  NOTREACHED();
  return false;
}
<commit_msg>Fix breakage from r3643.<commit_after>// Copyright (c) 2008 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chrome/browser/greasemonkey_master.h"

#include <vector>

#include "base/file_util.h"
#include "base/logging.h"
#include "base/path_service.h"
#include "base/pickle.h"
#include "base/string_util.h"
#include "chrome/common/chrome_paths.h"
#include "googleurl/src/gurl.h"
#include "net/base/net_util.h"

bool GreasemonkeyMaster::UpdateScripts() {
  std::vector<std::wstring> scripts;
  std::wstring path;

  PathService::Get(chrome::DIR_USER_SCRIPTS, &path);
  file_util::FileEnumerator enumerator(path, false,
                                       file_util::FileEnumerator::FILES,
                                       L"*.user.js");
  for (std::wstring file = enumerator.Next(); !file.empty();
       file = enumerator.Next()) {
    scripts.push_back(file);
  }

  // Pickle scripts data.
  Pickle pickle;
  pickle.WriteSize(scripts.size());
  for (std::vector<std::wstring>::iterator path = scripts.begin();
       path != scripts.end(); ++path) {
    std::string file_url = net::FilePathToFileURL(*path).spec();
    std::string contents;
    // TODO(aa): Support unicode script files.
    file_util::ReadFileToString(*path, &contents);

    // Write scripts as 'data' so that we can read it out in the slave without
    // allocating a new string.
    pickle.WriteData(file_url.c_str(), file_url.length());
    pickle.WriteData(contents.c_str(), contents.length());
  }

  // Create the shared memory object.
  scoped_ptr<SharedMemory> temp_shared_memory(new SharedMemory());
  if (!temp_shared_memory.get()) {
    return false;
  }

  shared_memory_serial_++;
  if (!temp_shared_memory->Create(std::wstring(), // anonymous
                                  false, // read-only
                                  false, // open existing
                                  pickle.size())) {
    return false;
  }

  // Map into our process.
  if (!temp_shared_memory->Map(pickle.size())) {
    return false;
  }

  // Copy the pickle to shared memory.
  memcpy(temp_shared_memory->memory(), pickle.data(), pickle.size());

  shared_memory_.reset(temp_shared_memory.release());
  return true;
}

bool GreasemonkeyMaster::ShareToProcess(ProcessHandle process,
                                        SharedMemoryHandle* new_handle) {
  if (shared_memory_.get())
    return shared_memory_->ShareToProcess(process, new_handle);

  NOTREACHED();
  return false;
}
<|endoftext|>


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

#include <string>

#include "chrome/browser/net/url_fixer_upper.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/common/url_constants.h"
#include "chrome/test/automation/tab_proxy.h"
#include "chrome/test/automation/browser_proxy.h"
#include "chrome/test/ui/ui_test.h"
#include "net/url_request/url_request_unittest.h"

using std::wstring;

namespace {

const wchar_t kDocRoot[] = L"chrome/test/data";

}  // namespace

class LoginPromptTest : public UITest {
 protected:
  LoginPromptTest()
      : UITest(),
        username_basic_(L"basicuser"),
        username_digest_(L"digestuser"),
        password_(L"secret"),
        password_bad_(L"denyme") {
  }

  void NavigateTab(TabProxy* tab_proxy, const GURL& url) {
    ASSERT_TRUE(tab_proxy->NavigateToURL(url));
  }

  void AppendTab(const GURL& url) {
    scoped_refptr<BrowserProxy> window_proxy(automation()->GetBrowserWindow(0));
    ASSERT_TRUE(window_proxy.get());
    ASSERT_TRUE(window_proxy->AppendTab(url));
  }

 protected:
  wstring username_basic_;
  wstring username_digest_;
  wstring password_;
  wstring password_bad_;
};

wstring ExpectedTitleFromAuth(const wstring& username,
                              const wstring& password) {
  // The TestServer sets the title to username/password on successful login.
  return username + L"/" + password;
}

// Test that "Basic" HTTP authentication works.
TEST_F(LoginPromptTest, TestBasicAuth) {
  scoped_refptr<HTTPTestServer> server =
      HTTPTestServer::CreateServer(kDocRoot, NULL);
  ASSERT_TRUE(NULL != server.get());
  scoped_refptr<TabProxy> tab(GetActiveTab());
  ASSERT_TRUE(tab.get());
  NavigateTab(tab.get(), server->TestServerPageW(L"auth-basic"));

  EXPECT_TRUE(tab->NeedsAuth());
  EXPECT_FALSE(tab->SetAuth(username_basic_, password_bad_));
  EXPECT_TRUE(tab->NeedsAuth());
  EXPECT_TRUE(tab->CancelAuth());
  EXPECT_EQ(L"Denied: wrong password", GetActiveTabTitle());

  NavigateTab(tab.get(), server->TestServerPageW(L"auth-basic"));

  EXPECT_TRUE(tab->NeedsAuth());
  EXPECT_TRUE(tab->SetAuth(username_basic_, password_));
  EXPECT_EQ(ExpectedTitleFromAuth(username_basic_, password_),
            GetActiveTabTitle());
}

// Test that "Digest" HTTP authentication works.
TEST_F(LoginPromptTest, TestDigestAuth) {
  scoped_refptr<HTTPTestServer> server =
      HTTPTestServer::CreateServer(kDocRoot, NULL);
  ASSERT_TRUE(NULL != server.get());
  scoped_refptr<TabProxy> tab(GetActiveTab());
  ASSERT_TRUE(tab.get());
  NavigateTab(tab.get(), server->TestServerPageW(L"auth-digest"));

  EXPECT_TRUE(tab->NeedsAuth());
  EXPECT_FALSE(tab->SetAuth(username_digest_, password_bad_));
  EXPECT_TRUE(tab->CancelAuth());
  EXPECT_EQ(L"Denied: wrong password", GetActiveTabTitle());

  NavigateTab(tab.get(), server->TestServerPageW(L"auth-digest"));

  EXPECT_TRUE(tab->NeedsAuth());
  EXPECT_TRUE(tab->SetAuth(username_digest_, password_));
  EXPECT_EQ(ExpectedTitleFromAuth(username_digest_, password_),
            GetActiveTabTitle());
}

// Test that logging in on 2 tabs at once works.
// Flaky, http://crbug.com/25794.
TEST_F(LoginPromptTest, FLAKY_TestTwoAuths) {
  scoped_refptr<HTTPTestServer> server =
      HTTPTestServer::CreateServer(kDocRoot, NULL);
  ASSERT_TRUE(NULL != server.get());

  scoped_refptr<TabProxy> basic_tab(GetActiveTab());
  ASSERT_TRUE(basic_tab.get());
  NavigateTab(basic_tab.get(), server->TestServerPageW(L"auth-basic"));

  AppendTab(GURL(chrome::kAboutBlankURL));
  scoped_refptr<TabProxy> digest_tab(GetActiveTab());
  ASSERT_TRUE(digest_tab.get());
  NavigateTab(digest_tab.get(), server->TestServerPageW(L"auth-digest"));

  // TODO(devint): http://b/1158262 basic_tab is not active, so this logs in to
  // a page whose tab isn't active, which isn't actually possible for the user
  // to do. I had a fix for this, but I'm reverting it to see if it makes the
  // test less flaky.
  EXPECT_TRUE(basic_tab->NeedsAuth());
  EXPECT_TRUE(basic_tab->SetAuth(username_basic_, password_));
  EXPECT_TRUE(digest_tab->NeedsAuth());
  EXPECT_TRUE(digest_tab->SetAuth(username_digest_, password_));

  wstring title;
  EXPECT_TRUE(basic_tab->GetTabTitle(&title));
  EXPECT_EQ(ExpectedTitleFromAuth(username_basic_, password_), title);

  EXPECT_TRUE(digest_tab->GetTabTitle(&title));
  EXPECT_EQ(ExpectedTitleFromAuth(username_digest_, password_), title);
}

// Test that cancelling authentication works.
TEST_F(LoginPromptTest, TestCancelAuth) {
  scoped_refptr<HTTPTestServer> server =
      HTTPTestServer::CreateServer(kDocRoot, NULL);
  ASSERT_TRUE(NULL != server.get());
  scoped_refptr<TabProxy> tab(GetActiveTab());
  ASSERT_TRUE(tab.get());

  // First navigate to a test server page so we have something to go back to.
  EXPECT_TRUE(tab->NavigateToURL(server->TestServerPageW(L"a")));

  // Navigating while auth is requested is the same as cancelling.
  NavigateTab(tab.get(), server->TestServerPageW(L"auth-basic"));
  EXPECT_TRUE(tab->NeedsAuth());
  EXPECT_TRUE(tab->NavigateToURL(server->TestServerPageW(L"b")));
  EXPECT_FALSE(tab->NeedsAuth());

  NavigateTab(tab.get(), server->TestServerPageW(L"auth-basic"));
  EXPECT_TRUE(tab->NeedsAuth());
  EXPECT_TRUE(tab->GoBack());  // should bring us back to 'a'
  EXPECT_FALSE(tab->NeedsAuth());

  // Now add a page and go back, so we have something to go forward to.
  EXPECT_TRUE(tab->NavigateToURL(server->TestServerPageW(L"c")));
  EXPECT_TRUE(tab->GoBack());  // should bring us back to 'a'

  NavigateTab(tab.get(), server->TestServerPageW(L"auth-basic"));
  EXPECT_TRUE(tab->NeedsAuth());
  EXPECT_TRUE(tab->GoForward());  // should bring us to 'c'
  EXPECT_FALSE(tab->NeedsAuth());

  // Now test that cancelling works as expected.
  NavigateTab(tab.get(), server->TestServerPageW(L"auth-basic"));
  EXPECT_TRUE(tab->NeedsAuth());
  EXPECT_TRUE(tab->CancelAuth());
  EXPECT_FALSE(tab->NeedsAuth());
  EXPECT_EQ(L"Denied: no auth", GetActiveTabTitle());
}
<commit_msg>ChromeOS: Label LoginPromptTest.TestDigestAuth as flaky. It's failing under Valgrind sometimes.<commit_after>// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include <string>

#include "chrome/browser/net/url_fixer_upper.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/common/url_constants.h"
#include "chrome/test/automation/tab_proxy.h"
#include "chrome/test/automation/browser_proxy.h"
#include "chrome/test/ui/ui_test.h"
#include "net/url_request/url_request_unittest.h"

using std::wstring;

namespace {

const wchar_t kDocRoot[] = L"chrome/test/data";

}  // namespace

class LoginPromptTest : public UITest {
 protected:
  LoginPromptTest()
      : UITest(),
        username_basic_(L"basicuser"),
        username_digest_(L"digestuser"),
        password_(L"secret"),
        password_bad_(L"denyme") {
  }

  void NavigateTab(TabProxy* tab_proxy, const GURL& url) {
    ASSERT_TRUE(tab_proxy->NavigateToURL(url));
  }

  void AppendTab(const GURL& url) {
    scoped_refptr<BrowserProxy> window_proxy(automation()->GetBrowserWindow(0));
    ASSERT_TRUE(window_proxy.get());
    ASSERT_TRUE(window_proxy->AppendTab(url));
  }

 protected:
  wstring username_basic_;
  wstring username_digest_;
  wstring password_;
  wstring password_bad_;
};

wstring ExpectedTitleFromAuth(const wstring& username,
                              const wstring& password) {
  // The TestServer sets the title to username/password on successful login.
  return username + L"/" + password;
}

// Test that "Basic" HTTP authentication works.
TEST_F(LoginPromptTest, TestBasicAuth) {
  scoped_refptr<HTTPTestServer> server =
      HTTPTestServer::CreateServer(kDocRoot, NULL);
  ASSERT_TRUE(NULL != server.get());
  scoped_refptr<TabProxy> tab(GetActiveTab());
  ASSERT_TRUE(tab.get());
  NavigateTab(tab.get(), server->TestServerPageW(L"auth-basic"));

  EXPECT_TRUE(tab->NeedsAuth());
  EXPECT_FALSE(tab->SetAuth(username_basic_, password_bad_));
  EXPECT_TRUE(tab->NeedsAuth());
  EXPECT_TRUE(tab->CancelAuth());
  EXPECT_EQ(L"Denied: wrong password", GetActiveTabTitle());

  NavigateTab(tab.get(), server->TestServerPageW(L"auth-basic"));

  EXPECT_TRUE(tab->NeedsAuth());
  EXPECT_TRUE(tab->SetAuth(username_basic_, password_));
  EXPECT_EQ(ExpectedTitleFromAuth(username_basic_, password_),
            GetActiveTabTitle());
}

// http://crbug.com/38580
#if defined(OS_CHROMEOS)
#define TestDigestAuth FLAKY_TestDigestAuth
#endif
// Test that "Digest" HTTP authentication works.
TEST_F(LoginPromptTest, TestDigestAuth) {
  scoped_refptr<HTTPTestServer> server =
      HTTPTestServer::CreateServer(kDocRoot, NULL);
  ASSERT_TRUE(NULL != server.get());
  scoped_refptr<TabProxy> tab(GetActiveTab());
  ASSERT_TRUE(tab.get());
  NavigateTab(tab.get(), server->TestServerPageW(L"auth-digest"));

  EXPECT_TRUE(tab->NeedsAuth());
  EXPECT_FALSE(tab->SetAuth(username_digest_, password_bad_));
  EXPECT_TRUE(tab->CancelAuth());
  EXPECT_EQ(L"Denied: wrong password", GetActiveTabTitle());

  NavigateTab(tab.get(), server->TestServerPageW(L"auth-digest"));

  EXPECT_TRUE(tab->NeedsAuth());
  EXPECT_TRUE(tab->SetAuth(username_digest_, password_));
  EXPECT_EQ(ExpectedTitleFromAuth(username_digest_, password_),
            GetActiveTabTitle());
}

// Test that logging in on 2 tabs at once works.
// Flaky, http://crbug.com/25794.
TEST_F(LoginPromptTest, FLAKY_TestTwoAuths) {
  scoped_refptr<HTTPTestServer> server =
      HTTPTestServer::CreateServer(kDocRoot, NULL);
  ASSERT_TRUE(NULL != server.get());

  scoped_refptr<TabProxy> basic_tab(GetActiveTab());
  ASSERT_TRUE(basic_tab.get());
  NavigateTab(basic_tab.get(), server->TestServerPageW(L"auth-basic"));

  AppendTab(GURL(chrome::kAboutBlankURL));
  scoped_refptr<TabProxy> digest_tab(GetActiveTab());
  ASSERT_TRUE(digest_tab.get());
  NavigateTab(digest_tab.get(), server->TestServerPageW(L"auth-digest"));

  // TODO(devint): http://b/1158262 basic_tab is not active, so this logs in to
  // a page whose tab isn't active, which isn't actually possible for the user
  // to do. I had a fix for this, but I'm reverting it to see if it makes the
  // test less flaky.
  EXPECT_TRUE(basic_tab->NeedsAuth());
  EXPECT_TRUE(basic_tab->SetAuth(username_basic_, password_));
  EXPECT_TRUE(digest_tab->NeedsAuth());
  EXPECT_TRUE(digest_tab->SetAuth(username_digest_, password_));

  wstring title;
  EXPECT_TRUE(basic_tab->GetTabTitle(&title));
  EXPECT_EQ(ExpectedTitleFromAuth(username_basic_, password_), title);

  EXPECT_TRUE(digest_tab->GetTabTitle(&title));
  EXPECT_EQ(ExpectedTitleFromAuth(username_digest_, password_), title);
}

// Test that cancelling authentication works.
TEST_F(LoginPromptTest, TestCancelAuth) {
  scoped_refptr<HTTPTestServer> server =
      HTTPTestServer::CreateServer(kDocRoot, NULL);
  ASSERT_TRUE(NULL != server.get());
  scoped_refptr<TabProxy> tab(GetActiveTab());
  ASSERT_TRUE(tab.get());

  // First navigate to a test server page so we have something to go back to.
  EXPECT_TRUE(tab->NavigateToURL(server->TestServerPageW(L"a")));

  // Navigating while auth is requested is the same as cancelling.
  NavigateTab(tab.get(), server->TestServerPageW(L"auth-basic"));
  EXPECT_TRUE(tab->NeedsAuth());
  EXPECT_TRUE(tab->NavigateToURL(server->TestServerPageW(L"b")));
  EXPECT_FALSE(tab->NeedsAuth());

  NavigateTab(tab.get(), server->TestServerPageW(L"auth-basic"));
  EXPECT_TRUE(tab->NeedsAuth());
  EXPECT_TRUE(tab->GoBack());  // should bring us back to 'a'
  EXPECT_FALSE(tab->NeedsAuth());

  // Now add a page and go back, so we have something to go forward to.
  EXPECT_TRUE(tab->NavigateToURL(server->TestServerPageW(L"c")));
  EXPECT_TRUE(tab->GoBack());  // should bring us back to 'a'

  NavigateTab(tab.get(), server->TestServerPageW(L"auth-basic"));
  EXPECT_TRUE(tab->NeedsAuth());
  EXPECT_TRUE(tab->GoForward());  // should bring us to 'c'
  EXPECT_FALSE(tab->NeedsAuth());

  // Now test that cancelling works as expected.
  NavigateTab(tab.get(), server->TestServerPageW(L"auth-basic"));
  EXPECT_TRUE(tab->NeedsAuth());
  EXPECT_TRUE(tab->CancelAuth());
  EXPECT_FALSE(tab->NeedsAuth());
  EXPECT_EQ(L"Denied: no auth", GetActiveTabTitle());
}
<|endoftext|>


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

#include "chrome/renderer/page_click_tracker.h"

#include "chrome/renderer/page_click_listener.h"
#include "chrome/renderer/render_view.h"
#include "third_party/WebKit/WebKit/chromium/public/WebDocument.h"
#include "third_party/WebKit/WebKit/chromium/public/WebDOMMouseEvent.h"
#include "third_party/WebKit/WebKit/chromium/public/WebFrame.h"
#include "third_party/WebKit/WebKit/chromium/public/WebInputElement.h"
#include "third_party/WebKit/WebKit/chromium/public/WebString.h"
#include "third_party/WebKit/WebKit/chromium/public/WebView.h"

using WebKit::WebDOMEvent;
using WebKit::WebDOMMouseEvent;
using WebKit::WebElement;
using WebKit::WebFormControlElement;
using WebKit::WebFrame;
using WebKit::WebInputElement;
using WebKit::WebInputEvent;
using WebKit::WebMouseEvent;
using WebKit::WebNode;
using WebKit::WebString;
using WebKit::WebView;

PageClickTracker::PageClickTracker(RenderView* render_view)
    : render_view_(render_view),
      was_focused_(false) {
}

PageClickTracker::~PageClickTracker() {
  // Note that even though RenderView calls StopTrackingFrame when notified that
  // a frame was closed, it might not always get that notification from WebKit
  // for all frames.
  // By the time we get here, the frame could have been destroyed so we cannot
  // unregister listeners in frames remaining in tracked_frames_ as they might
  // be invalid.
}

void PageClickTracker::StartTrackingFrame(WebFrame* frame) {
  tracked_frames_.push_back(frame);
  frame->document().addEventListener("mousedown", this, false);
}

void PageClickTracker::StopTrackingFrame(WebFrame* frame, bool frame_detached) {
  FrameList::iterator iter =
      std::find(tracked_frames_.begin(), tracked_frames_.end(), frame);
  if (iter == tracked_frames_.end()) {
    // Some frames might never load contents so we may not have a listener on
    // them.  Calling removeEventListener() on them would trigger an assert, so
    // we need to keep track of which frames we are listening to.
    return;
  }
  tracked_frames_.erase(iter);
  // If the frame has been detached, all event listeners have already been
  // removed.
  if (!frame_detached)
    frame->document().removeEventListener("mousedown", this, false);
}

void PageClickTracker::DidHandleMouseEvent(const WebMouseEvent& event) {
  if (event.type != WebInputEvent::MouseDown ||
      last_node_clicked_.isNull()) {
    return;
  }

  // We are only interested in text field clicks.
  if (!last_node_clicked_.isElementNode())
    return;
  const WebElement& element = last_node_clicked_.toConst<WebElement>();
  if (!element.isFormControlElement())
    return;
  const WebFormControlElement& control =
      element.toConst<WebFormControlElement>();
  if (control.formControlType() != WebString::fromUTF8("text"))
    return;

  const WebInputElement& input_element = element.toConst<WebInputElement>();

  bool is_focused = (last_node_clicked_ == GetFocusedNode());
  ObserverListBase<PageClickListener>::Iterator it(listeners_);
  PageClickListener* listener;
  while ((listener = it.GetNext()) != NULL) {
    if (listener->InputElementClicked(input_element, was_focused_, is_focused))
      break;
  }

  last_node_clicked_.reset();
}

void PageClickTracker::AddListener(PageClickListener* listener) {
  listeners_.AddObserver(listener);
}

void PageClickTracker::RemoveListener(PageClickListener* listener) {
  listeners_.RemoveObserver(listener);
}

void PageClickTracker::handleEvent(const WebDOMEvent& event) {
  last_node_clicked_.reset();

  DCHECK(event.isMouseEvent());
  const WebDOMMouseEvent mouse_event = event.toConst<WebDOMMouseEvent>();
  DCHECK(mouse_event.buttonDown());
  if (mouse_event.button() != 0)
    return;  // We are only interested in left clicks.

  // Remember which node has focus before the click is processed.
  // We'll get a notification once the mouse event has been processed
  // (DidHandleMouseEvent), we'll notify the listener at that point.
  last_node_clicked_ = mouse_event.target();
  was_focused_ = (GetFocusedNode() == last_node_clicked_);
}

WebNode PageClickTracker::GetFocusedNode() {
  WebView* web_view = render_view_->webview();
  if (!web_view)
    return WebNode();

  WebFrame* web_frame = web_view->focusedFrame();
  if (!web_frame)
    return WebNode();

  return web_frame->document().focusedNode();
}
<commit_msg>Added check in page click tracker to ensure events passed in are mouse events<commit_after>// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chrome/renderer/page_click_tracker.h"

#include "chrome/renderer/page_click_listener.h"
#include "chrome/renderer/render_view.h"
#include "third_party/WebKit/WebKit/chromium/public/WebDocument.h"
#include "third_party/WebKit/WebKit/chromium/public/WebDOMMouseEvent.h"
#include "third_party/WebKit/WebKit/chromium/public/WebFrame.h"
#include "third_party/WebKit/WebKit/chromium/public/WebInputElement.h"
#include "third_party/WebKit/WebKit/chromium/public/WebString.h"
#include "third_party/WebKit/WebKit/chromium/public/WebView.h"

using WebKit::WebDOMEvent;
using WebKit::WebDOMMouseEvent;
using WebKit::WebElement;
using WebKit::WebFormControlElement;
using WebKit::WebFrame;
using WebKit::WebInputElement;
using WebKit::WebInputEvent;
using WebKit::WebMouseEvent;
using WebKit::WebNode;
using WebKit::WebString;
using WebKit::WebView;

PageClickTracker::PageClickTracker(RenderView* render_view)
    : render_view_(render_view),
      was_focused_(false) {
}

PageClickTracker::~PageClickTracker() {
  // Note that even though RenderView calls StopTrackingFrame when notified that
  // a frame was closed, it might not always get that notification from WebKit
  // for all frames.
  // By the time we get here, the frame could have been destroyed so we cannot
  // unregister listeners in frames remaining in tracked_frames_ as they might
  // be invalid.
}

void PageClickTracker::StartTrackingFrame(WebFrame* frame) {
  tracked_frames_.push_back(frame);
  frame->document().addEventListener("mousedown", this, false);
}

void PageClickTracker::StopTrackingFrame(WebFrame* frame, bool frame_detached) {
  FrameList::iterator iter =
      std::find(tracked_frames_.begin(), tracked_frames_.end(), frame);
  if (iter == tracked_frames_.end()) {
    // Some frames might never load contents so we may not have a listener on
    // them.  Calling removeEventListener() on them would trigger an assert, so
    // we need to keep track of which frames we are listening to.
    return;
  }
  tracked_frames_.erase(iter);
  // If the frame has been detached, all event listeners have already been
  // removed.
  if (!frame_detached)
    frame->document().removeEventListener("mousedown", this, false);
}

void PageClickTracker::DidHandleMouseEvent(const WebMouseEvent& event) {
  if (event.type != WebInputEvent::MouseDown ||
      last_node_clicked_.isNull()) {
    return;
  }

  // We are only interested in text field clicks.
  if (!last_node_clicked_.isElementNode())
    return;
  const WebElement& element = last_node_clicked_.toConst<WebElement>();
  if (!element.isFormControlElement())
    return;
  const WebFormControlElement& control =
      element.toConst<WebFormControlElement>();
  if (control.formControlType() != WebString::fromUTF8("text"))
    return;

  const WebInputElement& input_element = element.toConst<WebInputElement>();

  bool is_focused = (last_node_clicked_ == GetFocusedNode());
  ObserverListBase<PageClickListener>::Iterator it(listeners_);
  PageClickListener* listener;
  while ((listener = it.GetNext()) != NULL) {
    if (listener->InputElementClicked(input_element, was_focused_, is_focused))
      break;
  }

  last_node_clicked_.reset();
}

void PageClickTracker::AddListener(PageClickListener* listener) {
  listeners_.AddObserver(listener);
}

void PageClickTracker::RemoveListener(PageClickListener* listener) {
  listeners_.RemoveObserver(listener);
}

void PageClickTracker::handleEvent(const WebDOMEvent& event) {
  last_node_clicked_.reset();

  if (!event.isMouseEvent())
    return;

  const WebDOMMouseEvent mouse_event = event.toConst<WebDOMMouseEvent>();
  DCHECK(mouse_event.buttonDown());
  if (mouse_event.button() != 0)
    return;  // We are only interested in left clicks.

  // Remember which node has focus before the click is processed.
  // We'll get a notification once the mouse event has been processed
  // (DidHandleMouseEvent), we'll notify the listener at that point.
  last_node_clicked_ = mouse_event.target();
  was_focused_ = (GetFocusedNode() == last_node_clicked_);
}

WebNode PageClickTracker::GetFocusedNode() {
  WebView* web_view = render_view_->webview();
  if (!web_view)
    return WebNode();

  WebFrame* web_frame = web_view->focusedFrame();
  if (!web_frame)
    return WebNode();

  return web_frame->document().focusedNode();
}
<|endoftext|>


<commit_before>// RUN: cat %s | %cling | FileCheck %s
// XFAIL: vg_leak
// Expected to fail on 32 bit machine because we need to pass the storage object
// in a proper way for 32 bit machines. And it has invalid mem accesses.

#include "cling/Interpreter/Interpreter.h"
#include "cling/Interpreter/Value.h"

cling::Value V;
V // CHECK: (cling::Value) <<<invalid>>> @0x{{.*}}

gCling->evaluate("1;", &V);
V // CHECK: (cling::Value) boxes [(int) 1]

long LongV = 17;
gCling->evaluate("LongV;", &V);
V // CHECK: (cling::Value) boxes [(long) 17]

int* IntP = (int*)0x12;
gCling->evaluate("IntP;", &V);
V // CHECK: (cling::Value) boxes [(int *) 0x12]

cling::Value Result;
Result.value = llvm::PTOGV(&V); // SRet
gCling->evaluate("V", &Result);
Result // CHECK: (cling::Value) boxes [(cling::Value) ]
V // CHECK: (cling::Value) boxes [(int *) 0x12]

// Savannah #96277
gCling->evaluate("double sin(double); double one = sin(3.141/2);", &V);
one // CHECK: (double) 1.000000e+00
<commit_msg>Better: mark it as xfail on 32 bit and when running with valgrind.<commit_after>// RUN: cat %s | %cling | FileCheck %s
// XFAIL: i686, vg_leak
// Expected to fail on 32 bit machine because we need to pass the storage object
// in a proper way for 32 bit machines. And it has invalid mem accesses.

#include "cling/Interpreter/Interpreter.h"
#include "cling/Interpreter/Value.h"

cling::Value V;
V // CHECK: (cling::Value) <<<invalid>>> @0x{{.*}}

gCling->evaluate("1;", &V);
V // CHECK: (cling::Value) boxes [(int) 1]

long LongV = 17;
gCling->evaluate("LongV;", &V);
V // CHECK: (cling::Value) boxes [(long) 17]

int* IntP = (int*)0x12;
gCling->evaluate("IntP;", &V);
V // CHECK: (cling::Value) boxes [(int *) 0x12]

cling::Value Result;
Result.value = llvm::PTOGV(&V); // SRet
gCling->evaluate("V", &Result);
Result // CHECK: (cling::Value) boxes [(cling::Value) ]
V // CHECK: (cling::Value) boxes [(int *) 0x12]

// Savannah #96277
gCling->evaluate("double sin(double); double one = sin(3.141/2);", &V);
one // CHECK: (double) 1.000000e+00
<|endoftext|>


<commit_before>/* testlibsrsircpp.cpp - (C) 2014, Emir Marincic
 * libsrsircpp - C++ wrapper for libsrsirc
 * See README for contact-, COPYING for license information. */

#include <iostream>
#include <cstdlib>

#include <libsrsircpp/irc_oo.h>

using namespace std;

int
main(int argc, char **argv)
{
	IRC handle;
	handle.Nick("Testircpp");
	handle.Uname("Testircpp");
	handle.ConFlags(0);
	handle.Server("irc.quakenet.org", "6667");
	if(!handle.Connect(10*1000000UL)){
		cout<<"Failed to connect"<<endl;
		return -1;
	}
	if(!handle.Write("JOIN #Lea2")){
		cout<<"Couldn't join"<<endl;
		return -1;
	}
	if(!handle.Write("PRIVMSG #Lea2 :Teeeest")){
		cout<<"Couldn't Write"<<endl;
		return -1;
	}
	return EXIT_SUCCESS;
}
<commit_msg>Editor auto quoting... Not so helpful<commit_after>/* testlibsrsircpp.cpp - (C) 2014, Emir Marincic
 * libsrsircpp - C++ wrapper for libsrsirc
 * See README for contact-, COPYING for license information. */

#include <iostream>
#include <cstdlib>

#include <libsrsircpp/irc_oo.h>

using namespace std;

int
main(int argc, char **argv)
{
	IRC handle;
	handle.Nick("Testircpp");
	handle.Uname("Testircpp");
	handle.ConFlags(0);
	handle.Server("irc.quakenet.org", 6667);
	if(!handle.Connect(10*1000000UL)){
		cout<<"Failed to connect"<<endl;
		return -1;
	}
	if(!handle.Write("JOIN #Lea2")){
		cout<<"Couldn't join"<<endl;
		return -1;
	}
	if(!handle.Write("PRIVMSG #Lea2 :Teeeest")){
		cout<<"Couldn't Write"<<endl;
		return -1;
	}
	return EXIT_SUCCESS;
}
<|endoftext|>


<commit_before>#pragma once

#include <boost/operators.hpp>

#include <iterator>

#include "defaults.hpp"
#include "tools.hpp"

namespace gftools {

/** This class describes a point on a grid. It has an index (integer) and a value (pretty much anything) , and it
maps between the two. The index is used for fast access, and the value is used for other things like interpolation/physics/math.*/
template <typename ValueType> class point_base :
    boost::less_than_comparable<point_base<ValueType> >,
    boost::equality_comparable<point_base<ValueType> >
 {
public:
    //there is a small wrapper for integers down below. Here we exclude grids of ints to avoid confusion in the cast operators.
    static_assert(!std::is_same<ValueType,int>::value, "Can't create a grid of ints");

    typedef ValueType value_type;

    ///cast operator to value type
    operator ValueType() const { return val_; }
    ///cast operator to index type
    explicit operator size_t() const { return index_; }
    ///another cast operator to index type
    explicit operator int() const { return index_; }

    ///constructor with a pair of values and indices
    point_base(ValueType val, size_t index):val_(val),index_(index){}

    bool operator==(const point_base &rhs) const {return (val_ == rhs.val_) && (index_ == rhs.index_);}
    bool operator<(const point_base &rhs) const {return this->index_ < rhs.index_;}
    friend std::ostream& operator<<(std::ostream& lhs, const point_base &p){lhs<<"{"<<p.val_<<"<-["<<p.index_<<"]}"; return lhs;};

    ValueType value() const { return val_; }
    size_t index() const { return index_; }

protected:
    ///grid point (in physical units)
    ValueType val_;
    ///grid point index
    size_t index_;
};

/** A representation of a one-dimensional grid, which stores an array of the ValueType values. */
//template <typename ValueType, class Derived, typename = typename std::enable_if<!std::is_same<ValueType, int>::value>::type>
template <typename ValueType, class Derived>
class grid_base : public boost::equality_comparable<grid_base<ValueType, Derived>> {
public:
    /** A point combines a point of the grid and it's index. */
    struct point : point_base<ValueType> {
        //point():point_base<ValueType>::point_base(){};
        point(ValueType val, size_t index):point_base<ValueType>::point_base(val,index){};
        point(const point_base<ValueType> &in):point_base<ValueType>::point_base(in){};
        point(point_base<ValueType> &&in):point_base<ValueType>::point_base(std::forward<point_base<ValueType>>(in)){};
        };

    typedef ValueType value_type;

    grid_base(const std::vector<point> & vals);

    /** Empty constructor. */
    grid_base();
    /** Copy from vector. */
    grid_base(const std::vector<ValueType> & vals);
    /** Initialize the values from a given function, that maps the integer values
     * to the ValueType values.
     */
    grid_base(int min, int max, std::function<ValueType (int)> f);
    /** Copy constructor. */
    grid_base(const grid_base& rhs):vals_(rhs.vals_){};
    /** Move constructor. */
    grid_base(grid_base&& rhs){vals_.swap(rhs.vals_);};
    /** rvalue assignment. */
    grid_base& operator=(grid_base &&rhs){vals_.swap(rhs.vals_); return (*this);};
    /** Returns a value at given index. */
    point operator[](size_t in) const;
    /** Returns all values. */
    const std::vector<point> & points() const;
    /** Returns values of all points. */
    std::vector<ValueType> values() const;
    /** Checks if a point is present in a grid. */
    bool check_point(point in, real_type tolerance = std::numeric_limits<real_type>::epsilon()) const;
    /** Returns size of grid. */
    size_t size() const;

    /** Returns the closest point to the given value. */
    point find_nearest(ValueType in) const;
    /** Get a value of an object at the given point, which is defined on a grid. */
    template <class Obj> auto eval(Obj &&in, point x) const ->decltype(in[0]);

    /** Shift a point by the given value. */
    point shift(point in, ValueType shift_arg) const;
    ValueType shift(ValueType in, ValueType shift_arg) const;
    point shift (point in, point shift_arg) const;

    // CFTP forwards
    /** Get a value of an object at the given coordinate, which is defined on a grid. */
    template <class Obj>
        auto eval(Obj &in, ValueType x) const ->decltype(in[0])
        { return static_cast<const Derived*>(this)->eval(in,x); };
    /** Returns a tuple of left closest index, weight, right closest index and weight, which are the closest to input value. */
    /** Integrate over grid. */
    //template <class Obj> auto integrate(const Obj &in) const ->decltype(in[vals_[0]])
    //    { return static_cast<const Derived*>(this)->integrate(in); };
    /** Integrate over grid with extra arguments provided. */
    template <class Obj, typename std::result_of<Obj(point)>::type>
        auto integrate(Obj &&in) const ->
            typename std::remove_reference<typename std::result_of<Obj(point)>::type>::type
                { return static_cast<const Derived*>(this)->integrate(in); };
    /// Make the object printable.
    template <typename ValType, class Derived2> friend std::ostream& operator<<(std::ostream& lhs, const grid_base<ValType,Derived2> &gr);
    /// Compare 2 grids
    bool operator==(const grid_base &rhs) const;

    std::vector<point> vals_;
    class ex_wrong_index : public std::exception { virtual const char* what() const throw(); };
};

namespace extra {
/// A small helper struct to decorate a function object with [] method.
template <typename F, typename Grid>
struct function_proxy {
    F f_;
    const Grid& grid_;
    function_proxy(F f, Grid const& grid):f_(f),grid_(grid){}
    typedef typename std::result_of<F(typename Grid::value_type)>::type value_type;
    value_type operator[](int i) const {return f_((grid_.points()[i]).value()); }
};
}

//
// grid_base implementation
//

template <typename ValueType, class Derived>
grid_base<ValueType,Derived>::grid_base()
{};

template <typename ValueType, class Derived>
grid_base<ValueType,Derived>::grid_base(const std::vector<point> &vals):vals_(vals)
{
};

template <typename ValueType, class Derived>
grid_base<ValueType,Derived>::grid_base(const std::vector<ValueType> &vals)
{
    vals_.reserve(vals.size());
    for (size_t i=0; i<vals.size(); ++i) { vals_.emplace_back(point(vals[i], i)); };
};

template <typename ValueType, class Derived>
grid_base<ValueType,Derived>::grid_base(int min, int max, std::function<ValueType (int)> f)
{
    if (max<min) std::swap(min,max);
    size_t n_points = max-min;
    vals_.reserve(n_points);
    for (int i=0; i<n_points; ++i) vals_.emplace_back(f(min+i), i) ;
}

template <typename ValueType, class Derived>
inline typename grid_base<ValueType,Derived>::point grid_base<ValueType,Derived>::operator[](size_t index) const
{
    if (index>vals_.size()) throw ex_wrong_index();
    return vals_[index];
}

template <typename ValueType, class Derived>
inline const std::vector<typename grid_base<ValueType,Derived>::point> & grid_base<ValueType,Derived>::points() const
{
    return vals_;
}

template <typename ValueType, class Derived>
inline std::vector<ValueType> grid_base<ValueType,Derived>::values() const
{
    std::vector<ValueType> out;
    out.reserve(vals_.size());
    for (const auto& x : vals_) out.emplace_back(x.value());
    return out;
}

template <typename ValueType, class Derived>
inline size_t grid_base<ValueType,Derived>::size() const
{
    return vals_.size();
}

template <typename ValueType, class Derived>
inline bool grid_base<ValueType,Derived>::check_point(point in, real_type tolerance) const
{
    return (in.index() < vals_.size() && std::abs(in.value() - vals_[in.index()].value()) < tolerance);
}

template <typename ValueType, class Derived>
template <class Obj>
inline auto grid_base<ValueType,Derived>::eval(Obj &&in, point x) const ->decltype(in[0])
{
    if (check_point(x)) return in[x.index()];
    else { ERROR ("Point not found"); throw ex_wrong_index(); };
}

template <typename ValueType, class Derived>
inline typename grid_base<ValueType,Derived>::point grid_base<ValueType,Derived>::find_nearest(ValueType in) const
{
    static_assert(std::is_same<bool,decltype(std::declval<ValueType>() < std::declval<ValueType>())>::value,
        "Default find_nearest is written only for less-comparable types");
    auto nearest_iter = std::lower_bound(vals_.begin(), vals_.end(), in, [](ValueType x, ValueType y){return x<y;});
    size_t dist = std::distance(vals_.begin(), nearest_iter);
    if (dist > 0 && std::abs(complex_type(vals_[dist].value()) - complex_type(in)) > std::abs(complex_type(vals_[dist-1].value()) - complex_type(in)) ) dist--;
    return vals_[dist];
}

template <typename ValueType, class Derived>
inline typename grid_base<ValueType,Derived>::point grid_base<ValueType,Derived>::shift(point in, ValueType shift_arg) const
{
    if (tools::is_float_equal(shift_arg, 0.0)) return in;
    ValueType out(in.value());
    out = static_cast<const Derived*>(this)->shift(ValueType(in),shift_arg);
    point p1 = static_cast<const Derived*>(this)->find_nearest(out);
    if (!tools::is_float_equal(p1.value(), out, std::abs(p1.value() - ((p1.index()!=0)?vals_[p1.index() - 1]:vals_[p1.index()+1]).value())/10.)) {
        #ifndef NDEBUG
        ERROR("Couldn't shift point" <<  in << " by " << shift_arg << " got " << out);
        #endif
        throw (ex_wrong_index());
        }
    else return p1;
}

template <typename ValueType, class Derived>
inline ValueType grid_base<ValueType,Derived>::shift(ValueType in, ValueType shift_arg) const
{
    return in+shift_arg;
}

template <typename ValueType, class Derived>
inline typename grid_base<ValueType,Derived>::point grid_base<ValueType,Derived>::shift(point in, point shift_arg) const
{
    size_t index = (in.index() + shift_arg.index())%vals_.size();
    #ifndef NDEBUG
    ValueType val = static_cast<const Derived*>(this)->shift(in.value(), shift_arg.value());
    if (!tools::is_float_equal(val, vals_[index].value())) throw (ex_wrong_index());
    #endif
    return vals_[index];

}

template <typename ValueType, class Derived>
inline bool grid_base<ValueType,Derived>::operator==(const grid_base &rhs) const
{
    bool out = (this->size() == rhs.size());
    for (int i=0; i<vals_.size() && out; i++) {
        out = out && tools::is_float_equal(vals_[i].value(), rhs.vals_[i].value(), num_io<double>::tolerance());
    }
    return out;
}

template <typename ValueType, class Derived>
std::ostream& operator<<(std::ostream& lhs, const grid_base<ValueType,Derived> &gr)
{
    lhs << "{";
    //lhs << gr.vals_;
    std::ostream_iterator<ValueType> out_it (lhs,", ");
    std::transform(gr.vals_.begin(),gr.vals_.end(), out_it, [](const typename grid_base<ValueType,Derived>::point &x){return ValueType(x);});
    lhs << "}";
    return lhs;
}

template <typename ValueType, class Derived>
const char* grid_base<ValueType,Derived>::ex_wrong_index::what() const throw(){
     return "Index out of bounds";
};

} // end :: namespace gftools

//#include "grid_tools.hpp"

<commit_msg>comparison should be purely based on ints not floats<commit_after>#pragma once

#include <boost/operators.hpp>

#include <iterator>

#include "defaults.hpp"
#include "tools.hpp"

namespace gftools {

/** This class describes a point on a grid. It has an index (integer) and a value (pretty much anything) , and it
maps between the two. The index is used for fast access, and the value is used for other things like interpolation/physics/math.*/
template <typename ValueType> class point_base :
    ///dependence on this provides additional comparison operators
    boost::less_than_comparable<point_base<ValueType> >,
    ///dependence on this provides additional comparison operators
    boost::equality_comparable<point_base<ValueType> >
 {
public:
    //there is a small wrapper for integers down below. Here we exclude grids of ints to avoid confusion in the cast operators.
    static_assert(!std::is_same<ValueType,int>::value, "Can't create a grid of ints");

    typedef ValueType value_type;

    ///cast operator to value type
    operator ValueType() const { return val_; }
    ///cast operator to index type
    explicit operator size_t() const { return index_; }
    ///another cast operator to index type
    explicit operator int() const { return index_; }

    ///constructor with a pair of values and indices
    point_base(ValueType val, size_t index):val_(val),index_(index){}

    bool operator==(const point_base &rhs) const {return index_ == rhs.index_;}
    bool operator<(const point_base &rhs) const {return this->index_ < rhs.index_;}
    friend std::ostream& operator<<(std::ostream& lhs, const point_base &p){lhs<<"{"<<p.val_<<"<-["<<p.index_<<"]}"; return lhs;};

    ValueType value() const { return val_; }
    size_t index() const { return index_; }

protected:
    ///grid point (in physical units)
    ValueType val_;
    ///grid point index
    size_t index_;
};

/** A representation of a one-dimensional grid, which stores an array of the ValueType values. */
//template <typename ValueType, class Derived, typename = typename std::enable_if<!std::is_same<ValueType, int>::value>::type>
template <typename ValueType, class Derived>
class grid_base : public boost::equality_comparable<grid_base<ValueType, Derived>> {
public:
    /** A point combines a point of the grid and it's index. */
    struct point : point_base<ValueType> {
        //point():point_base<ValueType>::point_base(){};
        point(ValueType val, size_t index):point_base<ValueType>::point_base(val,index){};
        point(const point_base<ValueType> &in):point_base<ValueType>::point_base(in){};
        point(point_base<ValueType> &&in):point_base<ValueType>::point_base(std::forward<point_base<ValueType>>(in)){};
        };

    typedef ValueType value_type;

    grid_base(const std::vector<point> & vals);

    /** Empty constructor. */
    grid_base();
    /** Copy from vector. */
    grid_base(const std::vector<ValueType> & vals);
    /** Initialize the values from a given function, that maps the integer values
     * to the ValueType values.
     */
    grid_base(int min, int max, std::function<ValueType (int)> f);
    /** Copy constructor. */
    grid_base(const grid_base& rhs):vals_(rhs.vals_){};
    /** Move constructor. */
    grid_base(grid_base&& rhs){vals_.swap(rhs.vals_);};
    /** rvalue assignment. */
    grid_base& operator=(grid_base &&rhs){vals_.swap(rhs.vals_); return (*this);};
    /** Returns a value at given index. */
    point operator[](size_t in) const;
    /** Returns all values. */
    const std::vector<point> & points() const;
    /** Returns values of all points. */
    std::vector<ValueType> values() const;
    /** Checks if a point is present in a grid. */
    bool check_point(point in, real_type tolerance = std::numeric_limits<real_type>::epsilon()) const;
    /** Returns size of grid. */
    size_t size() const;

    /** Returns the closest point to the given value. */
    point find_nearest(ValueType in) const;
    /** Get a value of an object at the given point, which is defined on a grid. */
    template <class Obj> auto eval(Obj &&in, point x) const ->decltype(in[0]);

    /** Shift a point by the given value. */
    point shift(point in, ValueType shift_arg) const;
    ValueType shift(ValueType in, ValueType shift_arg) const;
    point shift (point in, point shift_arg) const;

    // CFTP forwards
    /** Get a value of an object at the given coordinate, which is defined on a grid. */
    template <class Obj>
        auto eval(Obj &in, ValueType x) const ->decltype(in[0])
        { return static_cast<const Derived*>(this)->eval(in,x); };
    /** Returns a tuple of left closest index, weight, right closest index and weight, which are the closest to input value. */
    /** Integrate over grid. */
    //template <class Obj> auto integrate(const Obj &in) const ->decltype(in[vals_[0]])
    //    { return static_cast<const Derived*>(this)->integrate(in); };
    /** Integrate over grid with extra arguments provided. */
    template <class Obj, typename std::result_of<Obj(point)>::type>
        auto integrate(Obj &&in) const ->
            typename std::remove_reference<typename std::result_of<Obj(point)>::type>::type
                { return static_cast<const Derived*>(this)->integrate(in); };
    /// Make the object printable.
    template <typename ValType, class Derived2> friend std::ostream& operator<<(std::ostream& lhs, const grid_base<ValType,Derived2> &gr);
    /// Compare 2 grids
    bool operator==(const grid_base &rhs) const;

    std::vector<point> vals_;
    class ex_wrong_index : public std::exception { virtual const char* what() const throw(); };
};

namespace extra {
/// A small helper struct to decorate a function object with [] method.
template <typename F, typename Grid>
struct function_proxy {
    F f_;
    const Grid& grid_;
    function_proxy(F f, Grid const& grid):f_(f),grid_(grid){}
    typedef typename std::result_of<F(typename Grid::value_type)>::type value_type;
    value_type operator[](int i) const {return f_((grid_.points()[i]).value()); }
};
}

//
// grid_base implementation
//

template <typename ValueType, class Derived>
grid_base<ValueType,Derived>::grid_base()
{};

template <typename ValueType, class Derived>
grid_base<ValueType,Derived>::grid_base(const std::vector<point> &vals):vals_(vals)
{
};

template <typename ValueType, class Derived>
grid_base<ValueType,Derived>::grid_base(const std::vector<ValueType> &vals)
{
    vals_.reserve(vals.size());
    for (size_t i=0; i<vals.size(); ++i) { vals_.emplace_back(point(vals[i], i)); };
};

template <typename ValueType, class Derived>
grid_base<ValueType,Derived>::grid_base(int min, int max, std::function<ValueType (int)> f)
{
    if (max<min) std::swap(min,max);
    size_t n_points = max-min;
    vals_.reserve(n_points);
    for (int i=0; i<n_points; ++i) vals_.emplace_back(f(min+i), i) ;
}

template <typename ValueType, class Derived>
inline typename grid_base<ValueType,Derived>::point grid_base<ValueType,Derived>::operator[](size_t index) const
{
    if (index>vals_.size()) throw ex_wrong_index();
    return vals_[index];
}

template <typename ValueType, class Derived>
inline const std::vector<typename grid_base<ValueType,Derived>::point> & grid_base<ValueType,Derived>::points() const
{
    return vals_;
}

template <typename ValueType, class Derived>
inline std::vector<ValueType> grid_base<ValueType,Derived>::values() const
{
    std::vector<ValueType> out;
    out.reserve(vals_.size());
    for (const auto& x : vals_) out.emplace_back(x.value());
    return out;
}

template <typename ValueType, class Derived>
inline size_t grid_base<ValueType,Derived>::size() const
{
    return vals_.size();
}

template <typename ValueType, class Derived>
inline bool grid_base<ValueType,Derived>::check_point(point in, real_type tolerance) const
{
    return (in.index() < vals_.size() && std::abs(in.value() - vals_[in.index()].value()) < tolerance);
}

template <typename ValueType, class Derived>
template <class Obj>
inline auto grid_base<ValueType,Derived>::eval(Obj &&in, point x) const ->decltype(in[0])
{
    if (check_point(x)) return in[x.index()];
    else { ERROR ("Point not found"); throw ex_wrong_index(); };
}

template <typename ValueType, class Derived>
inline typename grid_base<ValueType,Derived>::point grid_base<ValueType,Derived>::find_nearest(ValueType in) const
{
    static_assert(std::is_same<bool,decltype(std::declval<ValueType>() < std::declval<ValueType>())>::value,
        "Default find_nearest is written only for less-comparable types");
    auto nearest_iter = std::lower_bound(vals_.begin(), vals_.end(), in, [](ValueType x, ValueType y){return x<y;});
    size_t dist = std::distance(vals_.begin(), nearest_iter);
    if (dist > 0 && std::abs(complex_type(vals_[dist].value()) - complex_type(in)) > std::abs(complex_type(vals_[dist-1].value()) - complex_type(in)) ) dist--;
    return vals_[dist];
}

template <typename ValueType, class Derived>
inline typename grid_base<ValueType,Derived>::point grid_base<ValueType,Derived>::shift(point in, ValueType shift_arg) const
{
    if (tools::is_float_equal(shift_arg, 0.0)) return in;
    ValueType out(in.value());
    out = static_cast<const Derived*>(this)->shift(ValueType(in),shift_arg);
    point p1 = static_cast<const Derived*>(this)->find_nearest(out);
    if (!tools::is_float_equal(p1.value(), out, std::abs(p1.value() - ((p1.index()!=0)?vals_[p1.index() - 1]:vals_[p1.index()+1]).value())/10.)) {
        #ifndef NDEBUG
        ERROR("Couldn't shift point" <<  in << " by " << shift_arg << " got " << out);
        #endif
        throw (ex_wrong_index());
        }
    else return p1;
}

template <typename ValueType, class Derived>
inline ValueType grid_base<ValueType,Derived>::shift(ValueType in, ValueType shift_arg) const
{
    return in+shift_arg;
}

template <typename ValueType, class Derived>
inline typename grid_base<ValueType,Derived>::point grid_base<ValueType,Derived>::shift(point in, point shift_arg) const
{
    size_t index = (in.index() + shift_arg.index())%vals_.size();
    #ifndef NDEBUG
    ValueType val = static_cast<const Derived*>(this)->shift(in.value(), shift_arg.value());
    if (!tools::is_float_equal(val, vals_[index].value())) throw (ex_wrong_index());
    #endif
    return vals_[index];

}

template <typename ValueType, class Derived>
inline bool grid_base<ValueType,Derived>::operator==(const grid_base &rhs) const
{
    bool out = (this->size() == rhs.size());
    for (int i=0; i<vals_.size() && out; i++) {
        out = out && tools::is_float_equal(vals_[i].value(), rhs.vals_[i].value(), num_io<double>::tolerance());
    }
    return out;
}

template <typename ValueType, class Derived>
std::ostream& operator<<(std::ostream& lhs, const grid_base<ValueType,Derived> &gr)
{
    lhs << "{";
    //lhs << gr.vals_;
    std::ostream_iterator<ValueType> out_it (lhs,", ");
    std::transform(gr.vals_.begin(),gr.vals_.end(), out_it, [](const typename grid_base<ValueType,Derived>::point &x){return ValueType(x);});
    lhs << "}";
    return lhs;
}

template <typename ValueType, class Derived>
const char* grid_base<ValueType,Derived>::ex_wrong_index::what() const throw(){
     return "Index out of bounds";
};

} // end :: namespace gftools

//#include "grid_tools.hpp"

<|endoftext|>


<commit_before>/*
    This file is part of KAddressBook.

    Copyright (c) 2007 Tobias Koenig <tokoe@kde.org>

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

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License along
    with this program; if not, write to the Free Software Foundation, Inc.,
    51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/

#include "aboutdata.h"
#include <kcmdlineargs.h>
#include <klocale.h>
#include <kuniqueapplication.h>
#include <akonadi/control.h>

#include "mainwindow.h"

int main( int argc, char **argv )
{
  AboutData about;

  KCmdLineArgs::init( argc, argv, &about );

  KCmdLineOptions options;
  KCmdLineArgs::addCmdLineOptions( options );
  KUniqueApplication::addCmdLineOptions();

  if ( !KUniqueApplication::start() )
    exit( 0 );

  KUniqueApplication app;
  KGlobal::locale()->insertCatalog( "libkdepim" );
  KGlobal::locale()->insertCatalog( "kabc" );

  MainWindow *window = new MainWindow;
  window->show();

  Akonadi::Control::start( window );

  return app.exec();
}
<commit_msg>needs this translation catalog too<commit_after>/*
    This file is part of KAddressBook.

    Copyright (c) 2007 Tobias Koenig <tokoe@kde.org>

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

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License along
    with this program; if not, write to the Free Software Foundation, Inc.,
    51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/

#include "aboutdata.h"
#include <kcmdlineargs.h>
#include <klocale.h>
#include <kuniqueapplication.h>
#include <akonadi/control.h>

#include "mainwindow.h"

int main( int argc, char **argv )
{
  AboutData about;

  KCmdLineArgs::init( argc, argv, &about );

  KCmdLineOptions options;
  KCmdLineArgs::addCmdLineOptions( options );
  KUniqueApplication::addCmdLineOptions();

  if ( !KUniqueApplication::start() )
    exit( 0 );

  KUniqueApplication app;
  KGlobal::locale()->insertCatalog( "libkdepim" );
  KGlobal::locale()->insertCatalog( "kabc" );
  KGlobal::locale()->insertCatalog( "libakonadi" );

  MainWindow *window = new MainWindow;
  window->show();

  Akonadi::Control::start( window );

  return app.exec();
}
<|endoftext|>


<commit_before>#include "HopsanCore.h"
#include "TicToc.h"
#include "CoreUtilities/Delay.h"

void test1()
{
    TicToc totaltimer("totaltimer");

    //Create master component
    ComponentSystem simulationmodel("simulationmodel");
    //Create other components
    ComponentPressureSource psourceL("ps_left_side", 10e5);
    ComponentOrifice orificeL("orifice_left_side", 1e-12);
    ComponentVolume volumeC("volume_center");
    //ComponentTLMlossless volumeC("volume_center");
    ComponentOrifice orificeR("orifice_right_side", 1e-12);
    ComponentPressureSource psourceR("ps_right_side", 0e5);

    //Add components
    simulationmodel.addComponent(psourceL);
    simulationmodel.addComponent(orificeL);
    simulationmodel.addComponent(volumeC);
    simulationmodel.addComponent(orificeR);
    simulationmodel.addComponent(psourceR);
    //Connect components
    simulationmodel.connect(psourceL, "P1", orificeL, "P1");
    simulationmodel.connect(orificeL, "P2", volumeC, "P1");
    simulationmodel.connect(volumeC, "P2", orificeR, "P1");
    simulationmodel.connect(orificeR, "P2", psourceR, "P1");

    //Run simulation
    TicToc prealloctimer("prealloctimer");
    simulationmodel.preAllocateLogSpace(0, 10);
    prealloctimer.TocPrint();

    TicToc simutimer("simutimer");
    simulationmodel.simulate(0,10);
    simutimer.TocPrint();

    totaltimer.TocPrint();

    //Test write to file
    TicToc filewritetimer("filewritetimer");
    volumeC.getPort("P1").getNode().saveLogData("output.txt");
    filewritetimer.TocPrint();
    cout << "test1() Done!" << endl;
}

void test2() //Test of the Delay utillity class
{
	Delay d1(.15, .1); //delay .15 with sampletime .1
	for (int i=0; i < 11; ++i) {
		cout << "Value: " << i << "    Delayed value: " << d1.value() << endl;
		d1.update(i);
	}
}

void testTLM()
{
	/*   Exempelsystem:

	   q       T, Zc
	 ------>o=========o p

	 */
	ComponentSystem simulationmodel("simulationmodel");
    //Create other components
    ComponentFlowSourceQ qsourceL(    "qs_left_side",  1.0);
    ComponentTLMlossless lineC(       "line_center",   3.0, 0.2);
    ComponentPressureSourceQ psourceR("ps_right_side", 1.0);

    //Add components
    simulationmodel.addComponent(qsourceL);
    simulationmodel.addComponent(lineC);
    simulationmodel.addComponent(psourceR);

    //List and set parameters
    lineC.listParametersConsole();
    lineC.setParameter("Zc",  3.0);
    lineC.setParameter("TD", 0.1);
    lineC.listParametersConsole();

    //Connect components
    simulationmodel.connect(qsourceL, "P1", lineC, "P1");
    simulationmodel.connect(lineC, "P2", psourceR, "P1");

    //Run simulation
    simulationmodel.preAllocateLogSpace(0, 1.0);

    simulationmodel.simulate(0.0, 1.0);

    //Test write to file
    lineC.getPort("P1").getNode().saveLogData("output.txt");

	//Finished
    cout << "testTLM Done!" << endl;

}

void testTLMlumped()
{
	/*   Exempelsystem:

	   q         T, Zc
             v  v  v  v  v
	 ------>o=============o p
             ^  ^  ^  ^  ^
            R/8 R/4 ... R/8

	 */
    double R  = 1.0;
    double Zc = 3.0;
    double T  = 0.1;

	ComponentSystem simulationmodel("simulationmodel");
    //Create other components
    ComponentFlowSourceQ qsourceL("qs_left_side",  1.0);
    ComponentTLMRlineR lineL("line_left",     Zc, T/4.0, R/8.0, 0.0);
    ComponentOrifice orificeL("orifice_L", 4.0*R);
    ComponentTLMRlineR lineLC("line_lcenter", Zc, T/4.0, 0.0, 0.0);
    ComponentOrifice orificeC("orifice_C", 4.0*R);
    ComponentTLMRlineR lineRC("line_rcenter", Zc, T/4.0, 0.0, 0.0);
    ComponentOrifice orificeR("orifice_R", 4.0*R);
    ComponentTLMRlineR lineR("line_right",    Zc, T/4.0, 0.0, R/8.0);
    ComponentPressureSourceQ psourceR("ps_right_side", 1.0);

    //Add components
    simulationmodel.addComponent(qsourceL);
    simulationmodel.addComponent(lineL);
    simulationmodel.addComponent(orificeL);
    simulationmodel.addComponent(lineLC);
    simulationmodel.addComponent(orificeC);
    simulationmodel.addComponent(lineRC);
    simulationmodel.addComponent(orificeR);
    simulationmodel.addComponent(lineR);
    simulationmodel.addComponent(psourceR);

    //List and set parameters
    lineLC.listParametersConsole();

    //Connect components
    simulationmodel.connect(qsourceL, "P1", lineL, "P1");
    simulationmodel.connect(lineL, "P2", orificeL, "P1");
    simulationmodel.connect(orificeL, "P2", lineLC, "P1");
    simulationmodel.connect(lineLC, "P2", orificeC, "P1");
    simulationmodel.connect(orificeC, "P2", lineRC, "P1");
    simulationmodel.connect(lineRC, "P2", orificeR, "P1");
    simulationmodel.connect(orificeR, "P2", lineR, "P1");
    simulationmodel.connect(lineR, "P2", psourceR, "P1");

    //Run simulation
    simulationmodel.preAllocateLogSpace(0.0, 2.0);

    simulationmodel.simulate(0.0, 2.0);

    //Test write to file
    lineL.getPort("P1").getNode().saveLogData("output.txt");

	//Finished
    cout << "testTLMlumped() Done!" << endl;

}

void test3()
{
	/*   Exempelsystem:
					  Kc
	   q       T, Zc  v
	 ------>o=========----o p
	                  ^
	 */
	ComponentSystem simulationmodel("simulationmodel");
    //Create other components
    ComponentFlowSourceQ qsourceL(   "qs_left_side",       1.0);
    ComponentTLMlossless lineC(      "line_center",        1.0, 0.1, 0.0);
    ComponentOrifice orificeR(       "orifice_right_side", 3.0);
    ComponentPressureSource psourceR("ps_right_side",      1.0);

    //Add components
    simulationmodel.addComponent(qsourceL);
    simulationmodel.addComponent(lineC);
    simulationmodel.addComponent(orificeR);
    simulationmodel.addComponent(psourceR);

    //Connect components
    simulationmodel.connect(qsourceL, "P1", lineC,    "P1");
    simulationmodel.connect(lineC,    "P2", orificeR, "P1");
    simulationmodel.connect(orificeR, "P2", psourceR, "P1");

    //List and set parameters
    qsourceL.listParametersConsole();
    lineC.listParametersConsole();
    orificeR.listParametersConsole();
    psourceR.listParametersConsole();
    lineC.setParameter("Zc", 1.0);
    lineC.setParameter("TD", 0.005);
    qsourceL.listParametersConsole();
    lineC.listParametersConsole();
    orificeR.listParametersConsole();
    psourceR.listParametersConsole();

    //Run simulation
    simulationmodel.preAllocateLogSpace(0.0, 1.0);

    simulationmodel.simulate(0.0, 1.0);

    //Test write to file
    lineC.getPort("P1").getNode().saveLogData("output.txt");
    lineC.getPort("P2").getNode().saveLogData("output2.txt");

	//Finished
    cout << "test3() Done!" << endl;
}

void test_external_lib()
{
    HopsanEssentials Hopsan;

    //Create master component
    ComponentSystem simulationmodel("simulationmodel");
    //Create other components
    ComponentPressureSource psourceL("ps_left_side", 10e5);
    //ComponentOrifice orificeL("orifice_left_side", 1e-12);

    #ifdef WIN32
    Hopsan.externalLoader.load("./libHydraulic.dll");
    #elif defined MAC
    Hopsan.externalLoader.load("/Users/bjoer37/svn/HOPSAN++/bin/Debug/libHydraulic.dylib");
    #else
    Hopsan.externalLoader.load("./bin/Debug/libHydraulic.so");
    #endif

    cout << "afterload" << endl;

    Component* orificeL = Hopsan.getComponentFactoryPtr()->CreateInstance("ComponentExternalOrifice");
    Component* volumeC = Hopsan.getComponentFactoryPtr()->CreateInstance("ComponentExternalVolume");
    Component* orificeR = Hopsan.getComponentFactoryPtr()->CreateInstance("ComponentExternalOrifice");
    orificeR->setName("right orifice");
    orificeR->setParameter("Kc", 1e-12);

    //ComponentOrifice orificeR("orifice_right_side", 1e-12);
    ComponentPressureSource psourceR("ps_right_side", 0e5);

    //Add components
    simulationmodel.addComponent(psourceL);
    simulationmodel.addComponent(*orificeL);
    simulationmodel.addComponent(*volumeC);
    simulationmodel.addComponent(*orificeR);
    simulationmodel.addComponent(psourceR);
    //Connect components
    simulationmodel.connect(psourceL, "P1", *orificeL, "P1");
    simulationmodel.connect(*orificeL, "P2", *volumeC, "P1");
    simulationmodel.connect(*volumeC, "P2", *orificeR, "P1");
    simulationmodel.connect(*orificeR, "P2", psourceR, "P1");

    //list some stuff
    orificeR->listParametersConsole();

    //Run simulation
    simulationmodel.preAllocateLogSpace(0, 100);
    simulationmodel.simulate(0,100);

    //Test write to file
    volumeC->getPort("P1").getNode().saveLogData("output.txt");

    cout << "test_external_lib() Done!" << endl;

}

void testSignal()
{
	/*   Exempelsystem:
					  Kc
	   q       T, Zc  v
	 ------>o=========----o p
	                  ^
	 */
	ComponentSystem simulationmodel("simulationmodel");
    //Create other components
    ComponentSource sourceL("source_left", 1.0);
    ComponentGain gainC("gain_center", 1.0);
    ComponentSink sinkR("sink_right");

    //Add components
    simulationmodel.addComponent(sourceL);
    simulationmodel.addComponent(gainC);
    simulationmodel.addComponent(sinkR);

    //Connect components
    simulationmodel.connect(sourceL, "out", gainC, "in");
    simulationmodel.connect(gainC, "out", sinkR, "in");

    //List and set parameters
    sourceL.listParametersConsole();
    gainC.listParametersConsole();
    sourceL.setParameter("Value", 2.0);
    gainC.setParameter("Gain", 3.0);
    sourceL.listParametersConsole();
    gainC.listParametersConsole();

    //Run simulation
    simulationmodel.preAllocateLogSpace(0.0, 1.0);

    simulationmodel.simulate(0.0, 1.0);

    //Test write to file
    sinkR.getPort("in").getNode().saveLogData("output.txt");

	//Finished
    cout << "testSignal() Done!" << endl;
}

int main()
{
//    test1();
    test_external_lib();
//    testSignal();
    return 0;
}
<commit_msg>Added HopsanEssential Hopsan; to every test case. Without it, Node factory will not be initialized.<commit_after>#include "HopsanCore.h"
#include "TicToc.h"
#include "CoreUtilities/Delay.h"

void test1()
{
    HopsanEssentials Hopsan;
    TicToc totaltimer("totaltimer");

    //Create master component
    ComponentSystem simulationmodel("simulationmodel");
    //Create other components
    ComponentPressureSource psourceL("ps_left_side", 10e5);
    ComponentOrifice orificeL("orifice_left_side", 1e-12);
    ComponentVolume volumeC("volume_center");
    //ComponentTLMlossless volumeC("volume_center");
    ComponentOrifice orificeR("orifice_right_side", 1e-12);
    ComponentPressureSource psourceR("ps_right_side", 0e5);

    //Add components
    simulationmodel.addComponent(psourceL);
    simulationmodel.addComponent(orificeL);
    simulationmodel.addComponent(volumeC);
    simulationmodel.addComponent(orificeR);
    simulationmodel.addComponent(psourceR);
    //Connect components
    simulationmodel.connect(psourceL, "P1", orificeL, "P1");
    simulationmodel.connect(orificeL, "P2", volumeC, "P1");
    simulationmodel.connect(volumeC, "P2", orificeR, "P1");
    simulationmodel.connect(orificeR, "P2", psourceR, "P1");

    //Run simulation
    TicToc prealloctimer("prealloctimer");
    simulationmodel.preAllocateLogSpace(0, 10);
    prealloctimer.TocPrint();

    TicToc simutimer("simutimer");
    simulationmodel.simulate(0,10);
    simutimer.TocPrint();

    totaltimer.TocPrint();

    //Test write to file
    TicToc filewritetimer("filewritetimer");
    volumeC.getPort("P1").getNode().saveLogData("output.txt");
    filewritetimer.TocPrint();
    cout << "test1() Done!" << endl;
}

void test2() //Test of the Delay utillity class
{
	Delay d1(.15, .1); //delay .15 with sampletime .1
	for (int i=0; i < 11; ++i) {
		cout << "Value: " << i << "    Delayed value: " << d1.value() << endl;
		d1.update(i);
	}
}

void testTLM()
{
    HopsanEssentials Hopsan;
	/*   Exempelsystem:

	   q       T, Zc
	 ------>o=========o p

	 */
	ComponentSystem simulationmodel("simulationmodel");
    //Create other components
    ComponentFlowSourceQ qsourceL(    "qs_left_side",  1.0);
    ComponentTLMlossless lineC(       "line_center",   3.0, 0.2);
    ComponentPressureSourceQ psourceR("ps_right_side", 1.0);

    //Add components
    simulationmodel.addComponent(qsourceL);
    simulationmodel.addComponent(lineC);
    simulationmodel.addComponent(psourceR);

    //List and set parameters
    lineC.listParametersConsole();
    lineC.setParameter("Zc",  3.0);
    lineC.setParameter("TD", 0.1);
    lineC.listParametersConsole();

    //Connect components
    simulationmodel.connect(qsourceL, "P1", lineC, "P1");
    simulationmodel.connect(lineC, "P2", psourceR, "P1");

    //Run simulation
    simulationmodel.preAllocateLogSpace(0, 1.0);

    simulationmodel.simulate(0.0, 1.0);

    //Test write to file
    lineC.getPort("P1").getNode().saveLogData("output.txt");

	//Finished
    cout << "testTLM Done!" << endl;

}

void testTLMlumped()
{
    HopsanEssentials Hopsan;
	/*   Exempelsystem:

	   q         T, Zc
             v  v  v  v  v
	 ------>o=============o p
             ^  ^  ^  ^  ^
            R/8 R/4 ... R/8

	 */
    double R  = 1.0;
    double Zc = 3.0;
    double T  = 0.1;

	ComponentSystem simulationmodel("simulationmodel");
    //Create other components
    ComponentFlowSourceQ qsourceL("qs_left_side",  1.0);
    ComponentTLMRlineR lineL("line_left",     Zc, T/4.0, R/8.0, 0.0);
    ComponentOrifice orificeL("orifice_L", 4.0*R);
    ComponentTLMRlineR lineLC("line_lcenter", Zc, T/4.0, 0.0, 0.0);
    ComponentOrifice orificeC("orifice_C", 4.0*R);
    ComponentTLMRlineR lineRC("line_rcenter", Zc, T/4.0, 0.0, 0.0);
    ComponentOrifice orificeR("orifice_R", 4.0*R);
    ComponentTLMRlineR lineR("line_right",    Zc, T/4.0, 0.0, R/8.0);
    ComponentPressureSourceQ psourceR("ps_right_side", 1.0);

    //Add components
    simulationmodel.addComponent(qsourceL);
    simulationmodel.addComponent(lineL);
    simulationmodel.addComponent(orificeL);
    simulationmodel.addComponent(lineLC);
    simulationmodel.addComponent(orificeC);
    simulationmodel.addComponent(lineRC);
    simulationmodel.addComponent(orificeR);
    simulationmodel.addComponent(lineR);
    simulationmodel.addComponent(psourceR);

    //List and set parameters
    lineLC.listParametersConsole();

    //Connect components
    simulationmodel.connect(qsourceL, "P1", lineL, "P1");
    simulationmodel.connect(lineL, "P2", orificeL, "P1");
    simulationmodel.connect(orificeL, "P2", lineLC, "P1");
    simulationmodel.connect(lineLC, "P2", orificeC, "P1");
    simulationmodel.connect(orificeC, "P2", lineRC, "P1");
    simulationmodel.connect(lineRC, "P2", orificeR, "P1");
    simulationmodel.connect(orificeR, "P2", lineR, "P1");
    simulationmodel.connect(lineR, "P2", psourceR, "P1");

    //Run simulation
    simulationmodel.preAllocateLogSpace(0.0, 2.0);

    simulationmodel.simulate(0.0, 2.0);

    //Test write to file
    lineL.getPort("P1").getNode().saveLogData("output.txt");

	//Finished
    cout << "testTLMlumped() Done!" << endl;

}

void test3()
{
    HopsanEssentials Hopsan;
	/*   Exempelsystem:
					  Kc
	   q       T, Zc  v
	 ------>o=========----o p
	                  ^
	 */
	ComponentSystem simulationmodel("simulationmodel");
    //Create other components
    ComponentFlowSourceQ qsourceL(   "qs_left_side",       1.0);
    ComponentTLMlossless lineC(      "line_center",        1.0, 0.1, 0.0);
    ComponentOrifice orificeR(       "orifice_right_side", 3.0);
    ComponentPressureSource psourceR("ps_right_side",      1.0);

    //Add components
    simulationmodel.addComponent(qsourceL);
    simulationmodel.addComponent(lineC);
    simulationmodel.addComponent(orificeR);
    simulationmodel.addComponent(psourceR);

    //Connect components
    simulationmodel.connect(qsourceL, "P1", lineC,    "P1");
    simulationmodel.connect(lineC,    "P2", orificeR, "P1");
    simulationmodel.connect(orificeR, "P2", psourceR, "P1");

    //List and set parameters
    qsourceL.listParametersConsole();
    lineC.listParametersConsole();
    orificeR.listParametersConsole();
    psourceR.listParametersConsole();
    lineC.setParameter("Zc", 1.0);
    lineC.setParameter("TD", 0.005);
    qsourceL.listParametersConsole();
    lineC.listParametersConsole();
    orificeR.listParametersConsole();
    psourceR.listParametersConsole();

    //Run simulation
    simulationmodel.preAllocateLogSpace(0.0, 1.0);

    simulationmodel.simulate(0.0, 1.0);

    //Test write to file
    lineC.getPort("P1").getNode().saveLogData("output.txt");
    lineC.getPort("P2").getNode().saveLogData("output2.txt");

	//Finished
    cout << "test3() Done!" << endl;
}

void test_external_lib()
{
    HopsanEssentials Hopsan;

    //Create master component
    ComponentSystem simulationmodel("simulationmodel");
    //Create other components
    ComponentPressureSource psourceL("ps_left_side", 10e5);
    //ComponentOrifice orificeL("orifice_left_side", 1e-12);

    #ifdef WIN32
    Hopsan.externalLoader.load("./libHydraulic.dll");
    #elif defined MAC
    Hopsan.externalLoader.load("/Users/bjoer37/svn/HOPSAN++/bin/Debug/libHydraulic.dylib");
    #else
    Hopsan.externalLoader.load("./bin/Debug/libHydraulic.so");
    #endif

    cout << "afterload" << endl;

    Component* orificeL = Hopsan.getComponentFactoryPtr()->CreateInstance("ComponentExternalOrifice");
    Component* volumeC = Hopsan.getComponentFactoryPtr()->CreateInstance("ComponentExternalVolume");
    Component* orificeR = Hopsan.getComponentFactoryPtr()->CreateInstance("ComponentExternalOrifice");
    orificeR->setName("right orifice");
    orificeR->setParameter("Kc", 1e-12);

    //ComponentOrifice orificeR("orifice_right_side", 1e-12);
    ComponentPressureSource psourceR("ps_right_side", 0e5);

    //Add components
    simulationmodel.addComponent(psourceL);
    simulationmodel.addComponent(*orificeL);
    simulationmodel.addComponent(*volumeC);
    simulationmodel.addComponent(*orificeR);
    simulationmodel.addComponent(psourceR);
    //Connect components
    simulationmodel.connect(psourceL, "P1", *orificeL, "P1");
    simulationmodel.connect(*orificeL, "P2", *volumeC, "P1");
    simulationmodel.connect(*volumeC, "P2", *orificeR, "P1");
    simulationmodel.connect(*orificeR, "P2", psourceR, "P1");

    //list some stuff
    orificeR->listParametersConsole();

    //Run simulation
    simulationmodel.preAllocateLogSpace(0, 100);
    simulationmodel.simulate(0,100);

    //Test write to file
    volumeC->getPort("P1").getNode().saveLogData("output.txt");

    cout << "test_external_lib() Done!" << endl;

}

void testSignal()
{
    HopsanEssentials Hopsan;
	/*   Exempelsystem:
					  Kc
	   q       T, Zc  v
	 ------>o=========----o p
	                  ^
	 */
	ComponentSystem simulationmodel("simulationmodel");
    //Create other components
    ComponentSource sourceL("source_left", 1.0);
    ComponentGain gainC("gain_center", 1.0);
    ComponentSink sinkR("sink_right");

    //Add components
    simulationmodel.addComponent(sourceL);
    simulationmodel.addComponent(gainC);
    simulationmodel.addComponent(sinkR);

    //Connect components
    simulationmodel.connect(sourceL, "out", gainC, "in");
    simulationmodel.connect(gainC, "out", sinkR, "in");

    //List and set parameters
    sourceL.listParametersConsole();
    gainC.listParametersConsole();
    sourceL.setParameter("Value", 2.0);
    gainC.setParameter("Gain", 3.0);
    sourceL.listParametersConsole();
    gainC.listParametersConsole();

    //Run simulation
    simulationmodel.preAllocateLogSpace(0.0, 1.0);

    simulationmodel.simulate(0.0, 1.0);

    //Test write to file
    sinkR.getPort("in").getNode().saveLogData("output.txt");

	//Finished
    cout << "testSignal() Done!" << endl;
}

int main()
{
    test1();
    test_external_lib();
    testSignal();
    return 0;
}
<|endoftext|>


<commit_before>#include <v8.h>
#include <node.h>
#include <gtk/gtk.h>
#include <webkit/webkitwebview.h>

using namespace node;
using namespace v8;

void destroy (void)
{
  gtk_main_quit ();
}

static Handle<Value> create_window(const Arguments& args)
{
  HandleScope scope;

  if (args.Length() != 3) {
    return ThrowException(Exception::TypeError(String::New("`url`, `width`, and `height` arguments are required")));
  }
  if (!args[0]->IsString()) {
    return ThrowException(Exception::TypeError(String::New("`url` must be a string")));
  }
  if (!args[1]->IsInt32()) {
    return ThrowException(Exception::TypeError(String::New("`width` must be an int32")));
  }
  if (!args[2]->IsInt32()) {
    return ThrowException(Exception::TypeError(String::New("`height` must be an int32")));
  }

  String::Utf8Value url(args[0]->ToString());
  int width = args[1]->Int32Value();
  int height = args[2]->Int32Value();

  GtkWidget *window;
  GtkWidget *scrolled_window;
  GtkWidget *web_view;

  gtk_init (NULL, NULL);

  window = gtk_window_new (GTK_WINDOW_TOPLEVEL);
  scrolled_window = gtk_scrolled_window_new (NULL, NULL);
  web_view = webkit_web_view_new ();

  gtk_signal_connect (GTK_OBJECT (window), "destroy", GTK_SIGNAL_FUNC (destroy), NULL);

  gtk_container_add (GTK_CONTAINER (scrolled_window), web_view);
  gtk_container_add (GTK_CONTAINER (window), scrolled_window);

  webkit_web_view_load_uri (WEBKIT_WEB_VIEW (web_view), *url);

  gtk_window_set_default_size (GTK_WINDOW (window), width, height);
  gtk_widget_show_all (window);

  // TODO: find a way to not block the node event loop
  gtk_main ();

  return Undefined();

}

extern "C" {
  static void init(Handle<Object> target)
  {
    NODE_SET_METHOD(target, "createWindow", create_window);
  }

  NODE_MODULE(topcube_native, init);
}
<commit_msg>Added title loading support<commit_after>#include <v8.h>
#include <node.h>
#include <gtk/gtk.h>
#include <webkit/webkitwebview.h>

using namespace node;
using namespace v8;

GtkWidget *window;
GtkWidget *scrolled_window;
GtkWidget *web_view;

void destroy (void)
{
  gtk_main_quit ();
}

void title_change (void)
{
	gtk_window_set_title(GTK_WINDOW (window), webkit_web_view_get_title(WEBKIT_WEB_VIEW (web_view)));
}

static Handle<Value> create_window(const Arguments& args)
{
  HandleScope scope;

  if (args.Length() != 3) {
    return ThrowException(Exception::TypeError(String::New("`url`, `width`, and `height` arguments are required")));
  }
  if (!args[0]->IsString()) {
    return ThrowException(Exception::TypeError(String::New("`url` must be a string")));
  }
  if (!args[1]->IsInt32()) {
    return ThrowException(Exception::TypeError(String::New("`width` must be an int32")));
  }
  if (!args[2]->IsInt32()) {
    return ThrowException(Exception::TypeError(String::New("`height` must be an int32")));
  }

  String::Utf8Value url(args[0]->ToString());
  int width = args[1]->Int32Value();
  int height = args[2]->Int32Value();

  gtk_init (NULL, NULL);

  window = gtk_window_new (GTK_WINDOW_TOPLEVEL);
  scrolled_window = gtk_scrolled_window_new (NULL, NULL);
  web_view = webkit_web_view_new ();

  gtk_signal_connect (GTK_OBJECT (window), "destroy", GTK_SIGNAL_FUNC (destroy), NULL);
  gtk_signal_connect (GTK_OBJECT (web_view), "title-changed", GTK_SIGNAL_FUNC (title_change), NULL);

  gtk_container_add (GTK_CONTAINER (scrolled_window), web_view);
  gtk_container_add (GTK_CONTAINER (window), scrolled_window);

  webkit_web_view_load_uri (WEBKIT_WEB_VIEW (web_view), *url);

  gtk_window_set_default_size (GTK_WINDOW (window), width, height);
  gtk_widget_show_all (window);

  // TODO: find a way to not block the node event loop
  gtk_main ();

  return Undefined();

}

extern "C" {
  static void init(Handle<Object> target)
  {
    NODE_SET_METHOD(target, "createWindow", create_window);
  }

  NODE_MODULE(topcube_native, init);
}
<|endoftext|>