<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 <sstream>
#include <string>

#include "base/command_line.h"
#include "base/file_path.h"
#include "base/path_service.h"
#include "base/string_util.h"
#include "chrome/browser/net/url_request_failed_dns_job.h"
#include "chrome/browser/net/url_request_mock_http_job.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/common/url_constants.h"
#include "chrome/test/automation/browser_proxy.h"
#include "chrome/test/automation/tab_proxy.h"
#include "chrome/test/ui/ui_test.h"
#include "net/base/net_util.h"
#include "net/test/test_server.h"

namespace {

class ResourceDispatcherTest : public UITest {
 public:
  void CheckTitleTest(const std::wstring& file,
                      const std::wstring& expected_title,
                      int expected_navigations) {
    NavigateToURLBlockUntilNavigationsComplete(
        URLRequestMockHTTPJob::GetMockUrl(FilePath::FromWStringHack(file)),
        expected_navigations);
    EXPECT_EQ(expected_title, GetActiveTabTitle());
  }

 protected:
  ResourceDispatcherTest() : UITest() {
    dom_automation_enabled_ = true;
  }
};

TEST_F(ResourceDispatcherTest, SniffHTMLWithNoContentType) {
  CheckTitleTest(L"content-sniffer-test0.html",
                 L"Content Sniffer Test 0", 1);
}

TEST_F(ResourceDispatcherTest, RespectNoSniffDirective) {
  CheckTitleTest(L"nosniff-test.html", L"", 1);
}

TEST_F(ResourceDispatcherTest, DoNotSniffHTMLFromTextPlain) {
  CheckTitleTest(L"content-sniffer-test1.html", L"", 1);
}

TEST_F(ResourceDispatcherTest, DoNotSniffHTMLFromImageGIF) {
  CheckTitleTest(L"content-sniffer-test2.html", L"", 1);
}

TEST_F(ResourceDispatcherTest, SniffNoContentTypeNoData) {
  CheckTitleTest(L"content-sniffer-test3.html",
                 L"Content Sniffer Test 3", 1);
  EXPECT_EQ(1, GetTabCount());

  // Make sure the download shelf is not showing.
  scoped_refptr<BrowserProxy> browser(automation()->GetBrowserWindow(0));
  ASSERT_TRUE(browser.get());
  bool visible = false;
  ASSERT_TRUE(browser->IsShelfVisible(&visible));
  EXPECT_FALSE(visible);
}

TEST_F(ResourceDispatcherTest, ContentDispositionEmpty) {
  CheckTitleTest(L"content-disposition-empty.html", L"success", 1);
}

TEST_F(ResourceDispatcherTest, ContentDispositionInline) {
  CheckTitleTest(L"content-disposition-inline.html", L"success", 1);
}

// Test for bug #1091358.
// Flaky: http://crbug.com/62595
TEST_F(ResourceDispatcherTest, FLAKY_SyncXMLHttpRequest) {
  net::TestServer test_server(net::TestServer::TYPE_HTTP,
                              FilePath(FILE_PATH_LITERAL("chrome/test/data")));
  ASSERT_TRUE(test_server.Start());

  scoped_refptr<BrowserProxy> browser_proxy(automation()->GetBrowserWindow(0));
  ASSERT_TRUE(browser_proxy.get());
  scoped_refptr<TabProxy> tab(browser_proxy->GetActiveTab());
  ASSERT_TRUE(tab.get());
  ASSERT_EQ(AUTOMATION_MSG_NAVIGATION_SUCCESS,
            tab->NavigateToURL(test_server.GetURL(
                "files/sync_xmlhttprequest.html")));

  // Let's check the XMLHttpRequest ran successfully.
  bool success = false;
  EXPECT_TRUE(tab->ExecuteAndExtractBool(L"",
      L"window.domAutomationController.send(DidSyncRequestSucceed());",
      &success));
  EXPECT_TRUE(success);
}

TEST_F(ResourceDispatcherTest, SyncXMLHttpRequest_Disallowed) {
  net::TestServer test_server(net::TestServer::TYPE_HTTP,
                              FilePath(FILE_PATH_LITERAL("chrome/test/data")));
  ASSERT_TRUE(test_server.Start());

  scoped_refptr<BrowserProxy> browser_proxy(automation()->GetBrowserWindow(0));
  ASSERT_TRUE(browser_proxy.get());
  scoped_refptr<TabProxy> tab(browser_proxy->GetActiveTab());
  ASSERT_TRUE(tab.get());
  ASSERT_EQ(AUTOMATION_MSG_NAVIGATION_SUCCESS,
            tab->NavigateToURL(test_server.GetURL(
                "files/sync_xmlhttprequest_disallowed.html")));

  // Let's check the XMLHttpRequest ran successfully.
  bool success = false;
  EXPECT_TRUE(tab->ExecuteAndExtractBool(L"",
      L"window.domAutomationController.send(DidSucceed());",
      &success));
  EXPECT_TRUE(success);
}

// Test for bug #1159553 -- A synchronous xhr (whose content-type is
// downloadable) would trigger download and hang the renderer process,
// if executed while navigating to a new page.
// Disabled -- http://code.google.com/p/chromium/issues/detail?id=56264
TEST_F(ResourceDispatcherTest, DISABLED_SyncXMLHttpRequest_DuringUnload) {
  net::TestServer test_server(net::TestServer::TYPE_HTTP,
                              FilePath(FILE_PATH_LITERAL("chrome/test/data")));
  ASSERT_TRUE(test_server.Start());

  scoped_refptr<BrowserProxy> browser_proxy(automation()->GetBrowserWindow(0));
  ASSERT_TRUE(browser_proxy.get());
  scoped_refptr<TabProxy> tab(browser_proxy->GetActiveTab());
  ASSERT_TRUE(tab.get());

  ASSERT_EQ(AUTOMATION_MSG_NAVIGATION_SUCCESS,
            tab->NavigateToURL(test_server.GetURL(
                "files/sync_xmlhttprequest_during_unload.html")));

  // Confirm that the page has loaded (since it changes its title during load).
  std::wstring tab_title;
  EXPECT_TRUE(tab->GetTabTitle(&tab_title));
  EXPECT_EQ(L"sync xhr on unload", tab_title);

  // Navigate to a new page, to dispatch unload event and trigger xhr.
  // (the bug would make this step hang the renderer).
  ASSERT_EQ(AUTOMATION_MSG_NAVIGATION_SUCCESS,
            tab->NavigateToURL(test_server.GetURL("files/title2.html")));

  // Check that the new page got loaded, and that no download was triggered.
  EXPECT_TRUE(tab->GetTabTitle(&tab_title));
  EXPECT_EQ(L"Title Of Awesomeness", tab_title);

  bool shelf_is_visible = false;
  scoped_refptr<BrowserProxy> browser(automation()->GetBrowserWindow(0));
  ASSERT_TRUE(browser.get());
  EXPECT_TRUE(browser->IsShelfVisible(&shelf_is_visible));
  EXPECT_FALSE(shelf_is_visible);
}

// Tests that onunload is run for cross-site requests.  (Bug 1114994)
TEST_F(ResourceDispatcherTest, CrossSiteOnunloadCookie) {
  net::TestServer test_server(net::TestServer::TYPE_HTTP,
                              FilePath(FILE_PATH_LITERAL("chrome/test/data")));
  ASSERT_TRUE(test_server.Start());

  scoped_refptr<BrowserProxy> browser_proxy(automation()->GetBrowserWindow(0));
  ASSERT_TRUE(browser_proxy.get());
  scoped_refptr<TabProxy> tab(browser_proxy->GetActiveTab());
  ASSERT_TRUE(tab.get());

  GURL url(test_server.GetURL("files/onunload_cookie.html"));
  ASSERT_EQ(AUTOMATION_MSG_NAVIGATION_SUCCESS, tab->NavigateToURL(url));

  // Confirm that the page has loaded (since it changes its title during load).
  std::wstring tab_title;
  EXPECT_TRUE(tab->GetTabTitle(&tab_title));
  EXPECT_EQ(L"set cookie on unload", tab_title);

  // Navigate to a new cross-site page, to dispatch unload event and set the
  // cookie.
  CheckTitleTest(L"content-sniffer-test0.html",
                 L"Content Sniffer Test 0", 1);

  // Check that the cookie was set.
  std::string value_result;
  ASSERT_TRUE(tab->GetCookieByName(url, "onunloadCookie", &value_result));
  ASSERT_FALSE(value_result.empty());
  ASSERT_STREQ("foo", value_result.c_str());
}

#if !defined(OS_MACOSX)
// Tests that the onbeforeunload and onunload logic is shortcutted if the old
// renderer is gone.  In that case, we don't want to wait for the old renderer
// to run the handlers.
// We need to disable this on Mac because the crash causes the OS CrashReporter
// process to kick in to analyze the poor dead renderer.  Unfortunately, if the
// app isn't stripped of debug symbols, this takes about five minutes to
// complete and isn't conducive to quick turnarounds. As we don't currently
// strip the app on the build bots, this is bad times.
TEST_F(ResourceDispatcherTest, CrossSiteAfterCrash) {
  // This test only works in multi-process mode
  if (in_process_renderer())
    return;

  scoped_refptr<BrowserProxy> browser_proxy(automation()->GetBrowserWindow(0));
  ASSERT_TRUE(browser_proxy.get());
  scoped_refptr<TabProxy> tab(browser_proxy->GetActiveTab());
  ASSERT_TRUE(tab.get());

  // Cause the renderer to crash.
#if defined(OS_WIN) || defined(USE_LINUX_BREAKPAD)
  expected_crashes_ = 1;
#endif
  ASSERT_TRUE(tab->NavigateToURLAsync(GURL(chrome::kAboutCrashURL)));
  // Wait for browser to notice the renderer crash.
  PlatformThread::Sleep(sleep_timeout_ms());

  // Navigate to a new cross-site page.  The browser should not wait around for
  // the old renderer's on{before}unload handlers to run.
  CheckTitleTest(L"content-sniffer-test0.html",
                 L"Content Sniffer Test 0", 1);
}
#endif  // !defined(OS_MACOSX)

// Tests that cross-site navigations work when the new page does not go through
// the BufferedEventHandler (e.g., non-http{s} URLs).  (Bug 1225872)
TEST_F(ResourceDispatcherTest, CrossSiteNavigationNonBuffered) {
  scoped_refptr<BrowserProxy> browser_proxy(automation()->GetBrowserWindow(0));
  ASSERT_TRUE(browser_proxy.get());
  scoped_refptr<TabProxy> tab(browser_proxy->GetActiveTab());
  ASSERT_TRUE(tab.get());

  // Start with an HTTP page.
  CheckTitleTest(L"content-sniffer-test0.html",
                 L"Content Sniffer Test 0", 1);

  // Now load a file:// page, which does not use the BufferedEventHandler.
  // Make sure that the page loads and displays a title, and doesn't get stuck.
  FilePath test_file(test_data_directory_);
  test_file = test_file.AppendASCII("title2.html");
  ASSERT_EQ(AUTOMATION_MSG_NAVIGATION_SUCCESS,
            tab->NavigateToURL(net::FilePathToFileURL(test_file)));
  EXPECT_EQ(L"Title Of Awesomeness", GetActiveTabTitle());
}

// Tests that a cross-site navigation to an error page (resulting in the link
// doctor page) still runs the onunload handler and can support navigations
// away from the link doctor page.  (Bug 1235537)
TEST_F(ResourceDispatcherTest, CrossSiteNavigationErrorPage) {
  net::TestServer test_server(net::TestServer::TYPE_HTTP,
                              FilePath(FILE_PATH_LITERAL("chrome/test/data")));
  ASSERT_TRUE(test_server.Start());

  scoped_refptr<BrowserProxy> browser_proxy(automation()->GetBrowserWindow(0));
  ASSERT_TRUE(browser_proxy.get());
  scoped_refptr<TabProxy> tab(browser_proxy->GetActiveTab());
  ASSERT_TRUE(tab.get());

  GURL url(test_server.GetURL("files/onunload_cookie.html"));
  ASSERT_EQ(AUTOMATION_MSG_NAVIGATION_SUCCESS, tab->NavigateToURL(url));

  // Confirm that the page has loaded (since it changes its title during load).
  std::wstring tab_title;
  EXPECT_TRUE(tab->GetTabTitle(&tab_title));
  EXPECT_EQ(L"set cookie on unload", tab_title);

  // Navigate to a new cross-site URL that results in an error page.
  // TODO(creis): If this causes crashes or hangs, it might be for the same
  // reason as ErrorPageTest::DNSError.  See bug 1199491 and
  // http://crbug.com/22877.
  ASSERT_EQ(AUTOMATION_MSG_NAVIGATION_SUCCESS,
            tab->NavigateToURLBlockUntilNavigationsComplete(
                GURL(URLRequestFailedDnsJob::kTestUrl), 2));
  EXPECT_NE(L"set cookie on unload", GetActiveTabTitle());

  // Check that the cookie was set, meaning that the onunload handler ran.
  std::string value_result;
  EXPECT_TRUE(tab->GetCookieByName(url, "onunloadCookie", &value_result));
  EXPECT_FALSE(value_result.empty());
  EXPECT_STREQ("foo", value_result.c_str());

  // Check that renderer-initiated navigations still work.  In a previous bug,
  // the ResourceDispatcherHost would think that such navigations were
  // cross-site, because we didn't clean up from the previous request.  Since
  // TabContents was in the NORMAL state, it would ignore the attempt to run
  // the onunload handler, and the navigation would fail.
  // (Test by redirecting to javascript:window.location='someURL'.)
  GURL test_url(test_server.GetURL("files/title2.html"));
  std::string redirect_url = "javascript:window.location='" +
      test_url.possibly_invalid_spec() + "'";
  ASSERT_EQ(AUTOMATION_MSG_NAVIGATION_SUCCESS,
            tab->NavigateToURL(GURL(redirect_url)));
  EXPECT_TRUE(tab->GetTabTitle(&tab_title));
  EXPECT_EQ(L"Title Of Awesomeness", tab_title);
}

TEST_F(ResourceDispatcherTest, CrossOriginRedirectBlocked) {
  // We expect the following URL requests from this test:
  // 1-  http://mock.http/cross-origin-redirect-blocked.html
  // 2-  http://mock.http/redirect-to-title2.html
  // 3-  http://mock.http/title2.html
  //
  // If the redirect in #2 were not blocked, we'd also see a request
  // for http://mock.http:4000/title2.html, and the title would be different.
  CheckTitleTest(L"cross-origin-redirect-blocked.html",
                 L"Title Of More Awesomeness", 2);
}

// Tests that ResourceDispatcherHostRequestInfo is updated correctly on failed
// requests, to prevent calling Read on a request that has already failed.
// See bug 40250.
TEST_F(ResourceDispatcherTest, CrossSiteFailedRequest) {
  scoped_refptr<BrowserProxy> browser_proxy(automation()->GetBrowserWindow(0));
  ASSERT_TRUE(browser_proxy.get());
  scoped_refptr<TabProxy> tab(browser_proxy->GetActiveTab());
  ASSERT_TRUE(tab.get());

  // Visit another URL first to trigger a cross-site navigation.
  GURL url(chrome::kChromeUINewTabURL);
  ASSERT_EQ(AUTOMATION_MSG_NAVIGATION_SUCCESS, tab->NavigateToURL(url));

  // Visit a URL that fails without calling ResourceDispatcherHost::Read.
  GURL broken_url("chrome://theme");
  ASSERT_EQ(AUTOMATION_MSG_NAVIGATION_SUCCESS, tab->NavigateToURL(broken_url));

  // Make sure the navigation finishes.
  std::wstring tab_title;
  EXPECT_TRUE(tab->GetTabTitle(&tab_title));
  EXPECT_EQ(L"chrome://theme/ is not available", tab_title);
}

}  // namespace
<commit_msg>Marking the ResourceDispatcherTest.SyncXMLHttpRequest_Disallowed as flaky<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 <sstream>
#include <string>

