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

#include <string>

#include "app/l10n_util.h"
#include "base/sys_info.h"
#include "chrome/browser/app_modal_dialog.h"
#include "chrome/browser/browser.h"
#include "chrome/browser/browser_process.h"
#include "chrome/browser/renderer_host/render_process_host.h"
#include "chrome/browser/tab_contents/tab_contents.h"
#include "chrome/common/page_transition_types.h"
#include "chrome/test/in_process_browser_test.h"
#include "chrome/test/ui_test_utils.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "grit/chromium_strings.h"
#include "grit/generated_resources.h"

const std::string BEFORE_UNLOAD_HTML =
    "<title>beforeunload</title>"
    ""
    "";

const std::wstring OPEN_NEW_BEFOREUNLOAD_PAGE =
    L"w=window.open(); w.onbeforeunload=function(e){return 'foo'};";

namespace {

// Given a page title, returns the expected window caption string.
std::wstring WindowCaptionFromPageTitle(std::wstring page_title) {
#if defined(OS_WIN) || defined(OS_LINUX)
  if (page_title.empty())
    return l10n_util::GetString(IDS_PRODUCT_NAME);

  return l10n_util::GetStringF(IDS_BROWSER_WINDOW_TITLE_FORMAT, page_title);
#elif defined(OS_MACOSX)
  // On Mac, we don't want to suffix the page title with the application name.
  if (page_title.empty())
    return l10n_util::GetString(IDS_BROWSER_WINDOW_MAC_TAB_UNTITLED);
  return page_title;
#endif
}

// Returns the number of active RenderProcessHosts.
int CountRenderProcessHosts() {
  int result = 0;
  for (RenderProcessHost::iterator i(RenderProcessHost::AllHostsIterator());
       !i.IsAtEnd(); i.Advance())
    ++result;
  return result;
}

}  // namespace

class BrowserTest : public InProcessBrowserTest {
 protected:
  // In RTL locales wrap the page title with RTL embedding characters so that it
  // matches the value returned by GetWindowTitle().
  std::wstring LocaleWindowCaptionFromPageTitle(
      const std::wstring& expected_title) {
    std::wstring page_title = WindowCaptionFromPageTitle(expected_title);
#if defined(OS_WIN)
    std::string locale = g_browser_process->GetApplicationLocale();
    if (l10n_util::GetTextDirectionForLocale(locale.c_str()) ==
        l10n_util::RIGHT_TO_LEFT) {
      l10n_util::WrapStringWithLTRFormatting(&page_title);
    }

    return page_title;
#else
    // Do we need to use the above code on POSIX as well?
    return page_title;
#endif
  }
};

// Launch the app on a page with no title, check that the app title was set
// correctly.
IN_PROC_BROWSER_TEST_F(BrowserTest, NoTitle) {
  ui_test_utils::NavigateToURL(browser(),
                               ui_test_utils::GetTestUrl(L".", L"title1.html"));
  EXPECT_EQ(LocaleWindowCaptionFromPageTitle(L"title1.html"),
            UTF16ToWideHack(browser()->GetWindowTitleForCurrentTab()));
  string16 tab_title;
  ASSERT_TRUE(ui_test_utils::GetCurrentTabTitle(browser(), &tab_title));
  EXPECT_EQ(ASCIIToUTF16("title1.html"), tab_title);
}

// Launch the app, navigate to a page with a title, check that the app title
// was set correctly.
IN_PROC_BROWSER_TEST_F(BrowserTest, Title) {
  ui_test_utils::NavigateToURL(browser(),
                               ui_test_utils::GetTestUrl(L".", L"title2.html"));
  const std::wstring test_title(L"Title Of Awesomeness");
  EXPECT_EQ(LocaleWindowCaptionFromPageTitle(test_title),
            UTF16ToWideHack(browser()->GetWindowTitleForCurrentTab()));
  string16 tab_title;
  ASSERT_TRUE(ui_test_utils::GetCurrentTabTitle(browser(), &tab_title));
  EXPECT_EQ(WideToUTF16(test_title), tab_title);
}

#if !defined(OS_MACOSX)
// TODO(port): BUG16322
IN_PROC_BROWSER_TEST_F(BrowserTest, JavascriptAlertActivatesTab) {
  GURL url(ui_test_utils::GetTestUrl(L".", L"title1.html"));
  ui_test_utils::NavigateToURL(browser(), url);
  browser()->AddTabWithURL(url, GURL(), PageTransition::TYPED,
                           true, 0, false, NULL);
  EXPECT_EQ(2, browser()->tab_count());
  EXPECT_EQ(0, browser()->selected_index());
  TabContents* second_tab = browser()->GetTabContentsAt(1);
  ASSERT_TRUE(second_tab);
  second_tab->render_view_host()->ExecuteJavascriptInWebFrame(L"",
      L"alert('Activate!');");
  AppModalDialog* alert = ui_test_utils::WaitForAppModalDialog();
  alert->CloseModalDialog();
  EXPECT_EQ(2, browser()->tab_count());
  EXPECT_EQ(1, browser()->selected_index());
}
#endif  // !defined(OS_MACOSX)

// Create 34 tabs and verify that a lot of processes have been created. The
// exact number of processes depends on the amount of memory. Previously we
// had a hard limit of 31 processes and this test is mainly directed at
// verifying that we don't crash when we pass this limit.
IN_PROC_BROWSER_TEST_F(BrowserTest, ThirtyFourTabs) {
  GURL url(ui_test_utils::GetTestUrl(L".", L"title2.html"));

  // There is one initial tab.
  for (int ix = 0; ix != 33; ++ix) {
    browser()->AddTabWithURL(url, GURL(), PageTransition::TYPED,
                             true, 0, false, NULL);
  }
  EXPECT_EQ(34, browser()->tab_count());

  // See browser\renderer_host\render_process_host.cc for the algorithm to
  // decide how many processes to create.
  if (base::SysInfo::AmountOfPhysicalMemoryMB() >= 2048) {
    EXPECT_GE(CountRenderProcessHosts(), 24);
  } else {
    EXPECT_LE(CountRenderProcessHosts(), 23);
  }
}

// Test for crbug.com/22004.  Reloading a page with a before unload handler and
// then canceling the dialog should not leave the throbber spinning.
IN_PROC_BROWSER_TEST_F(BrowserTest, ReloadThenCancelBeforeUnload) {
  GURL url("data:text/html," + BEFORE_UNLOAD_HTML);
  ui_test_utils::NavigateToURL(browser(), url);

  // Navigate to another page, but click cancel in the dialog.  Make sure that
  // the throbber stops spinning.
  browser()->Reload();
  AppModalDialog* alert = ui_test_utils::WaitForAppModalDialog();
  alert->CloseModalDialog();
  EXPECT_FALSE(browser()->GetSelectedTabContents()->is_loading());

  // Clear the beforeunload handler so the test can easily exit.
  browser()->GetSelectedTabContents()->render_view_host()->
      ExecuteJavascriptInWebFrame(L"", L"onbeforeunload=null;");
}

// Test for crbug.com/11647.  A page closed with window.close() should not have
// two beforeunload dialogs shown.
IN_PROC_BROWSER_TEST_F(BrowserTest, SingleBeforeUnloadAfterWindowClose) {
  browser()->GetSelectedTabContents()->render_view_host()->
      ExecuteJavascriptInWebFrame(L"", OPEN_NEW_BEFOREUNLOAD_PAGE);

  // Close the new window with JavaScript, which should show a single
  // beforeunload dialog.  Then show another alert, to make it easy to verify
  // that a second beforeunload dialog isn't shown.
  browser()->GetTabContentsAt(0)->render_view_host()->
      ExecuteJavascriptInWebFrame(L"", L"w.close(); alert('bar');");
  AppModalDialog* alert = ui_test_utils::WaitForAppModalDialog();
  alert->AcceptWindow();

  alert = ui_test_utils::WaitForAppModalDialog();
  EXPECT_FALSE(alert->is_before_unload_dialog());
  alert->AcceptWindow();
}

// Test that get_process_idle_time() returns reasonable values when compared
// with time deltas measured locally.
IN_PROC_BROWSER_TEST_F(BrowserTest, RenderIdleTime) {
  base::TimeTicks start = base::TimeTicks::Now();
  ui_test_utils::NavigateToURL(browser(),
                               ui_test_utils::GetTestUrl(L".", L"title1.html"));
  RenderProcessHost::iterator it(RenderProcessHost::AllHostsIterator());
  for (; !it.IsAtEnd(); it.Advance()) {
    base::TimeDelta renderer_td =
        it.GetCurrentValue()->get_child_process_idle_time();
    base::TimeDelta browser_td = base::TimeTicks::Now() - start;
    EXPECT_TRUE(browser_td >= renderer_td);
  }
}
<commit_msg>Mark BrowserTest.SingleBeforeUnloadAfterWindowClose as flaky.<commit_after>// Copyright (c) 2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include <string>

#include "app/l10n_util.h"
#include "base/sys_info.h"
#include "chrome/browser/app_modal_dialog.h"
#include "chrome/browser/browser.h"
#include "chrome/browser/browser_process.h"
#include "chrome/browser/renderer_host/render_process_host.h"
#include "chrome/browser/tab_contents/tab_contents.h"
#include "chrome/common/page_transition_types.h"
#include "chrome/test/in_process_browser_test.h"
#include "chrome/test/ui_test_utils.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "grit/chromium_strings.h"
#include "grit/generated_resources.h"

const std::string BEFORE_UNLOAD_HTML =
    "<title>beforeunload</title>"
    ""
    "";

const std::wstring OPEN_NEW_BEFOREUNLOAD_PAGE =
    L"w=window.open(); w.onbeforeunload=function(e){return 'foo'};";

namespace {

// Given a page title, returns the expected window caption string.
std::wstring WindowCaptionFromPageTitle(std::wstring page_title) {
#if defined(OS_WIN) || defined(OS_LINUX)
  if (page_title.empty())
    return l10n_util::GetString(IDS_PRODUCT_NAME);

  return l10n_util::GetStringF(IDS_BROWSER_WINDOW_TITLE_FORMAT, page_title);
#elif defined(OS_MACOSX)
  // On Mac, we don't want to suffix the page title with the application name.
  if (page_title.empty())
    return l10n_util::GetString(IDS_BROWSER_WINDOW_MAC_TAB_UNTITLED);
  return page_title;
#endif
}

// Returns the number of active RenderProcessHosts.
int CountRenderProcessHosts() {
  int result = 0;
  for (RenderProcessHost::iterator i(RenderProcessHost::AllHostsIterator());
       !i.IsAtEnd(); i.Advance())
    ++result;
  return result;
}

}  // namespace

class BrowserTest : public InProcessBrowserTest {
 protected:
  // In RTL locales wrap the page title with RTL embedding characters so that it
  // matches the value returned by GetWindowTitle().
  std::wstring LocaleWindowCaptionFromPageTitle(
      const std::wstring& expected_title) {
    std::wstring page_title = WindowCaptionFromPageTitle(expected_title);
#if defined(OS_WIN)
    std::string locale = g_browser_process->GetApplicationLocale();
    if (l10n_util::GetTextDirectionForLocale(locale.c_str()) ==
        l10n_util::RIGHT_TO_LEFT) {
      l10n_util::WrapStringWithLTRFormatting(&page_title);
    }

    return page_title;
#else
    // Do we need to use the above code on POSIX as well?
    return page_title;
#endif
  }
};

// Launch the app on a page with no title, check that the app title was set
// correctly.
IN_PROC_BROWSER_TEST_F(BrowserTest, NoTitle) {
  ui_test_utils::NavigateToURL(browser(),
                               ui_test_utils::GetTestUrl(L".", L"title1.html"));
  EXPECT_EQ(LocaleWindowCaptionFromPageTitle(L"title1.html"),
            UTF16ToWideHack(browser()->GetWindowTitleForCurrentTab()));
  string16 tab_title;
  ASSERT_TRUE(ui_test_utils::GetCurrentTabTitle(browser(), &tab_title));
  EXPECT_EQ(ASCIIToUTF16("title1.html"), tab_title);
}

// Launch the app, navigate to a page with a title, check that the app title
// was set correctly.
IN_PROC_BROWSER_TEST_F(BrowserTest, Title) {
  ui_test_utils::NavigateToURL(browser(),
                               ui_test_utils::GetTestUrl(L".", L"title2.html"));
  const std::wstring test_title(L"Title Of Awesomeness");
  EXPECT_EQ(LocaleWindowCaptionFromPageTitle(test_title),
            UTF16ToWideHack(browser()->GetWindowTitleForCurrentTab()));
  string16 tab_title;
  ASSERT_TRUE(ui_test_utils::GetCurrentTabTitle(browser(), &tab_title));
  EXPECT_EQ(WideToUTF16(test_title), tab_title);
}

#if !defined(OS_MACOSX)
// TODO(port): BUG16322
IN_PROC_BROWSER_TEST_F(BrowserTest, JavascriptAlertActivatesTab) {
  GURL url(ui_test_utils::GetTestUrl(L".", L"title1.html"));
  ui_test_utils::NavigateToURL(browser(), url);
  browser()->AddTabWithURL(url, GURL(), PageTransition::TYPED,
                           true, 0, false, NULL);
  EXPECT_EQ(2, browser()->tab_count());
  EXPECT_EQ(0, browser()->selected_index());
  TabContents* second_tab = browser()->GetTabContentsAt(1);
  ASSERT_TRUE(second_tab);
  second_tab->render_view_host()->ExecuteJavascriptInWebFrame(L"",
      L"alert('Activate!');");
  AppModalDialog* alert = ui_test_utils::WaitForAppModalDialog();
  alert->CloseModalDialog();
  EXPECT_EQ(2, browser()->tab_count());
  EXPECT_EQ(1, browser()->selected_index());
}
#endif  // !defined(OS_MACOSX)

// Create 34 tabs and verify that a lot of processes have been created. The
// exact number of processes depends on the amount of memory. Previously we
// had a hard limit of 31 processes and this test is mainly directed at
// verifying that we don't crash when we pass this limit.
IN_PROC_BROWSER_TEST_F(BrowserTest, ThirtyFourTabs) {
  GURL url(ui_test_utils::GetTestUrl(L".", L"title2.html"));

  // There is one initial tab.
  for (int ix = 0; ix != 33; ++ix) {
    browser()->AddTabWithURL(url, GURL(), PageTransition::TYPED,
                             true, 0, false, NULL);
  }
  EXPECT_EQ(34, browser()->tab_count());

  // See browser\renderer_host\render_process_host.cc for the algorithm to
  // decide how many processes to create.
  if (base::SysInfo::AmountOfPhysicalMemoryMB() >= 2048) {
    EXPECT_GE(CountRenderProcessHosts(), 24);
  } else {
    EXPECT_LE(CountRenderProcessHosts(), 23);
  }
}

// Test for crbug.com/22004.  Reloading a page with a before unload handler and
// then canceling the dialog should not leave the throbber spinning.
IN_PROC_BROWSER_TEST_F(BrowserTest, ReloadThenCancelBeforeUnload) {
  GURL url("data:text/html," + BEFORE_UNLOAD_HTML);
  ui_test_utils::NavigateToURL(browser(), url);

  // Navigate to another page, but click cancel in the dialog.  Make sure that
  // the throbber stops spinning.
  browser()->Reload();
  AppModalDialog* alert = ui_test_utils::WaitForAppModalDialog();
  alert->CloseModalDialog();
  EXPECT_FALSE(browser()->GetSelectedTabContents()->is_loading());

  // Clear the beforeunload handler so the test can easily exit.
  browser()->GetSelectedTabContents()->render_view_host()->
      ExecuteJavascriptInWebFrame(L"", L"onbeforeunload=null;");
}

// Test for crbug.com/11647.  A page closed with window.close() should not have
// two beforeunload dialogs shown.
IN_PROC_BROWSER_TEST_F(BrowserTest, FLAKY_SingleBeforeUnloadAfterWindowClose) {
  browser()->GetSelectedTabContents()->render_view_host()->
      ExecuteJavascriptInWebFrame(L"", OPEN_NEW_BEFOREUNLOAD_PAGE);

  // Close the new window with JavaScript, which should show a single
  // beforeunload dialog.  Then show another alert, to make it easy to verify
  // that a second beforeunload dialog isn't shown.
  browser()->GetTabContentsAt(0)->render_view_host()->
      ExecuteJavascriptInWebFrame(L"", L"w.close(); alert('bar');");
  AppModalDialog* alert = ui_test_utils::WaitForAppModalDialog();
  alert->AcceptWindow();

  alert = ui_test_utils::WaitForAppModalDialog();
  EXPECT_FALSE(alert->is_before_unload_dialog());
  alert->AcceptWindow();
}

// Test that get_process_idle_time() returns reasonable values when compared
// with time deltas measured locally.
IN_PROC_BROWSER_TEST_F(BrowserTest, RenderIdleTime) {
  base::TimeTicks start = base::TimeTicks::Now();
  ui_test_utils::NavigateToURL(browser(),
                               ui_test_utils::GetTestUrl(L".", L"title1.html"));
  RenderProcessHost::iterator it(RenderProcessHost::AllHostsIterator());
  for (; !it.IsAtEnd(); it.Advance()) {
    base::TimeDelta renderer_td =
        it.GetCurrentValue()->get_child_process_idle_time();
    base::TimeDelta browser_td = base::TimeTicks::Now() - start;
    EXPECT_TRUE(browser_td >= renderer_td);
  }
}
<|endoftext|>


<commit_before>#define SCREEN_HEIGHT 480
#define SCREEN_WIDTH 640

namespace kb {

// SCENE (BASE) ================================================================
class Scene {
private:

protected:
    sf::RenderWindow* app;
    Scene* id_scene;

public:
    virtual bool init(sf::RenderWindow* app, Scene *id);
    virtual char step();
    virtual void draw();
};

// SCENE0 ======================================================================
class Scene0 : public Scene {
private:
    sf::Font* font;
    sf::Text* text;

public:
    bool init(sf::RenderWindow* app, Scene *id);
    char step();
    void draw();
};

// SCENE1 ======================================================================
class Scene1 : public Scene {
private:
    sf::Sprite *image_index;
    sf::Texture* image_texture;

public:
    bool init(sf::RenderWindow* app, Scene *id);
    char step();
    void draw();
};

};
<commit_msg>edit screen_height and screen width<commit_after>#define SCREEN_HEIGHT 640
#define SCREEN_WIDTH 1200

namespace kb {

// SCENE (BASE) ================================================================
class Scene {
private:

protected:
    sf::RenderWindow* app;
    Scene* id_scene;

public:
    virtual bool init(sf::RenderWindow* app, Scene *id);
    virtual char step();
    virtual void draw();
};

// SCENE0 ======================================================================
class Scene0 : public Scene {
private:
    sf::Font* font;
    sf::Text* text;

public:
    bool init(sf::RenderWindow* app, Scene *id);
    char step();
    void draw();
};

// SCENE1 ======================================================================
class Scene1 : public Scene {
private:
    sf::Sprite *image_index;
    sf::Texture* image_texture;

public:
    bool init(sf::RenderWindow* app, Scene *id);
    char step();
    void draw();
};

};
<|endoftext|>


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

#include "chrome/browser/browser_url_handler.h"

#include "base/string_util.h"
#include "chrome/browser/browser_about_handler.h"
#include "chrome/browser/extensions/extension_web_ui.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/ui/webui/chrome_web_ui_factory.h"
#include "chrome/common/url_constants.h"
#include "content/browser/webui/web_ui.h"
#include "googleurl/src/gurl.h"

// Handles rewriting view-source URLs for what we'll actually load.
static bool HandleViewSource(GURL* url, Profile* profile) {
  if (url->SchemeIs(chrome::kViewSourceScheme)) {
    // Load the inner URL instead.
    *url = GURL(url->path());

    // Bug 26129: limit view-source to view the content and not any
    // other kind of 'active' url scheme like 'javascript' or 'data'.
    static const char* const allowed_sub_schemes[] = {
      chrome::kHttpScheme, chrome::kHttpsScheme, chrome::kFtpScheme,
      chrome::kChromeDevToolsScheme, chrome::kChromeUIScheme,
      chrome::kFileScheme
    };

    bool is_sub_scheme_allowed = false;
    for (size_t i = 0; i < arraysize(allowed_sub_schemes); i++) {
      if (url->SchemeIs(allowed_sub_schemes[i])) {
        is_sub_scheme_allowed = true;
        break;
      }
    }

    if (!is_sub_scheme_allowed) {
      *url = GURL(chrome::kAboutBlankURL);
      return false;
    }

    return true;
  }
  return false;
}

// Turns a non view-source URL into the corresponding view-source URL.
static bool ReverseViewSource(GURL* url, Profile* profile) {
  // No action necessary if the URL is already view-source:
  if (url->SchemeIs(chrome::kViewSourceScheme))
    return false;

  url_canon::Replacements<char> repl;
  repl.SetScheme(chrome::kViewSourceScheme,
      url_parse::Component(0, strlen(chrome::kViewSourceScheme)));
  repl.SetPath(url->spec().c_str(),
      url_parse::Component(0, url->spec().size()));
  *url = url->ReplaceComponents(repl);
  return true;
}

// Handles rewriting Web UI URLs.
static bool HandleWebUI(GURL* url, Profile* profile) {
  if (!ChromeWebUIFactory::GetInstance()->UseWebUIForURL(profile, *url))
    return false;

  // Special case the new tab page. In older versions of Chrome, the new tab
  // page was hosted at chrome-internal:<blah>. This might be in people's saved
  // sessions or bookmarks, so we say any URL with that scheme triggers the new
  // tab page.
  if (url->SchemeIs(chrome::kChromeInternalScheme)) {
    // Rewrite it with the proper new tab URL.
    *url = GURL(chrome::kChromeUINewTabURL);
  }

  return true;
}

std::vector<BrowserURLHandler::HandlerPair> BrowserURLHandler::url_handlers_;

// static
void BrowserURLHandler::InitURLHandlers() {
  if (!url_handlers_.empty())
    return;

  // Visual Studio 2010 has problems converting NULL to the null pointer for
  // std::pair.  See http://connect.microsoft.com/VisualStudio/feedback/details/520043/error-converting-from-null-to-a-pointer-type-in-std-pair
  // It will work if we pass nullptr.
#if defined(_MSC_VER) && _MSC_VER >= 1600
  URLHandler null_handler = nullptr;
#else
  URLHandler null_handler = NULL;
#endif

  // Add the default URL handlers.
  url_handlers_.push_back(
      HandlerPair(&ExtensionWebUI::HandleChromeURLOverride, null_handler));
  // about:
  url_handlers_.push_back(HandlerPair(&WillHandleBrowserAboutURL,
                                      null_handler));
  // chrome: & friends.
  url_handlers_.push_back(HandlerPair(&HandleWebUI, null_handler));
  // view-source:
  url_handlers_.push_back(HandlerPair(&HandleViewSource, &ReverseViewSource));
}

// static
void BrowserURLHandler::RewriteURLIfNecessary(GURL* url, Profile* profile,
                                              bool* reverse_on_redirect) {
  if (url_handlers_.empty())
    InitURLHandlers();
  for (size_t i = 0; i < url_handlers_.size(); ++i) {
    if ((*url_handlers_[i].first)(url, profile)) {
      *reverse_on_redirect = (url_handlers_[i].second != NULL);
      return;
    }
  }
}

// static
bool BrowserURLHandler::ReverseURLRewrite(
    GURL* url, const GURL& original, Profile* profile) {
  for (size_t i = 0; i < url_handlers_.size(); ++i) {
    GURL test_url(original);
    if ((*url_handlers_[i].first)(&test_url, profile)) {
      if (url_handlers_[i].second)
        return (*url_handlers_[i].second)(url, profile);
      else
        return false;
    }
  }
  return false;
}
<commit_msg>BMC#19078 handling of special URLs not consistent.<commit_after>// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chrome/browser/browser_url_handler.h"

#include "base/command_line.h"
#include "base/string_util.h"
#include "chrome/browser/browser_about_handler.h"
#include "chrome/browser/extensions/extension_web_ui.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/ui/webui/chrome_web_ui_factory.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/common/url_constants.h"
#include "content/browser/webui/web_ui.h"
#include "googleurl/src/gurl.h"

// Handles rewriting view-source URLs for what we'll actually load.
static bool HandleViewSource(GURL* url, Profile* profile) {
  if (url->SchemeIs(chrome::kViewSourceScheme)) {
    // Load the inner URL instead.
    *url = GURL(url->path());

    // Bug 26129: limit view-source to view the content and not any
    // other kind of 'active' url scheme like 'javascript' or 'data'.
    static const char* const allowed_sub_schemes[] = {
      chrome::kHttpScheme, chrome::kHttpsScheme, chrome::kFtpScheme,
      chrome::kChromeDevToolsScheme, chrome::kChromeUIScheme,
      chrome::kFileScheme
    };

    bool is_sub_scheme_allowed = false;
    for (size_t i = 0; i < arraysize(allowed_sub_schemes); i++) {
      if (url->SchemeIs(allowed_sub_schemes[i])) {
        is_sub_scheme_allowed = true;
        break;
      }
    }

    if (!is_sub_scheme_allowed) {
      *url = GURL(chrome::kAboutBlankURL);
      return false;
    }

    return true;
  }
  return false;
}