#include "base/command_line.h"
#include "base/file_path.h"
#include "base/path_service.h"
#include "base/string_util.h"
#include "chrome/browser/net/url_request_failed_dns_job.h"
#include "chrome/browser/net/url_request_mock_http_job.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/common/url_constants.h"
#include "chrome/test/automation/browser_proxy.h"
#include "chrome/test/automation/tab_proxy.h"
#include "chrome/test/ui/ui_test.h"
#include "net/base/net_util.h"
#include "net/test/test_server.h"

namespace {

class ResourceDispatcherTest : public UITest {
 public:
  void CheckTitleTest(const std::wstring& file,
                      const std::wstring& expected_title,
                      int expected_navigations) {
    NavigateToURLBlockUntilNavigationsComplete(
        URLRequestMockHTTPJob::GetMockUrl(FilePath::FromWStringHack(file)),
        expected_navigations);
    EXPECT_EQ(expected_title, GetActiveTabTitle());
  }

 protected:
  ResourceDispatcherTest() : UITest() {
    dom_automation_enabled_ = true;
  }
};

TEST_F(ResourceDispatcherTest, SniffHTMLWithNoContentType) {
  CheckTitleTest(L"content-sniffer-test0.html",
                 L"Content Sniffer Test 0", 1);
}

TEST_F(ResourceDispatcherTest, RespectNoSniffDirective) {
  CheckTitleTest(L"nosniff-test.html", L"", 1);
}

TEST_F(ResourceDispatcherTest, DoNotSniffHTMLFromTextPlain) {
  CheckTitleTest(L"content-sniffer-test1.html", L"", 1);
}

TEST_F(ResourceDispatcherTest, DoNotSniffHTMLFromImageGIF) {
  CheckTitleTest(L"content-sniffer-test2.html", L"", 1);
}

TEST_F(ResourceDispatcherTest, SniffNoContentTypeNoData) {
  CheckTitleTest(L"content-sniffer-test3.html",
                 L"Content Sniffer Test 3", 1);
  EXPECT_EQ(1, GetTabCount());

  // Make sure the download shelf is not showing.
  scoped_refptr<BrowserProxy> browser(automation()->GetBrowserWindow(0));
  ASSERT_TRUE(browser.get());
  bool visible = false;
  ASSERT_TRUE(browser->IsShelfVisible(&visible));
  EXPECT_FALSE(visible);
}

TEST_F(ResourceDispatcherTest, ContentDispositionEmpty) {
  CheckTitleTest(L"content-disposition-empty.html", L"success", 1);
}

TEST_F(ResourceDispatcherTest, ContentDispositionInline) {
  CheckTitleTest(L"content-disposition-inline.html", L"success", 1);
}

// Test for bug #1091358.
// Flaky: http://crbug.com/62595
TEST_F(ResourceDispatcherTest, FLAKY_SyncXMLHttpRequest) {
  net::TestServer test_server(net::TestServer::TYPE_HTTP,
                              FilePath(FILE_PATH_LITERAL("chrome/test/data")));
  ASSERT_TRUE(test_server.Start());

  scoped_refptr<BrowserProxy> browser_proxy(automation()->GetBrowserWindow(0));
  ASSERT_TRUE(browser_proxy.get());
  scoped_refptr<TabProxy> tab(browser_proxy->GetActiveTab());
  ASSERT_TRUE(tab.get());
  ASSERT_EQ(AUTOMATION_MSG_NAVIGATION_SUCCESS,
            tab->NavigateToURL(test_server.GetURL(
                "files/sync_xmlhttprequest.html")));

  // Let's check the XMLHttpRequest ran successfully.
  bool success = false;
  EXPECT_TRUE(tab->ExecuteAndExtractBool(L"",
      L"window.domAutomationController.send(DidSyncRequestSucceed());",
      &success));
  EXPECT_TRUE(success);
}

// http://code.google.com/p/chromium/issues/detail?id=62776
TEST_F(ResourceDispatcherTest, FLAKY_SyncXMLHttpRequest_Disallowed) {
  net::TestServer test_server(net::TestServer::TYPE_HTTP,
                              FilePath(FILE_PATH_LITERAL("chrome/test/data")));
  ASSERT_TRUE(test_server.Start());

  scoped_refptr<BrowserProxy> browser_proxy(automation()->GetBrowserWindow(0));
  ASSERT_TRUE(browser_proxy.get());
  scoped_refptr<TabProxy> tab(browser_proxy->GetActiveTab());
  ASSERT_TRUE(tab.get());
  ASSERT_EQ(AUTOMATION_MSG_NAVIGATION_SUCCESS,
            tab->NavigateToURL(test_server.GetURL(
                "files/sync_xmlhttprequest_disallowed.html")));

  // Let's check the XMLHttpRequest ran successfully.
  bool success = false;
  EXPECT_TRUE(tab->ExecuteAndExtractBool(L"",
      L"window.domAutomationController.send(DidSucceed());",
      &success));
  EXPECT_TRUE(success);
}

// Test for bug #1159553 -- A synchronous xhr (whose content-type is
// downloadable) would trigger download and hang the renderer process,
// if executed while navigating to a new page.
// Disabled -- http://code.google.com/p/chromium/issues/detail?id=56264
TEST_F(ResourceDispatcherTest, DISABLED_SyncXMLHttpRequest_DuringUnload) {
  net::TestServer test_server(net::TestServer::TYPE_HTTP,
                              FilePath(FILE_PATH_LITERAL("chrome/test/data")));
  ASSERT_TRUE(test_server.Start());

  scoped_refptr<BrowserProxy> browser_proxy(automation()->GetBrowserWindow(0));
  ASSERT_TRUE(browser_proxy.get());
  scoped_refptr<TabProxy> tab(browser_proxy->GetActiveTab());
  ASSERT_TRUE(tab.get());

  ASSERT_EQ(AUTOMATION_MSG_NAVIGATION_SUCCESS,
            tab->NavigateToURL(test_server.GetURL(
                "files/sync_xmlhttprequest_during_unload.html")));

  // Confirm that the page has loaded (since it changes its title during load).
  std::wstring tab_title;
  EXPECT_TRUE(tab->GetTabTitle(&tab_title));
  EXPECT_EQ(L"sync xhr on unload", tab_title);

  // Navigate to a new page, to dispatch unload event and trigger xhr.
  // (the bug would make this step hang the renderer).
  ASSERT_EQ(AUTOMATION_MSG_NAVIGATION_SUCCESS,
            tab->NavigateToURL(test_server.GetURL("files/title2.html")));

  // Check that the new page got loaded, and that no download was triggered.
  EXPECT_TRUE(tab->GetTabTitle(&tab_title));
  EXPECT_EQ(L"Title Of Awesomeness", tab_title);

  bool shelf_is_visible = false;
  scoped_refptr<BrowserProxy> browser(automation()->GetBrowserWindow(0));
  ASSERT_TRUE(browser.get());
  EXPECT_TRUE(browser->IsShelfVisible(&shelf_is_visible));
  EXPECT_FALSE(shelf_is_visible);
}

// Tests that onunload is run for cross-site requests.  (Bug 1114994)
TEST_F(ResourceDispatcherTest, CrossSiteOnunloadCookie) {
  net::TestServer test_server(net::TestServer::TYPE_HTTP,
                              FilePath(FILE_PATH_LITERAL("chrome/test/data")));
  ASSERT_TRUE(test_server.Start());

  scoped_refptr<BrowserProxy> browser_proxy(automation()->GetBrowserWindow(0));
  ASSERT_TRUE(browser_proxy.get());
  scoped_refptr<TabProxy> tab(browser_proxy->GetActiveTab());
  ASSERT_TRUE(tab.get());

  GURL url(test_server.GetURL("files/onunload_cookie.html"));
  ASSERT_EQ(AUTOMATION_MSG_NAVIGATION_SUCCESS, tab->NavigateToURL(url));

  // Confirm that the page has loaded (since it changes its title during load).
  std::wstring tab_title;
  EXPECT_TRUE(tab->GetTabTitle(&tab_title));
  EXPECT_EQ(L"set cookie on unload", tab_title);

  // Navigate to a new cross-site page, to dispatch unload event and set the
  // cookie.
  CheckTitleTest(L"content-sniffer-test0.html",
                 L"Content Sniffer Test 0", 1);

  // Check that the cookie was set.
  std::string value_result;
  ASSERT_TRUE(tab->GetCookieByName(url, "onunloadCookie", &value_result));
  ASSERT_FALSE(value_result.empty());
  ASSERT_STREQ("foo", value_result.c_str());
}

#if !defined(OS_MACOSX)
// Tests that the onbeforeunload and onunload logic is shortcutted if the old
// renderer is gone.  In that case, we don't want to wait for the old renderer
// to run the handlers.
// We need to disable this on Mac because the crash causes the OS CrashReporter
// process to kick in to analyze the poor dead renderer.  Unfortunately, if the
// app isn't stripped of debug symbols, this takes about five minutes to
// complete and isn't conducive to quick turnarounds. As we don't currently
// strip the app on the build bots, this is bad times.
TEST_F(ResourceDispatcherTest, CrossSiteAfterCrash) {
  // This test only works in multi-process mode
  if (in_process_renderer())
    return;

  scoped_refptr<BrowserProxy> browser_proxy(automation()->GetBrowserWindow(0));
  ASSERT_TRUE(browser_proxy.get());
  scoped_refptr<TabProxy> tab(browser_proxy->GetActiveTab());
  ASSERT_TRUE(tab.get());

  // Cause the renderer to crash.
#if defined(OS_WIN) || defined(USE_LINUX_BREAKPAD)
  expected_crashes_ = 1;
#endif
  ASSERT_TRUE(tab->NavigateToURLAsync(GURL(chrome::kAboutCrashURL)));
  // Wait for browser to notice the renderer crash.
  PlatformThread::Sleep(sleep_timeout_ms());

  // Navigate to a new cross-site page.  The browser should not wait around for
  // the old renderer's on{before}unload handlers to run.
  CheckTitleTest(L"content-sniffer-test0.html",
                 L"Content Sniffer Test 0", 1);
}
#endif  // !defined(OS_MACOSX)

// Tests that cross-site navigations work when the new page does not go through
// the BufferedEventHandler (e.g., non-http{s} URLs).  (Bug 1225872)
TEST_F(ResourceDispatcherTest, CrossSiteNavigationNonBuffered) {
  scoped_refptr<BrowserProxy> browser_proxy(automation()->GetBrowserWindow(0));
  ASSERT_TRUE(browser_proxy.get());
  scoped_refptr<TabProxy> tab(browser_proxy->GetActiveTab());
  ASSERT_TRUE(tab.get());

  // Start with an HTTP page.
  CheckTitleTest(L"content-sniffer-test0.html",
                 L"Content Sniffer Test 0", 1);

  // Now load a file:// page, which does not use the BufferedEventHandler.
  // Make sure that the page loads and displays a title, and doesn't get stuck.
  FilePath test_file(test_data_directory_);
  test_file = test_file.AppendASCII("title2.html");
  ASSERT_EQ(AUTOMATION_MSG_NAVIGATION_SUCCESS,
            tab->NavigateToURL(net::FilePathToFileURL(test_file)));
  EXPECT_EQ(L"Title Of Awesomeness", GetActiveTabTitle());
}

// Tests that a cross-site navigation to an error page (resulting in the link
// doctor page) still runs the onunload handler and can support navigations
// away from the link doctor page.  (Bug 1235537)
TEST_F(ResourceDispatcherTest, CrossSiteNavigationErrorPage) {
  net::TestServer test_server(net::TestServer::TYPE_HTTP,
                              FilePath(FILE_PATH_LITERAL("chrome/test/data")));
  ASSERT_TRUE(test_server.Start());

  scoped_refptr<BrowserProxy> browser_proxy(automation()->GetBrowserWindow(0));
  ASSERT_TRUE(browser_proxy.get());
  scoped_refptr<TabProxy> tab(browser_proxy->GetActiveTab());
  ASSERT_TRUE(tab.get());

  GURL url(test_server.GetURL("files/onunload_cookie.html"));
  ASSERT_EQ(AUTOMATION_MSG_NAVIGATION_SUCCESS, tab->NavigateToURL(url));

  // Confirm that the page has loaded (since it changes its title during load).
  std::wstring tab_title;
  EXPECT_TRUE(tab->GetTabTitle(&tab_title));
  EXPECT_EQ(L"set cookie on unload", tab_title);

  // Navigate to a new cross-site URL that results in an error page.
  // TODO(creis): If this causes crashes or hangs, it might be for the same
  // reason as ErrorPageTest::DNSError.  See bug 1199491 and
  // http://crbug.com/22877.
  ASSERT_EQ(AUTOMATION_MSG_NAVIGATION_SUCCESS,
            tab->NavigateToURLBlockUntilNavigationsComplete(
                GURL(URLRequestFailedDnsJob::kTestUrl), 2));
  EXPECT_NE(L"set cookie on unload", GetActiveTabTitle());

  // Check that the cookie was set, meaning that the onunload handler ran.
  std::string value_result;
  EXPECT_TRUE(tab->GetCookieByName(url, "onunloadCookie", &value_result));
  EXPECT_FALSE(value_result.empty());
  EXPECT_STREQ("foo", value_result.c_str());

  // Check that renderer-initiated navigations still work.  In a previous bug,
  // the ResourceDispatcherHost would think that such navigations were
  // cross-site, because we didn't clean up from the previous request.  Since
  // TabContents was in the NORMAL state, it would ignore the attempt to run
  // the onunload handler, and the navigation would fail.
  // (Test by redirecting to javascript:window.location='someURL'.)
  GURL test_url(test_server.GetURL("files/title2.html"));
  std::string redirect_url = "javascript:window.location='" +
      test_url.possibly_invalid_spec() + "'";
  ASSERT_EQ(AUTOMATION_MSG_NAVIGATION_SUCCESS,
            tab->NavigateToURL(GURL(redirect_url)));
  EXPECT_TRUE(tab->GetTabTitle(&tab_title));
  EXPECT_EQ(L"Title Of Awesomeness", tab_title);
}

TEST_F(ResourceDispatcherTest, CrossOriginRedirectBlocked) {
  // We expect the following URL requests from this test:
  // 1-  http://mock.http/cross-origin-redirect-blocked.html
  // 2-  http://mock.http/redirect-to-title2.html
  // 3-  http://mock.http/title2.html
  //
  // If the redirect in #2 were not blocked, we'd also see a request
  // for http://mock.http:4000/title2.html, and the title would be different.
  CheckTitleTest(L"cross-origin-redirect-blocked.html",
                 L"Title Of More Awesomeness", 2);
}

// Tests that ResourceDispatcherHostRequestInfo is updated correctly on failed
// requests, to prevent calling Read on a request that has already failed.
// See bug 40250.
TEST_F(ResourceDispatcherTest, CrossSiteFailedRequest) {
  scoped_refptr<BrowserProxy> browser_proxy(automation()->GetBrowserWindow(0));
  ASSERT_TRUE(browser_proxy.get());
  scoped_refptr<TabProxy> tab(browser_proxy->GetActiveTab());
  ASSERT_TRUE(tab.get());

  // Visit another URL first to trigger a cross-site navigation.
  GURL url(chrome::kChromeUINewTabURL);
  ASSERT_EQ(AUTOMATION_MSG_NAVIGATION_SUCCESS, tab->NavigateToURL(url));

  // Visit a URL that fails without calling ResourceDispatcherHost::Read.
  GURL broken_url("chrome://theme");
  ASSERT_EQ(AUTOMATION_MSG_NAVIGATION_SUCCESS, tab->NavigateToURL(broken_url));

  // Make sure the navigation finishes.
  std::wstring tab_title;
  EXPECT_TRUE(tab->GetTabTitle(&tab_title));
  EXPECT_EQ(L"chrome://theme/ is not available", tab_title);
}

}  // namespace
<|endoftext|>