// Turns a non view-source URL into the corresponding view-source URL.
static bool ReverseViewSource(GURL* url, Profile* profile) {
  // No action necessary if the URL is already view-source:
  if (url->SchemeIs(chrome::kViewSourceScheme))
    return false;

  url_canon::Replacements<char> repl;
  repl.SetScheme(chrome::kViewSourceScheme,
      url_parse::Component(0, strlen(chrome::kViewSourceScheme)));
  repl.SetPath(url->spec().c_str(),
      url_parse::Component(0, url->spec().size()));
  *url = url->ReplaceComponents(repl);
  return true;
}

// Handles rewriting Web UI URLs.
static bool HandleWebUI(GURL* url, Profile* profile) {
#if !defined(TOOLKIT_MEEGOTOUCH)
  if (!ChromeWebUIFactory::GetInstance()->UseWebUIForURL(profile, *url))
    return false;
#else
  if (!ChromeWebUIFactory::GetInstance()->UseWebUIForURL(profile, *url)) {
    // Let browser handle chrome:// urls like about:blank
    if(CommandLine::ForCurrentProcess()->HasSwitch(
       switches::kDisableChromeWebUi)) {
      if (url->SchemeIs(chrome::kChromeUIScheme) ||
          url->SchemeIs(chrome::kChromeDevToolsScheme) ||
          url->SchemeIs(chrome::kChromeInternalScheme)) {
        *url = GURL(chrome::kAboutBlankURL);
      }
    }
    return false;
  }
#endif

  // Special case the new tab page. In older versions of Chrome, the new tab
  // page was hosted at chrome-internal:<blah>. This might be in people's saved
  // sessions or bookmarks, so we say any URL with that scheme triggers the new
  // tab page.
  if (url->SchemeIs(chrome::kChromeInternalScheme)) {
    // Rewrite it with the proper new tab URL.
    *url = GURL(chrome::kChromeUINewTabURL);
  }

  return true;
}

std::vector<BrowserURLHandler::HandlerPair> BrowserURLHandler::url_handlers_;

// static
void BrowserURLHandler::InitURLHandlers() {
  if (!url_handlers_.empty())
    return;

  // Visual Studio 2010 has problems converting NULL to the null pointer for
  // std::pair.  See http://connect.microsoft.com/VisualStudio/feedback/details/520043/error-converting-from-null-to-a-pointer-type-in-std-pair
  // It will work if we pass nullptr.
#if defined(_MSC_VER) && _MSC_VER >= 1600
  URLHandler null_handler = nullptr;
#else
  URLHandler null_handler = NULL;
#endif

  // Add the default URL handlers.
  url_handlers_.push_back(
      HandlerPair(&ExtensionWebUI::HandleChromeURLOverride, null_handler));
  // about:
  url_handlers_.push_back(HandlerPair(&WillHandleBrowserAboutURL,
                                      null_handler));
  // chrome: & friends.
  url_handlers_.push_back(HandlerPair(&HandleWebUI, null_handler));
  // view-source:
  url_handlers_.push_back(HandlerPair(&HandleViewSource, &ReverseViewSource));
}

// static
void BrowserURLHandler::RewriteURLIfNecessary(GURL* url, Profile* profile,
                                              bool* reverse_on_redirect) {
  if (url_handlers_.empty())
    InitURLHandlers();
  for (size_t i = 0; i < url_handlers_.size(); ++i) {
    if ((*url_handlers_[i].first)(url, profile)) {
      *reverse_on_redirect = (url_handlers_[i].second != NULL);
      return;
    }
  }
}

// static
bool BrowserURLHandler::ReverseURLRewrite(
    GURL* url, const GURL& original, Profile* profile) {
  for (size_t i = 0; i < url_handlers_.size(); ++i) {
    GURL test_url(original);
    if ((*url_handlers_[i].first)(&test_url, profile)) {
      if (url_handlers_[i].second)
        return (*url_handlers_[i].second)(url, profile);
      else
        return false;
    }
  }
  return false;
}
<|endoftext|>


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

#include "chrome/browser/views/tab_icon_view.h"

#if defined(OS_WIN)
#include <windows.h>
#include <shellapi.h>
#endif

#include "app/gfx/canvas.h"
#include "app/gfx/favicon_size.h"
#include "app/resource_bundle.h"
#include "base/file_util.h"
#include "base/logging.h"
#include "base/path_service.h"
#include "chrome/app/chrome_dll_resource.h"
#include "chrome/browser/tab_contents/tab_contents.h"
#include "grit/app_resources.h"
#include "grit/theme_resources.h"

#if defined(OS_WIN)
#include "app/gfx/icon_util.h"
#endif

static bool g_initialized = false;
static SkBitmap* g_default_fav_icon = NULL;
static SkBitmap* g_throbber_frames = NULL;
static SkBitmap* g_throbber_frames_light = NULL;
static int g_throbber_frame_count;

// static
void TabIconView::InitializeIfNeeded() {
  if (!g_initialized) {
    ResourceBundle &rb = ResourceBundle::GetSharedInstance();

#if defined(OS_WIN)
    // The default window icon is the application icon, not the default
    // favicon.
    std::wstring exe_path;
    PathService::Get(base::DIR_EXE, &exe_path);
    file_util::AppendToPath(&exe_path, L"chrome.exe");
    HICON app_icon = ExtractIcon(NULL, exe_path.c_str(), 0);
    g_default_fav_icon =
        IconUtil::CreateSkBitmapFromHICON(app_icon, gfx::Size(16, 16));
    DestroyIcon(app_icon);
#else
    NOTIMPLEMENTED();
#endif

    g_throbber_frames = rb.GetBitmapNamed(IDR_THROBBER);
    g_throbber_frames_light = rb.GetBitmapNamed(IDR_THROBBER_LIGHT);
    g_throbber_frame_count = g_throbber_frames->width() /
        g_throbber_frames->height();

    // Verify that our light and dark styles have the same number of frames.
    DCHECK(g_throbber_frame_count ==
        g_throbber_frames_light->width() / g_throbber_frames_light->height());
    g_initialized = true;
  }
}

TabIconView::TabIconView(TabIconViewModel* model)
    : model_(model),
      throbber_running_(false),
      is_light_(false),
      throbber_frame_(0) {
  InitializeIfNeeded();
}

TabIconView::~TabIconView() {
}

void TabIconView::Update() {
  if (throbber_running_) {
    // We think the tab is loading.
    if (!model_->ShouldTabIconViewAnimate()) {
      // Woops, tab is invalid or not loading, reset our status and schedule
      // a paint.
      throbber_running_ = false;
      SchedulePaint();
    } else {
      // The tab is still loading, increment the frame.
      throbber_frame_ = (throbber_frame_ + 1) % g_throbber_frame_count;
      SchedulePaint();
    }
  } else if (model_->ShouldTabIconViewAnimate()) {
    // We didn't think we were loading, but the tab is loading. Reset the
    // frame and status and schedule a paint.
    throbber_running_ = true;
    throbber_frame_ = 0;
    SchedulePaint();
  }
}

void TabIconView::PaintThrobber(gfx::Canvas* canvas) {
  int image_size = g_throbber_frames->height();
  PaintIcon(canvas, is_light_ ? *g_throbber_frames_light : *g_throbber_frames,
            throbber_frame_ * image_size, 0, image_size, image_size, false);
}

void TabIconView::PaintFavIcon(gfx::Canvas* canvas, const SkBitmap& bitmap) {
  PaintIcon(canvas, bitmap, 0, 0, bitmap.width(), bitmap.height(), true);
}

void TabIconView::PaintIcon(gfx::Canvas* canvas,
                            const SkBitmap& bitmap,
                            int src_x,
                            int src_y,
                            int src_w,
                            int src_h,
                            bool filter) {
  // For source images smaller than the favicon square, scale them as if they
  // were padded to fit the favicon square, so we don't blow up tiny favicons
  // into larger or nonproportional results.
  float float_src_w = static_cast<float>(src_w);
  float float_src_h = static_cast<float>(src_h);
  float scalable_w, scalable_h;
  if (src_w <= kFavIconSize && src_h <= kFavIconSize) {
    scalable_w = scalable_h = kFavIconSize;
  } else {
    scalable_w = float_src_w;
    scalable_h = float_src_h;
  }

  // Scale proportionately.
  float scale = std::min(static_cast<float>(width()) / scalable_w,
                         static_cast<float>(height()) / scalable_h);
  int dest_w = static_cast<int>(float_src_w * scale);
  int dest_h = static_cast<int>(float_src_h * scale);

  // Center the scaled image.
  canvas->DrawBitmapInt(bitmap, src_x, src_y, src_w, src_h,
                        (width() - dest_w) / 2, (height() - dest_h) / 2, dest_w,
                        dest_h, filter);
}

void TabIconView::Paint(gfx::Canvas* canvas) {
  bool rendered = false;

  if (throbber_running_) {
    rendered = true;
    PaintThrobber(canvas);
  } else {
    SkBitmap favicon = model_->GetFavIconForTabIconView();
    if (!favicon.isNull()) {
      rendered = true;
      PaintFavIcon(canvas, favicon);
    }
  }

  if (!rendered)
    PaintFavIcon(canvas, *g_default_fav_icon);
}

gfx::Size TabIconView::GetPreferredSize() {
  return gfx::Size(kFavIconSize, kFavIconSize);
}
<commit_msg>Another fix for issue 13724: Don't hard code chrome.exe<commit_after>// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chrome/browser/views/tab_icon_view.h"

#if defined(OS_WIN)
#include <windows.h>
#include <shellapi.h>
#endif

#include "app/gfx/canvas.h"
#include "app/gfx/favicon_size.h"
#include "app/resource_bundle.h"
#include "base/file_util.h"
#include "base/logging.h"
#include "base/path_service.h"
#include "chrome/app/chrome_dll_resource.h"
#include "chrome/browser/tab_contents/tab_contents.h"
#include "chrome/common/chrome_constants.h"
#include "grit/app_resources.h"
#include "grit/theme_resources.h"

#if defined(OS_WIN)
#include "app/gfx/icon_util.h"
#endif

static bool g_initialized = false;
static SkBitmap* g_default_fav_icon = NULL;
static SkBitmap* g_throbber_frames = NULL;
static SkBitmap* g_throbber_frames_light = NULL;
static int g_throbber_frame_count;

// static
void TabIconView::InitializeIfNeeded() {
  if (!g_initialized) {
    ResourceBundle &rb = ResourceBundle::GetSharedInstance();

#if defined(OS_WIN)
    // The default window icon is the application icon, not the default
    // favicon.
    std::wstring exe_path;
    PathService::Get(base::DIR_EXE, &exe_path);
    file_util::AppendToPath(&exe_path,
        chrome::kBrowserProcessExecutableName);

    HICON app_icon = ExtractIcon(NULL, exe_path.c_str(), 0);
    g_default_fav_icon =
        IconUtil::CreateSkBitmapFromHICON(app_icon, gfx::Size(16, 16));
    DestroyIcon(app_icon);
#else
    NOTIMPLEMENTED();
#endif

    g_throbber_frames = rb.GetBitmapNamed(IDR_THROBBER);
    g_throbber_frames_light = rb.GetBitmapNamed(IDR_THROBBER_LIGHT);
    g_throbber_frame_count = g_throbber_frames->width() /
        g_throbber_frames->height();

    // Verify that our light and dark styles have the same number of frames.
    DCHECK(g_throbber_frame_count ==
        g_throbber_frames_light->width() / g_throbber_frames_light->height());
    g_initialized = true;
  }
}

TabIconView::TabIconView(TabIconViewModel* model)
    : model_(model),
      throbber_running_(false),
      is_light_(false),
      throbber_frame_(0) {
  InitializeIfNeeded();
}

TabIconView::~TabIconView() {
}

void TabIconView::Update() {
  if (throbber_running_) {
    // We think the tab is loading.
    if (!model_->ShouldTabIconViewAnimate()) {
      // Woops, tab is invalid or not loading, reset our status and schedule
      // a paint.
      throbber_running_ = false;
      SchedulePaint();
    } else {
      // The tab is still loading, increment the frame.
      throbber_frame_ = (throbber_frame_ + 1) % g_throbber_frame_count;
      SchedulePaint();
    }
  } else if (model_->ShouldTabIconViewAnimate()) {
    // We didn't think we were loading, but the tab is loading. Reset the
    // frame and status and schedule a paint.
    throbber_running_ = true;
    throbber_frame_ = 0;
    SchedulePaint();
  }
}

void TabIconView::PaintThrobber(gfx::Canvas* canvas) {
  int image_size = g_throbber_frames->height();
  PaintIcon(canvas, is_light_ ? *g_throbber_frames_light : *g_throbber_frames,
            throbber_frame_ * image_size, 0, image_size, image_size, false);
}

void TabIconView::PaintFavIcon(gfx::Canvas* canvas, const SkBitmap& bitmap) {
  PaintIcon(canvas, bitmap, 0, 0, bitmap.width(), bitmap.height(), true);
}

void TabIconView::PaintIcon(gfx::Canvas* canvas,
                            const SkBitmap& bitmap,
                            int src_x,
                            int src_y,
                            int src_w,
                            int src_h,
                            bool filter) {
  // For source images smaller than the favicon square, scale them as if they
  // were padded to fit the favicon square, so we don't blow up tiny favicons
  // into larger or nonproportional results.
  float float_src_w = static_cast<float>(src_w);
  float float_src_h = static_cast<float>(src_h);
  float scalable_w, scalable_h;
  if (src_w <= kFavIconSize && src_h <= kFavIconSize) {
    scalable_w = scalable_h = kFavIconSize;
  } else {
    scalable_w = float_src_w;
    scalable_h = float_src_h;
  }

  // Scale proportionately.
  float scale = std::min(static_cast<float>(width()) / scalable_w,
                         static_cast<float>(height()) / scalable_h);
  int dest_w = static_cast<int>(float_src_w * scale);
  int dest_h = static_cast<int>(float_src_h * scale);

  // Center the scaled image.
  canvas->DrawBitmapInt(bitmap, src_x, src_y, src_w, src_h,
                        (width() - dest_w) / 2, (height() - dest_h) / 2, dest_w,
                        dest_h, filter);
}

void TabIconView::Paint(gfx::Canvas* canvas) {
  bool rendered = false;

  if (throbber_running_) {
    rendered = true;
    PaintThrobber(canvas);
  } else {
    SkBitmap favicon = model_->GetFavIconForTabIconView();
    if (!favicon.isNull()) {
      rendered = true;
      PaintFavIcon(canvas, favicon);
    }
  }

  if (!rendered)
    PaintFavIcon(canvas, *g_default_fav_icon);
}

gfx::Size TabIconView::GetPreferredSize() {
  return gfx::Size(kFavIconSize, kFavIconSize);
}
<|endoftext|>


<commit_before>#include "Schema.hpp"
#include <sstream>

static std::string translateType(const DataType& type) {
  std::ostringstream stream;
  if(type.typeTag == DataTypeTag::Integer) {
    stream << "Integer";
  } else if(type.typeTag == DataTypeTag::Numeric) {
    stream << "Numeric<" << (int) type.attributes.numeric.integerPlaces
           << "," << (int) type.attributes.numeric.decimalPlaces << ">";
  } else if(type.typeTag == DataTypeTag::Char) {
    stream << "Char<" << (int) type.attributes.charLen << ">";
  } else if(type.typeTag == DataTypeTag::VarChar) {
    stream << "Varchar<" << (int) type.attributes.charLen << ">";
  } else if(type.typeTag == DataTypeTag::Date) {
    stream << "Date";
  } else if(type.typeTag == DataTypeTag::Timestamp) {
    stream << "Timestamp";
  }
  return stream.str();
}

template<typename T, typename Callable>
static void generateList(std::ostream& out, const std::vector<T>& elements, Callable cb, std::string seperator = ", ") {
  auto first = true;
  for(const auto& elem : elements) {
    if(!first) out << seperator;
    cb(out, elem);
    first = false;
  }
}

void Schema::generateCppCode(std::ostream& out) {
  out <<
    "#ifndef H_Schema\n"
    "#define H_Schema\n"
    "#include <vector>\n"
    "#include <map>\n"
    "#include <unordered_map>\n"
    "#include \"schema/Types.hpp\"\n";
  for(auto& table : tables) {
    out << "//--------------------------------------------------\n"
           "struct " << table.name << "_t {\n";
    // actual columns
    for(auto& column : table.columns) {
      out << "  std::vector<" << translateType(column.type) << "> col_" << column.name << ";\n";
    }
    // primary key index
    if(!table.primaryKey.empty()) {
      if(table.primaryKeyPrefixIndexable) {
        out << "  std::map<std::tuple<";
      } else {
        out << "  std::unordered_map<std::tuple<";
      }
      generateList(out, table.primaryKey, [&](auto& out, auto& col){
               out << translateType(table.columns[col].type);
          });
      out << ">, size_t> primary_key_idx;\n";
    }
    // additional idcs
    for(auto& idx : table.indices) {
      if(idx.prefixIndexable) {
        out << "  std::map<std::tuple<";
      } else {
        out << "  std::unordered_map<std::tuple<";
      }
      generateList(out, idx.columns, [&](auto& out, auto& col){
               out << translateType(table.columns[col].type);
          });
      out << ">, size_t> idx_" << idx.name << ";\n";
    }
    // insert
    out << "  void insert_tuple(";
    generateList(out, table.columns, [&](auto& out, auto& column){
            out << translateType(column.type) << " " << column.name;
        });
    out << ") {\n";
    for(auto& column : table.columns) {
      out << "    this->col_" << column.name << ".push_back(" << column.name << ");\n";
    }
    auto generateIndexInsert = [&](const std::string& idxName, const std::vector<unsigned>& idxCols){
      out << "    this->" << idxName << ".insert(std::make_pair(std::make_tuple(";
      generateList(out, idxCols, [&](auto& out, auto& col){
              out << table.columns[col].name;
          });
      out << "), this->col_" << table.columns[0].name << ".size()))\n";
    };
    if(!table.primaryKey.empty()) {
      generateIndexInsert("primary_key_idx", table.primaryKey);
    }
    for(auto& idx : table.indices) {
      generateIndexInsert("idx_" + idx.name, idx.columns);
    }
    out << "  }\n";
    // delete
    out << "  void delete_tuple(size_t tid) {\n";
    for(auto& column : table.columns) {
      out << "    this->col_" << column.name << "[tid] = this->col_" << column.name << ".back();\n";
      out << "    this->col_" << column.name << ".pop_back();\n";
    }
    auto generateIndexDelete = [&](const std::string& idxName, const std::vector<unsigned>& idxCols){
      out << "    this->" << idxName << ".erase(std::make_tuple(";
      generateList(out, idxCols, [&](auto& out, auto& col){
              out << "this->col_" << table.columns[col].name << "[tid]";
          });
      out << "));\n";
      out << "    this->" << idxName << "[std::make_tuple(";
      generateList(out, idxCols, [&](auto& out, auto& col){
              out << "this->col_" << table.columns[col].name << ".back()";
          });
      out << ")] = tid;\n";
    };
    if(!table.primaryKey.empty()) {
      generateIndexDelete("primary_key_idx", table.primaryKey);
    }
    for(auto& idx : table.indices) {
      generateIndexDelete("idx_" + idx.name, idx.columns);
    }
    out << "  }\n";
    //TODO: parse
    out << "}\n";
  }
  out << "//--------------------------------------------------\n"
         "#endif";
}
<commit_msg>schema generation: bug fix in delete_tuple<commit_after>#include "Schema.hpp"
#include <sstream>

static std::string translateType(const DataType& type) {
  std::ostringstream stream;
  if(type.typeTag == DataTypeTag::Integer) {
    stream << "Integer";
  } else if(type.typeTag == DataTypeTag::Numeric) {
    stream << "Numeric<" << (int) type.attributes.numeric.integerPlaces
           << "," << (int) type.attributes.numeric.decimalPlaces << ">";
  } else if(type.typeTag == DataTypeTag::Char) {
    stream << "Char<" << (int) type.attributes.charLen << ">";
  } else if(type.typeTag == DataTypeTag::VarChar) {
    stream << "Varchar<" << (int) type.attributes.charLen << ">";
  } else if(type.typeTag == DataTypeTag::Date) {
    stream << "Date";
  } else if(type.typeTag == DataTypeTag::Timestamp) {
    stream << "Timestamp";
  }
  return stream.str();
}

template<typename T, typename Callable>
static void generateList(std::ostream& out, const std::vector<T>& elements, Callable cb, std::string seperator = ", ") {
  auto first = true;
  for(const auto& elem : elements) {
    if(!first) out << seperator;
    cb(out, elem);
    first = false;
  }
}

void Schema::generateCppCode(std::ostream& out) {
  out <<
    "#ifndef H_Schema\n"
    "#define H_Schema\n"
    "#include <vector>\n"
    "#include <map>\n"
    "#include <unordered_map>\n"
    "#include \"schema/Types.hpp\"\n";
  for(auto& table : tables) {
    out << "//--------------------------------------------------\n"
           "struct " << table.name << "_t {\n";
    // actual columns
    for(auto& column : table.columns) {
      out << "  std::vector<" << translateType(column.type) << "> col_" << column.name << ";\n";
    }
    // primary key index
    if(!table.primaryKey.empty()) {
      if(table.primaryKeyPrefixIndexable) {
        out << "  std::map<std::tuple<";
      } else {
        out << "  std::unordered_map<std::tuple<";
      }
      generateList(out, table.primaryKey, [&](auto& out, auto& col){
               out << translateType(table.columns[col].type);
          });
      out << ">, size_t> primary_key_idx;\n";
    }
    // additional idcs
    for(auto& idx : table.indices) {
      if(idx.prefixIndexable) {
        out << "  std::map<std::tuple<";
      } else {
        out << "  std::unordered_map<std::tuple<";
      }
      generateList(out, idx.columns, [&](auto& out, auto& col){
               out << translateType(table.columns[col].type);
          });
      out << ">, size_t> idx_" << idx.name << ";\n";
    }
    // insert
    out << "  void insert_tuple(";
    generateList(out, table.columns, [&](auto& out, auto& column){
            out << translateType(column.type) << " " << column.name;
        });
    out << ") {\n";
    for(auto& column : table.columns) {
      out << "    this->col_" << column.name << ".push_back(" << column.name << ");\n";
    }
    auto generateIndexInsert = [&](const std::string& idxName, const std::vector<unsigned>& idxCols){
      out << "    this->" << idxName << ".insert(std::make_pair(std::make_tuple(";
      generateList(out, idxCols, [&](auto& out, auto& col){
              out << table.columns[col].name;
          });
      out << "), this->col_" << table.columns[0].name << ".size()))\n";
    };
    if(!table.primaryKey.empty()) {
      generateIndexInsert("primary_key_idx", table.primaryKey);
    }
    for(auto& idx : table.indices) {
      generateIndexInsert("idx_" + idx.name, idx.columns);
    }
    out << "  }\n";
    // delete
    out << "  void delete_tuple(size_t tid) {\n";
    auto generateIndexDelete = [&](const std::string& idxName, const std::vector<unsigned>& idxCols){
      out << "    this->" << idxName << ".erase(std::make_tuple(";
      generateList(out, idxCols, [&](auto& out, auto& col){
              out << "this->col_" << table.columns[col].name << "[tid]";
          });
      out << "));\n";
      out << "    this->" << idxName << "[std::make_tuple(";
      generateList(out, idxCols, [&](auto& out, auto& col){
              out << "this->col_" << table.columns[col].name << ".back()";
          });
      out << ")] = tid;\n";
    };
    if(!table.primaryKey.empty()) {
      generateIndexDelete("primary_key_idx", table.primaryKey);
    }
    for(auto& idx : table.indices) {
      generateIndexDelete("idx_" + idx.name, idx.columns);
    }
    for(auto& column : table.columns) {
      out << "    this->col_" << column.name << "[tid] = this->col_" << column.name << ".back();\n";
      out << "    this->col_" << column.name << ".pop_back();\n";
    }
    out << "  }\n";
    //TODO: parse
    out << "}\n";
  }
  out << "//--------------------------------------------------\n"
         "#endif";
}
<|endoftext|>