<commit_before>#include "ex14_16_String.h"
#include <algorithm>
#include <cstring>

std::allocator<char> String::alloc;

std::pair<char*, char*> String::alloc_n_copy(const char *a, const char *b) {
	auto newdata = alloc.allocate(b - a + 1);
	alloc.construct(newdata + (b - a), '\0');
	return{ newdata, std::uninitialized_copy(a, b, newdata) };
}

void String::free() {
	if (elements) {
		std::for_each(elements, end, [](char& c) { alloc.destroy(&c); });
		alloc.deallocate(elements, end - elements);
	}
}

String::String(const char *c) {
	const char *ce = c;
	while (*ce)
		++ce;
	auto newdata = alloc_n_copy(c, ce);
	elements = newdata.first;
	end = newdata.second;
}

String::String(const String& s) {
	auto newdata = alloc_n_copy(s.elements, s.end);
	elements = newdata.first;
	end = newdata.second;
}

String& String::operator=(const String &s) {
	auto newdata = alloc_n_copy(s.elements, s.end);
	free();
	elements = newdata.first;
	end = newdata.second;
	return *this;
}

String::~String() {
	free();
}

bool operator==(const String& lhs, const String& rhs) {
	return !strcmp(lhs.elements, rhs.elements);
}

bool operator!=(const String& lhs, const String& rhs) {
	return !(lhs == rhs);
}
<commit_msg>Delete ex14_16_String.cpp<commit_after><|endoftext|>


<commit_before>/* vim: set ai et ts=4 sw=4: */

#include "rapidjson/document.h"
#include "rapidjson/stringbuffer.h"
#include "defer.h"
#include <PersistentStorage.h>
#include <rapidjson/writer.h>
#include <stdexcept>
#include <string>

using namespace rapidjson;
using namespace rocksdb;

PersistentStorage::PersistentStorage() {
    _db = nullptr;

    Options options;

    options.IncreaseParallelism();
    options.OptimizeLevelStyleCompaction();
    options.create_if_missing = true;

    Status s = rocksdb::DB::Open(options, "hurma_data", &_db);
    if(!s.ok())
        throw std::runtime_error("PersistentStorage::PersistentStorage() - DB::Open failed");
}

PersistentStorage::~PersistentStorage() {
    if(_db != nullptr)
        delete _db;
}

void PersistentStorage::set(const std::string& key, const std::string& value) {
    Document val;

    if(val.Parse(value.c_str()).HasParseError())
        throw std::runtime_error("PersistentStore::set() - validation failed");

    Status s = _db->Put(WriteOptions(), key, value);
    if(!s.ok())
        throw std::runtime_error("PersistentStore::set() - _db->Put failed");
}

std::string PersistentStorage::get(const std::string& key, bool* found) {
    std::string value = "";
    Status s = _db->Get(ReadOptions(), key, &value);
    *found = s.ok();
    return value;
}

// TODO: impelemt more efficient interation for wide ranges
std::string PersistentStorage::getRange(const std::string& key_from, const std::string& key_to) {
    rocksdb::Iterator* it = _db->NewIterator(rocksdb::ReadOptions());
    defer(delete it);

    Document result;
    result.SetObject();

    for(it->Seek(key_from); it->Valid() && it->key().ToString() <= key_to; it->Next()) {
        std::string key = it->key().ToString();
        std::string value = it->value().ToString();

        // Add "key": { ... value object ... } to the resulting document
        Value k(key.c_str(), result.GetAllocator());
        Document val_doc;
        val_doc.Parse(value.c_str());
        Value v(val_doc, result.GetAllocator());
        result.AddMember(k, v, result.GetAllocator());
    }

    // Check for any errors found during the scan
    if(!it->status().ok())
        throw std::runtime_error("PersistentStore::getRange() - error during the scan");

    StringBuffer sb;
    Writer<StringBuffer> writer(sb);
    result.Accept(writer);

    return sb.GetString();
}

void PersistentStorage::del(const std::string& key, bool* found) {
    std::string value = "";
    Status check = _db->Get(ReadOptions(), key, &value);
    *found = check.ok();
    if(!check.ok())
        return;
    Status s = _db->Delete(WriteOptions(), key);

    *found = s.ok();
}
<commit_msg>clang-format<commit_after>/* vim: set ai et ts=4 sw=4: */

#include "defer.h"
#include "rapidjson/document.h"
#include "rapidjson/stringbuffer.h"
#include <PersistentStorage.h>
#include <rapidjson/writer.h>
#include <stdexcept>
#include <string>

using namespace rapidjson;
using namespace rocksdb;

PersistentStorage::PersistentStorage() {
    _db = nullptr;

    Options options;

    options.IncreaseParallelism();
    options.OptimizeLevelStyleCompaction();
    options.create_if_missing = true;

    Status s = rocksdb::DB::Open(options, "hurma_data", &_db);
    if(!s.ok())
        throw std::runtime_error("PersistentStorage::PersistentStorage() - DB::Open failed");
}

PersistentStorage::~PersistentStorage() {
    if(_db != nullptr)
        delete _db;
}

void PersistentStorage::set(const std::string& key, const std::string& value) {
    Document val;

    if(val.Parse(value.c_str()).HasParseError())
        throw std::runtime_error("PersistentStore::set() - validation failed");

    Status s = _db->Put(WriteOptions(), key, value);
    if(!s.ok())
        throw std::runtime_error("PersistentStore::set() - _db->Put failed");
}

std::string PersistentStorage::get(const std::string& key, bool* found) {
    std::string value = "";
    Status s = _db->Get(ReadOptions(), key, &value);
    *found = s.ok();
    return value;
}

// TODO: impelemt more efficient interation for wide ranges
std::string PersistentStorage::getRange(const std::string& key_from, const std::string& key_to) {
    rocksdb::Iterator* it = _db->NewIterator(rocksdb::ReadOptions());
    defer(delete it);

    Document result;
    result.SetObject();

    for(it->Seek(key_from); it->Valid() && it->key().ToString() <= key_to; it->Next()) {
        std::string key = it->key().ToString();
        std::string value = it->value().ToString();

        // Add "key": { ... value object ... } to the resulting document
        Value k(key.c_str(), result.GetAllocator());
        Document val_doc;
        val_doc.Parse(value.c_str());
        Value v(val_doc, result.GetAllocator());
        result.AddMember(k, v, result.GetAllocator());
    }

    // Check for any errors found during the scan
    if(!it->status().ok())
        throw std::runtime_error("PersistentStore::getRange() - error during the scan");

    StringBuffer sb;
    Writer<StringBuffer> writer(sb);
    result.Accept(writer);

    return sb.GetString();
}

void PersistentStorage::del(const std::string& key, bool* found) {
    std::string value = "";
    Status check = _db->Get(ReadOptions(), key, &value);
    *found = check.ok();
    if(!check.ok())
        return;
    Status s = _db->Delete(WriteOptions(), key);

    *found = s.ok();
}
<|endoftext|>


<commit_before>// -*- Mode: C++; tab-width: 2; -*-
// vi: set ts=2:
//
// $Id: Socket_test.C,v 1.9 2003/05/08 13:55:26 anhi Exp $

#include <BALL/CONCEPT/classTest.h>

///////////////////////////
#include <BALL/SYSTEM/socket.h>
#include <unistd.h>

#ifdef BALL_COMPILER_MSVC
#	include<windows.h>
#	include<process.h>
#endif

///////////////////////////

using namespace BALL;

SockInetBuf sock_inet_buf(SocketBuf::sock_stream);
char c;

void socket_listener(void*)
{
	sock_inet_buf.listen();
	IOStreamSocket  s(sock_inet_buf.accept());
	s.get(c);
}

START_TEST(Socket, "$Id: Socket_test.C,v 1.9 2003/05/08 13:55:26 anhi Exp $")
using namespace BALL;

/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////

CHECK(simple socket transmission)

	sock_inet_buf.bind();
	int port = sock_inet_buf.localport();
	STATUS("localport = " << sock_inet_buf.localport())
	STATUS("localhost = " << sock_inet_buf.localhost())

#ifdef BALL_COMPILER_MSVC
	_beginthread(socket_listener,0,NULL);
	Sleep(1);
	IOStreamSocket sio(SocketBuf::sock_stream);
	int result = sio->connect(sock_inet_buf.localhost(), port);
	STATUS("B:connect = " << result)
	sio.put((char)123);
	sio.flush();
	STATUS("B:done.")
#else
	if (fork())
	{
		socket_listener(0);
	}
	else
	{
		sleep(1);
		IOStreamSocket  sio(SocketBuf::sock_stream);
		int result = sio->connect(sock_inet_buf.localhost(), port);
		STATUS("B:connect = " << result)
		sio.put((char)123);
		STATUS("B:done.")
		return 0;
	}
#endif

	TEST_EQUAL((int)c, (int)123);
RESULT

/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
END_TEST
<commit_msg>no message<commit_after>// -*- Mode: C++; tab-width: 2; -*-
// vi: set ts=2:
//
// $Id: Socket_test.C,v 1.10 2003/07/03 11:55:05 amoll Exp $

#include <BALL/CONCEPT/classTest.h>

///////////////////////////
#include <BALL/SYSTEM/socket.h>
#include <unistd.h>

#ifdef BALL_COMPILER_MSVC
#	include<windows.h>
#	include<process.h>
#endif

///////////////////////////

using namespace BALL;

SockInetBuf sock_inet_buf(SocketBuf::sock_stream);
char c;

void socket_listener(void*)
{
	sock_inet_buf.listen();
	IOStreamSocket  s(sock_inet_buf.accept());
	s.get(c);
}

START_TEST(Socket, "$Id: Socket_test.C,v 1.10 2003/07/03 11:55:05 amoll Exp $")
using namespace BALL;

/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////

CHECK([EXTRA]simple socket transmission)

	sock_inet_buf.bind();
	int port = sock_inet_buf.localport();
	STATUS("localport = " << sock_inet_buf.localport())
	STATUS("localhost = " << sock_inet_buf.localhost())

#ifdef BALL_COMPILER_MSVC
	_beginthread(socket_listener,0,NULL);
	Sleep(1);
	IOStreamSocket sio(SocketBuf::sock_stream);
	int result = sio->connect(sock_inet_buf.localhost(), port);
	STATUS("B:connect = " << result)
	sio.put((char)123);
	sio.flush();
	STATUS("B:done.")
#else
	if (fork())
	{
		socket_listener(0);
	}
	else
	{
		sleep(1);
		IOStreamSocket  sio(SocketBuf::sock_stream);
		int result = sio->connect(sock_inet_buf.localhost(), port);
		STATUS("B:connect = " << result)
		sio.put((char)123);
		STATUS("B:done.")
		return 0;
	}
#endif

	TEST_EQUAL((int)c, (int)123);
RESULT

/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
END_TEST
<|endoftext|>


<commit_before>#include "mitkOpenGLRenderer.h"
#include "Mapper.h"
#include "mitkImageMapper2D.h"
#include "BaseVtkMapper2D.h"
#include "BaseVtkMapper3D.h"
#include "LevelWindow.h"
#include "mitkVtkInteractorCameraController.h"
#include "mitkVtkRenderWindow.h"
#include "mitkRenderWindow.h"

#include <vtkRenderer.h>
#include <vtkLight.h>
#include <vtkLightKit.h>
#include <vtkRenderWindow.h>
#include <vtkTransform.h>
#include <vtkCamera.h>

#include "PlaneGeometry.h"
#include "mitkProperties.h"
#include <queue>
#include <utility>

//##ModelId=3E33ECF301AD
mitk::OpenGLRenderer::OpenGLRenderer() : m_VtkMapperPresent(false),
	m_VtkRenderer(NULL), m_MitkVtkRenderWindow(NULL)
{
  m_CameraController=NULL;
  m_CameraController = VtkInteractorCameraController::New();
  m_CameraController->AddRenderer(this);

  m_DataChangedCommand = itk::MemberCommand<mitk::OpenGLRenderer>::New();
#ifdef WIN32
  m_DataChangedCommand->SetCallbackFunction(this, mitk::OpenGLRenderer::DataChangedEvent);
#else
  m_DataChangedCommand->SetCallbackFunction(this, &mitk::OpenGLRenderer::DataChangedEvent);
#endif
}

//##ModelId=3E3D28AB0018
void mitk::OpenGLRenderer::SetData(mitk::DataTreeIterator* iterator)
{
  if(iterator!=GetData())
  {

    bool geometry_is_set=false;

    if(m_DataTreeIterator!=NULL)
    {
      //remove old connections
      mitk::DataTreeIterator* it=m_DataTreeIterator->clone();
      while(it->hasNext())
      {
        it->next();
        BaseData::Pointer data=it->get()->GetData();
      }
      delete it;
    }

    BaseRenderer::SetData(iterator);

    if (iterator != NULL)
    {
      //initialize world geometry: use first slice of first node containing an image
      mitk::DataTreeIterator* it=m_DataTreeIterator->clone();
      while(it->hasNext())
      {
        it->next();
        BaseData::Pointer data=it->get()->GetData();
        if(data.IsNotNull())
        {
          if(geometry_is_set==false)
          {
            Image::Pointer image = dynamic_cast<Image*>(data.GetPointer());
            if(image.IsNotNull())
            {
              SetWorldGeometry(image->GetGeometry2D(0, 0));
              geometry_is_set=true;
            }
          }
          //@todo add connections
          //data->AddObserver(itk::EndEvent(), m_DataChangedCommand);
        }
      }
      delete it;
    }

    //update the vtk-based mappers
    Update(); //this is only called to check, whether we have vtk-based mappers!
    UpdateVtkActors();

    Modified();
  }
}

//##ModelId=3ED91D060305
void mitk::OpenGLRenderer::UpdateVtkActors()
{
  VtkInteractorCameraController* vicc=dynamic_cast<VtkInteractorCameraController*>(m_CameraController.GetPointer());

  if (m_VtkMapperPresent == false)
  {
    if(vicc!=NULL)
      vicc->GetVtkInteractor()->Disable();
    return;
  }

  if(vicc!=NULL)
    vicc->GetVtkInteractor()->Enable();

  //    m_LightKit->RemoveLightsFromRenderer(this->m_VtkRenderer);

  //    m_MitkVtkRenderWindow->RemoveRenderer(m_VtkRenderer);
  //    m_VtkRenderer->Delete();

  bool newRenderer = false;
  if(m_VtkRenderer==NULL)
  {
    m_VtkRenderer = vtkRenderer::New();
    m_VtkRenderer->SetLayer(0);
    m_MitkVtkRenderWindow->AddRenderer( this->m_VtkRenderer );
    newRenderer = true;

    //strange: when using a simple light, the backface of the planes are not shown (regardless of SetNumberOfLayers)
    //m_Light = vtkLight::New();
    //m_VtkRenderer->AddLight( m_Light );
    m_LightKit = vtkLightKit::New();
    m_LightKit->AddLightsToRenderer(m_VtkRenderer);
  }

   m_VtkRenderer->RemoveAllProps();

  //strange: when using a simple light, the backface of the planes are not shown (regardless of SetNumberOfLayers)
  //m_Light->Delete();
  //m_Light = vtkLight::New();
  //m_VtkRenderer->AddLight( m_Light );
  if(m_LightKit!=NULL)
  {
    m_LightKit = vtkLightKit::New();
    m_LightKit->AddLightsToRenderer(m_VtkRenderer);
  }

  //    try
  if (m_DataTreeIterator != NULL)
  {
    mitk::DataTreeIterator* it=m_DataTreeIterator->clone();
    while(it->hasNext())
    {
      it->next();
      mitk::Mapper::Pointer mapper = it->get()->GetMapper(m_MapperID);
      if(mapper.IsNotNull())
      {
        BaseVtkMapper2D* anVtkMapper2D;
        anVtkMapper2D=dynamic_cast<BaseVtkMapper2D*>(mapper.GetPointer());
        if(anVtkMapper2D != NULL)
        {
          anVtkMapper2D->Update(this);
          m_VtkRenderer->AddProp(anVtkMapper2D->GetProp());
        }
        else
        {
          BaseVtkMapper3D* anVtkMapper3D;
          anVtkMapper3D=dynamic_cast<BaseVtkMapper3D*>(mapper.GetPointer());
          if(anVtkMapper3D != NULL)
          {
            anVtkMapper3D->Update(this);
            m_VtkRenderer->AddProp(anVtkMapper3D->GetProp());
          }
        }
      }
    }
    delete it;
  }

  if(newRenderer)
    m_VtkRenderer->GetActiveCamera()->Elevation(-90);

  //    catch( ::itk::ExceptionObject ee)
  //    {
  //        printf("%s\n",ee.what());
  ////        itkGenericOutputMacro(ee->what());
  //    }
  //    catch( ...)
  //    {
  //            printf("test\n");
  //    }
}

//##ModelId=3E330D260255
void mitk::OpenGLRenderer::Update()
{
  if(m_DataTreeIterator == NULL) return;

  m_VtkMapperPresent=false;

  mitk::DataTreeIterator* it=m_DataTreeIterator->clone();
  while(it->hasNext())
  {
    it->next();
    //      mitk::LevelWindow lw;
    //unsigned int dummy[] = {10,10,10};
    //Geometry3D geometry(3,dummy);
    mitk::Mapper::Pointer mapper = it->get()->GetMapper(m_MapperID);
    if(mapper.IsNotNull())
    {
      Mapper2D* mapper2d=dynamic_cast<Mapper2D*>(mapper.GetPointer());
      if(mapper2d != NULL)
      {
        BaseVtkMapper2D* vtkmapper2d=dynamic_cast<BaseVtkMapper2D*>(mapper.GetPointer());
        if(vtkmapper2d != NULL)
        {
          vtkmapper2d->Update(this);
          m_VtkMapperPresent=true;
        }
        else
          mapper2d->Update();
        //ImageMapper2D* imagemapper2d=dynamic_cast<ImageMapper2D*>(mapper.GetPointer());
      }
      else
      {
        BaseVtkMapper3D* vtkmapper3d=dynamic_cast<BaseVtkMapper3D*>(mapper.GetPointer());
        if(vtkmapper3d != NULL)
        {
          vtkmapper3d->Update(this);
          m_VtkMapperPresent=true;
        }
      }
    }
  }

  delete it;
  Modified();
  m_LastUpdateTime=GetMTime();
}

//##ModelId=3E330D2903CC
void mitk::OpenGLRenderer::Render()
{
  //if we do not have any data, we do nothing else but clearing our window
  if(GetData() == NULL)
  {
    glClear(GL_COLOR_BUFFER_BIT);
     if(m_VtkMapperPresent) {
      //    m_MitkVtkRenderWindow->MitkRender();
     } else
      m_RenderWindow->swapBuffers();

    return;
  }

  //has someone transformed our worldgeometry-node? if so, incorporate this transform into
  //the worldgeometry itself and reset the transform of the node to identity
  /*	if(m_WorldGeometryTransformTime<m_WorldGeometryNode->GetVtkTransform()->GetMTime())
  {
  vtkTransform *i;
  m_WorldGeometry->TransformGeometry(m_WorldGeometryNode->GetVtkTransform());
  m_WorldGeometryNode->GetVtkTransform()->Identity();
  m_WorldGeometryTransformTime=GetWorldGeometryNode()->GetVtkTransform()->GetMTime();
  }
  */
  //has the data tree been changed?
  if(dynamic_cast<mitk::DataTree*>(GetData()->getTree()) == NULL ) return;
  //	if(m_LastUpdateTime<((mitk::DataTree*)GetData()->getTree())->GetMTime())
  if(m_LastUpdateTime < dynamic_cast<mitk::DataTree*>(GetData()->getTree())->GetMTime() )
  {
    //yes: update vtk-actors
    Update();
    UpdateVtkActors();
  }
  else
  //has anything else changed (geometry to display, etc.)?
  if (m_LastUpdateTime<GetMTime() ||
    m_LastUpdateTime<GetDisplayGeometry()->GetMTime() ||
    m_LastUpdateTime<GetDisplayGeometry()->GetWorldGeometry()->GetMTime())
  {
    //std::cout << "OpenGLRenderer calling its update..." << std::endl;
    Update();
  }
  else
  if(m_MapperID==2)
  { //@todo in 3D mode wird sonst nix geupdated, da z.Z. weder camera noch nderung des Baums beachtet wird!!!
    Update();
  }

  glClear(GL_COLOR_BUFFER_BIT);

  //PlaneGeometry* myPlaneGeom =
  //  dynamic_cast<PlaneGeometry *>((mitk::Geometry2D*)(GetWorldGeometry()));

  glViewport (0, 0, m_Size[0], m_Size[1]);
  glMatrixMode( GL_PROJECTION );
  glLoadIdentity();
  gluOrtho2D( 0.0, m_Size[0], 0.0, m_Size[1] );
  glMatrixMode( GL_MODELVIEW );

  mitk::DataTreeIterator* it=m_DataTreeIterator->clone();
  mitk::DataTree::Pointer tree = dynamic_cast <mitk::DataTree *> (it->getTree());
  //	std::cout << "Render:: tree: " <<  *tree << std::endl;

  typedef std::pair<int, GLMapper2D*> LayerMapperPair;
  std::priority_queue<LayerMapperPair> layers;
  int mapperNo = 0;
  while(it->hasNext())
  {
    it->next();

    mitk::DataTreeNode::Pointer node = it->get();
    mitk::Mapper::Pointer mapper = node->GetMapper(m_MapperID);
    if(mapper.IsNotNull())
    {
      GLMapper2D* mapper2d=dynamic_cast<GLMapper2D*>(mapper.GetPointer());
      if(mapper2d!=NULL)
      {
        // mapper without a layer property are painted first
        int layer=-1;
        node->GetIntProperty("layer", layer, this);
        // pushing negative layer value, since default sort for
        // priority_queue is lessthan
        layers.push(LayerMapperPair(- (layer<<16) - mapperNo ,mapper2d));
        mapperNo++;
      }
    }
  }

  delete it;
  while (!layers.empty()) {
    layers.top().second->Paint(this);
    layers.pop();
  }
  if(m_VtkMapperPresent) {
    m_MitkVtkRenderWindow->MitkRender();
  }
  else
    m_RenderWindow->swapBuffers();
 }

/*!
\brief Initialize the OpenGLRenderer

This method is called from the two Constructors
*/
void mitk::OpenGLRenderer::InitRenderer(mitk::RenderWindow* renderwindow)
{
  BaseRenderer::InitRenderer(renderwindow);

  m_InitNeeded = true;
  m_ResizeNeeded = true;

  m_MitkVtkRenderWindow = mitk::VtkRenderWindow::New();
  m_MitkVtkRenderWindow->SetMitkRenderer(this);
  /**@todo SetNumberOfLayers commented out, because otherwise the backface of the planes are not shown (only, when a light is added).
  * But we need SetNumberOfLayers(2) later, when we want to prevent vtk to clear the widget before it renders (i.e., when we render something in the scene before vtk).
  */
  //m_MitkVtkRenderWindow->SetNumberOfLayers(2);

  if(m_CameraController.IsNotNull())
    ((VtkInteractorCameraController*)m_CameraController.GetPointer())->SetRenderWindow(m_MitkVtkRenderWindow);

  //we should disable vtk doublebuffering, but then it doesn't work
  //m_MitkVtkRenderWindow->SwapBuffersOff();

}

/*!
\brief Destructs the OpenGLRenderer.
*/
//##ModelId=3E33ECF301B7
mitk::OpenGLRenderer::~OpenGLRenderer() {
  m_VtkRenderer->Delete();
  m_MitkVtkRenderWindow->Delete();
}

/*!
\brief Initialize the OpenGL Window
*/
//##ModelId=3E33145B0096
void mitk::OpenGLRenderer::Initialize( ) {

  glClearColor(0.0, 0.0, 0.0, 1.0);
  glColor3f(1.0, 0.0, 0.0);

}