<commit_before>/*
 * Software License Agreement (BSD License)
 *
 *  Copyright (c) 2011, Alexandru-Eugen Ichim
 *                      Willow Garage, Inc
 *  All rights reserved.
 *
 *  Redistribution and use in source and binary forms, with or without
 *  modification, are permitted provided that the following conditions
 *  are met:
 *
 *   * Redistributions of source code must retain the above copyright
 *     notice, this list of conditions and the following disclaimer.
 *   * Redistributions in binary form must reproduce the above
 *     copyright notice, this list of conditions and the following
 *     disclaimer in the documentation and/or other materials provided
 *     with the distribution.
 *   * Neither the name of Willow Garage, Inc. nor the names of its
 *     contributors may be used to endorse or promote products derived
 *     from this software without specific prior written permission.
 *
 *  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 *  "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 *  LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
 *  FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
 *  COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
 *  INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
 *  BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 *  LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
 *  CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 *  LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
 *  ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 *  POSSIBILITY OF SUCH DAMAGE.
 *
 * $Id$
 */

#ifndef PCL_KEYPOINTS_IMPL_SMOOTHEDSURFACESKEYPOINT_H_
#define PCL_KEYPOINTS_IMPL_SMOOTHEDSURFACESKEYPOINT_H_

#include "pcl/keypoints/smoothed_surfaces_keypoint.h"
#include <pcl/kdtree/kdtree_flann.h>

//////////////////////////////////////////////////////////////////////////////////////////////
template <typename PointT, typename PointNT> void
pcl::SmoothedSurfacesKeypoint<PointT, PointNT>::addSmoothedPointCloud (PointCloudTConstPtr &cloud,
                                                                       PointCloudNTConstPtr &normals,
                                                                       KdTreePtr &kdtree,
                                                                       float &scale)
{
  clouds_.push_back (cloud);
  cloud_normals_.push_back (normals);
  cloud_trees_.push_back (kdtree);
  scales_.push_back (std::pair<float, size_t> (scale, scales_.size ()));
}

//////////////////////////////////////////////////////////////////////////////////////////////
template <typename PointT, typename PointNT> void
pcl::SmoothedSurfacesKeypoint<PointT, PointNT>::resetClouds ()
{
  clouds_.clear ();
  cloud_normals_.clear ();
  scales_.clear ();
}

//////////////////////////////////////////////////////////////////////////////////////////////
template <typename PointT, typename PointNT> void
pcl::SmoothedSurfacesKeypoint<PointT, PointNT>::detectKeypoints (PointCloudT &output)
{
  // Calculate differences for each cloud
  std::vector<std::vector<float> > diffs (scales_.size ());

  // The cloud with the smallest scale has no differences
  std::vector<float> aux_diffs (input_->points.size (), 0.0f);
  diffs[scales_[0].second] = aux_diffs;

  for (size_t scale_i = 1; scale_i < clouds_.size (); ++scale_i)
  {
    diffs[scale_i].resize (input_->points.size ());
    size_t cloud_i = scales_[scale_i].second,
        cloud_i_minus_one = scales_[scale_i - 1].second;
    for (size_t point_i = 0; point_i < input_->points.size (); ++point_i)
      diffs[cloud_i][point_i] = cloud_normals_[cloud_i]->points[point_i].getNormalVector3fMap ().dot (
          clouds_[cloud_i]->points[point_i].getVector3fMap () - clouds_[cloud_i_minus_one]->points[point_i].getVector3fMap ());

    // Setup kdtree for this cloud
    cloud_trees_[cloud_i]->setInputCloud (clouds_[cloud_i]);
  }

  // Find minima and maxima in differences inside the input cloud
  tree_->setInputCloud (input_);
  for (int point_i = 0; point_i < input_->points.size (); ++point_i)
  {
    std::vector<int> nn_indices;
    std::vector<float> nn_distances;
    tree_->radiusSearch (point_i, input_scale_ * neighborhood_constant_, nn_indices, nn_distances);

    bool is_min = true, is_max = true;
    for (std::vector<int>::iterator nn_it = nn_indices.begin (); nn_it != nn_indices.end (); ++nn_it)
      if (*nn_it != point_i)
      {
        if (diffs[input_index_][point_i] < diffs[input_index_][*nn_it])
          is_max = false;
        else
          is_min = false;
      }

    // If the point is a local minimum/maximum, check if it so over all the scales
    if (is_min || is_max)
    {
      bool passed = true;
      for (size_t scale_i = 0; scale_i < scales_.size (); ++scale_i)
      {
        size_t cloud_i = scales_[scale_i].second;
        // skip input cloud
        if (cloud_i == clouds_.size ())
          continue;

        nn_indices.clear (); nn_distances.clear ();
        cloud_trees_[cloud_i]->radiusSearch (point_i, scales_[scale_i].first * neighborhood_constant_, nn_indices, nn_distances);

        bool is_min_other_scale = true, is_max_other_scale = true;
        for (std::vector<int>::iterator nn_it = nn_indices.begin (); nn_it != nn_indices.end (); ++nn_it)
          if (*nn_it != point_i)
          {
            if (diffs[input_index_][point_i] < diffs[cloud_i][*nn_it])
              is_max_other_scale = false;
            else
              is_min_other_scale = false;
          }

        if ( (is_min == true && is_min_other_scale == false) || (is_max == true && is_max_other_scale == false) )
        {
          passed = false;
          break;
        }
      }

      // check if point was minimum/maximum over all the scales
      if (passed)
        output.points.push_back (input_->points[point_i]);
    }
  }
}

//////////////////////////////////////////////////////////////////////////////////////////////
template <typename PointT, typename PointNT> bool
pcl::SmoothedSurfacesKeypoint<PointT, PointNT>::initCompute ()
{
  if ( !PCLBase<PointT>::initCompute ())
  {
    PCL_ERROR ("[pcl::SmoothedSurfacesKeypoints::initCompute] PCLBase::initCompute failed\n");
    return false;
  }

  if (!normals_)
  {
    PCL_ERROR ("[pcl::SmoothedSurfacesKeypoints::initCompute] Input normals were not set\n");
    return false;
  }
  if (clouds_.size () == 0)
  {
    PCL_ERROR ("[pcl::SmoothedSurfacesKeypoints::initCompute] No other clouds were set apart from the input\n");
    return false;
  }

  if (input_->points.size () != normals_->points.size ())
  {
    PCL_ERROR ("[pcl::SmoothedSurfacesKeypoints::initCompute] The input cloud and the input normals differ in size\n");
    return false;
  }

  for (size_t cloud_i = 0; cloud_i < clouds_.size (); ++cloud_i)
  {
    if (clouds_[cloud_i]->points.size () != input_->points.size ())
    {
      PCL_ERROR ("[pcl::SmoothedSurfacesKeypoints::initCompute] Cloud %d does not have the same number of points as the input cloud\n", cloud_i);
      return false;
    }

    if (cloud_normals_[cloud_i]->points.size () != input_->points.size ())
    {
      PCL_ERROR ("[pcl::SmoothedSurfacesKeypoints::initCompute] Normals for cloud %d do not have the same number of points as the input cloud\n", cloud_i);
      return false;
    }
  }

  // Add the input cloud as the last index
  scales_.push_back (std::pair<float, size_t> (input_scale_, scales_.size ()));
  clouds_.push_back (input_);
  cloud_normals_.push_back (normals_);
  // Sort the clouds by their scales
  sort (scales_.begin (), scales_.end (), compareScalesFunction);

  // Find the index of the input after sorting
  for (size_t i = 0; i < scales_.size (); ++i)
    if (scales_[i].second == scales_.size () - 1)
    {
      input_index_ = i;
      break;
    }

  return true;
}

#define PCL_INSTANTIATE_SmoothedSurfacesKeypoint(T,NT) template class PCL_EXPORTS pcl::SmoothedSurfacesKeypoint<T,NT>;

#endif /* PCL_KEYPOINTS_IMPL_SMOOTHEDSURFACESKEYPOINT_H_ */
<commit_msg>fixed a compiler warning<commit_after>/*
 * Software License Agreement (BSD License)
 *
 *  Copyright (c) 2011, Alexandru-Eugen Ichim
 *                      Willow Garage, Inc
 *  All rights reserved.
 *
 *  Redistribution and use in source and binary forms, with or without
 *  modification, are permitted provided that the following conditions
 *  are met:
 *
 *   * Redistributions of source code must retain the above copyright
 *     notice, this list of conditions and the following disclaimer.
 *   * Redistributions in binary form must reproduce the above
 *     copyright notice, this list of conditions and the following
 *     disclaimer in the documentation and/or other materials provided
 *     with the distribution.
 *   * Neither the name of Willow Garage, Inc. nor the names of its
 *     contributors may be used to endorse or promote products derived
 *     from this software without specific prior written permission.
 *
 *  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 *  "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 *  LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
 *  FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
 *  COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
 *  INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
 *  BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 *  LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
 *  CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 *  LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
 *  ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 *  POSSIBILITY OF SUCH DAMAGE.
 *
 * $Id$
 */

#ifndef PCL_KEYPOINTS_IMPL_SMOOTHEDSURFACESKEYPOINT_H_
#define PCL_KEYPOINTS_IMPL_SMOOTHEDSURFACESKEYPOINT_H_

#include "pcl/keypoints/smoothed_surfaces_keypoint.h"
#include <pcl/kdtree/kdtree_flann.h>

//////////////////////////////////////////////////////////////////////////////////////////////
template <typename PointT, typename PointNT> void
pcl::SmoothedSurfacesKeypoint<PointT, PointNT>::addSmoothedPointCloud (PointCloudTConstPtr &cloud,
                                                                       PointCloudNTConstPtr &normals,
                                                                       KdTreePtr &kdtree,
                                                                       float &scale)
{
  clouds_.push_back (cloud);
  cloud_normals_.push_back (normals);
  cloud_trees_.push_back (kdtree);
  scales_.push_back (std::pair<float, size_t> (scale, scales_.size ()));
}

//////////////////////////////////////////////////////////////////////////////////////////////
template <typename PointT, typename PointNT> void
pcl::SmoothedSurfacesKeypoint<PointT, PointNT>::resetClouds ()
{
  clouds_.clear ();
  cloud_normals_.clear ();
  scales_.clear ();
}

//////////////////////////////////////////////////////////////////////////////////////////////
template <typename PointT, typename PointNT> void
pcl::SmoothedSurfacesKeypoint<PointT, PointNT>::detectKeypoints (PointCloudT &output)
{
  // Calculate differences for each cloud
  std::vector<std::vector<float> > diffs (scales_.size ());

  // The cloud with the smallest scale has no differences
  std::vector<float> aux_diffs (input_->points.size (), 0.0f);
  diffs[scales_[0].second] = aux_diffs;

  for (size_t scale_i = 1; scale_i < clouds_.size (); ++scale_i)
  {
    diffs[scale_i].resize (input_->points.size ());
    size_t cloud_i = scales_[scale_i].second,
        cloud_i_minus_one = scales_[scale_i - 1].second;
    for (size_t point_i = 0; point_i < input_->points.size (); ++point_i)
      diffs[cloud_i][point_i] = cloud_normals_[cloud_i]->points[point_i].getNormalVector3fMap ().dot (
          clouds_[cloud_i]->points[point_i].getVector3fMap () - clouds_[cloud_i_minus_one]->points[point_i].getVector3fMap ());

    // Setup kdtree for this cloud
    cloud_trees_[cloud_i]->setInputCloud (clouds_[cloud_i]);
  }

  // Find minima and maxima in differences inside the input cloud
  tree_->setInputCloud (input_);
  for (int point_i = 0; point_i < (int)input_->points.size (); ++point_i)
  {
    std::vector<int> nn_indices;
    std::vector<float> nn_distances;
    tree_->radiusSearch (point_i, input_scale_ * neighborhood_constant_, nn_indices, nn_distances);

    bool is_min = true, is_max = true;
    for (std::vector<int>::iterator nn_it = nn_indices.begin (); nn_it != nn_indices.end (); ++nn_it)
      if (*nn_it != point_i)
      {
        if (diffs[input_index_][point_i] < diffs[input_index_][*nn_it])
          is_max = false;
        else
          is_min = false;
      }

    // If the point is a local minimum/maximum, check if it so over all the scales
    if (is_min || is_max)
    {
      bool passed = true;
      for (size_t scale_i = 0; scale_i < scales_.size (); ++scale_i)
      {
        size_t cloud_i = scales_[scale_i].second;
        // skip input cloud
        if (cloud_i == clouds_.size ())
          continue;

        nn_indices.clear (); nn_distances.clear ();
        cloud_trees_[cloud_i]->radiusSearch (point_i, scales_[scale_i].first * neighborhood_constant_, nn_indices, nn_distances);

        bool is_min_other_scale = true, is_max_other_scale = true;
        for (std::vector<int>::iterator nn_it = nn_indices.begin (); nn_it != nn_indices.end (); ++nn_it)
          if (*nn_it != point_i)
          {
            if (diffs[input_index_][point_i] < diffs[cloud_i][*nn_it])
              is_max_other_scale = false;
            else
              is_min_other_scale = false;
          }

        if ( (is_min == true && is_min_other_scale == false) || (is_max == true && is_max_other_scale == false) )
        {
          passed = false;
          break;
        }
      }

      // check if point was minimum/maximum over all the scales
      if (passed)
        output.points.push_back (input_->points[point_i]);
    }
  }
}