/*!
\brief Resize the OpenGL Window
*/
//##ModelId=3E33145B00D2
void mitk::OpenGLRenderer::Resize(int w, int h)
{
  glViewport (0, 0, w, h);
  glMatrixMode( GL_PROJECTION );
  glLoadIdentity();
  gluOrtho2D( 0.0, w, 0.0, h );
  glMatrixMode( GL_MODELVIEW );

  BaseRenderer::Resize(w, h);

  Update();
  //    m_MitkVtkRenderWindow->SetSize(w,h); //@FIXME?
}

/*!
\brief Render the scene
*/
//##ModelId=3E33145B005A
void mitk::OpenGLRenderer::Paint( )
{

//  glFlush();
//  m_RenderWindow->swapBuffers();
  Render();
}

//##ModelId=3E3314B0005C
void mitk::OpenGLRenderer::SetWindowId(void * id)
{
  m_MitkVtkRenderWindow->SetWindowId( id );
}

//##ModelId=3E3799420227
void mitk::OpenGLRenderer::InitSize(int w, int h)
{
  m_MitkVtkRenderWindow->SetSize(w,h);
  GetDisplayGeometry()->SetSizeInDisplayUnits(w, h);
  GetDisplayGeometry()->Fit();
  Modified();
  Update();
}

//##ModelId=3EF59AD20235
void mitk::OpenGLRenderer::SetMapperID(const MapperSlotId mapperId)
{
  Superclass::SetMapperID(mapperId);
  Update();
  UpdateVtkActors();
}

//##ModelId=3EF162760271
void mitk::OpenGLRenderer::MakeCurrent()
{
  if(m_RenderWindow!=NULL)
  {
    m_RenderWindow->MakeCurrent();
  }
}

void mitk::OpenGLRenderer::DataChangedEvent(const itk::Object *caller, const itk::EventObject &event)
{
  if(m_RenderWindow!=NULL)
  {
    m_RenderWindow->Update();
  }
}
<commit_msg>ivo removed bug: starting without data and clicking in a non vtk window lead into seg.-fault<commit_after>#include "mitkOpenGLRenderer.h"
#include "Mapper.h"
#include "mitkImageMapper2D.h"
#include "BaseVtkMapper2D.h"
#include "BaseVtkMapper3D.h"
#include "LevelWindow.h"
#include "mitkVtkInteractorCameraController.h"
#include "mitkVtkRenderWindow.h"
#include "mitkRenderWindow.h"

#include <vtkRenderer.h>
#include <vtkLight.h>
#include <vtkLightKit.h>
#include <vtkRenderWindow.h>
#include <vtkTransform.h>
#include <vtkCamera.h>

#include "PlaneGeometry.h"
#include "mitkProperties.h"
#include <queue>
#include <utility>

//##ModelId=3E33ECF301AD
mitk::OpenGLRenderer::OpenGLRenderer() : m_VtkMapperPresent(false),
	m_VtkRenderer(NULL), m_MitkVtkRenderWindow(NULL)
{
  m_CameraController=NULL;
  m_CameraController = VtkInteractorCameraController::New();
  m_CameraController->AddRenderer(this);

  m_DataChangedCommand = itk::MemberCommand<mitk::OpenGLRenderer>::New();
#ifdef WIN32
  m_DataChangedCommand->SetCallbackFunction(this, mitk::OpenGLRenderer::DataChangedEvent);
#else
  m_DataChangedCommand->SetCallbackFunction(this, &mitk::OpenGLRenderer::DataChangedEvent);
#endif
}

//##ModelId=3E3D28AB0018
void mitk::OpenGLRenderer::SetData(mitk::DataTreeIterator* iterator)
{
  if(iterator!=GetData())
  {

    bool geometry_is_set=false;

    if(m_DataTreeIterator!=NULL)
    {
      //remove old connections
      mitk::DataTreeIterator* it=m_DataTreeIterator->clone();
      while(it->hasNext())
      {
        it->next();
        BaseData::Pointer data=it->get()->GetData();
      }
      delete it;
    }

    BaseRenderer::SetData(iterator);

    if (iterator != NULL)
    {
      //initialize world geometry: use first slice of first node containing an image
      mitk::DataTreeIterator* it=m_DataTreeIterator->clone();
      while(it->hasNext())
      {
        it->next();
        BaseData::Pointer data=it->get()->GetData();
        if(data.IsNotNull())
        {
          if(geometry_is_set==false)
          {
            Image::Pointer image = dynamic_cast<Image*>(data.GetPointer());
            if(image.IsNotNull())
            {
              SetWorldGeometry(image->GetGeometry2D(0, 0));
              geometry_is_set=true;
            }
          }
          //@todo add connections
          //data->AddObserver(itk::EndEvent(), m_DataChangedCommand);
        }
      }
      delete it;
    }

    //update the vtk-based mappers
    Update(); //this is only called to check, whether we have vtk-based mappers!
    UpdateVtkActors();

    Modified();
  }
}

//##ModelId=3ED91D060305
void mitk::OpenGLRenderer::UpdateVtkActors()
{
  VtkInteractorCameraController* vicc=dynamic_cast<VtkInteractorCameraController*>(m_CameraController.GetPointer());

  if (m_VtkMapperPresent == false)
  {
    if(vicc!=NULL)
      vicc->GetVtkInteractor()->Disable();
    return;
  }

  if(vicc!=NULL)
    vicc->GetVtkInteractor()->Enable();

  //    m_LightKit->RemoveLightsFromRenderer(this->m_VtkRenderer);

  //    m_MitkVtkRenderWindow->RemoveRenderer(m_VtkRenderer);
  //    m_VtkRenderer->Delete();

  bool newRenderer = false;
  if(m_VtkRenderer==NULL)
  {
    m_VtkRenderer = vtkRenderer::New();
    m_VtkRenderer->SetLayer(0);
    m_MitkVtkRenderWindow->AddRenderer( this->m_VtkRenderer );
    newRenderer = true;

    //strange: when using a simple light, the backface of the planes are not shown (regardless of SetNumberOfLayers)
    //m_Light = vtkLight::New();
    //m_VtkRenderer->AddLight( m_Light );
    m_LightKit = vtkLightKit::New();
    m_LightKit->AddLightsToRenderer(m_VtkRenderer);
  }

   m_VtkRenderer->RemoveAllProps();

  //strange: when using a simple light, the backface of the planes are not shown (regardless of SetNumberOfLayers)
  //m_Light->Delete();
  //m_Light = vtkLight::New();
  //m_VtkRenderer->AddLight( m_Light );
  if(m_LightKit!=NULL)
  {
    m_LightKit = vtkLightKit::New();
    m_LightKit->AddLightsToRenderer(m_VtkRenderer);
  }

  //    try
  if (m_DataTreeIterator != NULL)
  {
    mitk::DataTreeIterator* it=m_DataTreeIterator->clone();
    while(it->hasNext())
    {
      it->next();
      mitk::Mapper::Pointer mapper = it->get()->GetMapper(m_MapperID);
      if(mapper.IsNotNull())
      {
        BaseVtkMapper2D* anVtkMapper2D;
        anVtkMapper2D=dynamic_cast<BaseVtkMapper2D*>(mapper.GetPointer());
        if(anVtkMapper2D != NULL)
        {
          anVtkMapper2D->Update(this);
          m_VtkRenderer->AddProp(anVtkMapper2D->GetProp());
        }
        else
        {
          BaseVtkMapper3D* anVtkMapper3D;
          anVtkMapper3D=dynamic_cast<BaseVtkMapper3D*>(mapper.GetPointer());
          if(anVtkMapper3D != NULL)
          {
            anVtkMapper3D->Update(this);
            m_VtkRenderer->AddProp(anVtkMapper3D->GetProp());
          }
        }
      }
    }
    delete it;
  }

  if(newRenderer)
    m_VtkRenderer->GetActiveCamera()->Elevation(-90);

  //    catch( ::itk::ExceptionObject ee)
  //    {
  //        printf("%s\n",ee.what());
  ////        itkGenericOutputMacro(ee->what());
  //    }
  //    catch( ...)
  //    {
  //            printf("test\n");
  //    }
}

//##ModelId=3E330D260255
void mitk::OpenGLRenderer::Update()
{
  if(m_DataTreeIterator == NULL) return;

  m_VtkMapperPresent=false;

  mitk::DataTreeIterator* it=m_DataTreeIterator->clone();
  while(it->hasNext())
  {
    it->next();
    //      mitk::LevelWindow lw;
    //unsigned int dummy[] = {10,10,10};
    //Geometry3D geometry(3,dummy);
    mitk::Mapper::Pointer mapper = it->get()->GetMapper(m_MapperID);
    if(mapper.IsNotNull())
    {
      Mapper2D* mapper2d=dynamic_cast<Mapper2D*>(mapper.GetPointer());
      if(mapper2d != NULL)
      {
        BaseVtkMapper2D* vtkmapper2d=dynamic_cast<BaseVtkMapper2D*>(mapper.GetPointer());
        if(vtkmapper2d != NULL)
        {
          vtkmapper2d->Update(this);
          m_VtkMapperPresent=true;
        }
        else
          mapper2d->Update();
        //ImageMapper2D* imagemapper2d=dynamic_cast<ImageMapper2D*>(mapper.GetPointer());
      }
      else
      {
        BaseVtkMapper3D* vtkmapper3d=dynamic_cast<BaseVtkMapper3D*>(mapper.GetPointer());
        if(vtkmapper3d != NULL)
        {
          vtkmapper3d->Update(this);
          m_VtkMapperPresent=true;
        }
      }
    }
  }

  delete it;
  Modified();
  m_LastUpdateTime=GetMTime();
}

//##ModelId=3E330D2903CC
void mitk::OpenGLRenderer::Render()
{
  //if we do not have any data, we do nothing else but clearing our window
  if(GetData() == NULL)
  {
    glClear(GL_COLOR_BUFFER_BIT);
     if(m_VtkMapperPresent) {
      //    m_MitkVtkRenderWindow->MitkRender();
     } else
      m_RenderWindow->swapBuffers();

    return;
  }

  //has someone transformed our worldgeometry-node? if so, incorporate this transform into
  //the worldgeometry itself and reset the transform of the node to identity
  /*	if(m_WorldGeometryTransformTime<m_WorldGeometryNode->GetVtkTransform()->GetMTime())
  {
  vtkTransform *i;
  m_WorldGeometry->TransformGeometry(m_WorldGeometryNode->GetVtkTransform());
  m_WorldGeometryNode->GetVtkTransform()->Identity();
  m_WorldGeometryTransformTime=GetWorldGeometryNode()->GetVtkTransform()->GetMTime();
  }
  */
  //has the data tree been changed?
  if(dynamic_cast<mitk::DataTree*>(GetData()->getTree()) == NULL ) return;
  //	if(m_LastUpdateTime<((mitk::DataTree*)GetData()->getTree())->GetMTime())
  if(m_LastUpdateTime < dynamic_cast<mitk::DataTree*>(GetData()->getTree())->GetMTime() )
  {
    //yes: update vtk-actors
    Update();
    UpdateVtkActors();
  }
  else
  //has anything else changed (geometry to display, etc.)?
  if (m_LastUpdateTime<GetMTime() ||
    m_LastUpdateTime<GetDisplayGeometry()->GetMTime() ||
    m_LastUpdateTime<GetDisplayGeometry()->GetWorldGeometry()->GetMTime())
  {
    //std::cout << "OpenGLRenderer calling its update..." << std::endl;
    Update();
  }
  else
  if(m_MapperID==2)
  { //@todo in 3D mode wird sonst nix geupdated, da z.Z. weder camera noch nderung des Baums beachtet wird!!!
    Update();
  }

  glClear(GL_COLOR_BUFFER_BIT);

  //PlaneGeometry* myPlaneGeom =
  //  dynamic_cast<PlaneGeometry *>((mitk::Geometry2D*)(GetWorldGeometry()));

  glViewport (0, 0, m_Size[0], m_Size[1]);
  glMatrixMode( GL_PROJECTION );
  glLoadIdentity();
  gluOrtho2D( 0.0, m_Size[0], 0.0, m_Size[1] );
  glMatrixMode( GL_MODELVIEW );

  mitk::DataTreeIterator* it=m_DataTreeIterator->clone();
  mitk::DataTree::Pointer tree = dynamic_cast <mitk::DataTree *> (it->getTree());
  //	std::cout << "Render:: tree: " <<  *tree << std::endl;

  typedef std::pair<int, GLMapper2D*> LayerMapperPair;
  std::priority_queue<LayerMapperPair> layers;
  int mapperNo = 0;
  while(it->hasNext())
  {
    it->next();

    mitk::DataTreeNode::Pointer node = it->get();
    mitk::Mapper::Pointer mapper = node->GetMapper(m_MapperID);
    if(mapper.IsNotNull())
    {
      GLMapper2D* mapper2d=dynamic_cast<GLMapper2D*>(mapper.GetPointer());
      if(mapper2d!=NULL)
      {
        // mapper without a layer property are painted first
        int layer=-1;
        node->GetIntProperty("layer", layer, this);
        // pushing negative layer value, since default sort for
        // priority_queue is lessthan
        layers.push(LayerMapperPair(- (layer<<16) - mapperNo ,mapper2d));
        mapperNo++;
      }
    }
  }

  delete it;
  while (!layers.empty()) {
    layers.top().second->Paint(this);
    layers.pop();
  }
  if(m_VtkMapperPresent) {
    m_MitkVtkRenderWindow->MitkRender();
  }
  else
    m_RenderWindow->swapBuffers();
 }

/*!
\brief Initialize the OpenGLRenderer

This method is called from the two Constructors
*/
void mitk::OpenGLRenderer::InitRenderer(mitk::RenderWindow* renderwindow)
{
  BaseRenderer::InitRenderer(renderwindow);

  m_InitNeeded = true;
  m_ResizeNeeded = true;

  m_MitkVtkRenderWindow = mitk::VtkRenderWindow::New();
  m_MitkVtkRenderWindow->SetMitkRenderer(this);
  /**@todo SetNumberOfLayers commented out, because otherwise the backface of the planes are not shown (only, when a light is added).
  * But we need SetNumberOfLayers(2) later, when we want to prevent vtk to clear the widget before it renders (i.e., when we render something in the scene before vtk).
  */
  //m_MitkVtkRenderWindow->SetNumberOfLayers(2);

  if(m_CameraController.IsNotNull())
  {
    VtkInteractorCameraController* vicc=dynamic_cast<VtkInteractorCameraController*>(m_CameraController.GetPointer());
    if(vicc!=NULL)
    {
      vicc->SetRenderWindow(m_MitkVtkRenderWindow);
      vicc->GetVtkInteractor()->Disable();
    }
  }

  //we should disable vtk doublebuffering, but then it doesn't work
  //m_MitkVtkRenderWindow->SwapBuffersOff();

}

/*!
\brief Destructs the OpenGLRenderer.
*/
//##ModelId=3E33ECF301B7
mitk::OpenGLRenderer::~OpenGLRenderer() {
  m_VtkRenderer->Delete();
  m_MitkVtkRenderWindow->Delete();
}

/*!
\brief Initialize the OpenGL Window
*/
//##ModelId=3E33145B0096
void mitk::OpenGLRenderer::Initialize( ) {

  glClearColor(0.0, 0.0, 0.0, 1.0);
  glColor3f(1.0, 0.0, 0.0);

}

/*!
\brief Resize the OpenGL Window
*/
//##ModelId=3E33145B00D2
void mitk::OpenGLRenderer::Resize(int w, int h)
{
  glViewport (0, 0, w, h);
  glMatrixMode( GL_PROJECTION );
  glLoadIdentity();
  gluOrtho2D( 0.0, w, 0.0, h );
  glMatrixMode( GL_MODELVIEW );

  BaseRenderer::Resize(w, h);

  Update();
  //    m_MitkVtkRenderWindow->SetSize(w,h); //@FIXME?
}

/*!
\brief Render the scene
*/
//##ModelId=3E33145B005A
void mitk::OpenGLRenderer::Paint( )
{

//  glFlush();
//  m_RenderWindow->swapBuffers();
  Render();
}

//##ModelId=3E3314B0005C
void mitk::OpenGLRenderer::SetWindowId(void * id)
{
  m_MitkVtkRenderWindow->SetWindowId( id );
}

//##ModelId=3E3799420227
void mitk::OpenGLRenderer::InitSize(int w, int h)
{
  m_MitkVtkRenderWindow->SetSize(w,h);
  GetDisplayGeometry()->SetSizeInDisplayUnits(w, h);
  GetDisplayGeometry()->Fit();
  Modified();
  Update();
}

//##ModelId=3EF59AD20235
void mitk::OpenGLRenderer::SetMapperID(const MapperSlotId mapperId)
{
  Superclass::SetMapperID(mapperId);
  Update();
  UpdateVtkActors();
}

//##ModelId=3EF162760271
void mitk::OpenGLRenderer::MakeCurrent()
{
  if(m_RenderWindow!=NULL)
  {
    m_RenderWindow->MakeCurrent();
  }
}

void mitk::OpenGLRenderer::DataChangedEvent(const itk::Object *caller, const itk::EventObject &event)
{
  if(m_RenderWindow!=NULL)
  {
    m_RenderWindow->Update();
  }
}
<|endoftext|>


<commit_before>/*=========================================================================

Program:   Medical Imaging & Interaction Toolkit
Module:    $RCSfile: mitkPropertyManager.cpp,v $
Language:  C++
Date:      $Date$
Version:   $Revision: 1.12 $

Copyright (c) German Cancer Research Center, Division of Medical and
Biological Informatics. All rights reserved.
See MITKCopyright.txt or http://www.mitk.org/copyright.html for details.

This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE.  See the above copyright notices for more information.

=========================================================================*/

#include "QmitkPointListWidget.h"

#include "mitkGlobalInteraction.h"
#include "mitkPointSetReader.h"
#include "mitkPointSetWriter.h"

#include <QGridLayout>
#include <QPushButton>
#include <QMessageBox>
#include <QFileDialog>

#include "btnSetPoints.xpm"
#include "btnClear.xpm"
#include "btnLoad.xpm"
#include "btnSave.xpm"

QmitkPointListWidget::QmitkPointListWidget( QWidget* parent, Qt::WindowFlags f )
:QWidget( parent, f ),
 m_PointSetNode(NULL),
 m_NodeObserverTag(0)
{
  QGridLayout* layout = new QGridLayout;
  layout->setContentsMargins( 0, 0, 0, 0 );
  this->setLayout( layout );
  this->setContentsMargins( 0, 0, 0, 0 );

  m_ListView = new QmitkPointListView( this );
  layout->addWidget( m_ListView, 0, 0, 1, 4 ); // span 4 cols

  const QIcon iconEdit( btnSetPoints_xpm );
  m_BtnEdit = new QPushButton( iconEdit, "", this );
  m_BtnEdit->setToolTip("Toggle point editing (use CTRL+left mouse button)");
  connect( m_BtnEdit, SIGNAL(toggled(bool)), this, SLOT(OnEditPointSetButtonToggled(bool)) );
  m_BtnEdit->setCheckable( true ); // installs/removes pointset interactor
  layout->addWidget( m_BtnEdit, 1, 0 );

  const QIcon iconClear( btnClear_xpm ); // clears whole point set
  m_BtnClear = new QPushButton( iconClear, "", this );
  m_BtnClear->setToolTip("Erase all points from list");
  connect( m_BtnClear, SIGNAL(clicked()), this, SLOT(OnClearPointSetButtonClicked()) );
  layout->addWidget( m_BtnClear, 1, 1 );

  const QIcon iconLoad( btnLoad_xpm ); // loads a point set from file
  m_BtnLoad = new QPushButton( iconLoad, "", this );
  m_BtnLoad->setToolTip("Load list of points from file (REPLACES current content)");
  connect( m_BtnLoad, SIGNAL(clicked()), this, SLOT(OnLoadPointSetButtonClicked()) );
  layout->addWidget( m_BtnLoad, 1, 2 );

  const QIcon iconSave( btnSave_xpm ); // saves point set to file
  m_BtnSave = new QPushButton( iconSave, "", this );
  m_BtnSave->setToolTip("Save points to file");
  connect( m_BtnSave, SIGNAL(clicked()), this, SLOT(OnSavePointSetButtonClicked()) );
  layout->addWidget( m_BtnSave, 1, 3 );

  ObserveNewNode(NULL);
}

QmitkPointListWidget::~QmitkPointListWidget()
{
}

void QmitkPointListWidget::SetPointSetNode( mitk::DataTreeNode* node )
{
  ObserveNewNode(node);

  if (node)
  {
    mitk::PointSet* pointSet = dynamic_cast<mitk::PointSet*>( node->GetData() );
    m_ListView->SetPointSet( pointSet );
  }
  else
  {
    m_ListView->SetPointSet( NULL );
  }
}

void QmitkPointListWidget::SetMultiWidget( QmitkStdMultiWidget* multiWidget )
{
  m_ListView->SetMultiWidget( multiWidget );
}

void QmitkPointListWidget::DeactivateInteractor(bool deactivate)
{
  if (deactivate)
  {
    if (m_Interactor)
    {
      mitk::GlobalInteraction::GetInstance()->RemoveInteractor( m_Interactor );
      m_Interactor = NULL;
      m_BtnEdit->setChecked( false );
    }
  }
}

void QmitkPointListWidget::ObserveNewNode( mitk::DataTreeNode* node )
{
  // remove old observer
  if ( m_PointSetNode != NULL )
  {
    if (m_Interactor)
    {
      mitk::GlobalInteraction::GetInstance()->RemoveInteractor( m_Interactor );
      m_Interactor = NULL;
      m_BtnEdit->setChecked( false );
    }

    m_PointSetNode->RemoveObserver( m_NodeObserverTag );
  }

  m_PointSetNode = node;

  // add new observer if neccessary
  if ( m_PointSetNode != NULL )
  {
    itk::ReceptorMemberCommand<QmitkPointListWidget>::Pointer command = itk::ReceptorMemberCommand<QmitkPointListWidget>::New();
    command->SetCallbackFunction( this, &QmitkPointListWidget::OnNodeDeleted );
    m_NodeObserverTag = m_PointSetNode->AddObserver( itk::DeleteEvent(), command );
  }
  else
  {
    m_NodeObserverTag = 0;
  }

  m_BtnEdit->setEnabled( m_PointSetNode != NULL );
  m_BtnClear->setEnabled( m_PointSetNode != NULL );
  m_BtnLoad->setEnabled( m_PointSetNode != NULL );
  m_BtnSave->setEnabled( m_PointSetNode != NULL );
}

void QmitkPointListWidget::OnNodeDeleted( const itk::EventObject & e )
{
  m_PointSetNode = NULL;
  m_NodeObserverTag = 0;
  m_ListView->SetPointSet( NULL );
}

void QmitkPointListWidget::OnEditPointSetButtonToggled(bool checked)
{
  if (m_PointSetNode)
  {
    if (checked)
    {
      m_Interactor = mitk::PointSetInteractor::New("pointsetinteractor", m_PointSetNode);
      mitk::GlobalInteraction::GetInstance()->AddInteractor( m_Interactor );
    }
    else if ( m_Interactor )
    {
      mitk::GlobalInteraction::GetInstance()->RemoveInteractor( m_Interactor );
      m_Interactor = NULL;
    }
    emit EditPointSets(checked);
  }
}

void QmitkPointListWidget::OnClearPointSetButtonClicked()
{
  if (!m_PointSetNode) return;
  mitk::PointSet* pointSet = dynamic_cast<mitk::PointSet*>( m_PointSetNode->GetData() );
  if (!pointSet) return;
  if (pointSet->GetSize() == 0) return; // we don't have to disturb by asking silly questions

  switch( QMessageBox::question( this, tr("Clear Points"),
          tr("Remove all points from the displayed list?"),
          QMessageBox::Yes | QMessageBox::No, QMessageBox::No))
  {
    case QMessageBox::Yes:
      if (pointSet)
      {
        mitk::PointSet::DataType::PointsContainer::Pointer pointsContainer = pointSet->GetPointSet()->GetPoints();
        pointsContainer->Initialize(); // a call to initialize results in clearing the points container
      }
      mitk::RenderingManager::GetInstance()->RequestUpdateAll();
      break;

    case QMessageBox::No:
    default:
      break;
  }
  emit PointListChanged();
}

void QmitkPointListWidget::OnLoadPointSetButtonClicked()
{
  if (!m_PointSetNode) return;

  // get the name of the file to load
  QString filename = QFileDialog::getOpenFileName( NULL, QString::null, "MITK Point Sets (*.mps)", NULL );
  if ( filename.isEmpty() ) return;

  // attempt to load file
  try
  {
    mitk::PointSetReader::Pointer reader = mitk::PointSetReader::New();
    reader->SetFileName( filename.latin1() );
    reader->Update();

    mitk::PointSet::Pointer pointSet = reader->GetOutput();
    if ( pointSet.IsNull() )
    {
      QMessageBox::warning( this, "Load point set", QString("File reader could not read %1").arg(filename) );
      return;
    }

    // loading successful

    bool interactionOn( m_Interactor.IsNotNull() );
    if (interactionOn)
    {
      OnEditPointSetButtonToggled(false);
    }

    m_PointSetNode->SetData( pointSet );
    m_ListView->SetPointSet( pointSet );

    if (interactionOn)
    {
      OnEditPointSetButtonToggled(true);
    }
  }
  catch(...)
  {
    QMessageBox::warning( this, "Load point set", QString("File reader collapsed while reading %1").arg(filename) );
  }
  emit PointListChanged();
}

void QmitkPointListWidget::OnSavePointSetButtonClicked()
{
  if (!m_PointSetNode) return;
  mitk::PointSet* pointSet = dynamic_cast<mitk::PointSet*>( m_PointSetNode->GetData() );
  if (!pointSet) return; // don't write empty point sets. If application logic requires something else then do something else.
  if (pointSet->GetSize() == 0) return;

  // let the user choose a file
  std::string name("");

  QString fileNameProposal = "PointSet.mps";
  QString aFilename = QFileDialog::getSaveFileName( fileNameProposal.latin1() );
  if ( aFilename.isEmpty() ) return;

  try
  {
    // instantiate the writer and add the point-sets to write
    mitk::PointSetWriter::Pointer writer = mitk::PointSetWriter::New();
    writer->SetInput( pointSet );
    writer->SetFileName( aFilename.latin1() );
    writer->Update();
  }
  catch(...)
  {
    QMessageBox::warning( this, "Save point set",
                          QString("File writer reported problems writing %1\n\n"
                                  "PLEASE CHECK output file!").arg(aFilename) );
  }
}

<commit_msg>COMP: restructuring<commit_after>/*=========================================================================

Program:   Medical Imaging & Interaction Toolkit
Module:    $RCSfile: mitkPropertyManager.cpp,v $
Language:  C++
Date:      $Date$
Version:   $Revision: 1.12 $

Copyright (c) German Cancer Research Center, Division of Medical and
Biological Informatics. All rights reserved.
See MITKCopyright.txt or http://www.mitk.org/copyright.html for details.

This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE.  See the above copyright notices for more information.

=========================================================================*/

#include "QmitkPointListWidget.h"

#include "mitkGlobalInteraction.h"
#include "mitkPointSetReader.h"
#include "mitkPointSetWriter.h"

#include <QGridLayout>
#include <QPushButton>
#include <QMessageBox>
#include <QFileDialog>

#include "btnSetPoints.xpm"
#include "btnClear.xpm"
#include "btnLoad.xpm"
#include "btnSave.xpm"