//////////////////////////////////////////////////////////////////////////////////////////////
template <typename PointT, typename PointNT> bool
pcl::SmoothedSurfacesKeypoint<PointT, PointNT>::initCompute ()
{
  if ( !PCLBase<PointT>::initCompute ())
  {
    PCL_ERROR ("[pcl::SmoothedSurfacesKeypoints::initCompute] PCLBase::initCompute failed\n");
    return false;
  }

  if (!normals_)
  {
    PCL_ERROR ("[pcl::SmoothedSurfacesKeypoints::initCompute] Input normals were not set\n");
    return false;
  }
  if (clouds_.size () == 0)
  {
    PCL_ERROR ("[pcl::SmoothedSurfacesKeypoints::initCompute] No other clouds were set apart from the input\n");
    return false;
  }

  if (input_->points.size () != normals_->points.size ())
  {
    PCL_ERROR ("[pcl::SmoothedSurfacesKeypoints::initCompute] The input cloud and the input normals differ in size\n");
    return false;
  }

  for (size_t cloud_i = 0; cloud_i < clouds_.size (); ++cloud_i)
  {
    if (clouds_[cloud_i]->points.size () != input_->points.size ())
    {
      PCL_ERROR ("[pcl::SmoothedSurfacesKeypoints::initCompute] Cloud %d does not have the same number of points as the input cloud\n", cloud_i);
      return false;
    }

    if (cloud_normals_[cloud_i]->points.size () != input_->points.size ())
    {
      PCL_ERROR ("[pcl::SmoothedSurfacesKeypoints::initCompute] Normals for cloud %d do not have the same number of points as the input cloud\n", cloud_i);
      return false;
    }
  }

  // Add the input cloud as the last index
  scales_.push_back (std::pair<float, size_t> (input_scale_, scales_.size ()));
  clouds_.push_back (input_);
  cloud_normals_.push_back (normals_);
  // Sort the clouds by their scales
  sort (scales_.begin (), scales_.end (), compareScalesFunction);

  // Find the index of the input after sorting
  for (size_t i = 0; i < scales_.size (); ++i)
    if (scales_[i].second == scales_.size () - 1)
    {
      input_index_ = i;
      break;
    }

  return true;
}

#define PCL_INSTANTIATE_SmoothedSurfacesKeypoint(T,NT) template class PCL_EXPORTS pcl::SmoothedSurfacesKeypoint<T,NT>;

#endif /* PCL_KEYPOINTS_IMPL_SMOOTHEDSURFACESKEYPOINT_H_ */
<|endoftext|>


<commit_before>///
/// @file  FactorTable.hpp
/// @brief The FactorTable class is used to save memory. It combines
///        the lpf[n] (least prime factor) and mu[n] (Möbius function)
///        lookup tables into a single factor_table[n] which
///        furthermore only contains entries for numbers which are
///        not divisible by 2, 3, 5 and 7.
///        The factor table concept has first been devised and
///        implemented by Christian Bau in 2003.
///
///        FactorTable.lpf(index) is equal to (n = get_number(index)):
///
///         * 0      if moebius(n) = 0
///         * lpf    if !is_prime(n) && moebius(n) = -1
///         * lpf-1  if !is_prime(n) && moebius(n) = 1
///         * n      if  is_prime(n) && n < T_MAX
///         * T_MAX  if  is_prime(n) && n > T_MAX
///
/// Copyright (C) 2014 Kim Walisch, <kim.walisch@gmail.com>
///
/// This file is distributed under the BSD License. See the COPYING
/// file in the top level directory.
///

#ifndef FACTORTABLE_HPP
#define FACTORTABLE_HPP

#include <primecount.hpp>
#include <pmath.hpp>

#include <algorithm>
#include <cassert>
#include <limits>
#include <stdint.h>
#include <vector>

namespace primecount {

/// AbstractFactorTable contains static FactorTable
/// data and it used to convert:
/// 1) A number into a FactorTable index.
/// 2) A FactorTable index into a number.
///
class AbstractFactorTable
{
protected:
  virtual ~AbstractFactorTable() { }

public:
  /// @pre number > 0
  static void to_index(int64_t* number)
  {
    assert(*number > 0);
    *number = get_index(*number);
  }

  /// @pre number > 0
  static int64_t get_index(int64_t number)
  {
    assert(number > 0);
    int64_t quotient = number / 210;
    int64_t remainder = number % 210;
    return 48 * quotient + indexes_[remainder];
  }

  static int64_t get_number(int64_t index)
  {
    int64_t quotient = index / 48;
    int64_t remainder = index % 48;
    return 210 * quotient + numbers_[remainder];
  }

private:
  static const uint8_t numbers_[48];
  static const  int8_t indexes_[210];
};

template <typename T>
class FactorTable : public AbstractFactorTable
{
public:
  /// @param y  factor numbers <= y
  FactorTable(int64_t y)
  {
    if (y > max())
      throw primecount_error("y must be <= FactorTable::max().");
    y = std::max<int64_t>(8, y);
    T T_MAX = std::numeric_limits<T>::max();
    init_factors(y, T_MAX);
  }

  static int64_t max()
  {
    int64_t T_MAX = std::numeric_limits<T>::max();
    return ipow(T_MAX - 1, 2) - 1;
  }

  /// Get the least prime factor (lpf) of the number get_number(index).
  /// The result is different from lpf in some situations:
  /// 1) lpf(index) returns T_MAX if get_number(index) is a prime > T_MAX.
  /// 2) lpf(index) returns lpf minus one if mu(index) == 1.
  /// 3) lpf(index) returns 0 if get_number(index) has a squared prime factor.
  ///
  int64_t lpf(int64_t index) const
  {
    return factors_[index];
  }

  /// Get the Möbius function value of the number get_number(index).
  /// For performance reasons mu(index) == 0 is not supported.
  /// @pre mu(index) != 0 (i.e. lpf(index) != 0)
  ///
  int64_t mu(int64_t index) const
  {
    assert(lpf(index) != 0);
    return (factors_[index] & 1) ? -1 : 1;
  }

private:
  void init_factors(int64_t y, T T_MAX)
  {
    int64_t sqrty = isqrt(y);
    factors_.resize(get_index(y) + 1, T_MAX);
    factors_[0] = T_MAX - 1;

    for (size_t i = 1; i < factors_.size(); i++)
    {
      if (factors_[i] == T_MAX)
      {
        int64_t prime = get_number(i);
        int64_t multiple = prime * get_number(1);

        if (prime < T_MAX)
          factors_[i] = (T) prime;
        else if (multiple > y)
          break;

        for (int64_t j = 2; multiple <= y; multiple = prime * get_number(j++))
        {
          int64_t index = get_index(multiple);
          // prime is the smallest factor of multiple
          if (factors_[index] == T_MAX)
            factors_[index] = (T) prime;
          // the least significant bit indicates whether multiple has
          // an even (0) or odd (1) number of prime factors
          else if (factors_[index] != 0)
            factors_[index] ^= 1;
        }

        // Möbius function is 0 if n has a squared prime factor
        if (prime <= sqrty)
        {
          multiple = prime * prime;
          for (int64_t j = 1; multiple <= y; multiple = prime * prime * get_number(j++))
            factors_[get_index(multiple)] = 0;
        }
      }
    }
  }

  std::vector<T> factors_;
};

} // namespace

#endif
<commit_msg>Update comment<commit_after>///
/// @file  FactorTable.hpp
/// @brief The FactorTable class is used to save memory. It combines
///        the lpf[n] (least prime factor) and mu[n] (Möbius function)
///        lookup tables into a single factors_[n] table which
///        furthermore only contains entries for numbers which are
///        not divisible by 2, 3, 5 and 7.
///        The factor table concept has first been devised and
///        implemented by Christian Bau in 2003.
///
///        FactorTable.lpf(index) is equal to (n = get_number(index)):
///
///         * 0      if moebius(n) = 0
///         * lpf    if !is_prime(n) && moebius(n) = -1
///         * lpf-1  if !is_prime(n) && moebius(n) = 1
///         * n      if  is_prime(n) && n < T_MAX
///         * T_MAX  if  is_prime(n) && n > T_MAX
///
/// Copyright (C) 2014 Kim Walisch, <kim.walisch@gmail.com>
///
/// This file is distributed under the BSD License. See the COPYING
/// file in the top level directory.
///

#ifndef FACTORTABLE_HPP
#define FACTORTABLE_HPP

#include <primecount.hpp>
#include <pmath.hpp>

#include <algorithm>
#include <cassert>
#include <limits>
#include <stdint.h>
#include <vector>

namespace primecount {

/// AbstractFactorTable contains static FactorTable
/// data and it used to convert:
/// 1) A number into a FactorTable index.
/// 2) A FactorTable index into a number.
///
class AbstractFactorTable
{
protected:
  virtual ~AbstractFactorTable() { }

public:
  /// @pre number > 0
  static void to_index(int64_t* number)
  {
    assert(*number > 0);
    *number = get_index(*number);
  }

  /// @pre number > 0
  static int64_t get_index(int64_t number)
  {
    assert(number > 0);
    int64_t quotient = number / 210;
    int64_t remainder = number % 210;
    return 48 * quotient + indexes_[remainder];
  }

  static int64_t get_number(int64_t index)
  {
    int64_t quotient = index / 48;
    int64_t remainder = index % 48;
    return 210 * quotient + numbers_[remainder];
  }

private:
  static const uint8_t numbers_[48];
  static const  int8_t indexes_[210];
};

template <typename T>
class FactorTable : public AbstractFactorTable
{
public:
  /// @param y  factor numbers <= y
  FactorTable(int64_t y)
  {
    if (y > max())
      throw primecount_error("y must be <= FactorTable::max().");
    y = std::max<int64_t>(8, y);
    T T_MAX = std::numeric_limits<T>::max();
    init_factors(y, T_MAX);
  }

  static int64_t max()
  {
    int64_t T_MAX = std::numeric_limits<T>::max();
    return ipow(T_MAX - 1, 2) - 1;
  }

  /// Get the least prime factor (lpf) of the number get_number(index).
  /// The result is different from lpf in some situations:
  /// 1) lpf(index) returns T_MAX if get_number(index) is a prime > T_MAX.
  /// 2) lpf(index) returns lpf minus one if mu(index) == 1.
  /// 3) lpf(index) returns 0 if get_number(index) has a squared prime factor.
  ///
  int64_t lpf(int64_t index) const
  {
    return factors_[index];
  }

  /// Get the Möbius function value of the number get_number(index).
  /// For performance reasons mu(index) == 0 is not supported.
  /// @pre mu(index) != 0 (i.e. lpf(index) != 0)
  ///
  int64_t mu(int64_t index) const
  {
    assert(lpf(index) != 0);
    return (factors_[index] & 1) ? -1 : 1;
  }

private:
  void init_factors(int64_t y, T T_MAX)
  {
    int64_t sqrty = isqrt(y);
    factors_.resize(get_index(y) + 1, T_MAX);
    factors_[0] = T_MAX - 1;

    for (size_t i = 1; i < factors_.size(); i++)
    {
      if (factors_[i] == T_MAX)
      {
        int64_t prime = get_number(i);
        int64_t multiple = prime * get_number(1);

        if (prime < T_MAX)
          factors_[i] = (T) prime;
        else if (multiple > y)
          break;

        for (int64_t j = 2; multiple <= y; multiple = prime * get_number(j++))
        {
          int64_t index = get_index(multiple);
          // prime is the smallest factor of multiple
          if (factors_[index] == T_MAX)
            factors_[index] = (T) prime;
          // the least significant bit indicates whether multiple has
          // an even (0) or odd (1) number of prime factors
          else if (factors_[index] != 0)
            factors_[index] ^= 1;
        }

        // Möbius function is 0 if n has a squared prime factor
        if (prime <= sqrty)
        {
          multiple = prime * prime;
          for (int64_t j = 1; multiple <= y; multiple = prime * prime * get_number(j++))
            factors_[get_index(multiple)] = 0;
        }
      }
    }
  }