QmitkPointListWidget::QmitkPointListWidget( QWidget* parent, Qt::WindowFlags f )
:QWidget( parent, f ),
 m_PointSetNode(NULL),
 m_NodeObserverTag(0)
{
  QGridLayout* layout = new QGridLayout;
  layout->setContentsMargins( 0, 0, 0, 0 );
  this->setLayout( layout );
  this->setContentsMargins( 0, 0, 0, 0 );

  m_ListView = new QmitkPointListView( this );
  layout->addWidget( m_ListView, 0, 0, 1, 4 ); // span 4 cols

  const QIcon iconEdit( btnSetPoints_xpm );
  m_BtnEdit = new QPushButton( iconEdit, "", this );
  m_BtnEdit->setToolTip("Toggle point editing (use CTRL+left mouse button)");
  connect( m_BtnEdit, SIGNAL(toggled(bool)), this, SLOT(OnEditPointSetButtonToggled(bool)) );
  m_BtnEdit->setCheckable( true ); // installs/removes pointset interactor
  layout->addWidget( m_BtnEdit, 1, 0 );

  const QIcon iconClear( btnClear_xpm ); // clears whole point set
  m_BtnClear = new QPushButton( iconClear, "", this );
  m_BtnClear->setToolTip("Erase all points from list");
  connect( m_BtnClear, SIGNAL(clicked()), this, SLOT(OnClearPointSetButtonClicked()) );
  layout->addWidget( m_BtnClear, 1, 1 );

  const QIcon iconLoad( btnLoad_xpm ); // loads a point set from file
  m_BtnLoad = new QPushButton( iconLoad, "", this );
  m_BtnLoad->setToolTip("Load list of points from file (REPLACES current content)");
  connect( m_BtnLoad, SIGNAL(clicked()), this, SLOT(OnLoadPointSetButtonClicked()) );
  layout->addWidget( m_BtnLoad, 1, 2 );

  const QIcon iconSave( btnSave_xpm ); // saves point set to file
  m_BtnSave = new QPushButton( iconSave, "", this );
  m_BtnSave->setToolTip("Save points to file");
  connect( m_BtnSave, SIGNAL(clicked()), this, SLOT(OnSavePointSetButtonClicked()) );
  layout->addWidget( m_BtnSave, 1, 3 );

  ObserveNewNode(NULL);
}

QmitkPointListWidget::~QmitkPointListWidget()
{
}

void QmitkPointListWidget::SetPointSetNode( mitk::DataTreeNode* node )
{
  ObserveNewNode(node);

  if (node)
  {
    mitk::PointSet* pointSet = dynamic_cast<mitk::PointSet*>( node->GetData() );
    m_ListView->SetPointSet( pointSet );
  }
  else
  {
    m_ListView->SetPointSet( NULL );
  }
}

void QmitkPointListWidget::SetMultiWidget( QmitkStdMultiWidget* multiWidget )
{
  m_ListView->SetMultiWidget( multiWidget );
}

void QmitkPointListWidget::DeactivateInteractor(bool deactivate)
{
  if (deactivate)
  {
    if (m_Interactor)
    {
      mitk::GlobalInteraction::GetInstance()->RemoveInteractor( m_Interactor );
      m_Interactor = NULL;
      m_BtnEdit->setChecked( false );
    }
  }
}

void QmitkPointListWidget::ObserveNewNode( mitk::DataTreeNode* node )
{
  // remove old observer
  if ( m_PointSetNode != NULL )
  {
    if (m_Interactor)
    {
      mitk::GlobalInteraction::GetInstance()->RemoveInteractor( m_Interactor );
      m_Interactor = NULL;
      m_BtnEdit->setChecked( false );
    }

    m_PointSetNode->RemoveObserver( m_NodeObserverTag );
  }

  m_PointSetNode = node;

  // add new observer if neccessary
  if ( m_PointSetNode != NULL )
  {
    itk::ReceptorMemberCommand<QmitkPointListWidget>::Pointer command = itk::ReceptorMemberCommand<QmitkPointListWidget>::New();
    command->SetCallbackFunction( this, &QmitkPointListWidget::OnNodeDeleted );
    m_NodeObserverTag = m_PointSetNode->AddObserver( itk::DeleteEvent(), command );
  }
  else
  {
    m_NodeObserverTag = 0;
  }

  m_BtnEdit->setEnabled( m_PointSetNode != NULL );
  m_BtnClear->setEnabled( m_PointSetNode != NULL );
  m_BtnLoad->setEnabled( m_PointSetNode != NULL );
  m_BtnSave->setEnabled( m_PointSetNode != NULL );
}

void QmitkPointListWidget::OnNodeDeleted( const itk::EventObject & e )
{
  m_PointSetNode = NULL;
  m_NodeObserverTag = 0;
  m_ListView->SetPointSet( NULL );
}

void QmitkPointListWidget::OnEditPointSetButtonToggled(bool checked)
{
  if (m_PointSetNode)
  {
    if (checked)
    {
      m_Interactor = mitk::PointSetInteractor::New("pointsetinteractor", m_PointSetNode);
      mitk::GlobalInteraction::GetInstance()->AddInteractor( m_Interactor );
    }
    else if ( m_Interactor )
    {
      mitk::GlobalInteraction::GetInstance()->RemoveInteractor( m_Interactor );
      m_Interactor = NULL;
    }
    emit EditPointSets(checked);
  }
}

void QmitkPointListWidget::OnClearPointSetButtonClicked()
{
  if (!m_PointSetNode) return;
  mitk::PointSet* pointSet = dynamic_cast<mitk::PointSet*>( m_PointSetNode->GetData() );
  if (!pointSet) return;
  if (pointSet->GetSize() == 0) return; // we don't have to disturb by asking silly questions

  switch( QMessageBox::question( this, tr("Clear Points"),
          tr("Remove all points from the displayed list?"),
          QMessageBox::Yes | QMessageBox::No, QMessageBox::No))
  {
    case QMessageBox::Yes:
      if (pointSet)
      {
        mitk::PointSet::DataType::PointsContainer::Pointer pointsContainer = pointSet->GetPointSet()->GetPoints();
        pointsContainer->Initialize(); // a call to initialize results in clearing the points container
      }
      mitk::RenderingManager::GetInstance()->RequestUpdateAll();
      break;

    case QMessageBox::No:
    default:
      break;
  }
  emit PointListChanged();
}

void QmitkPointListWidget::OnLoadPointSetButtonClicked()
{
  if (!m_PointSetNode) return;

  // get the name of the file to load
  QString filename = QFileDialog::getOpenFileName( NULL, QString::null, "MITK Point Sets (*.mps)", NULL );
  if ( filename.isEmpty() ) return;

  // attempt to load file
  try
  {
    mitk::PointSetReader::Pointer reader = mitk::PointSetReader::New();
    reader->SetFileName( filename.toLatin1() );
    reader->Update();

    mitk::PointSet::Pointer pointSet = reader->GetOutput();
    if ( pointSet.IsNull() )
    {
      QMessageBox::warning( this, "Load point set", QString("File reader could not read %1").arg(filename) );
      return;
    }

    // loading successful

    bool interactionOn( m_Interactor.IsNotNull() );
    if (interactionOn)
    {
      OnEditPointSetButtonToggled(false);
    }

    m_PointSetNode->SetData( pointSet );
    m_ListView->SetPointSet( pointSet );

    if (interactionOn)
    {
      OnEditPointSetButtonToggled(true);
    }
  }
  catch(...)
  {
    QMessageBox::warning( this, "Load point set", QString("File reader collapsed while reading %1").arg(filename) );
  }
  emit PointListChanged();
}

void QmitkPointListWidget::OnSavePointSetButtonClicked()
{
  if (!m_PointSetNode) return;
  mitk::PointSet* pointSet = dynamic_cast<mitk::PointSet*>( m_PointSetNode->GetData() );
  if (!pointSet) return; // don't write empty point sets. If application logic requires something else then do something else.
  if (pointSet->GetSize() == 0) return;

  // let the user choose a file
  std::string name("");

  QString fileNameProposal = "PointSet.mps";
  QString aFilename = QFileDialog::getSaveFileName( fileNameProposal.toLatin1() );
  if ( aFilename.isEmpty() ) return;

  try
  {
    // instantiate the writer and add the point-sets to write
    mitk::PointSetWriter::Pointer writer = mitk::PointSetWriter::New();
    writer->SetInput( pointSet );
    writer->SetFileName( aFilename.toLatin1() );
    writer->Update();
  }
  catch(...)
  {
    QMessageBox::warning( this, "Save point set",
                          QString("File writer reported problems writing %1\n\n"
                                  "PLEASE CHECK output file!").arg(aFilename) );
  }
}

<|endoftext|>


<commit_before>
#include "net.h"
#include "masternodeconfig.h"
#include "util.h"
#include "ui_interface.h"
#include "chainparams.h"

#include <boost/filesystem.hpp>
#include <boost/filesystem/fstream.hpp>

CMasternodeConfig masternodeConfig;

void CMasternodeConfig::add(std::string alias, std::string ip, std::string privKey, std::string txHash, std::string outputIndex) {
    CMasternodeEntry cme(alias, ip, privKey, txHash, outputIndex);
    entries.push_back(cme);
}

bool CMasternodeConfig::read(std::string& strErr) {
    int linenumber = 1;
    boost::filesystem::path pathMasternodeConfigFile = GetMasternodeConfigFile();
    boost::filesystem::ifstream streamConfig(pathMasternodeConfigFile);

    LogPrintf("loading masternode file at %s\n", pathMasternodeConfigFile.c_str());

    if (!streamConfig.good()) {
        FILE* configFile = fopen(pathMasternodeConfigFile.string().c_str(), "a");
        if (configFile != NULL) {
            std::string strHeader = "# Masternode config file\n"
                          "# Format: alias IP:port masternodeprivkey collateral_output_txid collateral_output_index\n"
                          "# Example: mn1 127.0.0.2:19999 93HaYBVUCYjEMeeH1Y4sBGLALQZE1Yc1K64xiqgX37tGBDQL8Xg 2bcd3c84c84f87eaa86e4e56834c92927a07f9e18718810b92e0d0324456a67c 0\n";
            fwrite(strHeader.c_str(), std::strlen(strHeader.c_str()), 1, configFile);
            fclose(configFile);
        }
        return true; // Nothing to read, so just return
    }

    for(std::string line; std::getline(streamConfig, line); linenumber++)
    {
        if(line.empty()) continue;

        std::istringstream iss(line);
        std::string comment, alias, ip, privKey, txHash, outputIndex;

        if (iss >> comment) {
            if(comment.at(0) == '#') continue;
            iss.str(line);
            iss.clear();
        }

        if (!(iss >> alias >> ip >> privKey >> txHash >> outputIndex)) {
            iss.str(line);
            iss.clear();
            if (!(iss >> alias >> ip >> privKey >> txHash >> outputIndex)) {
                strErr = _("Could not parse masternode.conf") + "\n" +
                        strprintf(_("Line: %d"), linenumber) + "\n\"" + line + "\"";
                streamConfig.close();
                return false;
            }
        }

        int mainnetDefaultPort = Params(CBaseChainParams::MAIN).GetDefaultPort();
        if(Params().NetworkIDString() == CBaseChainParams::MAIN) {
            if(CService(ip).GetPort() != mainnetDefaultPort) {
                strErr = _("Invalid port detected in masternode.conf") + "\n" +
                        strprintf(_("Line: %d"), linenumber) + "\n\"" + line + "\"" + "\n" +
                        strprintf(_("(must be %d for mainnet)"), mainnetDefaultPort);
                streamConfig.close();
                return false;
            }
        } else if(CService(ip).GetPort() == mainnetDefaultPort) {
            strErr = _("Invalid port detected in masternode.conf") + "\n" +
                    strprintf(_("Line: %d"), linenumber) + "\n\"" + line + "\"" + "\n" +
                    strprintf(_("(%d could be used only on mainnet)"), mainnetDefaultPort);
            streamConfig.close();
            return false;
        }

        add(alias, ip, privKey, txHash, outputIndex);
    }

    streamConfig.close();
    return true;
}
<commit_msg>fix CMasternodeConfig::read()<commit_after>
#include "net.h"
#include "masternodeconfig.h"
#include "util.h"
#include "ui_interface.h"
#include "chainparams.h"

#include <boost/filesystem.hpp>
#include <boost/filesystem/fstream.hpp>

CMasternodeConfig masternodeConfig;

void CMasternodeConfig::add(std::string alias, std::string ip, std::string privKey, std::string txHash, std::string outputIndex) {
    CMasternodeEntry cme(alias, ip, privKey, txHash, outputIndex);
    entries.push_back(cme);
}

bool CMasternodeConfig::read(std::string& strErr) {
    int linenumber = 1;
    boost::filesystem::path pathMasternodeConfigFile = GetMasternodeConfigFile();
    boost::filesystem::ifstream streamConfig(pathMasternodeConfigFile);

    LogPrintf("loading masternode file at %s\n", pathMasternodeConfigFile.string());

    if (!streamConfig.good()) {
        FILE* configFile = fopen(pathMasternodeConfigFile.string().c_str(), "a");
        if (configFile != NULL) {
            std::string strHeader = "# Masternode config file\n"
                          "# Format: alias IP:port masternodeprivkey collateral_output_txid collateral_output_index\n"
                          "# Example: mn1 127.0.0.2:19999 93HaYBVUCYjEMeeH1Y4sBGLALQZE1Yc1K64xiqgX37tGBDQL8Xg 2bcd3c84c84f87eaa86e4e56834c92927a07f9e18718810b92e0d0324456a67c 0\n";
            fwrite(strHeader.c_str(), std::strlen(strHeader.c_str()), 1, configFile);
            fclose(configFile);
        }
        return true; // Nothing to read, so just return
    }

    for(std::string line; std::getline(streamConfig, line); linenumber++)
    {
        if(line.empty()) continue;

        std::istringstream iss(line);
        std::string comment, alias, ip, privKey, txHash, outputIndex;

        if (iss >> comment) {
            if(comment.at(0) == '#') continue;
            iss.str(line);
            iss.clear();
        }

        if (!(iss >> alias >> ip >> privKey >> txHash >> outputIndex)) {
            iss.str(line);
            iss.clear();
            if (!(iss >> alias >> ip >> privKey >> txHash >> outputIndex)) {
                strErr = _("Could not parse masternode.conf") + "\n" +
                        strprintf(_("Line: %d"), linenumber) + "\n\"" + line + "\"";
                streamConfig.close();
                return false;
            }
        }

        int mainnetDefaultPort = Params(CBaseChainParams::MAIN).GetDefaultPort();
        if(Params().NetworkIDString() == CBaseChainParams::MAIN) {
            if(CService(ip).GetPort() != mainnetDefaultPort) {
                strErr = _("Invalid port detected in masternode.conf") + "\n" +
                        strprintf(_("Line: %d"), linenumber) + "\n\"" + line + "\"" + "\n" +
                        strprintf(_("(must be %d for mainnet)"), mainnetDefaultPort);
                streamConfig.close();
                return false;
            }
        } else if(CService(ip).GetPort() == mainnetDefaultPort) {
            strErr = _("Invalid port detected in masternode.conf") + "\n" +
                    strprintf(_("Line: %d"), linenumber) + "\n\"" + line + "\"" + "\n" +
                    strprintf(_("(%d could be used only on mainnet)"), mainnetDefaultPort);
            streamConfig.close();
            return false;
        }

        add(alias, ip, privKey, txHash, outputIndex);
    }

    streamConfig.close();
    return true;
}
<|endoftext|>