  std::vector<T> factors_;
};

} // namespace

#endif
<|endoftext|>


<commit_before>#include "pathos/core_minimal.h"
#include "pathos/render_minimal.h"

#include "daeloader.h"
#include "skinned_mesh.h"
#include <time.h>

using namespace std;
using namespace pathos;

/* ------------------------------------------------------------------------

								CONFIGURATION

------------------------------------------------------------------------- */
#define DAE_MODEL_ID              2
#define LOAD_SECOND_DAE_MODEL     0

constexpr int32 WINDOW_WIDTH    = 1920;
constexpr int32 WINDOW_HEIGHT   = 1080;
constexpr char* WINDOW_TITLE    = "Test: Skeletal Animation";
constexpr float FOVY            = 60.0f;
const glm::vec3 CAMERA_POSITION = glm::vec3(0.0f, 0.0f, 100.0f);
constexpr float CAMERA_Z_NEAR   = 1.0f;
constexpr float CAMERA_Z_FAR    = 10000.0f;

/* ------------------------------------------------------------------------

								PROGRAM CODE

------------------------------------------------------------------------- */

Camera* cam;
Scene scene;
	DirectionalLight *dlight;
	PointLight *plight;
	Mesh *model, *model2;
	SkinnedMesh *daeModel;
	SkinnedMesh *daeModel2;

void loadDAE();
void setupScene();
void tick();

int main(int argc, char** argv) {
	EngineConfig conf;
	conf.windowWidth  = WINDOW_WIDTH;
	conf.windowHeight = WINDOW_HEIGHT;
	conf.title        = WINDOW_TITLE;
	conf.rendererType = ERendererType::Deferred;
	conf.tick         = tick;
	Engine::init(argc, argv, conf);

	const float ar = static_cast<float>(conf.windowWidth) / static_cast<float>(conf.windowHeight);
	cam = new Camera(new PerspectiveLens(FOVY, ar, CAMERA_Z_NEAR, CAMERA_Z_FAR));
	cam->move(CAMERA_POSITION);

	loadDAE();
	setupScene();

	gEngine->setWorld(&scene, cam);
	gEngine->start();

	return 0;
}

void loadDAE() {
	bool invertWinding = false;
#if DAE_MODEL_ID == 0
	const std::string dir = "models/LOL_ashe/";
	const std::string model = dir + "Ashe.dae";
#elif DAE_MODEL_ID == 1
	const std::string dir = "models/LOL_project_ashe/";
	const std::string model = dir + "Project_Ashe.dae";
	invertWinding = true;
#else
	const std::string dir = "models/animtest/";
	const std::string model = dir + "animtest.dae";
#endif

	DAELoader loader(model.c_str(), dir.c_str(), aiProcessPreset_TargetRealtime_MaxQuality, invertWinding);
	if (loader.getMesh()) {
		daeModel = dynamic_cast<SkinnedMesh*>(loader.getMesh());
		daeModel->getTransform().appendScale(10.0f);
#if DAE_MODEL_ID == 2
		daeModel->getTransform().appendScale(0.3f);
		daeModel->getTransform().appendRotation(glm::radians(90.0f), glm::vec3(0, 1, 0));
#endif
		daeModel->getTransform().appendMove(0, 0, 50);
		scene.add(daeModel);
	} else {
		LOG(LogError, "Failed to load model: %s", model.c_str());
	}

#if LOAD_SECOND_DAE_MODEL
	const std::string dir2 = "models/Sonic/";
	const std::string model2 = dir2 + "Sonic.dae";
	DAELoader loader2(model2.c_str(), dir2.c_str(), aiProcessPreset_TargetRealtime_MaxQuality);
	daeModel2 = dynamic_cast<SkinnedMesh*>(loader2.getMesh());
	daeModel2->getTransform().appendScale(10.0f);
	daeModel2->getTransform().appendMove(20.0f, 0.0f, 50.0f);
	scene.add(daeModel2);
#endif
}

void setupScene() {
	plight = new PointLight(glm::vec3(0, 0, 0), glm::vec3(1.0f));
	dlight = new DirectionalLight(glm::vec3(0, 0, -1), glm::vec3(1.0f));
	scene.add(plight);
	scene.add(dlight);

	srand(static_cast<unsigned int>(time(NULL)));

	//---------------------------------------------------------------------------------------
	// create materials
	//---------------------------------------------------------------------------------------
	const char* cubeImgName[6] = {
		"cubemap1/pos_x.jpg", "cubemap1/neg_x.jpg",
		"cubemap1/pos_y.jpg", "cubemap1/neg_y.jpg",
		"cubemap1/pos_z.jpg", "cubemap1/neg_z.jpg"
	};
	FIBITMAP* cubeImg[6];
	for (int i = 0; i < 6; i++) cubeImg[i] = loadImage(cubeImgName[i]);
	GLuint cubeTexture = loadCubemapTexture(cubeImg);

	GLuint tex = loadTexture(loadImage("154.jpg"), true, true);
	GLuint tex_norm = loadTexture(loadImage("154_norm.jpg"), true, false);

	auto material_texture = new TextureMaterial(tex);
	auto material_color = new ColorMaterial;
	{
		auto color = static_cast<ColorMaterial*>(material_color);
		color->setAlbedo(1.0f, 1.0f, 1.0f);
		color->setMetallic(0.6f);
		color->setRoughness(0.5f);
	}
	auto material_cubemap = new CubeEnvMapMaterial(cubeTexture);
	auto material_wireframe = new WireframeMaterial(0.0f, 1.0f, 1.0f, 0.3f);

	//---------------------------------------------------------------------------------------
	// create geometries
	//---------------------------------------------------------------------------------------

	auto geom_sphere_big = new SphereGeometry(15.0f, 30);
	auto geom_sphere = new SphereGeometry(5.0f, 30);
	auto geom_plane = new PlaneGeometry(10.f, 10.f);
	auto geom_cube = new CubeGeometry(glm::vec3(5.0f));

	geom_sphere->calculateTangentBasis();
	geom_sphere_big->calculateTangentBasis();
	geom_plane->calculateTangentBasis();
	geom_cube->calculateTangentBasis();

	//---------------------------------------------------------------------------------------
	// create meshes
	//---------------------------------------------------------------------------------------

	for (int32_t i = 0; i < 8; ++i) {
		for (int32_t j = 0; j < 4; ++j) {
			Mesh* cube = new Mesh(geom_cube, material_color);
			glm::vec3 p0(-50.0f, 50.0f, -50.0f);
			float e = (rand() % 256) / 255.0f;
			float x = (rand() % 256) / 255.0f;
			float y = (rand() % 256) / 255.0f;
			float z = (rand() % 256) / 255.0f;
			cube->getTransform().appendRotation(e * 60.0f, glm::vec3(x, y, z));
			cube->getTransform().appendMove(p0 + glm::vec3(i * 15.0f, -j * 15.0f, 0.0f));
			scene.add(cube);
		}
	}

	model = new Mesh(geom_sphere_big, material_texture);
	model->getTransform().appendMove(-40, 0, 0);

	model2 = new Mesh(geom_sphere, material_color);
	model2->getTransform().appendScale(10.0f);
	model2->getTransform().appendMove(0, 50, -200);

	scene.add(model);
	scene.add(model2);
	scene.sky = new Skybox(cubeTexture);
	scene.godRaySource = model2;
}

void tick() {
	if (gConsole->isVisible() == false) {
		float speedX = 1.0f, speedY = 1.0f;
		float dx = gEngine->isDown('a') ? -speedX : gEngine->isDown('d') ? speedX : 0.0f;
		float dz = gEngine->isDown('w') ? -speedY : gEngine->isDown('s') ? speedY : 0.0f;
		float rotY = gEngine->isDown('q') ? -0.5f : gEngine->isDown('e') ? 0.5f : 0.0f;
		float rotX = gEngine->isDown('z') ? -0.5f : gEngine->isDown('x') ? 0.5f : 0.0f;
		cam->move(glm::vec3(dx, 0, dz));
		cam->rotateY(rotY);
		cam->rotateX(rotX);
	}

	model->getTransform().appendMove(0, 20, 0);
	model->getTransform().appendRotation(0.01f, glm::vec3(0, 0.5, 1));
	model->getTransform().appendMove(0, -20, 0);

#if DAE_MODEL_ID == 2
	static double time = 0.0;
	time += 0.01;
	if (time > 1.0) time = 0.0;
	daeModel->updateAnimation(0, time);
	daeModel->updateSoftwareSkinning();
	daeModel->getTransform().prependRotation(0.003f, glm::vec3(0, 1, 0));
#endif
}
<commit_msg>Fix build error for Test_SkeletalAnimation<commit_after>#include "pathos/core_minimal.h"
#include "pathos/render_minimal.h"

#include "daeloader.h"
#include "skinned_mesh.h"
#include <time.h>

using namespace std;
using namespace pathos;

/* ------------------------------------------------------------------------

								CONFIGURATION

------------------------------------------------------------------------- */
#define DAE_MODEL_ID              2
#define LOAD_SECOND_DAE_MODEL     0

constexpr int32 WINDOW_WIDTH    = 1920;
constexpr int32 WINDOW_HEIGHT   = 1080;
constexpr char* WINDOW_TITLE    = "Test: Skeletal Animation";
constexpr float FOVY            = 60.0f;
const glm::vec3 CAMERA_POSITION = glm::vec3(0.0f, 0.0f, 100.0f);
constexpr float CAMERA_Z_NEAR   = 1.0f;
constexpr float CAMERA_Z_FAR    = 10000.0f;

/* ------------------------------------------------------------------------

								PROGRAM CODE

------------------------------------------------------------------------- */

Camera* cam;
Scene scene;
	DirectionalLight *dlight;
	PointLight *plight;
	Mesh *model, *model2;
	SkinnedMesh *daeModel;
	SkinnedMesh *daeModel2;

void loadDAE();
void setupScene();
void tick(float deltaSeconds);

int main(int argc, char** argv) {
	EngineConfig conf;
	conf.windowWidth  = WINDOW_WIDTH;
	conf.windowHeight = WINDOW_HEIGHT;
	conf.title        = WINDOW_TITLE;
	conf.rendererType = ERendererType::Deferred;
	conf.tick         = tick;
	Engine::init(argc, argv, conf);

	const float ar = static_cast<float>(conf.windowWidth) / static_cast<float>(conf.windowHeight);
	cam = new Camera(new PerspectiveLens(FOVY, ar, CAMERA_Z_NEAR, CAMERA_Z_FAR));
	cam->move(CAMERA_POSITION);

	loadDAE();
	setupScene();

	gEngine->setWorld(&scene, cam);
	gEngine->start();

	return 0;
}

void loadDAE() {
	bool invertWinding = false;
#if DAE_MODEL_ID == 0
	const std::string dir = "models/LOL_ashe/";
	const std::string model = dir + "Ashe.dae";
#elif DAE_MODEL_ID == 1
	const std::string dir = "models/LOL_project_ashe/";
	const std::string model = dir + "Project_Ashe.dae";
	invertWinding = true;
#else
	const std::string dir = "models/animtest/";
	const std::string model = dir + "animtest.dae";
#endif

	DAELoader loader(model.c_str(), dir.c_str(), aiProcessPreset_TargetRealtime_MaxQuality, invertWinding);
	if (loader.getMesh()) {
		daeModel = dynamic_cast<SkinnedMesh*>(loader.getMesh());
		daeModel->getTransform().setScale(10.0f);
#if DAE_MODEL_ID == 2
		daeModel->getTransform().setScale(5.0f);
		daeModel->getTransform().setRotation(glm::radians(90.0f), glm::vec3(0.0f, 1.0f, 0.0f));
#endif
		daeModel->getTransform().setLocation(0.0f, 0.0f, 0.0f);
		scene.add(daeModel);
	} else {
		LOG(LogError, "Failed to load model: %s", model.c_str());
	}

#if LOAD_SECOND_DAE_MODEL
	const std::string dir2 = "models/Sonic/";
	const std::string model2 = dir2 + "Sonic.dae";
	DAELoader loader2(model2.c_str(), dir2.c_str(), aiProcessPreset_TargetRealtime_MaxQuality);
	daeModel2 = dynamic_cast<SkinnedMesh*>(loader2.getMesh());
	daeModel2->getTransform().appendScale(10.0f);
	daeModel2->getTransform().appendMove(20.0f, 0.0f, 50.0f);
	scene.add(daeModel2);
#endif
}

void setupScene() {
	plight = new PointLight(glm::vec3(0, 0, 0), glm::vec3(1.0f));
	dlight = new DirectionalLight(glm::vec3(0, 0, -1), glm::vec3(1.0f));
	scene.add(plight);
	scene.add(dlight);

	srand(static_cast<unsigned int>(time(NULL)));

	//---------------------------------------------------------------------------------------
	// create materials
	//---------------------------------------------------------------------------------------
	const char* cubeImgName[6] = {
		"cubemap1/pos_x.jpg", "cubemap1/neg_x.jpg",
		"cubemap1/pos_y.jpg", "cubemap1/neg_y.jpg",
		"cubemap1/pos_z.jpg", "cubemap1/neg_z.jpg"
	};
	FIBITMAP* cubeImg[6];
	for (int i = 0; i < 6; i++) cubeImg[i] = loadImage(cubeImgName[i]);
	GLuint cubeTexture = loadCubemapTexture(cubeImg);

	GLuint tex = loadTexture(loadImage("154.jpg"), true, true);
	GLuint tex_norm = loadTexture(loadImage("154_norm.jpg"), true, false);

	auto material_texture = new TextureMaterial(tex);
	auto material_color = new ColorMaterial;
	{
		auto color = static_cast<ColorMaterial*>(material_color);
		color->setAlbedo(1.0f, 1.0f, 1.0f);
		color->setMetallic(0.6f);
		color->setRoughness(0.5f);
	}
	auto material_cubemap = new CubeEnvMapMaterial(cubeTexture);
	auto material_wireframe = new WireframeMaterial(0.0f, 1.0f, 1.0f, 0.3f);

	//---------------------------------------------------------------------------------------
	// create geometries
	//---------------------------------------------------------------------------------------

	auto geom_sphere_big = new SphereGeometry(15.0f, 30);
	auto geom_sphere = new SphereGeometry(5.0f, 30);
	auto geom_plane = new PlaneGeometry(10.f, 10.f);
	auto geom_cube = new CubeGeometry(glm::vec3(5.0f));

	geom_sphere->calculateTangentBasis();
	geom_sphere_big->calculateTangentBasis();
	geom_plane->calculateTangentBasis();
	geom_cube->calculateTangentBasis();

	//---------------------------------------------------------------------------------------
	// create meshes
	//---------------------------------------------------------------------------------------

	for (int32_t i = 0; i < 8; ++i) {
		for (int32_t j = 0; j < 4; ++j) {
			Mesh* cube = new Mesh(geom_cube, material_color);
			glm::vec3 p0(-50.0f, 50.0f, -50.0f);
			float e = (rand() % 256) / 255.0f;
			float x = (rand() % 256) / 255.0f;
			float y = (rand() % 256) / 255.0f;
			float z = (rand() % 256) / 255.0f;
			cube->getTransform().setRotation(e * 60.0f, glm::vec3(x, y, z));
			cube->getTransform().setLocation(p0 + glm::vec3(i * 15.0f, -j * 15.0f, 0.0f));
			scene.add(cube);
		}
	}

	model = new Mesh(geom_sphere_big, material_texture);
	model->getTransform().setLocation(-40, 0, 0);

	model2 = new Mesh(geom_sphere, material_color);
	model2->getTransform().setScale(10.0f);
	model2->getTransform().setLocation(0, 50, -200);

	scene.add(model);
	scene.add(model2);
	scene.sky = new Skybox(cubeTexture);
	scene.godRaySource = model2;
}

void tick(float deltaSeconds) {
	if (gConsole->isVisible() == false) {
		float speedX = 1.0f, speedY = 1.0f;
		float dx = gEngine->isDown('a') ? -speedX : gEngine->isDown('d') ? speedX : 0.0f;
		float dz = gEngine->isDown('w') ? -speedY : gEngine->isDown('s') ? speedY : 0.0f;
		float rotY = gEngine->isDown('q') ? -0.5f : gEngine->isDown('e') ? 0.5f : 0.0f;
		float rotX = gEngine->isDown('z') ? -0.5f : gEngine->isDown('x') ? 0.5f : 0.0f;
		cam->move(glm::vec3(dx, 0, dz));
		cam->rotateY(rotY);
		cam->rotateX(rotX);
	}

	model->getTransform().setLocation(0, 20, 0);
	model->getTransform().setRotation(0.01f, glm::vec3(0, 0.5, 1));
	model->getTransform().setLocation(0, -20, 0);

#if DAE_MODEL_ID == 2
	static double time = 0.0;
	time += deltaSeconds;
	if (time > 1.0) time = 0.0;
	daeModel->updateAnimation(0, time);
	daeModel->updateSoftwareSkinning();
#endif
}
<|endoftext|>


<commit_before>
#include <memory>
#include <jsapi.h>
#ifndef MOZJS_MAJOR_VERSION
#include <jsversion.h>
#endif
#include <QtCore>

#include "webqq_calljs.hpp"

static JSClass global_class = {
	"global",
	JSCLASS_GLOBAL_FLAGS|JSCLASS_NEW_RESOLVE,
	JS_PropertyStub,
#ifdef MOZJS_MAJOR_VERSION
	JS_DeletePropertyStub,
#else
	JS_PropertyStub,
#endif
	JS_PropertyStub,
	JS_StrictPropertyStub,
	JS_EnumerateStub,
	JS_ResolveStub,
	JS_ConvertStub,
	NULL,
	JSCLASS_NO_OPTIONAL_MEMBERS
};

std::string webqq::qqimpl::call_js_helper_function_in_buffer(const char* js_content, int js_content_length, std::string helper_file, std::string function, std::vector< std::string > args)
{
#if MOZJS_MAJOR_VERSION >= 24
	std::shared_ptr<JSRuntime> jsrt{ JS_NewRuntime(1024*1024*10, JS_NO_HELPER_THREADS) , JS_DestroyRuntime};
#else
	std::shared_ptr<JSRuntime> jsrt{ JS_NewRuntime(1024*1024*10) , JS_DestroyRuntime};
#endif
	std::shared_ptr<JSContext> jsctx{ JS_NewContext(jsrt.get(), 16*1024) , JS_DestroyContext};

	JS_SetOptions(jsctx.get(), JS_GetOptions(jsctx.get()) |JSOPTION_VAROBJFIX|JSOPTION_COMPILE_N_GO|JSOPTION_NO_SCRIPT_RVAL);

#if JS_VERSION == 185
	JSObject* global_object = JS_NewCompartmentAndGlobalObject(jsctx.get(), &global_class, NULL);
#else
    JS::CompartmentOptions options;
    options.setVersion(JSVERSION_LATEST);

	JSObject* global_object = JS_NewGlobalObject(jsctx.get(), &global_class, NULL, options);
    JSAutoCompartment ac(jsctx.get(), global_object);
#endif
    JS_SetGlobalObject(jsctx.get(), global_object);

	JS_InitStandardClasses(jsctx.get(), global_object);

#if JS_VERSION == 185
	JSObject * script
#else
	JSScript * script
#endif
	= JS_CompileScript(jsctx.get(), global_object, js_content, js_content_length,  helper_file.c_str(), 0);

	JS_ExecuteScript(jsctx.get(), global_object, script, NULL);

	jsval res;
	std::vector<jsval> argv;
	char* res_;

	for (auto _a : args)
	{
		JSString* js_arg = JS_NewStringCopyN(jsctx.get(), _a.c_str(), _a.length());
		argv.push_back(STRING_TO_JSVAL(js_arg));
	}

	JS_CallFunctionName(jsctx.get(), global_object, function.c_str(), argv.size(), argv.data(), &res);

	res_ = JS_EncodeString(jsctx.get(),JSVAL_TO_STRING(res));
	std::string ret = res_;
	JS_free(jsctx.get(),res_);
	return ret;

}

std::string webqq::qqimpl::call_js_helper_function(std::string helper_file, std::string function, std::vector< std::string > args)
{
	QFile helperfile(helper_file.c_str());

	helperfile.open(QIODevice::ReadOnly);

	auto js_content = helperfile.readAll();

	return call_js_helper_function_in_buffer(js_content.constData(), js_content.length(), helper_file, function, args);

}

<commit_msg>tweak preprocessor<commit_after>
#include <memory>
#include <jsapi.h>
#ifndef MOZJS_MAJOR_VERSION
#include <jsversion.h>
#endif
#include <QtCore>

#include "webqq_calljs.hpp"

static JSClass global_class = {
	"global",
	JSCLASS_GLOBAL_FLAGS|JSCLASS_NEW_RESOLVE,
	JS_PropertyStub,
#ifdef MOZJS_MAJOR_VERSION
	JS_DeletePropertyStub,
#else
	JS_PropertyStub,
#endif
	JS_PropertyStub,
	JS_StrictPropertyStub,
	JS_EnumerateStub,
	JS_ResolveStub,
	JS_ConvertStub,
	NULL,
	JSCLASS_NO_OPTIONAL_MEMBERS
};

std::string webqq::qqimpl::call_js_helper_function_in_buffer(const char* js_content, int js_content_length, std::string helper_file, std::string function, std::vector< std::string > args)
{
#if MOZJS_MAJOR_VERSION >= 24
	std::shared_ptr<JSRuntime> jsrt{ JS_NewRuntime(1024*1024*10, JS_NO_HELPER_THREADS) , JS_DestroyRuntime};
#else
	std::shared_ptr<JSRuntime> jsrt{ JS_NewRuntime(1024*1024*10) , JS_DestroyRuntime};
#endif
	std::shared_ptr<JSContext> jsctx{ JS_NewContext(jsrt.get(), 16*1024) , JS_DestroyContext};

	JS_SetOptions(jsctx.get(), JS_GetOptions(jsctx.get()) |JSOPTION_VAROBJFIX|JSOPTION_COMPILE_N_GO|JSOPTION_NO_SCRIPT_RVAL);

#ifdef 	MOZJS_MAJOR_VERSION
    JS::CompartmentOptions options;
    options.setVersion(JSVERSION_LATEST);

	JSObject* global_object = JS_NewGlobalObject(jsctx.get(), &global_class, NULL, options);
    JSAutoCompartment ac(jsctx.get(), global_object);
#elif JS_VERSION == 185
	JSObject* global_object = JS_NewCompartmentAndGlobalObject(jsctx.get(), &global_class, NULL);
#else
	JSObject* global_object = JS_NewGlobalObject(jsctx.get(), &global_class, NULL);
#endif

	JS_SetGlobalObject(jsctx.get(), global_object);

	JS_InitStandardClasses(jsctx.get(), global_object);

#if JS_VERSION == 185
	JSObject * script
#else
	JSScript * script
#endif
	= JS_CompileScript(jsctx.get(), global_object, js_content, js_content_length,  helper_file.c_str(), 0);

	JS_ExecuteScript(jsctx.get(), global_object, script, NULL);

	jsval res;
	std::vector<jsval> argv;
	char* res_;

	for (auto _a : args)
	{
		JSString* js_arg = JS_NewStringCopyN(jsctx.get(), _a.c_str(), _a.length());
		argv.push_back(STRING_TO_JSVAL(js_arg));
	}

	JS_CallFunctionName(jsctx.get(), global_object, function.c_str(), argv.size(), argv.data(), &res);

	res_ = JS_EncodeString(jsctx.get(),JSVAL_TO_STRING(res));
	std::string ret = res_;
	JS_free(jsctx.get(),res_);
	return ret;

}

std::string webqq::qqimpl::call_js_helper_function(std::string helper_file, std::string function, std::vector< std::string > args)
{
	QFile helperfile(helper_file.c_str());

	helperfile.open(QIODevice::ReadOnly);

	auto js_content = helperfile.readAll();

	return call_js_helper_function_in_buffer(js_content.constData(), js_content.length(), helper_file, function, args);

}

<|endoftext|>


<commit_before>#include <fstream>
#include <string>

class Persons_File {
public:
	Persons_File() : is_empty(true), file_size(0) {
		;
	}
	std::string file_name;
	size_t file_size;
	bool is_empty;
	char * key;
	bool is_same;
	std::fstream stream;
	void openNew(std::string _file_name) {
		file_name = _file_name;
		stream.open(file_name, std::ios::out);
	}
};
<commit_msg>Update PersonsFile.hpp<commit_after>#include <fstream>
#include <string>

class Persons_File {
public:
	Persons_File() : is_empty(true), file_size(0) {
		;
	}
	std::string file_name;
	size_t file_size;
	bool is_empty;
	char * key;
	bool is_same;
	std::fstream stream;
	void openNew(std::string const & _file_name) {
		file_name = _file_name;
		stream.open(file_name, std::ios::out);
	}
};
<|endoftext|>