<commit_before>/****************************************************************************
 * Copyright (c) 2012-2018 by the DataTransferKit authors                   *
 * All rights reserved.                                                     *
 *                                                                          *
 * This file is part of the DataTransferKit library. DataTransferKit is     *
 * distributed under a BSD 3-clause license. For the licensing terms see    *
 * the LICENSE file in the top-level directory.                             *
 *                                                                          *
 * SPDX-License-Identifier: BSD-3-Clause                                    *
 ****************************************************************************/
#ifndef DTK_DETAILS_CONCEPTS_HPP
#define DTK_DETAILS_CONCEPTS_HPP

#include <DTK_DetailsAlgorithms.hpp>

#include <type_traits>

#if !defined( __cpp_lib_void_t )
namespace std
{
template <typename...>
using void_t = void;
}
#endif

namespace DataTransferKit
{
namespace Details
{

// Checks for existence of a free function that expands an object of type
// Geometry using an object of type Other
template <typename Geometry, typename Other, typename = void>
struct is_expandable : std::false_type
{
};

template <typename Geometry, typename Other>
struct is_expandable<
    Geometry, Other,
    std::void_t<decltype(
        expand( std::declval<Geometry &>(), std::declval<Other const &>() ) )>>
    : std::true_type
{
};

// Checks for existence of a free function that calculates the centroid of an
// object of type Geometry
template <typename Geometry, typename Point, typename = void>
struct has_centroid : std::false_type
{
};

template <typename Geometry, typename Point>
struct has_centroid<
    Geometry, Point,
    std::void_t<decltype( centroid( std::declval<Geometry const &>(),
                                    std::declval<Point &>() ) )>>
    : std::true_type
{
};

} // namespace Details
} // namespace DataTransferKit

#endif
<commit_msg>Use prepocessor directives to hide concepts from Doxygen that had trouble parsing<commit_after>/****************************************************************************
 * Copyright (c) 2012-2018 by the DataTransferKit authors                   *
 * All rights reserved.                                                     *
 *                                                                          *
 * This file is part of the DataTransferKit library. DataTransferKit is     *
 * distributed under a BSD 3-clause license. For the licensing terms see    *
 * the LICENSE file in the top-level directory.                             *
 *                                                                          *
 * SPDX-License-Identifier: BSD-3-Clause                                    *
 ****************************************************************************/
#ifndef DTK_DETAILS_CONCEPTS_HPP
#define DTK_DETAILS_CONCEPTS_HPP

#include <DTK_DetailsAlgorithms.hpp>

#include <type_traits>

#if !defined( __cpp_lib_void_t )
namespace std
{
template <typename...>
using void_t = void;
}
#endif

#if !defined( DOXYGEN_SHOULD_SKIP_THIS )
namespace DataTransferKit
{
namespace Details
{

// Checks for existence of a free function that expands an object of type
// Geometry using an object of type Other
template <typename Geometry, typename Other, typename = void>
struct is_expandable : std::false_type
{
};

template <typename Geometry, typename Other>
struct is_expandable<
    Geometry, Other,
    std::void_t<decltype(
        expand( std::declval<Geometry &>(), std::declval<Other const &>() ) )>>
    : std::true_type
{
};

// Checks for existence of a free function that calculates the centroid of an
// object of type Geometry
template <typename Geometry, typename Point, typename = void>
struct has_centroid : std::false_type
{
};

template <typename Geometry, typename Point>
struct has_centroid<
    Geometry, Point,
    std::void_t<decltype( centroid( std::declval<Geometry const &>(),
                                    std::declval<Point &>() ) )>>
    : std::true_type
{
};

} // namespace Details
} // namespace DataTransferKit
#endif // DOXYGEN_SHOULD_SKIP_THIS

#endif
<|endoftext|>


<commit_before>#include "vec3.h"

namespace fd {
namespace core {
namespace math {

vec3::vec3() : x(0), y(0), z(0) {}

vec3::vec3(float32 x, float32 y, float32 z) : x(x), y(y), z(z) {}

#pragma region vec-vec
//Asss
//float32
vec3& vec3::Add(const vec3& v) {
	__m128 vxmm = _mm_set_ps(0, v.z, v.y, v.x);
	__m128 xmm = _mm_set_ps(0, z, y, x);
	xmm = _mm_add_ps(xmm, vxmm);

	x = M128(xmm, 0);
	y = M128(xmm, 1);
	z = M128(xmm, 2);

	return *this;
}

//sub
//float32
vec3& vec3::Sub(const vec3& v) {
	__m128 vxmm = _mm_set_ps(0, v.z, v.y, v.x);
	__m128 xmm = _mm_set_ps(0, z, y, x);
	xmm = _mm_sub_ps(xmm, vxmm);

	x = M128(xmm, 0);
	y = M128(xmm, 1);
	z = M128(xmm, 2);

	return *this;
}

//Mul
//float32
vec3& vec3::Mul(const vec3& v) {
	__m128 vxmm = _mm_set_ps(0, v.z, v.y, v.x);
	__m128 xmm = _mm_set_ps(0, z, y, x);
	xmm = _mm_mul_ps(xmm, vxmm);

	x = M128(xmm, 0);
	y = M128(xmm, 1);
	z = M128(xmm, 2);

	return *this;
}

//Div
//float32
vec3& vec3::Div(const vec3& v) {
	__m128 vxmm = _mm_set_ps(0, v.z, v.y, v.x);
	__m128 xmm = _mm_set_ps(0, z, y, x);
	xmm = _mm_div_ps(xmm, vxmm);

	x = M128(xmm, 0);
	y = M128(xmm, 1);
	z = M128(xmm, 2);

	return *this;
}

#pragma endregion

#pragma region vec-shit

//Add
//float32
vec3& vec3::Add(float32 v) {
	__m128 vxmm = _mm_set_ps(0, v, v, v);
	__m128 xmm = _mm_set_ps(0, z, y, x);
	xmm = _mm_add_ps(xmm, vxmm);

	x = M128(xmm, 0);
	y = M128(xmm, 1);
	z = M128(xmm, 2);

	return *this;
}

//Sub
//float32
vec3& vec3::Sub(float32 v) {
	__m128 vxmm = _mm_set_ps(0, v, v, v);
	__m128 xmm = _mm_set_ps(0, z, y, x);
	xmm = _mm_sub_ps(xmm, vxmm);

	x = M128(xmm, 0);
	y = M128(xmm, 1);
	z = M128(xmm, 2);

	return *this;
}

//Mul
//float32
vec3& vec3::Mul(float32 v) {
	__m128 vxmm = _mm_set_ps(0, v, v, v);
	__m128 xmm = _mm_set_ps(0, z, y, x);
	xmm = _mm_mul_ps(xmm, vxmm);

	x = M128(xmm, 0);
	y = M128(xmm, 1);
	z = M128(xmm, 2);

	return *this;
}

//Div
//float32
vec3& vec3::Div(float32 v) {
	__m128 vxmm = _mm_set_ps(0, v, v, v);
	__m128 xmm = _mm_set_ps(0, z, y, x);
	xmm = _mm_div_ps(xmm, vxmm);

	x = M128(xmm, 0);
	y = M128(xmm, 1);
	z = M128(xmm, 2);

	return *this;
}

float32 vec3::Length() const {
	return sqrtf(x * x + y * y + z * z);
}

vec3& vec3::Normalize() {
	return Mul(1.0f / Length());
}

vec3 vec3::Cross(const vec3& v) const {
	__m128 xmm0 = _mm_set_ps(0, x, z, y);
	__m128 vxmm0 = _mm_set_ps(0, v.y, v.x, v.z);

	__m128 xmm1 = _mm_set_ps(0, y, x, z);
	__m128 vxmm1 = _mm_set_ps(0, v.x, v.z, v.y);

	xmm0 = _mm_mul_ps(xmm0, vxmm0);
	xmm1 = _mm_mul_ps(xmm1, vxmm1);

	xmm0 = _mm_sub_ps(xmm0, xmm1);

	return vec3(M128(xmm, 0), M128(xmm, 1), M128(xmm, 2));
}

float32 vec3::Dot(const vec3& v) const {
	__m128 xmm = _mm_set_ps(0, v.z, v.y, v.x);
	xmm = _mm_mul_ps(xmm, _mm_set_ps(0, y, z, x));
	return M128(xmm, 0) + M128(xmm, 1) + M128(xmm, 2);
}

#pragma endregion

}
}
}<commit_msg>I'm stupid<commit_after>#include "vec3.h"

namespace fd {
namespace core {
namespace math {

vec3::vec3() : x(0), y(0), z(0) {}

vec3::vec3(float32 x, float32 y, float32 z) : x(x), y(y), z(z) {}

#pragma region vec-vec
//Asss
//float32
vec3& vec3::Add(const vec3& v) {
	__m128 vxmm = _mm_set_ps(0, v.z, v.y, v.x);
	__m128 xmm = _mm_set_ps(0, z, y, x);
	xmm = _mm_add_ps(xmm, vxmm);

	x = M128(xmm, 0);
	y = M128(xmm, 1);
	z = M128(xmm, 2);

	return *this;
}

//sub
//float32
vec3& vec3::Sub(const vec3& v) {
	__m128 vxmm = _mm_set_ps(0, v.z, v.y, v.x);
	__m128 xmm = _mm_set_ps(0, z, y, x);
	xmm = _mm_sub_ps(xmm, vxmm);

	x = M128(xmm, 0);
	y = M128(xmm, 1);
	z = M128(xmm, 2);

	return *this;
}

//Mul
//float32
vec3& vec3::Mul(const vec3& v) {
	__m128 vxmm = _mm_set_ps(0, v.z, v.y, v.x);
	__m128 xmm = _mm_set_ps(0, z, y, x);
	xmm = _mm_mul_ps(xmm, vxmm);

	x = M128(xmm, 0);
	y = M128(xmm, 1);
	z = M128(xmm, 2);

	return *this;
}

//Div
//float32
vec3& vec3::Div(const vec3& v) {
	__m128 vxmm = _mm_set_ps(0, v.z, v.y, v.x);
	__m128 xmm = _mm_set_ps(0, z, y, x);
	xmm = _mm_div_ps(xmm, vxmm);

	x = M128(xmm, 0);
	y = M128(xmm, 1);
	z = M128(xmm, 2);

	return *this;
}

#pragma endregion

#pragma region vec-shit

//Add
//float32
vec3& vec3::Add(float32 v) {
	__m128 vxmm = _mm_set_ps(0, v, v, v);
	__m128 xmm = _mm_set_ps(0, z, y, x);
	xmm = _mm_add_ps(xmm, vxmm);

	x = M128(xmm, 0);
	y = M128(xmm, 1);
	z = M128(xmm, 2);

	return *this;
}

//Sub
//float32
vec3& vec3::Sub(float32 v) {
	__m128 vxmm = _mm_set_ps(0, v, v, v);
	__m128 xmm = _mm_set_ps(0, z, y, x);
	xmm = _mm_sub_ps(xmm, vxmm);

	x = M128(xmm, 0);
	y = M128(xmm, 1);
	z = M128(xmm, 2);

	return *this;
}

//Mul
//float32
vec3& vec3::Mul(float32 v) {
	__m128 vxmm = _mm_set_ps(0, v, v, v);
	__m128 xmm = _mm_set_ps(0, z, y, x);
	xmm = _mm_mul_ps(xmm, vxmm);

	x = M128(xmm, 0);
	y = M128(xmm, 1);
	z = M128(xmm, 2);

	return *this;
}

//Div
//float32
vec3& vec3::Div(float32 v) {
	__m128 vxmm = _mm_set_ps(0, v, v, v);
	__m128 xmm = _mm_set_ps(0, z, y, x);
	xmm = _mm_div_ps(xmm, vxmm);

	x = M128(xmm, 0);
	y = M128(xmm, 1);
	z = M128(xmm, 2);

	return *this;
}

float32 vec3::Length() const {
	return sqrtf(x * x + y * y + z * z);
}

vec3& vec3::Normalize() {
	return Mul(1.0f / Length());
}

vec3 vec3::Cross(const vec3& v) const {
	__m128 xmm0 = _mm_set_ps(0, x, z, y);
	__m128 vxmm0 = _mm_set_ps(0, v.y, v.x, v.z);

	__m128 xmm1 = _mm_set_ps(0, y, x, z);
	__m128 vxmm1 = _mm_set_ps(0, v.x, v.z, v.y);

	xmm0 = _mm_mul_ps(xmm0, vxmm0);
	xmm1 = _mm_mul_ps(xmm1, vxmm1);

	xmm0 = _mm_sub_ps(xmm0, xmm1);

	return vec3(M128(xmm0, 0), M128(xmm0, 1), M128(xmm0, 2));
}

float32 vec3::Dot(const vec3& v) const {
	__m128 xmm = _mm_set_ps(0, v.z, v.y, v.x);
	xmm = _mm_mul_ps(xmm, _mm_set_ps(0, y, z, x));
	return M128(xmm, 0) + M128(xmm, 1) + M128(xmm, 2);
}

#pragma endregion

}
}
}<|endoftext|>