text
stringlengths
54
60.6k
<commit_before><commit_msg>gpl: optimizations and documentation of area scaling<commit_after><|endoftext|>
<commit_before>// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/ui/webui/sync_promo/sync_promo_ui.h" #include "base/command_line.h" #include "base/string_number_conversions.h" #include "base/string_util.h" #include "base/stringprintf.h" #include "base/utf_string_conversions.h" #include "chrome/browser/browser_process.h" #include "chrome/browser/first_run/first_run.h" #include "chrome/browser/google/google_util.h" #include "chrome/browser/prefs/pref_service.h" #include "chrome/browser/profiles/profile.h" #include "chrome/browser/profiles/profile_info_cache.h" #include "chrome/browser/profiles/profile_manager.h" #include "chrome/browser/sync/profile_sync_service.h" #include "chrome/browser/sync/profile_sync_service_factory.h" #include "chrome/browser/ui/webui/chrome_url_data_manager.h" #include "chrome/browser/ui/webui/chrome_web_ui_data_source.h" #include "chrome/browser/ui/webui/options/core_options_handler.h" #include "chrome/browser/ui/webui/sync_promo/sync_promo_handler.h" #include "chrome/browser/ui/webui/sync_promo/sync_promo_trial.h" #include "chrome/browser/ui/webui/theme_source.h" #include "chrome/common/chrome_switches.h" #include "chrome/common/pref_names.h" #include "chrome/common/url_constants.h" #include "chrome/common/net/url_util.h" #include "content/public/browser/web_contents.h" #include "content/public/browser/web_ui.h" #include "google_apis/gaia/gaia_urls.h" #include "grit/browser_resources.h" #include "grit/generated_resources.h" #include "grit/theme_resources.h" #include "net/base/escape.h" #include "ui/base/l10n/l10n_util.h" using content::WebContents; namespace { const char kStringsJsFile[] = "strings.js"; const char kSyncPromoJsFile[] = "sync_promo.js"; const char kSyncPromoQueryKeyAutoClose[] = "auto_close"; const char kSyncPromoQueryKeyContinue[] = "continue"; const char kSyncPromoQueryKeyNextPage[] = "next_page"; const char kSyncPromoQueryKeySource[] = "source"; // TODO(rogerta): It would be better to use about:blank, but until that is // supported by Gaia this blank continue URL will be used. const char kContinueUrl[] = "http://www.google.com/gen_204"; // The maximum number of times we want to show the sync promo at startup. const int kSyncPromoShowAtStartupMaximum = 10; // Checks we want to show the sync promo for the given brand. bool AllowPromoAtStartupForCurrentBrand() { std::string brand; google_util::GetBrand(&brand); if (brand.empty()) return true; if (google_util::IsInternetCafeBrandCode(brand)) return false; // Enable for both organic and distribution. return true; } // The Web UI data source for the sync promo page. class SyncPromoUIHTMLSource : public ChromeWebUIDataSource { public: explicit SyncPromoUIHTMLSource(content::WebUI* web_ui); private: ~SyncPromoUIHTMLSource() {} DISALLOW_COPY_AND_ASSIGN(SyncPromoUIHTMLSource); }; SyncPromoUIHTMLSource::SyncPromoUIHTMLSource(content::WebUI* web_ui) : ChromeWebUIDataSource(chrome::kChromeUISyncPromoHost) { DictionaryValue localized_strings; options::CoreOptionsHandler::GetStaticLocalizedValues(&localized_strings); SyncSetupHandler::GetStaticLocalizedValues(&localized_strings, web_ui); AddLocalizedStrings(localized_strings); } } // namespace SyncPromoUI::SyncPromoUI(content::WebUI* web_ui) : WebUIController(web_ui) { SyncPromoHandler* handler = new SyncPromoHandler( g_browser_process->profile_manager()); web_ui->AddMessageHandler(handler); // Set up the chrome://theme/ source. Profile* profile = Profile::FromWebUI(web_ui); ThemeSource* theme = new ThemeSource(profile); ChromeURLDataManager::AddDataSource(profile, theme); // Set up the sync promo source. SyncPromoUIHTMLSource* html_source = new SyncPromoUIHTMLSource(web_ui); html_source->set_json_path(kStringsJsFile); html_source->add_resource_path(kSyncPromoJsFile, IDR_SYNC_PROMO_JS); html_source->set_default_resource(IDR_SYNC_PROMO_HTML); html_source->set_use_json_js_format_v2(); ChromeURLDataManager::AddDataSource(profile, html_source); sync_promo_trial::RecordUserShownPromo(web_ui); } // static bool SyncPromoUI::HasShownPromoAtStartup(Profile* profile) { return profile->GetPrefs()->HasPrefPath(prefs::kSyncPromoStartupCount); } // static bool SyncPromoUI::ShouldShowSyncPromo(Profile* profile) { #if defined(OS_CHROMEOS) // There's no need to show the sync promo on cros since cros users are logged // into sync already. return false; #endif // Honor the sync policies. if (!profile->GetOriginalProfile()->IsSyncAccessible()) return false; // If the user is already signed into sync then don't show the promo. ProfileSyncService* service = ProfileSyncServiceFactory::GetInstance()->GetForProfile( profile->GetOriginalProfile()); if (!service || service->HasSyncSetupCompleted()) return false; // Default to allow the promo. return true; } // static void SyncPromoUI::RegisterUserPrefs(PrefService* prefs) { prefs->RegisterIntegerPref( prefs::kSyncPromoStartupCount, 0, PrefService::UNSYNCABLE_PREF); prefs->RegisterBooleanPref( prefs::kSyncPromoUserSkipped, false, PrefService::UNSYNCABLE_PREF); prefs->RegisterBooleanPref(prefs::kSyncPromoShowOnFirstRunAllowed, true, PrefService::UNSYNCABLE_PREF); SyncPromoHandler::RegisterUserPrefs(prefs); } // static bool SyncPromoUI::ShouldShowSyncPromoAtStartup(Profile* profile, bool is_new_profile) { DCHECK(profile); if (!ShouldShowSyncPromo(profile)) return false; const CommandLine& command_line = *CommandLine::ForCurrentProcess(); if (command_line.HasSwitch(switches::kNoFirstRun)) is_new_profile = false; if (!is_new_profile) { if (!HasShownPromoAtStartup(profile)) return false; } if (HasUserSkippedSyncPromo(profile)) return false; // For Chinese users skip the sync promo. if (g_browser_process->GetApplicationLocale() == "zh-CN") return false; PrefService* prefs = profile->GetPrefs(); int show_count = prefs->GetInteger(prefs::kSyncPromoStartupCount); if (show_count >= kSyncPromoShowAtStartupMaximum) return false; // This pref can be set in the master preferences file to allow or disallow // showing the sync promo at startup. if (prefs->HasPrefPath(prefs::kSyncPromoShowOnFirstRunAllowed)) return prefs->GetBoolean(prefs::kSyncPromoShowOnFirstRunAllowed); // For now don't show the promo for some brands. if (!AllowPromoAtStartupForCurrentBrand()) return false; // Default to show the promo for Google Chrome builds. #if defined(GOOGLE_CHROME_BUILD) return true; #else return false; #endif } void SyncPromoUI::DidShowSyncPromoAtStartup(Profile* profile) { int show_count = profile->GetPrefs()->GetInteger( prefs::kSyncPromoStartupCount); show_count++; profile->GetPrefs()->SetInteger(prefs::kSyncPromoStartupCount, show_count); } bool SyncPromoUI::HasUserSkippedSyncPromo(Profile* profile) { return profile->GetPrefs()->GetBoolean(prefs::kSyncPromoUserSkipped); } void SyncPromoUI::SetUserSkippedSyncPromo(Profile* profile) { profile->GetPrefs()->SetBoolean(prefs::kSyncPromoUserSkipped, true); } // static GURL SyncPromoUI::GetSyncPromoURL(const GURL& next_page, Source source, bool auto_close) { DCHECK_NE(SOURCE_UNKNOWN, source); std::string url_string; if (UseWebBasedSigninFlow()) { // Build a Gaia-based URL that can be used to sign the user into chrome. // There are required request parameters: // // - tell Gaia which service the user is signing into. In this case, // a chrome sign in uses the service "chromiumsync" // - provide a continue URL. This is the URL that Gaia will redirect to // once the sign is complete. // // The continue URL includes a source parameter that can be extracted using // the function GetSourceForSyncPromoURL() below. This is used to know // which of the chrome sign in access points was used to sign the userr in. // See OneClickSigninHelper for details. url_string = GaiaUrls::GetInstance()->service_login_url(); url_string.append("?service=chromiumsync"); std::string continue_url = base::StringPrintf("%s?%s=%d", kContinueUrl, kSyncPromoQueryKeySource, static_cast<int>(source)); base::StringAppendF(&url_string, "&%s=%s", kSyncPromoQueryKeyContinue, net::EscapeQueryParamValue( continue_url, false).c_str()); } else { url_string = base::StringPrintf("%s?%s=%d", chrome::kChromeUISyncPromoURL, kSyncPromoQueryKeySource, static_cast<int>(source)); if (auto_close) base::StringAppendF(&url_string, "&%s=1", kSyncPromoQueryKeyAutoClose); if (!next_page.spec().empty()) { base::StringAppendF(&url_string, "&%s=%s", kSyncPromoQueryKeyNextPage, net::EscapeQueryParamValue(next_page.spec(), false).c_str()); } } return GURL(url_string); } // static GURL SyncPromoUI::GetNextPageURLForSyncPromoURL(const GURL& url) { std::string value; if (chrome_common_net::GetValueForKeyInQuery( url, kSyncPromoQueryKeyNextPage, &value)) { return GURL(value); } return GURL(); } // static SyncPromoUI::Source SyncPromoUI::GetSourceForSyncPromoURL(const GURL& url) { std::string value; if (chrome_common_net::GetValueForKeyInQuery( url, kSyncPromoQueryKeySource, &value)) { int source = 0; if (base::StringToInt(value, &source) && source >= SOURCE_START_PAGE && source < SOURCE_UNKNOWN) { return static_cast<Source>(source); } } return SOURCE_UNKNOWN; } // static bool SyncPromoUI::GetAutoCloseForSyncPromoURL(const GURL& url) { std::string value; if (chrome_common_net::GetValueForKeyInQuery( url, kSyncPromoQueryKeyAutoClose, &value)) { int source = 0; base::StringToInt(value, &source); return (source == 1); } return false; } // static bool SyncPromoUI::UseWebBasedSigninFlow() { #if defined(ENABLE_ONE_CLICK_SIGNIN) return !CommandLine::ForCurrentProcess()->HasSwitch( switches::kUseClientLoginSigninFlow); #else return false; #endif } <commit_msg>Don't show Sync promo if we have zero network connectivity.<commit_after>// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/ui/webui/sync_promo/sync_promo_ui.h" #include "base/command_line.h" #include "base/string_number_conversions.h" #include "base/string_util.h" #include "base/stringprintf.h" #include "base/utf_string_conversions.h" #include "chrome/browser/browser_process.h" #include "chrome/browser/first_run/first_run.h" #include "chrome/browser/google/google_util.h" #include "chrome/browser/prefs/pref_service.h" #include "chrome/browser/profiles/profile.h" #include "chrome/browser/profiles/profile_info_cache.h" #include "chrome/browser/profiles/profile_manager.h" #include "chrome/browser/sync/profile_sync_service.h" #include "chrome/browser/sync/profile_sync_service_factory.h" #include "chrome/browser/ui/webui/chrome_url_data_manager.h" #include "chrome/browser/ui/webui/chrome_web_ui_data_source.h" #include "chrome/browser/ui/webui/options/core_options_handler.h" #include "chrome/browser/ui/webui/sync_promo/sync_promo_handler.h" #include "chrome/browser/ui/webui/sync_promo/sync_promo_trial.h" #include "chrome/browser/ui/webui/theme_source.h" #include "chrome/common/chrome_switches.h" #include "chrome/common/pref_names.h" #include "chrome/common/url_constants.h" #include "chrome/common/net/url_util.h" #include "content/public/browser/web_contents.h" #include "content/public/browser/web_ui.h" #include "google_apis/gaia/gaia_urls.h" #include "grit/browser_resources.h" #include "grit/generated_resources.h" #include "grit/theme_resources.h" #include "net/base/escape.h" #include "net/base/network_change_notifier.h" #include "ui/base/l10n/l10n_util.h" using content::WebContents; namespace { const char kStringsJsFile[] = "strings.js"; const char kSyncPromoJsFile[] = "sync_promo.js"; const char kSyncPromoQueryKeyAutoClose[] = "auto_close"; const char kSyncPromoQueryKeyContinue[] = "continue"; const char kSyncPromoQueryKeyNextPage[] = "next_page"; const char kSyncPromoQueryKeySource[] = "source"; // TODO(rogerta): It would be better to use about:blank, but until that is // supported by Gaia this blank continue URL will be used. const char kContinueUrl[] = "http://www.google.com/gen_204"; // The maximum number of times we want to show the sync promo at startup. const int kSyncPromoShowAtStartupMaximum = 10; // Checks we want to show the sync promo for the given brand. bool AllowPromoAtStartupForCurrentBrand() { std::string brand; google_util::GetBrand(&brand); if (brand.empty()) return true; if (google_util::IsInternetCafeBrandCode(brand)) return false; // Enable for both organic and distribution. return true; } // The Web UI data source for the sync promo page. class SyncPromoUIHTMLSource : public ChromeWebUIDataSource { public: explicit SyncPromoUIHTMLSource(content::WebUI* web_ui); private: ~SyncPromoUIHTMLSource() {} DISALLOW_COPY_AND_ASSIGN(SyncPromoUIHTMLSource); }; SyncPromoUIHTMLSource::SyncPromoUIHTMLSource(content::WebUI* web_ui) : ChromeWebUIDataSource(chrome::kChromeUISyncPromoHost) { DictionaryValue localized_strings; options::CoreOptionsHandler::GetStaticLocalizedValues(&localized_strings); SyncSetupHandler::GetStaticLocalizedValues(&localized_strings, web_ui); AddLocalizedStrings(localized_strings); } } // namespace SyncPromoUI::SyncPromoUI(content::WebUI* web_ui) : WebUIController(web_ui) { SyncPromoHandler* handler = new SyncPromoHandler( g_browser_process->profile_manager()); web_ui->AddMessageHandler(handler); // Set up the chrome://theme/ source. Profile* profile = Profile::FromWebUI(web_ui); ThemeSource* theme = new ThemeSource(profile); ChromeURLDataManager::AddDataSource(profile, theme); // Set up the sync promo source. SyncPromoUIHTMLSource* html_source = new SyncPromoUIHTMLSource(web_ui); html_source->set_json_path(kStringsJsFile); html_source->add_resource_path(kSyncPromoJsFile, IDR_SYNC_PROMO_JS); html_source->set_default_resource(IDR_SYNC_PROMO_HTML); html_source->set_use_json_js_format_v2(); ChromeURLDataManager::AddDataSource(profile, html_source); sync_promo_trial::RecordUserShownPromo(web_ui); } // static bool SyncPromoUI::HasShownPromoAtStartup(Profile* profile) { return profile->GetPrefs()->HasPrefPath(prefs::kSyncPromoStartupCount); } // static bool SyncPromoUI::ShouldShowSyncPromo(Profile* profile) { #if defined(OS_CHROMEOS) // There's no need to show the sync promo on cros since cros users are logged // into sync already. return false; #endif // Don't bother if we don't have any kind of network connection. if (net::NetworkChangeNotifier::IsOffline()) return false; // Honor the sync policies. if (!profile->GetOriginalProfile()->IsSyncAccessible()) return false; // If the user is already signed into sync then don't show the promo. ProfileSyncService* service = ProfileSyncServiceFactory::GetInstance()->GetForProfile( profile->GetOriginalProfile()); if (!service || service->HasSyncSetupCompleted()) return false; // Default to allow the promo. return true; } // static void SyncPromoUI::RegisterUserPrefs(PrefService* prefs) { prefs->RegisterIntegerPref( prefs::kSyncPromoStartupCount, 0, PrefService::UNSYNCABLE_PREF); prefs->RegisterBooleanPref( prefs::kSyncPromoUserSkipped, false, PrefService::UNSYNCABLE_PREF); prefs->RegisterBooleanPref(prefs::kSyncPromoShowOnFirstRunAllowed, true, PrefService::UNSYNCABLE_PREF); SyncPromoHandler::RegisterUserPrefs(prefs); } // static bool SyncPromoUI::ShouldShowSyncPromoAtStartup(Profile* profile, bool is_new_profile) { DCHECK(profile); if (!ShouldShowSyncPromo(profile)) return false; const CommandLine& command_line = *CommandLine::ForCurrentProcess(); if (command_line.HasSwitch(switches::kNoFirstRun)) is_new_profile = false; if (!is_new_profile) { if (!HasShownPromoAtStartup(profile)) return false; } if (HasUserSkippedSyncPromo(profile)) return false; // For Chinese users skip the sync promo. if (g_browser_process->GetApplicationLocale() == "zh-CN") return false; PrefService* prefs = profile->GetPrefs(); int show_count = prefs->GetInteger(prefs::kSyncPromoStartupCount); if (show_count >= kSyncPromoShowAtStartupMaximum) return false; // This pref can be set in the master preferences file to allow or disallow // showing the sync promo at startup. if (prefs->HasPrefPath(prefs::kSyncPromoShowOnFirstRunAllowed)) return prefs->GetBoolean(prefs::kSyncPromoShowOnFirstRunAllowed); // For now don't show the promo for some brands. if (!AllowPromoAtStartupForCurrentBrand()) return false; // Default to show the promo for Google Chrome builds. #if defined(GOOGLE_CHROME_BUILD) return true; #else return false; #endif } void SyncPromoUI::DidShowSyncPromoAtStartup(Profile* profile) { int show_count = profile->GetPrefs()->GetInteger( prefs::kSyncPromoStartupCount); show_count++; profile->GetPrefs()->SetInteger(prefs::kSyncPromoStartupCount, show_count); } bool SyncPromoUI::HasUserSkippedSyncPromo(Profile* profile) { return profile->GetPrefs()->GetBoolean(prefs::kSyncPromoUserSkipped); } void SyncPromoUI::SetUserSkippedSyncPromo(Profile* profile) { profile->GetPrefs()->SetBoolean(prefs::kSyncPromoUserSkipped, true); } // static GURL SyncPromoUI::GetSyncPromoURL(const GURL& next_page, Source source, bool auto_close) { DCHECK_NE(SOURCE_UNKNOWN, source); std::string url_string; if (UseWebBasedSigninFlow()) { // Build a Gaia-based URL that can be used to sign the user into chrome. // There are required request parameters: // // - tell Gaia which service the user is signing into. In this case, // a chrome sign in uses the service "chromiumsync" // - provide a continue URL. This is the URL that Gaia will redirect to // once the sign is complete. // // The continue URL includes a source parameter that can be extracted using // the function GetSourceForSyncPromoURL() below. This is used to know // which of the chrome sign in access points was used to sign the userr in. // See OneClickSigninHelper for details. url_string = GaiaUrls::GetInstance()->service_login_url(); url_string.append("?service=chromiumsync"); std::string continue_url = base::StringPrintf("%s?%s=%d", kContinueUrl, kSyncPromoQueryKeySource, static_cast<int>(source)); base::StringAppendF(&url_string, "&%s=%s", kSyncPromoQueryKeyContinue, net::EscapeQueryParamValue( continue_url, false).c_str()); } else { url_string = base::StringPrintf("%s?%s=%d", chrome::kChromeUISyncPromoURL, kSyncPromoQueryKeySource, static_cast<int>(source)); if (auto_close) base::StringAppendF(&url_string, "&%s=1", kSyncPromoQueryKeyAutoClose); if (!next_page.spec().empty()) { base::StringAppendF(&url_string, "&%s=%s", kSyncPromoQueryKeyNextPage, net::EscapeQueryParamValue(next_page.spec(), false).c_str()); } } return GURL(url_string); } // static GURL SyncPromoUI::GetNextPageURLForSyncPromoURL(const GURL& url) { std::string value; if (chrome_common_net::GetValueForKeyInQuery( url, kSyncPromoQueryKeyNextPage, &value)) { return GURL(value); } return GURL(); } // static SyncPromoUI::Source SyncPromoUI::GetSourceForSyncPromoURL(const GURL& url) { std::string value; if (chrome_common_net::GetValueForKeyInQuery( url, kSyncPromoQueryKeySource, &value)) { int source = 0; if (base::StringToInt(value, &source) && source >= SOURCE_START_PAGE && source < SOURCE_UNKNOWN) { return static_cast<Source>(source); } } return SOURCE_UNKNOWN; } // static bool SyncPromoUI::GetAutoCloseForSyncPromoURL(const GURL& url) { std::string value; if (chrome_common_net::GetValueForKeyInQuery( url, kSyncPromoQueryKeyAutoClose, &value)) { int source = 0; base::StringToInt(value, &source); return (source == 1); } return false; } // static bool SyncPromoUI::UseWebBasedSigninFlow() { #if defined(ENABLE_ONE_CLICK_SIGNIN) return !CommandLine::ForCurrentProcess()->HasSwitch( switches::kUseClientLoginSigninFlow); #else return false; #endif } <|endoftext|>
<commit_before>/* * slicerenderer.cpp * * Created on: 09.05.2012 * Author: Ralph */ #include "../../glew/include/glew.h" #include <QtOpenGL/QGLShaderProgram> #include <QtGui/QVector3D> #include <QtGui/QMatrix4x4> #include "glfunctions.h" #include "slicerenderer.h" SliceRenderer::SliceRenderer() : ObjectRenderer(), vboIds( new GLuint[ 4 ] ), m_x( 0. ), m_y( 0. ), m_z( 0. ), m_xb( 0. ), m_yb( 0. ), m_zb( 0. ), m_xOld( -1 ), m_yOld( -1 ), m_zOld( -1 ), m_xbOld( -1 ), m_ybOld( -1 ), m_zbOld( -1 ) { } SliceRenderer::~SliceRenderer() { glDeleteBuffers( 4, vboIds ); delete[] vboIds; } void SliceRenderer::init() { initShader(); glGenBuffers( 4, vboIds ); GLushort indices[] = { 0, 1, 2, 0, 2, 3 }; // Transfer index data to VBO 0 glBindBuffer( GL_ELEMENT_ARRAY_BUFFER, vboIds[ 0 ] ); glBufferData( GL_ELEMENT_ARRAY_BUFFER, 6 * sizeof(GLushort), indices, GL_STATIC_DRAW ); initGeometry(); } void SliceRenderer::initShader() { m_program = GLFunctions::initShader( "slice" ); } void SliceRenderer::initGeometry() { m_x = model()->data( model()->index( 0, 100 ), Qt::UserRole ).toFloat(); m_y = model()->data( model()->index( 0, 101 ), Qt::UserRole ).toFloat(); m_z = model()->data( model()->index( 0, 102 ), Qt::UserRole ).toFloat(); int xi = model()->data( model()->index( 0, 100 ), Qt::UserRole ).toInt(); int yi = model()->data( model()->index( 0, 101 ), Qt::UserRole ).toInt(); int zi = model()->data( model()->index( 0, 102 ), Qt::UserRole ).toInt(); m_xb = model()->data( model()->index( 0, 103 ), Qt::UserRole ).toFloat(); m_yb = model()->data( model()->index( 0, 104 ), Qt::UserRole ).toFloat(); m_zb = model()->data( model()->index( 0, 105 ), Qt::UserRole ).toFloat(); int xbi = model()->data( model()->index( 0, 103 ), Qt::UserRole ).toInt(); int ybi = model()->data( model()->index( 0, 104 ), Qt::UserRole ).toInt(); int zbi = model()->data( model()->index( 0, 105 ), Qt::UserRole ).toInt(); float dx = model()->data( model()->index( 0, 106 ), Qt::UserRole ).toFloat(); float dy = model()->data( model()->index( 0, 107 ), Qt::UserRole ).toFloat(); float dz = model()->data( model()->index( 0, 108 ), Qt::UserRole ).toFloat(); m_x *= dx; m_y *= dy; m_z *= dz; m_xb *= dx; m_yb *= dy; m_zb *= dz; if ( zi != m_zOld || zbi != m_zbOld ) { VertexData verticesAxial[] = { { QVector3D( 0.0, 0.0, m_z ), QVector3D( 0.0, 0.0, m_z/m_zb ) }, { QVector3D( m_xb, 0.0, m_z ), QVector3D( 1.0, 0.0, m_z/m_zb ) }, { QVector3D( m_xb, m_yb, m_z ), QVector3D( 1.0, 1.0, m_z/m_zb ) }, { QVector3D( 0.0, m_yb, m_z ), QVector3D( 0.0, 1.0, m_z/m_zb ) } }; // Transfer vertex data to VBO 1 glBindBuffer( GL_ARRAY_BUFFER, vboIds[ 1 ] ); glBufferData( GL_ARRAY_BUFFER, 4 * sizeof(VertexData), verticesAxial, GL_STATIC_DRAW ); } if ( yi != m_yOld || ybi != m_ybOld ) { VertexData verticesCoronal[] = { { QVector3D( 0.0, m_y, 0.0 ), QVector3D( 0.0, m_y/m_yb, 0.0 ) }, { QVector3D( m_xb, m_y, 0.0 ), QVector3D( 1.0, m_y/m_yb, 0.0 ) }, { QVector3D( m_xb, m_y, m_zb ), QVector3D( 1.0, m_y/m_yb, 1.0 ) }, { QVector3D( 0.0, m_y, m_zb ), QVector3D( 0.0, m_y/m_yb, 1.0 ) } }; // Transfer vertex data to VBO 2 glBindBuffer( GL_ARRAY_BUFFER, vboIds[ 2 ] ); glBufferData( GL_ARRAY_BUFFER, 4 * sizeof(VertexData), verticesCoronal, GL_STATIC_DRAW ); } if ( xi != m_xOld || xbi != m_xbOld ) { VertexData verticesSagittal[] = { { QVector3D( m_x, 0.0, 0.0 ), QVector3D( m_x/m_xb, 0.0, 0.0 ) }, { QVector3D( m_x, m_yb, 0.0 ), QVector3D( m_x/m_xb, 1.0, 0.0 ) }, { QVector3D( m_x, m_yb, m_zb ), QVector3D( m_x/m_xb, 1.0, 1.0 ) }, { QVector3D( m_x, 0.0, m_zb ), QVector3D( m_x/m_xb, 0.0, 1.0 ) } }; // Transfer vertex data to VBO 3 glBindBuffer( GL_ARRAY_BUFFER, vboIds[ 3 ] ); glBufferData( GL_ARRAY_BUFFER, 4 * sizeof(VertexData), verticesSagittal, GL_STATIC_DRAW ); } m_xOld = xi; m_yOld = yi; m_zOld = zi; m_xbOld = xbi; m_ybOld = ybi; m_zbOld = zbi; } void SliceRenderer::setupTextures() { GLFunctions::setupTextures( model() ); } void SliceRenderer::setShaderVars() { GLFunctions::setSliceShaderVars( m_program, model() ); } void SliceRenderer::draw( QMatrix4x4 mvp_matrix ) { //qDebug() << "main gl draw"; setupTextures(); glColor4f( 0.0, 0.0, 0.0, 1.0 ); // Set modelview-projection matrix m_program->setUniformValue( "mvp_matrix", mvp_matrix ); initGeometry(); drawAxial(); drawCoronal(); drawSagittal(); } void SliceRenderer::drawAxial() { // Tell OpenGL which VBOs to use glBindBuffer( GL_ELEMENT_ARRAY_BUFFER, vboIds[ 0 ] ); glBindBuffer( GL_ARRAY_BUFFER, vboIds[ 1 ] ); setShaderVars(); // Draw cube geometry using indices from VBO 0 glDrawElements( GL_TRIANGLES, 6, GL_UNSIGNED_SHORT, 0 ); } void SliceRenderer::drawCoronal() { // Tell OpenGL which VBOs to use glBindBuffer( GL_ELEMENT_ARRAY_BUFFER, vboIds[ 0 ] ); glBindBuffer( GL_ARRAY_BUFFER, vboIds[ 2 ] ); setShaderVars(); // Draw cube geometry using indices from VBO 0 glDrawElements( GL_TRIANGLES, 6, GL_UNSIGNED_SHORT, 0 ); } void SliceRenderer::drawSagittal() { // Tell OpenGL which VBOs to use glBindBuffer( GL_ELEMENT_ARRAY_BUFFER, vboIds[ 0 ] ); glBindBuffer( GL_ARRAY_BUFFER, vboIds[ 3 ] ); setShaderVars(); // Draw cube geometry using indices from VBO 0 glDrawElements( GL_TRIANGLES, 6, GL_UNSIGNED_SHORT, 0 ); } <commit_msg>render slice in the middle of voxels<commit_after>/* * slicerenderer.cpp * * Created on: 09.05.2012 * Author: Ralph */ #include "../../glew/include/glew.h" #include <QtOpenGL/QGLShaderProgram> #include <QtGui/QVector3D> #include <QtGui/QMatrix4x4> #include "glfunctions.h" #include "slicerenderer.h" SliceRenderer::SliceRenderer() : ObjectRenderer(), vboIds( new GLuint[ 4 ] ), m_x( 0. ), m_y( 0. ), m_z( 0. ), m_xb( 0. ), m_yb( 0. ), m_zb( 0. ), m_xOld( -1 ), m_yOld( -1 ), m_zOld( -1 ), m_xbOld( -1 ), m_ybOld( -1 ), m_zbOld( -1 ) { } SliceRenderer::~SliceRenderer() { glDeleteBuffers( 4, vboIds ); delete[] vboIds; } void SliceRenderer::init() { initShader(); glGenBuffers( 4, vboIds ); GLushort indices[] = { 0, 1, 2, 0, 2, 3 }; // Transfer index data to VBO 0 glBindBuffer( GL_ELEMENT_ARRAY_BUFFER, vboIds[ 0 ] ); glBufferData( GL_ELEMENT_ARRAY_BUFFER, 6 * sizeof(GLushort), indices, GL_STATIC_DRAW ); initGeometry(); } void SliceRenderer::initShader() { m_program = GLFunctions::initShader( "slice" ); } void SliceRenderer::initGeometry() { m_x = model()->data( model()->index( 0, 100 ), Qt::UserRole ).toFloat(); m_y = model()->data( model()->index( 0, 101 ), Qt::UserRole ).toFloat(); m_z = model()->data( model()->index( 0, 102 ), Qt::UserRole ).toFloat(); int xi = model()->data( model()->index( 0, 100 ), Qt::UserRole ).toInt(); int yi = model()->data( model()->index( 0, 101 ), Qt::UserRole ).toInt(); int zi = model()->data( model()->index( 0, 102 ), Qt::UserRole ).toInt(); m_xb = model()->data( model()->index( 0, 103 ), Qt::UserRole ).toFloat(); m_yb = model()->data( model()->index( 0, 104 ), Qt::UserRole ).toFloat(); m_zb = model()->data( model()->index( 0, 105 ), Qt::UserRole ).toFloat(); int xbi = model()->data( model()->index( 0, 103 ), Qt::UserRole ).toInt(); int ybi = model()->data( model()->index( 0, 104 ), Qt::UserRole ).toInt(); int zbi = model()->data( model()->index( 0, 105 ), Qt::UserRole ).toInt(); float dx = model()->data( model()->index( 0, 106 ), Qt::UserRole ).toFloat(); float dy = model()->data( model()->index( 0, 107 ), Qt::UserRole ).toFloat(); float dz = model()->data( model()->index( 0, 108 ), Qt::UserRole ).toFloat(); float x = m_x * dx + dx / 2.; float y = m_y * dy + dy / 2.; float z = m_z * dz + dz / 2.; float xb = m_xb * dx; float yb = m_yb * dy; float zb = m_zb * dz; if ( zi != m_zOld || zbi != m_zbOld ) { VertexData verticesAxial[] = { { QVector3D( 0.0, 0.0, z ), QVector3D( 0.0, 0.0, z / zb ) }, { QVector3D( xb, 0.0, z ), QVector3D( 1.0, 0.0, z / zb ) }, { QVector3D( xb, yb, z ), QVector3D( 1.0, 1.0, z / zb ) }, { QVector3D( 0.0, yb, z ), QVector3D( 0.0, 1.0, z / zb ) } }; // Transfer vertex data to VBO 1 glBindBuffer( GL_ARRAY_BUFFER, vboIds[ 1 ] ); glBufferData( GL_ARRAY_BUFFER, 4 * sizeof(VertexData), verticesAxial, GL_STATIC_DRAW ); } if ( yi != m_yOld || ybi != m_ybOld ) { VertexData verticesCoronal[] = { { QVector3D( 0.0, y, 0.0 ), QVector3D( 0.0, y / yb, 0.0 ) }, { QVector3D( xb, y, 0.0 ), QVector3D( 1.0, y / yb, 0.0 ) }, { QVector3D( xb, y, zb ), QVector3D( 1.0, y / yb, 1.0 ) }, { QVector3D( 0.0, y, zb ), QVector3D( 0.0, y / yb, 1.0 ) } }; // Transfer vertex data to VBO 2 glBindBuffer( GL_ARRAY_BUFFER, vboIds[ 2 ] ); glBufferData( GL_ARRAY_BUFFER, 4 * sizeof(VertexData), verticesCoronal, GL_STATIC_DRAW ); } if ( xi != m_xOld || xbi != m_xbOld ) { VertexData verticesSagittal[] = { { QVector3D( x, 0.0, 0.0 ), QVector3D( x / xb, 0.0, 0.0 ) }, { QVector3D( x, yb, 0.0 ), QVector3D( x / xb, 1.0, 0.0 ) }, { QVector3D( x, yb, zb ), QVector3D( x / xb, 1.0, 1.0 ) }, { QVector3D( x, 0.0, zb ), QVector3D( x / xb, 0.0, 1.0 ) } }; // Transfer vertex data to VBO 3 glBindBuffer( GL_ARRAY_BUFFER, vboIds[ 3 ] ); glBufferData( GL_ARRAY_BUFFER, 4 * sizeof(VertexData), verticesSagittal, GL_STATIC_DRAW ); } m_xOld = xi; m_yOld = yi; m_zOld = zi; m_xbOld = xbi; m_ybOld = ybi; m_zbOld = zbi; } void SliceRenderer::setupTextures() { GLFunctions::setupTextures( model() ); } void SliceRenderer::setShaderVars() { GLFunctions::setSliceShaderVars( m_program, model() ); } void SliceRenderer::draw( QMatrix4x4 mvp_matrix ) { //qDebug() << "main gl draw"; setupTextures(); glColor4f( 0.0, 0.0, 0.0, 1.0 ); // Set modelview-projection matrix m_program->setUniformValue( "mvp_matrix", mvp_matrix ); initGeometry(); drawAxial(); drawCoronal(); drawSagittal(); } void SliceRenderer::drawAxial() { // Tell OpenGL which VBOs to use glBindBuffer( GL_ELEMENT_ARRAY_BUFFER, vboIds[ 0 ] ); glBindBuffer( GL_ARRAY_BUFFER, vboIds[ 1 ] ); setShaderVars(); // Draw cube geometry using indices from VBO 0 glDrawElements( GL_TRIANGLES, 6, GL_UNSIGNED_SHORT, 0 ); } void SliceRenderer::drawCoronal() { // Tell OpenGL which VBOs to use glBindBuffer( GL_ELEMENT_ARRAY_BUFFER, vboIds[ 0 ] ); glBindBuffer( GL_ARRAY_BUFFER, vboIds[ 2 ] ); setShaderVars(); // Draw cube geometry using indices from VBO 0 glDrawElements( GL_TRIANGLES, 6, GL_UNSIGNED_SHORT, 0 ); } void SliceRenderer::drawSagittal() { // Tell OpenGL which VBOs to use glBindBuffer( GL_ELEMENT_ARRAY_BUFFER, vboIds[ 0 ] ); glBindBuffer( GL_ARRAY_BUFFER, vboIds[ 3 ] ); setShaderVars(); // Draw cube geometry using indices from VBO 0 glDrawElements( GL_TRIANGLES, 6, GL_UNSIGNED_SHORT, 0 ); } <|endoftext|>
<commit_before>////////////////////////////////////////////////////////////////////////// // // Copyright (c) 2017, Image Engine Design 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 John Haddon nor the names of // any other contributors to this software 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. // ////////////////////////////////////////////////////////////////////////// #include "GafferUI/PlugAdder.h" #include "GafferUI/SpacerGadget.h" #include "GafferUI/StandardNodeGadget.h" #include "GafferUI/TextGadget.h" #include "Gaffer/BoxIO.h" #include "Gaffer/Metadata.h" #include "Gaffer/ScriptNode.h" #include "Gaffer/StringPlug.h" #include "Gaffer/UndoScope.h" #include "boost/algorithm/string/replace.hpp" #include "boost/bind.hpp" using namespace IECore; using namespace Gaffer; using namespace GafferUI; ////////////////////////////////////////////////////////////////////////// // PlugAdder ////////////////////////////////////////////////////////////////////////// namespace { class BoxIOPlugAdder : public PlugAdder { public : BoxIOPlugAdder( BoxIOPtr boxIO ) : m_boxIO( boxIO ) { m_boxIO->childAddedSignal().connect( boost::bind( &BoxIOPlugAdder::childAdded, this ) ); m_boxIO->childRemovedSignal().connect( boost::bind( &BoxIOPlugAdder::childRemoved, this ) ); updateVisibility(); } protected : bool canCreateConnection( const Plug *endpoint ) const override { if( !PlugAdder::canCreateConnection( endpoint ) ) { return false; } return endpoint->direction() == m_boxIO->direction(); } void createConnection( Plug *endpoint ) override { std::string name = endpoint->relativeName( endpoint->node() ); boost::replace_all( name, ".", "_" ); m_boxIO->namePlug()->setValue( name ); m_boxIO->setup( endpoint ); applyEdgeMetadata( m_boxIO->plug() ); if( m_boxIO->promotedPlug() ) { applyEdgeMetadata( m_boxIO->promotedPlug(), /* opposite = */ true ); } if( m_boxIO->direction() == Plug::In ) { endpoint->setInput( m_boxIO->plug() ); } else { m_boxIO->plug()->setInput( endpoint ); } } private : void childAdded() { updateVisibility(); } void childRemoved() { updateVisibility(); } void updateVisibility() { setVisible( !m_boxIO->plug() ); } BoxIOPtr m_boxIO; }; } // namespace ////////////////////////////////////////////////////////////////////////// // StringPlugValueGadget ////////////////////////////////////////////////////////////////////////// namespace { class NameGadget : public TextGadget { public : NameGadget( BoxIOPtr boxIO ) : TextGadget( boxIO->namePlug()->getValue() ), m_boxIO( boxIO ) { boxIO->plugSetSignal().connect( boost::bind( &NameGadget::plugSet, this, ::_1 ) ); } private : void plugSet( const Plug *plug ) { if( plug == m_boxIO->namePlug() ) { setText( m_boxIO->namePlug()->getValue() ); } } BoxIOPtr m_boxIO; }; } // namespace ////////////////////////////////////////////////////////////////////////// // NodeGadget ////////////////////////////////////////////////////////////////////////// namespace { struct BoxIONodeGadgetCreator { BoxIONodeGadgetCreator() { NodeGadget::registerNodeGadget( BoxIO::staticTypeId(), *this ); } NodeGadgetPtr operator()( NodePtr node ) { BoxIOPtr boxIO = runTimeCast<BoxIO>( node ); if( !boxIO ) { throw Exception( "Expected a BoxIO node" ); } StandardNodeGadgetPtr result = new StandardNodeGadget( node ); result->setEdgeGadget( StandardNodeGadget::LeftEdge, new BoxIOPlugAdder( boxIO ) ); result->setEdgeGadget( StandardNodeGadget::RightEdge, new BoxIOPlugAdder( boxIO ) ); result->setEdgeGadget( StandardNodeGadget::BottomEdge, new BoxIOPlugAdder( boxIO ) ); result->setEdgeGadget( StandardNodeGadget::TopEdge, new BoxIOPlugAdder( boxIO ) ); result->setContents( new NameGadget( boxIO ) ); return result; } }; BoxIONodeGadgetCreator g_boxIONodeGadgetCreator; } // namespace <commit_msg>BoxIONodeGadget : Apply edge metadata to passThrough plug<commit_after>////////////////////////////////////////////////////////////////////////// // // Copyright (c) 2017, Image Engine Design 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 John Haddon nor the names of // any other contributors to this software 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. // ////////////////////////////////////////////////////////////////////////// #include "GafferUI/PlugAdder.h" #include "GafferUI/SpacerGadget.h" #include "GafferUI/StandardNodeGadget.h" #include "GafferUI/TextGadget.h" #include "Gaffer/BoxIO.h" #include "Gaffer/BoxOut.h" #include "Gaffer/Metadata.h" #include "Gaffer/ScriptNode.h" #include "Gaffer/StringPlug.h" #include "Gaffer/UndoScope.h" #include "boost/algorithm/string/replace.hpp" #include "boost/bind.hpp" using namespace IECore; using namespace Gaffer; using namespace GafferUI; ////////////////////////////////////////////////////////////////////////// // PlugAdder ////////////////////////////////////////////////////////////////////////// namespace { class BoxIOPlugAdder : public PlugAdder { public : BoxIOPlugAdder( BoxIOPtr boxIO ) : m_boxIO( boxIO ) { m_boxIO->childAddedSignal().connect( boost::bind( &BoxIOPlugAdder::childAdded, this ) ); m_boxIO->childRemovedSignal().connect( boost::bind( &BoxIOPlugAdder::childRemoved, this ) ); updateVisibility(); } protected : bool canCreateConnection( const Plug *endpoint ) const override { if( !PlugAdder::canCreateConnection( endpoint ) ) { return false; } return endpoint->direction() == m_boxIO->direction(); } void createConnection( Plug *endpoint ) override { std::string name = endpoint->relativeName( endpoint->node() ); boost::replace_all( name, ".", "_" ); m_boxIO->namePlug()->setValue( name ); m_boxIO->setup( endpoint ); applyEdgeMetadata( m_boxIO->plug() ); if( BoxOut *boxOut = runTimeCast<BoxOut>( m_boxIO.get() ) ) { applyEdgeMetadata( boxOut->passThroughPlug() ); } if( m_boxIO->promotedPlug() ) { applyEdgeMetadata( m_boxIO->promotedPlug(), /* opposite = */ true ); } if( m_boxIO->direction() == Plug::In ) { endpoint->setInput( m_boxIO->plug() ); } else { m_boxIO->plug()->setInput( endpoint ); } } private : void childAdded() { updateVisibility(); } void childRemoved() { updateVisibility(); } void updateVisibility() { setVisible( !m_boxIO->plug() ); } BoxIOPtr m_boxIO; }; } // namespace ////////////////////////////////////////////////////////////////////////// // StringPlugValueGadget ////////////////////////////////////////////////////////////////////////// namespace { class NameGadget : public TextGadget { public : NameGadget( BoxIOPtr boxIO ) : TextGadget( boxIO->namePlug()->getValue() ), m_boxIO( boxIO ) { boxIO->plugSetSignal().connect( boost::bind( &NameGadget::plugSet, this, ::_1 ) ); } private : void plugSet( const Plug *plug ) { if( plug == m_boxIO->namePlug() ) { setText( m_boxIO->namePlug()->getValue() ); } } BoxIOPtr m_boxIO; }; } // namespace ////////////////////////////////////////////////////////////////////////// // NodeGadget ////////////////////////////////////////////////////////////////////////// namespace { struct BoxIONodeGadgetCreator { BoxIONodeGadgetCreator() { NodeGadget::registerNodeGadget( BoxIO::staticTypeId(), *this ); } NodeGadgetPtr operator()( NodePtr node ) { BoxIOPtr boxIO = runTimeCast<BoxIO>( node ); if( !boxIO ) { throw Exception( "Expected a BoxIO node" ); } StandardNodeGadgetPtr result = new StandardNodeGadget( node ); result->setEdgeGadget( StandardNodeGadget::LeftEdge, new BoxIOPlugAdder( boxIO ) ); result->setEdgeGadget( StandardNodeGadget::RightEdge, new BoxIOPlugAdder( boxIO ) ); result->setEdgeGadget( StandardNodeGadget::BottomEdge, new BoxIOPlugAdder( boxIO ) ); result->setEdgeGadget( StandardNodeGadget::TopEdge, new BoxIOPlugAdder( boxIO ) ); result->setContents( new NameGadget( boxIO ) ); return result; } }; BoxIONodeGadgetCreator g_boxIONodeGadgetCreator; } // namespace <|endoftext|>
<commit_before>//===-- X86ShuffleDecodeConstantPool.cpp - X86 shuffle decode -------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // Define several functions to decode x86 specific shuffle semantics using // constants from the constant pool. // //===----------------------------------------------------------------------===// #include "X86ShuffleDecodeConstantPool.h" #include "Utils/X86ShuffleDecode.h" #include "llvm/CodeGen/MachineValueType.h" #include "llvm/IR/Constants.h" //===----------------------------------------------------------------------===// // Vector Mask Decoding //===----------------------------------------------------------------------===// namespace llvm { void DecodePSHUFBMask(const Constant *C, SmallVectorImpl<int> &ShuffleMask) { Type *MaskTy = C->getType(); // It is not an error for the PSHUFB mask to not be a vector of i8 because the // constant pool uniques constants by their bit representation. // e.g. the following take up the same space in the constant pool: // i128 -170141183420855150465331762880109871104 // // <2 x i64> <i64 -9223372034707292160, i64 -9223372034707292160> // // <4 x i32> <i32 -2147483648, i32 -2147483648, // i32 -2147483648, i32 -2147483648> #ifndef NDEBUG unsigned MaskTySize = MaskTy->getPrimitiveSizeInBits(); assert(MaskTySize == 128 || MaskTySize == 256 || MaskTySize == 512); #endif if (!MaskTy->isVectorTy()) return; int NumElts = MaskTy->getVectorNumElements(); Type *EltTy = MaskTy->getVectorElementType(); if (!EltTy->isIntegerTy()) return; // The shuffle mask requires a byte vector - decode cases with // wider elements as well. unsigned BitWidth = cast<IntegerType>(EltTy)->getBitWidth(); if ((BitWidth % 8) != 0) return; int Scale = BitWidth / 8; int NumBytes = NumElts * Scale; ShuffleMask.reserve(NumBytes); for (int i = 0; i != NumElts; ++i) { Constant *COp = C->getAggregateElement(i); if (!COp) { ShuffleMask.clear(); return; } else if (isa<UndefValue>(COp)) { ShuffleMask.append(Scale, SM_SentinelUndef); continue; } APInt APElt = cast<ConstantInt>(COp)->getValue(); for (int j = 0; j != Scale; ++j) { // For AVX vectors with 32 bytes the base of the shuffle is the 16-byte // lane of the vector we're inside. int Base = ((i * Scale) + j) & ~0xf; uint64_t Element = APElt.getLoBits(8).getZExtValue(); APElt = APElt.lshr(8); // If the high bit (7) of the byte is set, the element is zeroed. if (Element & (1 << 7)) ShuffleMask.push_back(SM_SentinelZero); else { // Only the least significant 4 bits of the byte are used. int Index = Base + (Element & 0xf); ShuffleMask.push_back(Index); } } } assert(NumBytes == (int)ShuffleMask.size() && "Unexpected shuffle mask size"); } void DecodeVPERMILPMask(const Constant *C, unsigned ElSize, SmallVectorImpl<int> &ShuffleMask) { Type *MaskTy = C->getType(); // It is not an error for the PSHUFB mask to not be a vector of i8 because the // constant pool uniques constants by their bit representation. // e.g. the following take up the same space in the constant pool: // i128 -170141183420855150465331762880109871104 // // <2 x i64> <i64 -9223372034707292160, i64 -9223372034707292160> // // <4 x i32> <i32 -2147483648, i32 -2147483648, // i32 -2147483648, i32 -2147483648> if (ElSize != 32 && ElSize != 64) return; unsigned MaskTySize = MaskTy->getPrimitiveSizeInBits(); if (MaskTySize != 128 && MaskTySize != 256 && MaskTySize != 512) return; // Only support vector types. if (!MaskTy->isVectorTy()) return; // Make sure its an integer type. Type *VecEltTy = MaskTy->getVectorElementType(); if (!VecEltTy->isIntegerTy()) return; // Support any element type from byte up to element size. // This is necessary primarily because 64-bit elements get split to 32-bit // in the constant pool on 32-bit target. unsigned EltTySize = VecEltTy->getIntegerBitWidth(); if (EltTySize < 8 || EltTySize > ElSize) return; unsigned NumElements = MaskTySize / ElSize; assert((NumElements == 2 || NumElements == 4 || NumElements == 8 || NumElements == 16) && "Unexpected number of vector elements."); ShuffleMask.reserve(NumElements); unsigned NumElementsPerLane = 128 / ElSize; unsigned Factor = ElSize / EltTySize; for (unsigned i = 0; i < NumElements; ++i) { Constant *COp = C->getAggregateElement(i * Factor); if (!COp) { ShuffleMask.clear(); return; } else if (isa<UndefValue>(COp)) { ShuffleMask.push_back(SM_SentinelUndef); continue; } int Index = i & ~(NumElementsPerLane - 1); uint64_t Element = cast<ConstantInt>(COp)->getZExtValue(); if (ElSize == 64) Index += (Element >> 1) & 0x1; else Index += Element & 0x3; ShuffleMask.push_back(Index); } // TODO: Handle funny-looking vectors too. } void DecodeVPERMIL2PMask(const Constant *C, unsigned M2Z, unsigned ElSize, SmallVectorImpl<int> &ShuffleMask) { Type *MaskTy = C->getType(); unsigned MaskTySize = MaskTy->getPrimitiveSizeInBits(); if (MaskTySize != 128 && MaskTySize != 256) return; // Only support vector types. if (!MaskTy->isVectorTy()) return; // Make sure its an integer type. Type *VecEltTy = MaskTy->getVectorElementType(); if (!VecEltTy->isIntegerTy()) return; // Support any element type from byte up to element size. // This is necessary primarily because 64-bit elements get split to 32-bit // in the constant pool on 32-bit target. unsigned EltTySize = VecEltTy->getIntegerBitWidth(); if (EltTySize < 8 || EltTySize > ElSize) return; unsigned NumElements = MaskTySize / ElSize; assert((NumElements == 2 || NumElements == 4 || NumElements == 8) && "Unexpected number of vector elements."); ShuffleMask.reserve(NumElements); unsigned NumElementsPerLane = 128 / ElSize; unsigned Factor = ElSize / EltTySize; for (unsigned i = 0; i < NumElements; ++i) { Constant *COp = C->getAggregateElement(i * Factor); if (!COp) { ShuffleMask.clear(); return; } else if (isa<UndefValue>(COp)) { ShuffleMask.push_back(SM_SentinelUndef); continue; } // VPERMIL2 Operation. // Bits[3] - Match Bit. // Bits[2:1] - (Per Lane) PD Shuffle Mask. // Bits[2:0] - (Per Lane) PS Shuffle Mask. uint64_t Selector = cast<ConstantInt>(COp)->getZExtValue(); unsigned MatchBit = (Selector >> 3) & 0x1; // M2Z[0:1] MatchBit // 0Xb X Source selected by Selector index. // 10b 0 Source selected by Selector index. // 10b 1 Zero. // 11b 0 Zero. // 11b 1 Source selected by Selector index. if ((M2Z & 0x2) != 0u && MatchBit != (M2Z & 0x1)) { ShuffleMask.push_back(SM_SentinelZero); continue; } int Index = i & ~(NumElementsPerLane - 1); if (ElSize == 64) Index += (Selector >> 1) & 0x1; else Index += Selector & 0x3; int Src = (Selector >> 2) & 0x1; Index += Src * NumElements; ShuffleMask.push_back(Index); } // TODO: Handle funny-looking vectors too. } void DecodeVPPERMMask(const Constant *C, SmallVectorImpl<int> &ShuffleMask) { Type *MaskTy = C->getType(); assert(MaskTy->getPrimitiveSizeInBits() == 128); // Only support vector types. if (!MaskTy->isVectorTy()) return; // Make sure its an integer type. Type *VecEltTy = MaskTy->getVectorElementType(); if (!VecEltTy->isIntegerTy()) return; // The shuffle mask requires a byte vector - decode cases with // wider elements as well. unsigned BitWidth = cast<IntegerType>(VecEltTy)->getBitWidth(); if ((BitWidth % 8) != 0) return; int NumElts = MaskTy->getVectorNumElements(); int Scale = BitWidth / 8; int NumBytes = NumElts * Scale; ShuffleMask.reserve(NumBytes); for (int i = 0; i != NumElts; ++i) { Constant *COp = C->getAggregateElement(i); if (!COp) { ShuffleMask.clear(); return; } else if (isa<UndefValue>(COp)) { ShuffleMask.append(Scale, SM_SentinelUndef); continue; } // VPPERM Operation // Bits[4:0] - Byte Index (0 - 31) // Bits[7:5] - Permute Operation // // Permute Operation: // 0 - Source byte (no logical operation). // 1 - Invert source byte. // 2 - Bit reverse of source byte. // 3 - Bit reverse of inverted source byte. // 4 - 00h (zero - fill). // 5 - FFh (ones - fill). // 6 - Most significant bit of source byte replicated in all bit positions. // 7 - Invert most significant bit of source byte and replicate in all bit positions. APInt MaskElt = cast<ConstantInt>(COp)->getValue(); for (int j = 0; j != Scale; ++j) { APInt Index = MaskElt.getLoBits(5); APInt PermuteOp = MaskElt.lshr(5).getLoBits(3); MaskElt = MaskElt.lshr(8); if (PermuteOp == 4) { ShuffleMask.push_back(SM_SentinelZero); continue; } if (PermuteOp != 0) { ShuffleMask.clear(); return; } ShuffleMask.push_back((int)Index.getZExtValue()); } } assert(NumBytes == (int)ShuffleMask.size() && "Unexpected shuffle mask size"); } void DecodeVPERMVMask(const Constant *C, MVT VT, SmallVectorImpl<int> &ShuffleMask) { Type *MaskTy = C->getType(); if (MaskTy->isVectorTy()) { unsigned NumElements = MaskTy->getVectorNumElements(); if (NumElements == VT.getVectorNumElements()) { unsigned EltMaskSize = Log2_64(NumElements); for (unsigned i = 0; i < NumElements; ++i) { Constant *COp = C->getAggregateElement(i); if (!COp || (!isa<UndefValue>(COp) && !isa<ConstantInt>(COp))) { ShuffleMask.clear(); return; } if (isa<UndefValue>(COp)) ShuffleMask.push_back(SM_SentinelUndef); else { APInt Element = cast<ConstantInt>(COp)->getValue(); Element = Element.getLoBits(EltMaskSize); ShuffleMask.push_back(Element.getZExtValue()); } } } return; } // Scalar value; just broadcast it if (!isa<ConstantInt>(C)) return; uint64_t Element = cast<ConstantInt>(C)->getZExtValue(); int NumElements = VT.getVectorNumElements(); Element &= (1 << NumElements) - 1; for (int i = 0; i < NumElements; ++i) ShuffleMask.push_back(Element); } void DecodeVPERMV3Mask(const Constant *C, MVT VT, SmallVectorImpl<int> &ShuffleMask) { Type *MaskTy = C->getType(); unsigned NumElements = MaskTy->getVectorNumElements(); if (NumElements == VT.getVectorNumElements()) { unsigned EltMaskSize = Log2_64(NumElements * 2); for (unsigned i = 0; i < NumElements; ++i) { Constant *COp = C->getAggregateElement(i); if (!COp) { ShuffleMask.clear(); return; } if (isa<UndefValue>(COp)) ShuffleMask.push_back(SM_SentinelUndef); else { APInt Element = cast<ConstantInt>(COp)->getValue(); Element = Element.getLoBits(EltMaskSize); ShuffleMask.push_back(Element.getZExtValue()); } } } } } // llvm namespace <commit_msg>[X86][SSE] Added common helper for shuffle mask constant pool decodes.<commit_after>//===-- X86ShuffleDecodeConstantPool.cpp - X86 shuffle decode -------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // Define several functions to decode x86 specific shuffle semantics using // constants from the constant pool. // //===----------------------------------------------------------------------===// #include "X86ShuffleDecodeConstantPool.h" #include "Utils/X86ShuffleDecode.h" #include "llvm/ADT/SmallBitVector.h" #include "llvm/CodeGen/MachineValueType.h" #include "llvm/IR/Constants.h" //===----------------------------------------------------------------------===// // Vector Mask Decoding //===----------------------------------------------------------------------===// namespace llvm { static bool extractConstantMask(const Constant *C, unsigned MaskEltSizeInBits, SmallBitVector &UndefElts, SmallVectorImpl<uint64_t> &RawMask) { // It is not an error for shuffle masks to not be a vector of // MaskEltSizeInBits because the constant pool uniques constants by their // bit representation. // e.g. the following take up the same space in the constant pool: // i128 -170141183420855150465331762880109871104 // // <2 x i64> <i64 -9223372034707292160, i64 -9223372034707292160> // // <4 x i32> <i32 -2147483648, i32 -2147483648, // i32 -2147483648, i32 -2147483648> Type *CstTy = C->getType(); if (!CstTy->isVectorTy()) return false; Type *CstEltTy = CstTy->getVectorElementType(); if (!CstEltTy->isIntegerTy()) return false; unsigned CstSizeInBits = CstTy->getPrimitiveSizeInBits(); unsigned CstEltSizeInBits = CstTy->getScalarSizeInBits(); unsigned NumCstElts = CstTy->getVectorNumElements(); // Extract all the undef/constant element data and pack into single bitsets. APInt UndefBits(CstSizeInBits, 0); APInt MaskBits(CstSizeInBits, 0); for (unsigned i = 0; i != NumCstElts; ++i) { Constant *COp = C->getAggregateElement(i); if (!COp || (!isa<UndefValue>(COp) && !isa<ConstantInt>(COp))) return false; if (isa<UndefValue>(COp)) { APInt EltUndef = APInt::getLowBitsSet(CstSizeInBits, CstEltSizeInBits); UndefBits |= EltUndef.shl(i * CstEltSizeInBits); continue; } APInt EltBits = cast<ConstantInt>(COp)->getValue(); EltBits = EltBits.zextOrTrunc(CstSizeInBits); MaskBits |= EltBits.shl(i * CstEltSizeInBits); } // Now extract the undef/constant bit data into the raw shuffle masks. assert((CstSizeInBits % MaskEltSizeInBits) == 0 && ""); unsigned NumMaskElts = CstSizeInBits / MaskEltSizeInBits; UndefElts = SmallBitVector(NumMaskElts, false); RawMask.resize(NumMaskElts, 0); for (unsigned i = 0; i != NumMaskElts; ++i) { APInt EltUndef = UndefBits.lshr(i * MaskEltSizeInBits); EltUndef = EltUndef.zextOrTrunc(MaskEltSizeInBits); // Only treat the element as UNDEF if all bits are UNDEF, otherwise // treat it as zero. if (EltUndef.countPopulation() == MaskEltSizeInBits) { UndefElts[i] = true; RawMask[i] = 0; continue; } APInt EltBits = MaskBits.lshr(i * MaskEltSizeInBits); EltBits = EltBits.zextOrTrunc(MaskEltSizeInBits); RawMask[i] = EltBits.getZExtValue(); } return true; } void DecodePSHUFBMask(const Constant *C, SmallVectorImpl<int> &ShuffleMask) { Type *MaskTy = C->getType(); unsigned MaskTySize = MaskTy->getPrimitiveSizeInBits(); assert(MaskTySize == 128 || MaskTySize == 256 || MaskTySize == 512); // The shuffle mask requires a byte vector. SmallBitVector UndefElts; SmallVector<uint64_t, 32> RawMask; if (!extractConstantMask(C, 8, UndefElts, RawMask)) return; unsigned NumElts = RawMask.size(); assert((NumElts == 16 || NumElts == 32 || NumElts == 64) && "Unexpected number of vector elements."); for (unsigned i = 0; i != NumElts; ++i) { if (UndefElts[i]) { ShuffleMask.push_back(SM_SentinelUndef); continue; } uint64_t Element = RawMask[i]; // If the high bit (7) of the byte is set, the element is zeroed. if (Element & (1 << 7)) ShuffleMask.push_back(SM_SentinelZero); else { // For AVX vectors with 32 bytes the base of the shuffle is the 16-byte // lane of the vector we're inside. unsigned Base = i & ~0xf; // Only the least significant 4 bits of the byte are used. int Index = Base + (Element & 0xf); ShuffleMask.push_back(Index); } } } void DecodeVPERMILPMask(const Constant *C, unsigned ElSize, SmallVectorImpl<int> &ShuffleMask) { Type *MaskTy = C->getType(); unsigned MaskTySize = MaskTy->getPrimitiveSizeInBits(); assert(MaskTySize == 128 || MaskTySize == 256 || MaskTySize == 512); assert(ElSize == 32 || ElSize == 64); // The shuffle mask requires elements the same size as the target. SmallBitVector UndefElts; SmallVector<uint64_t, 8> RawMask; if (!extractConstantMask(C, ElSize, UndefElts, RawMask)) return; unsigned NumElts = RawMask.size(); unsigned NumEltsPerLane = 128 / ElSize; assert((NumElts == 2 || NumElts == 4 || NumElts == 8 || NumElts == 16) && "Unexpected number of vector elements."); for (unsigned i = 0; i != NumElts; ++i) { if (UndefElts[i]) { ShuffleMask.push_back(SM_SentinelUndef); continue; } int Index = i & ~(NumEltsPerLane - 1); uint64_t Element = RawMask[i]; if (ElSize == 64) Index += (Element >> 1) & 0x1; else Index += Element & 0x3; ShuffleMask.push_back(Index); } } void DecodeVPERMIL2PMask(const Constant *C, unsigned M2Z, unsigned ElSize, SmallVectorImpl<int> &ShuffleMask) { Type *MaskTy = C->getType(); unsigned MaskTySize = MaskTy->getPrimitiveSizeInBits(); assert(MaskTySize == 128 || MaskTySize == 256); // The shuffle mask requires elements the same size as the target. SmallBitVector UndefElts; SmallVector<uint64_t, 8> RawMask; if (!extractConstantMask(C, ElSize, UndefElts, RawMask)) return; unsigned NumElts = RawMask.size(); unsigned NumEltsPerLane = 128 / ElSize; assert((NumElts == 2 || NumElts == 4 || NumElts == 8) && "Unexpected number of vector elements."); for (unsigned i = 0; i != NumElts; ++i) { if (UndefElts[i]) { ShuffleMask.push_back(SM_SentinelUndef); continue; } // VPERMIL2 Operation. // Bits[3] - Match Bit. // Bits[2:1] - (Per Lane) PD Shuffle Mask. // Bits[2:0] - (Per Lane) PS Shuffle Mask. uint64_t Selector = RawMask[i]; unsigned MatchBit = (Selector >> 3) & 0x1; // M2Z[0:1] MatchBit // 0Xb X Source selected by Selector index. // 10b 0 Source selected by Selector index. // 10b 1 Zero. // 11b 0 Zero. // 11b 1 Source selected by Selector index. if ((M2Z & 0x2) != 0u && MatchBit != (M2Z & 0x1)) { ShuffleMask.push_back(SM_SentinelZero); continue; } int Index = i & ~(NumEltsPerLane - 1); if (ElSize == 64) Index += (Selector >> 1) & 0x1; else Index += Selector & 0x3; int Src = (Selector >> 2) & 0x1; Index += Src * NumElts; ShuffleMask.push_back(Index); } } void DecodeVPPERMMask(const Constant *C, SmallVectorImpl<int> &ShuffleMask) { Type *MaskTy = C->getType(); assert(MaskTy->getPrimitiveSizeInBits() == 128); // The shuffle mask requires a byte vector. SmallBitVector UndefElts; SmallVector<uint64_t, 32> RawMask; if (!extractConstantMask(C, 8, UndefElts, RawMask)) return; unsigned NumElts = RawMask.size(); assert(NumElts == 16 && "Unexpected number of vector elements."); for (unsigned i = 0; i != NumElts; ++i) { if (UndefElts[i]) { ShuffleMask.push_back(SM_SentinelUndef); continue; } // VPPERM Operation // Bits[4:0] - Byte Index (0 - 31) // Bits[7:5] - Permute Operation // // Permute Operation: // 0 - Source byte (no logical operation). // 1 - Invert source byte. // 2 - Bit reverse of source byte. // 3 - Bit reverse of inverted source byte. // 4 - 00h (zero - fill). // 5 - FFh (ones - fill). // 6 - Most significant bit of source byte replicated in all bit positions. // 7 - Invert most significant bit of source byte and replicate in all bit // positions. uint64_t Element = RawMask[i]; uint64_t Index = Element & 0x1F; uint64_t PermuteOp = (Element >> 5) & 0x7; if (PermuteOp == 4) { ShuffleMask.push_back(SM_SentinelZero); continue; } if (PermuteOp != 0) { ShuffleMask.clear(); return; } ShuffleMask.push_back((int)Index); } } void DecodeVPERMVMask(const Constant *C, MVT VT, SmallVectorImpl<int> &ShuffleMask) { Type *MaskTy = C->getType(); if (MaskTy->isVectorTy()) { unsigned NumElements = MaskTy->getVectorNumElements(); if (NumElements == VT.getVectorNumElements()) { unsigned EltMaskSize = Log2_64(NumElements); for (unsigned i = 0; i < NumElements; ++i) { Constant *COp = C->getAggregateElement(i); if (!COp || (!isa<UndefValue>(COp) && !isa<ConstantInt>(COp))) { ShuffleMask.clear(); return; } if (isa<UndefValue>(COp)) ShuffleMask.push_back(SM_SentinelUndef); else { APInt Element = cast<ConstantInt>(COp)->getValue(); Element = Element.getLoBits(EltMaskSize); ShuffleMask.push_back(Element.getZExtValue()); } } } return; } // Scalar value; just broadcast it if (!isa<ConstantInt>(C)) return; uint64_t Element = cast<ConstantInt>(C)->getZExtValue(); int NumElements = VT.getVectorNumElements(); Element &= (1 << NumElements) - 1; for (int i = 0; i < NumElements; ++i) ShuffleMask.push_back(Element); } void DecodeVPERMV3Mask(const Constant *C, MVT VT, SmallVectorImpl<int> &ShuffleMask) { Type *MaskTy = C->getType(); unsigned NumElements = MaskTy->getVectorNumElements(); if (NumElements == VT.getVectorNumElements()) { unsigned EltMaskSize = Log2_64(NumElements * 2); for (unsigned i = 0; i < NumElements; ++i) { Constant *COp = C->getAggregateElement(i); if (!COp) { ShuffleMask.clear(); return; } if (isa<UndefValue>(COp)) ShuffleMask.push_back(SM_SentinelUndef); else { APInt Element = cast<ConstantInt>(COp)->getValue(); Element = Element.getLoBits(EltMaskSize); ShuffleMask.push_back(Element.getZExtValue()); } } } } } // llvm namespace <|endoftext|>
<commit_before>/*========================================================================= * * Copyright RTK Consortium * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0.txt * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * *=========================================================================*/ #include "rtkconjugategradient_ggo.h" #include "rtkGgoFunctions.h" #include "rtkThreeDCircularProjectionGeometryXMLFile.h" #include "rtkConjugateGradientConeBeamReconstructionFilter.h" #include "rtkNormalizedJosephBackProjectionImageFilter.h" #include <iostream> #include <fstream> #include <iterator> #ifdef RTK_USE_CUDA #include <itkCudaImage.h> #endif #include <itkImageFileWriter.h> int main(int argc, char * argv[]) { GGO(rtkconjugategradient, args_info); typedef float OutputPixelType; const unsigned int Dimension = 3; std::vector<double> costs; std::ostream_iterator<double> costs_it(std::cout,"\n"); typedef itk::Image< OutputPixelType, Dimension > CPUOutputImageType; #ifdef RTK_USE_CUDA typedef itk::CudaImage< OutputPixelType, Dimension > OutputImageType; #else typedef CPUOutputImageType OutputImageType; #endif // Projections reader typedef rtk::ProjectionsReader< OutputImageType > ReaderType; ReaderType::Pointer reader = ReaderType::New(); rtk::SetProjectionsReaderFromGgo<ReaderType, args_info_rtkconjugategradient>(reader, args_info); // Geometry if(args_info.verbose_flag) std::cout << "Reading geometry information from " << args_info.geometry_arg << "..." << std::endl; rtk::ThreeDCircularProjectionGeometryXMLFileReader::Pointer geometryReader; geometryReader = rtk::ThreeDCircularProjectionGeometryXMLFileReader::New(); geometryReader->SetFilename(args_info.geometry_arg); TRY_AND_EXIT_ON_ITK_EXCEPTION( geometryReader->GenerateOutputInformation() ) // Create input: either an existing volume read from a file or a blank image itk::ImageSource< OutputImageType >::Pointer inputFilter; if(args_info.input_given) { // Read an existing image to initialize the volume typedef itk::ImageFileReader< OutputImageType > InputReaderType; InputReaderType::Pointer inputReader = InputReaderType::New(); inputReader->SetFileName( args_info.input_arg ); inputFilter = inputReader; } else { // Create new empty volume typedef rtk::ConstantImageSource< OutputImageType > ConstantImageSourceType; ConstantImageSourceType::Pointer constantImageSource = ConstantImageSourceType::New(); rtk::SetConstantImageSourceFromGgo<ConstantImageSourceType, args_info_rtkconjugategradient>(constantImageSource, args_info); inputFilter = constantImageSource; } // Read weights if given, otherwise default to weights all equal to one itk::ImageSource< OutputImageType >::Pointer weightsSource; if(args_info.weights_given) { typedef itk::ImageFileReader< OutputImageType > WeightsReaderType; WeightsReaderType::Pointer weightsReader = WeightsReaderType::New(); weightsReader->SetFileName( args_info.weights_arg ); weightsSource = weightsReader; } else { typedef rtk::ConstantImageSource< OutputImageType > ConstantWeightsSourceType; ConstantWeightsSourceType::Pointer constantWeightsSource = ConstantWeightsSourceType::New(); // Set the weights to be like the projections TRY_AND_EXIT_ON_ITK_EXCEPTION( reader->UpdateOutputInformation() ) constantWeightsSource->SetInformationFromImage(reader->GetOutput()); constantWeightsSource->SetConstant(1.0); weightsSource = constantWeightsSource; } // Read Support Mask if given itk::ImageSource< OutputImageType >::Pointer supportmaskSource; if(args_info.mask_given) { typedef itk::ImageFileReader< OutputImageType > MaskReaderType; MaskReaderType::Pointer supportmaskReader = MaskReaderType::New(); supportmaskReader->SetFileName( args_info.mask_arg ); supportmaskSource = supportmaskReader; } // Set the forward and back projection filters to be used typedef rtk::ConjugateGradientConeBeamReconstructionFilter<OutputImageType> ConjugateGradientFilterType; ConjugateGradientFilterType::Pointer conjugategradient = ConjugateGradientFilterType::New(); conjugategradient->SetForwardProjectionFilter(args_info.fp_arg); conjugategradient->SetBackProjectionFilter(args_info.bp_arg); conjugategradient->SetInput( inputFilter->GetOutput() ); conjugategradient->SetInput(1, reader->GetOutput()); conjugategradient->SetInput(2, weightsSource->GetOutput()); conjugategradient->SetPreconditioned(args_info.preconditioned_flag); conjugategradient->SetCudaConjugateGradient(!args_info.nocudacg_flag); conjugategradient->SetSupportMask(supportmaskSource->GetOutput() ); conjugategradient->SetIterationCosts(args_info.costs_flag); if (args_info.gamma_given) { conjugategradient->SetRegularized(true); conjugategradient->SetGamma(args_info.gamma_arg); } conjugategradient->SetGeometry( geometryReader->GetOutputObject() ); conjugategradient->SetNumberOfIterations( args_info.niterations_arg ); itk::TimeProbe readerProbe; if(args_info.time_flag) { std::cout << "Recording elapsed time... " << std::flush; readerProbe.Start(); } TRY_AND_EXIT_ON_ITK_EXCEPTION( conjugategradient->Update() ) if(args_info.time_flag) { // conjugategradient->PrintTiming(std::cout); readerProbe.Stop(); std::cout << "It took... " << readerProbe.GetMean() << ' ' << readerProbe.GetUnit() << std::endl; } if(args_info.costs_given) { costs=conjugategradient->GetResidualCosts(); std::cout << "Residual costs at each iteration :" << std::endl; copy(costs.begin(),costs.end(),costs_it); } // Write typedef itk::ImageFileWriter< OutputImageType > WriterType; WriterType::Pointer writer = WriterType::New(); writer->SetFileName( args_info.output_arg ); writer->SetInput( conjugategradient->GetOutput() ); TRY_AND_EXIT_ON_ITK_EXCEPTION( writer->Update() ) return EXIT_SUCCESS; } <commit_msg>Corrected a bug in setting the support mask (it is conditional).<commit_after>/*========================================================================= * * Copyright RTK Consortium * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0.txt * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * *=========================================================================*/ #include "rtkconjugategradient_ggo.h" #include "rtkGgoFunctions.h" #include "rtkThreeDCircularProjectionGeometryXMLFile.h" #include "rtkConjugateGradientConeBeamReconstructionFilter.h" #include "rtkNormalizedJosephBackProjectionImageFilter.h" #include <iostream> #include <fstream> #include <iterator> #ifdef RTK_USE_CUDA #include <itkCudaImage.h> #endif #include <itkImageFileWriter.h> int main(int argc, char * argv[]) { GGO(rtkconjugategradient, args_info); typedef float OutputPixelType; const unsigned int Dimension = 3; std::vector<double> costs; std::ostream_iterator<double> costs_it(std::cout,"\n"); typedef itk::Image< OutputPixelType, Dimension > CPUOutputImageType; #ifdef RTK_USE_CUDA typedef itk::CudaImage< OutputPixelType, Dimension > OutputImageType; #else typedef CPUOutputImageType OutputImageType; #endif // Projections reader typedef rtk::ProjectionsReader< OutputImageType > ReaderType; ReaderType::Pointer reader = ReaderType::New(); rtk::SetProjectionsReaderFromGgo<ReaderType, args_info_rtkconjugategradient>(reader, args_info); // Geometry if(args_info.verbose_flag) std::cout << "Reading geometry information from " << args_info.geometry_arg << "..." << std::endl; rtk::ThreeDCircularProjectionGeometryXMLFileReader::Pointer geometryReader; geometryReader = rtk::ThreeDCircularProjectionGeometryXMLFileReader::New(); geometryReader->SetFilename(args_info.geometry_arg); TRY_AND_EXIT_ON_ITK_EXCEPTION( geometryReader->GenerateOutputInformation() ) // Create input: either an existing volume read from a file or a blank image itk::ImageSource< OutputImageType >::Pointer inputFilter; if(args_info.input_given) { // Read an existing image to initialize the volume typedef itk::ImageFileReader< OutputImageType > InputReaderType; InputReaderType::Pointer inputReader = InputReaderType::New(); inputReader->SetFileName( args_info.input_arg ); inputFilter = inputReader; } else { // Create new empty volume typedef rtk::ConstantImageSource< OutputImageType > ConstantImageSourceType; ConstantImageSourceType::Pointer constantImageSource = ConstantImageSourceType::New(); rtk::SetConstantImageSourceFromGgo<ConstantImageSourceType, args_info_rtkconjugategradient>(constantImageSource, args_info); inputFilter = constantImageSource; } // Read weights if given, otherwise default to weights all equal to one itk::ImageSource< OutputImageType >::Pointer weightsSource; if(args_info.weights_given) { typedef itk::ImageFileReader< OutputImageType > WeightsReaderType; WeightsReaderType::Pointer weightsReader = WeightsReaderType::New(); weightsReader->SetFileName( args_info.weights_arg ); weightsSource = weightsReader; } else { typedef rtk::ConstantImageSource< OutputImageType > ConstantWeightsSourceType; ConstantWeightsSourceType::Pointer constantWeightsSource = ConstantWeightsSourceType::New(); // Set the weights to be like the projections TRY_AND_EXIT_ON_ITK_EXCEPTION( reader->UpdateOutputInformation() ) constantWeightsSource->SetInformationFromImage(reader->GetOutput()); constantWeightsSource->SetConstant(1.0); weightsSource = constantWeightsSource; } // Read Support Mask if given itk::ImageSource< OutputImageType >::Pointer supportmaskSource; if(args_info.mask_given) { typedef itk::ImageFileReader< OutputImageType > MaskReaderType; MaskReaderType::Pointer supportmaskReader = MaskReaderType::New(); supportmaskReader->SetFileName( args_info.mask_arg ); supportmaskSource = supportmaskReader; } // Set the forward and back projection filters to be used typedef rtk::ConjugateGradientConeBeamReconstructionFilter<OutputImageType> ConjugateGradientFilterType; ConjugateGradientFilterType::Pointer conjugategradient = ConjugateGradientFilterType::New(); conjugategradient->SetForwardProjectionFilter(args_info.fp_arg); conjugategradient->SetBackProjectionFilter(args_info.bp_arg); conjugategradient->SetInput( inputFilter->GetOutput() ); conjugategradient->SetInput(1, reader->GetOutput()); conjugategradient->SetInput(2, weightsSource->GetOutput()); conjugategradient->SetPreconditioned(args_info.preconditioned_flag); conjugategradient->SetCudaConjugateGradient(!args_info.nocudacg_flag); if(args_info.mask_given) { conjugategradient->SetSupportMask(supportmaskSource->GetOutput() ); } conjugategradient->SetIterationCosts(args_info.costs_flag); if (args_info.gamma_given) { conjugategradient->SetRegularized(true); conjugategradient->SetGamma(args_info.gamma_arg); } conjugategradient->SetGeometry( geometryReader->GetOutputObject() ); conjugategradient->SetNumberOfIterations( args_info.niterations_arg ); itk::TimeProbe readerProbe; if(args_info.time_flag) { std::cout << "Recording elapsed time... " << std::flush; readerProbe.Start(); } TRY_AND_EXIT_ON_ITK_EXCEPTION( conjugategradient->Update() ) if(args_info.time_flag) { // conjugategradient->PrintTiming(std::cout); readerProbe.Stop(); std::cout << "It took... " << readerProbe.GetMean() << ' ' << readerProbe.GetUnit() << std::endl; } if(args_info.costs_given) { costs=conjugategradient->GetResidualCosts(); std::cout << "Residual costs at each iteration :" << std::endl; copy(costs.begin(),costs.end(),costs_it); } // Write typedef itk::ImageFileWriter< OutputImageType > WriterType; WriterType::Pointer writer = WriterType::New(); writer->SetFileName( args_info.output_arg ); writer->SetInput( conjugategradient->GetOutput() ); TRY_AND_EXIT_ON_ITK_EXCEPTION( writer->Update() ) return EXIT_SUCCESS; } <|endoftext|>
<commit_before>/* * MIT License * * Copyright (c) 2017 Kevin Kirchner * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ /** * \file readelfpp.cpp * \brief A simple clone of readelf using \p libelfpp * \author Kevin Kirchner * \date 2017 * \copyright MIT LICENSE * * A simple clone of readelf from the GNU binutils using \p libelfpp. This * application is just a example and does not implement all features readelf * provides. */ #include <libelfpp/libelfpp.h> #include <tclap/CmdLine.h> #include "tinyformat.h" using namespace libelfpp; /// Prints the \p header of type \p ELFHeader to the output stream \p stream /// in a readelf-like style. /// /// \param header Pointer to the ELF header to print /// \param stream The stream to print to void printHeader(const std::shared_ptr<ELFFileHeader>& header, std::ostream& stream) { stream << "ELF Header:\n" << std::left; tfm::format(stream, "%-39s %s\n", "Class:", (header->is64Bit() ? "ELF64" : "ELF32")); tfm::format(stream, "%-39s %s\n", "Version:", std::to_string(header->getVersion()) + (header->getVersion() == 1 ? " (current)" : "")); tfm::format(stream, "%-39s %s\n", "Encoding:", std::string("2's complement, ") + (header->isLittleEndian() ? "Little" : "Big") + " Endian"); tfm::format(stream, "%-39s %s\n", "OS/ABI:", header->getABIString()); tfm::format(stream, "%-39s %s\n", "Type:", header->getELFTypeString()); tfm::format(stream, "%-39s %s\n", "Machine:", header->getMachineString()); tfm::format(stream, "%-39s 0x%X\n", "Entrypoint:", header->getEntryPoint()); tfm::format(stream, "%-39s %u (Bytes in File)\n", "Start of Program Headers:", header->getProgramHeaderOffset()); tfm::format(stream, "%-39s %u (Bytes in File)\n", "Start of Section Headers:", header->getSectionHeaderOffset()); tfm::format(stream, "%-39s 0x%X\n", "Flags:", header->getFlags()); tfm::format(stream, "%-39s %u (Bytes)\n", "Size of File Header:", header->getHeaderSize()); tfm::format(stream, "%-39s %u (Bytes)\n", "Size of Program Header:", header->getProgramHeaderSize()); tfm::format(stream, "%-39s %u\n", "Number of Program Headers:", header->getProgramHeaderNumber()); tfm::format(stream, "%-39s %u\n", "Size of Section Header:", header->getSectionHeaderSize()); tfm::format(stream, "%-39s %u\n", "Number of Section Headers:", header->getSectionHeaderNumber()); tfm::format(stream, "%-39s %u\n", "Section Header String Table Index:", header->getSectionHeaderStringTableIndex()); } /// Prints the sections of the file pointed to by \p pFile to the output /// stream \p stream in a readelf-like style. /// /// \param pFile Pointer to the file object /// \param stream The stream to print to void printSectionTable(const std::shared_ptr<ELFFile>& pFile, std::ostream& stream) { stream << "Section Headers:\n" << std::left; tfm::format(stream, " [%-2s] %-17s %-17s %-17s %-10s\n", "No", "Name", "Type", "Address", "Offset"); tfm::format(stream, " %-17s %-17s %-17s %-10s\n", "Size", "Entry Size", "Flags Link Info", "Align"); for (const auto& Section : pFile->sections()) { tfm::format(stream, " [%2u] %-17s %-17s %017X %08X\n", Section->getIndex(), Section->getName(), Section->getTypeString(), Section->getAddress(), Section->getOffset()); tfm::format(stream, " %017X %017X %5s %5u %5u %6u\n", Section->getSize(), Section->getEntrySize(), Section->getFlagsString(), Section->getLink(), Section->getInfo(), Section->getAddressAlignment()); } stream << "Key to Flags:\n"; stream << " W (write), A (alloc), X (execute), M (merge), S (strings), l (large)\n"; stream << " I (info), L (link order), G (group), T (TLS), E (exclude), x (unkown)\n"; stream << " O (extra OS processing required), o(OS specific), p (processor specific)\n"; } /// Prints the segments of the file pointed to by \p pFile to the output /// stream \p stream in a readelf-like style. /// /// \param pFile Pointer to the file object /// \param stream The stream to print to void printSegmentTable(const std::shared_ptr<ELFFile>& pFile, std::ostream& stream) { stream << "Program Headers:\n"; tfm::format(stream, " %-20s %-20s %-20s %-20s\n", "Type", "Offset", "Virtual Address", "Physical Address"); tfm::format(stream, " %-20s %-20s %-20s %-20s\n", "", "File Size", "Memory Size", " Flags Align"); for (const auto& Seg : pFile->segments()) { tfm::format(stream, " %-20s 0x%018X 0x%018X 0x%018X\n", Seg->getTypeString(), Seg->getOffset(), Seg->getVirtualAddress(), Seg->getPhysicalAddress()); tfm::format(stream, " %-20s 0x%018X 0x%018X %6s %8X\n", "", Seg->getFileSize(), Seg->getMemorySize(), Seg->getFlagsString(), Seg->getAddressAlignment()); } stream << "Mapping of Sections on Segments:\n"; std::string sectionNames = std::string(); for (const auto& Seg : pFile->segments()) { for (const auto& index : Seg->getAssociatedSections()) { sectionNames += pFile->sections().at(index)->getName() + " "; } tfm::format(stream, " %02d %s\n", Seg->getIndex(), sectionNames); sectionNames.clear(); } } /// Prints the dynamic section of the file pointed to by \p pFile to the /// stream \p stream in readelf-like style. /// /// \param pFile Pointer to the file object /// \param stream The stream to print to void printDynamicSection(const std::shared_ptr<ELFFile>& pFile, std::ostream& stream) { tfm::format(stream, "Dynamic section contains %d entries:\n", pFile->getDynamicSection()->getNumEntries()); tfm::format(stream, " %-20s %-20s %-30s\n", "Tag", "Type", "Value"); for (const auto& entry : pFile->getDynamicSection()->getAllEntries()) { tfm::format(stream, " 0x%018X %-20s %d\n", entry.tag, entry.getTypeString(), entry.value); } } /// Prints the symbol sections of an ELF file to the output stream \p stream /// in a readelf-like style. /// /// \param pFile Pointer to the file object /// \param stream The stream to print to void printSymbolSections(const std::shared_ptr<ELFFile>& pFile, std::ostream& stream) { for (const auto& SymSec : pFile->symbolSections()) { tfm::format(stream, "Symbol table '%s' contains %d entries:\n", SymSec->getName(), SymSec->getNumSymbols()); tfm::format(stream, "%6s: %-15s %-5s %-8s %-8s %-5s %-25s\n", "Num", "Value", "Size", "Type", "Bind", "Ndx", "Name"); std::shared_ptr<Symbol> Sym; for (size_t i = 0; i < SymSec->getNumSymbols(); ++i) { Sym = SymSec->getSymbol(i); if (!Sym) continue; tfm::format(stream, "%6d: %016X %5d %-8s %-8s %5d %-25s\n", i, Sym->value, Sym->size, Sym->getTypeString(), Sym->getBindString(), Sym->sectionIndex, Sym->name.substr(0, 25)); } stream << "\n"; } } /// Prints the notes sections of an ELF file to the output stream \p stream /// in a readelf-like style. /// /// \param pFile Pointer to the file object /// \param stream The stream to print to void printNotesSections(const std::shared_ptr<ELFFile> pFile, std::ostream& stream) { for (const auto& section : pFile->noteSections()) { tfm::format(stream, "Displaying notes found at file offset 0x%08X with length 0x%08X:\n", section->getOffset(), section->getSize()); tfm::format(stream, "%-20s %-12s %-10s\n", "Owner", "Data size", "Type"); for (size_t i = 0; i < section->getNumEntries(); i++) { auto entry = section->getEntry(i); tfm::format(stream, "%-20s 0x%08X 0x%08X\n", entry->Name, entry->Description.length(), entry->Type); } stream << "\n"; } } /// Prints the relocation sections of an ELF file to the output stream \p stream /// in a readelf-like style. /// /// \param pFile Pointer to the file object /// \param stream The stream to print to void printRelocSections(const std::shared_ptr<ELFFile> pFile, std::ostream& stream) { for (const auto& section : pFile->relocationSections()) { tfm::format(stream, "Relocation section '%s' at offset 0x%X contains %d entries:\n", section->getName(), section->getOffset(), section->getNumEntries()); tfm::format(stream, "%-12s %-12s %-8s %-16s %-55s\n", "Offset", "Info", "Type", "Sym. Value", "Sym. Name + Addend"); for (const auto& entry : section->getAllEntries()) { tfm::format(stream, "%012X %012X %08X %016X %s + %X\n", entry->Offset, entry->Info, entry->Type, entry->SymbolInstance->value, entry->SymbolInstance->name.substr(0, 45), entry->Addend); } stream << "\n"; } } /// Main function of \p readelfpp. /// /// \param argc Number of arguments /// \param argv Arguments as array of strings /// \return Integer value indicating termination state (0 means 'sucess', /// everything else means 'failure') int main(int argc, const char* argv[]) { try { TCLAP::CmdLine Cmd("Simple clone of readelf", ' ', getVersionString()); TCLAP::UnlabeledValueArg<std::string> FileNameArg("file", "The name of the ELF file to read", true, "", "filename"); TCLAP::SwitchArg HeaderSwitch("f", "file-header", "Displays the information contained in the ELF header at the start of the file.", false); TCLAP::SwitchArg SegmentSwitch("l", "segments", "Displays the information contained in the file's segment headers, if it has any.", false); TCLAP::SwitchArg SectionSwitch("S", "sections", "Displays the information contained in the file's section headers, if it has any.", false); TCLAP::SwitchArg AllHeadersSwitch("e", "headers", "Display all the headers in the file. Equivalent to -f -l -S.", false); TCLAP::SwitchArg SymbolSwitch("s", "symbols", "Displays the entries in symbol table section of the file, if it has one.", false); TCLAP::SwitchArg DynamicSwitch("d", "dynamic", "Displays the contents of the file's dynamic section, if it has one.", false); TCLAP::SwitchArg NotesSwitch("n", "notes", "Displays the contents of any notes sections, if any.", false); TCLAP::SwitchArg RelocSwitch("r", "relocs", "Displays the contents of the file's relocation section, if it has one.", false); Cmd.add(HeaderSwitch); Cmd.add(SegmentSwitch); Cmd.add(SectionSwitch); Cmd.add(AllHeadersSwitch); Cmd.add(SymbolSwitch); Cmd.add(DynamicSwitch); Cmd.add(FileNameArg); Cmd.add(NotesSwitch); Cmd.add(RelocSwitch); Cmd.parse(argc, argv); try { auto pFile = std::make_shared<ELFFile>(FileNameArg.getValue()); bool All = AllHeadersSwitch.getValue(); if (HeaderSwitch.getValue() || All) { printHeader(pFile->getHeader(), std::cout); } if (SectionSwitch.getValue() || All) { printSectionTable(pFile, std::cout); } if (SegmentSwitch.getValue() || All) { printSegmentTable(pFile, std::cout); } if (SymbolSwitch.getValue()) { printSymbolSections(pFile, std::cout); } if (DynamicSwitch.getValue()) { printDynamicSection(pFile, std::cout); } if (NotesSwitch.getValue()) { printNotesSections(pFile, std::cout); } if (RelocSwitch.getValue()) { printRelocSections(pFile, std::cout); } } catch (const std::runtime_error& err) { std::cerr << "ERROR: Creation of file " << FileNameArg.getValue() << " failed: " << err.what() << "\n"; return 1; } } catch (TCLAP::ArgException& e) { std::cerr << "ERROR: " << e.error() << "\n"; return 1; } return 0; }<commit_msg>Fix error that was introduced by changing API of getAssociatedSections().<commit_after>/* * MIT License * * Copyright (c) 2017 Kevin Kirchner * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ /** * \file readelfpp.cpp * \brief A simple clone of readelf using \p libelfpp * \author Kevin Kirchner * \date 2017 * \copyright MIT LICENSE * * A simple clone of readelf from the GNU binutils using \p libelfpp. This * application is just a example and does not implement all features readelf * provides. */ #include <libelfpp/libelfpp.h> #include <tclap/CmdLine.h> #include "tinyformat.h" using namespace libelfpp; /// Prints the \p header of type \p ELFHeader to the output stream \p stream /// in a readelf-like style. /// /// \param header Pointer to the ELF header to print /// \param stream The stream to print to void printHeader(const std::shared_ptr<ELFFileHeader>& header, std::ostream& stream) { stream << "ELF Header:\n" << std::left; tfm::format(stream, "%-39s %s\n", "Class:", (header->is64Bit() ? "ELF64" : "ELF32")); tfm::format(stream, "%-39s %s\n", "Version:", std::to_string(header->getVersion()) + (header->getVersion() == 1 ? " (current)" : "")); tfm::format(stream, "%-39s %s\n", "Encoding:", std::string("2's complement, ") + (header->isLittleEndian() ? "Little" : "Big") + " Endian"); tfm::format(stream, "%-39s %s\n", "OS/ABI:", header->getABIString()); tfm::format(stream, "%-39s %s\n", "Type:", header->getELFTypeString()); tfm::format(stream, "%-39s %s\n", "Machine:", header->getMachineString()); tfm::format(stream, "%-39s 0x%X\n", "Entrypoint:", header->getEntryPoint()); tfm::format(stream, "%-39s %u (Bytes in File)\n", "Start of Program Headers:", header->getProgramHeaderOffset()); tfm::format(stream, "%-39s %u (Bytes in File)\n", "Start of Section Headers:", header->getSectionHeaderOffset()); tfm::format(stream, "%-39s 0x%X\n", "Flags:", header->getFlags()); tfm::format(stream, "%-39s %u (Bytes)\n", "Size of File Header:", header->getHeaderSize()); tfm::format(stream, "%-39s %u (Bytes)\n", "Size of Program Header:", header->getProgramHeaderSize()); tfm::format(stream, "%-39s %u\n", "Number of Program Headers:", header->getProgramHeaderNumber()); tfm::format(stream, "%-39s %u\n", "Size of Section Header:", header->getSectionHeaderSize()); tfm::format(stream, "%-39s %u\n", "Number of Section Headers:", header->getSectionHeaderNumber()); tfm::format(stream, "%-39s %u\n", "Section Header String Table Index:", header->getSectionHeaderStringTableIndex()); } /// Prints the sections of the file pointed to by \p pFile to the output /// stream \p stream in a readelf-like style. /// /// \param pFile Pointer to the file object /// \param stream The stream to print to void printSectionTable(const std::shared_ptr<ELFFile>& pFile, std::ostream& stream) { stream << "Section Headers:\n" << std::left; tfm::format(stream, " [%-2s] %-17s %-17s %-17s %-10s\n", "No", "Name", "Type", "Address", "Offset"); tfm::format(stream, " %-17s %-17s %-17s %-10s\n", "Size", "Entry Size", "Flags Link Info", "Align"); for (const auto& Section : pFile->sections()) { tfm::format(stream, " [%2u] %-17s %-17s %017X %08X\n", Section->getIndex(), Section->getName(), Section->getTypeString(), Section->getAddress(), Section->getOffset()); tfm::format(stream, " %017X %017X %5s %5u %5u %6u\n", Section->getSize(), Section->getEntrySize(), Section->getFlagsString(), Section->getLink(), Section->getInfo(), Section->getAddressAlignment()); } stream << "Key to Flags:\n"; stream << " W (write), A (alloc), X (execute), M (merge), S (strings), l (large)\n"; stream << " I (info), L (link order), G (group), T (TLS), E (exclude), x (unkown)\n"; stream << " O (extra OS processing required), o(OS specific), p (processor specific)\n"; } /// Prints the segments of the file pointed to by \p pFile to the output /// stream \p stream in a readelf-like style. /// /// \param pFile Pointer to the file object /// \param stream The stream to print to void printSegmentTable(const std::shared_ptr<ELFFile>& pFile, std::ostream& stream) { stream << "Program Headers:\n"; tfm::format(stream, " %-20s %-20s %-20s %-20s\n", "Type", "Offset", "Virtual Address", "Physical Address"); tfm::format(stream, " %-20s %-20s %-20s %-20s\n", "", "File Size", "Memory Size", " Flags Align"); for (const auto& Seg : pFile->segments()) { tfm::format(stream, " %-20s 0x%018X 0x%018X 0x%018X\n", Seg->getTypeString(), Seg->getOffset(), Seg->getVirtualAddress(), Seg->getPhysicalAddress()); tfm::format(stream, " %-20s 0x%018X 0x%018X %6s %8X\n", "", Seg->getFileSize(), Seg->getMemorySize(), Seg->getFlagsString(), Seg->getAddressAlignment()); } stream << "Mapping of Sections on Segments:\n"; std::string sectionNames = std::string(); for (const auto& Seg : pFile->segments()) { for (const auto& Sec : Seg->getAssociatedSections()) { sectionNames += Sec->getName() + " "; } tfm::format(stream, " %02d %s\n", Seg->getIndex(), sectionNames); sectionNames.clear(); } } /// Prints the dynamic section of the file pointed to by \p pFile to the /// stream \p stream in readelf-like style. /// /// \param pFile Pointer to the file object /// \param stream The stream to print to void printDynamicSection(const std::shared_ptr<ELFFile>& pFile, std::ostream& stream) { tfm::format(stream, "Dynamic section contains %d entries:\n", pFile->getDynamicSection()->getNumEntries()); tfm::format(stream, " %-20s %-20s %-30s\n", "Tag", "Type", "Value"); for (const auto& entry : pFile->getDynamicSection()->getAllEntries()) { tfm::format(stream, " 0x%018X %-20s %d\n", entry.tag, entry.getTypeString(), entry.value); } } /// Prints the symbol sections of an ELF file to the output stream \p stream /// in a readelf-like style. /// /// \param pFile Pointer to the file object /// \param stream The stream to print to void printSymbolSections(const std::shared_ptr<ELFFile>& pFile, std::ostream& stream) { for (const auto& SymSec : pFile->symbolSections()) { tfm::format(stream, "Symbol table '%s' contains %d entries:\n", SymSec->getName(), SymSec->getNumSymbols()); tfm::format(stream, "%6s: %-15s %-5s %-8s %-8s %-5s %-25s\n", "Num", "Value", "Size", "Type", "Bind", "Ndx", "Name"); std::shared_ptr<Symbol> Sym; for (size_t i = 0; i < SymSec->getNumSymbols(); ++i) { Sym = SymSec->getSymbol(i); if (!Sym) continue; tfm::format(stream, "%6d: %016X %5d %-8s %-8s %5d %-25s\n", i, Sym->value, Sym->size, Sym->getTypeString(), Sym->getBindString(), Sym->sectionIndex, Sym->name.substr(0, 25)); } stream << "\n"; } } /// Prints the notes sections of an ELF file to the output stream \p stream /// in a readelf-like style. /// /// \param pFile Pointer to the file object /// \param stream The stream to print to void printNotesSections(const std::shared_ptr<ELFFile> pFile, std::ostream& stream) { for (const auto& section : pFile->noteSections()) { tfm::format(stream, "Displaying notes found at file offset 0x%08X with length 0x%08X:\n", section->getOffset(), section->getSize()); tfm::format(stream, "%-20s %-12s %-10s\n", "Owner", "Data size", "Type"); for (size_t i = 0; i < section->getNumEntries(); i++) { auto entry = section->getEntry(i); tfm::format(stream, "%-20s 0x%08X 0x%08X\n", entry->Name, entry->Description.length(), entry->Type); } stream << "\n"; } } /// Prints the relocation sections of an ELF file to the output stream \p stream /// in a readelf-like style. /// /// \param pFile Pointer to the file object /// \param stream The stream to print to void printRelocSections(const std::shared_ptr<ELFFile> pFile, std::ostream& stream) { for (const auto& section : pFile->relocationSections()) { tfm::format(stream, "Relocation section '%s' at offset 0x%X contains %d entries:\n", section->getName(), section->getOffset(), section->getNumEntries()); tfm::format(stream, "%-12s %-12s %-8s %-16s %-55s\n", "Offset", "Info", "Type", "Sym. Value", "Sym. Name + Addend"); for (const auto& entry : section->getAllEntries()) { tfm::format(stream, "%012X %012X %08X %016X %s + %X\n", entry->Offset, entry->Info, entry->Type, entry->SymbolInstance->value, entry->SymbolInstance->name.substr(0, 45), entry->Addend); } stream << "\n"; } } /// Main function of \p readelfpp. /// /// \param argc Number of arguments /// \param argv Arguments as array of strings /// \return Integer value indicating termination state (0 means 'sucess', /// everything else means 'failure') int main(int argc, const char* argv[]) { try { TCLAP::CmdLine Cmd("Simple clone of readelf", ' ', getVersionString()); TCLAP::UnlabeledValueArg<std::string> FileNameArg("file", "The name of the ELF file to read", true, "", "filename"); TCLAP::SwitchArg HeaderSwitch("f", "file-header", "Displays the information contained in the ELF header at the start of the file.", false); TCLAP::SwitchArg SegmentSwitch("l", "segments", "Displays the information contained in the file's segment headers, if it has any.", false); TCLAP::SwitchArg SectionSwitch("S", "sections", "Displays the information contained in the file's section headers, if it has any.", false); TCLAP::SwitchArg AllHeadersSwitch("e", "headers", "Display all the headers in the file. Equivalent to -f -l -S.", false); TCLAP::SwitchArg SymbolSwitch("s", "symbols", "Displays the entries in symbol table section of the file, if it has one.", false); TCLAP::SwitchArg DynamicSwitch("d", "dynamic", "Displays the contents of the file's dynamic section, if it has one.", false); TCLAP::SwitchArg NotesSwitch("n", "notes", "Displays the contents of any notes sections, if any.", false); TCLAP::SwitchArg RelocSwitch("r", "relocs", "Displays the contents of the file's relocation section, if it has one.", false); Cmd.add(HeaderSwitch); Cmd.add(SegmentSwitch); Cmd.add(SectionSwitch); Cmd.add(AllHeadersSwitch); Cmd.add(SymbolSwitch); Cmd.add(DynamicSwitch); Cmd.add(FileNameArg); Cmd.add(NotesSwitch); Cmd.add(RelocSwitch); Cmd.parse(argc, argv); try { auto pFile = std::make_shared<ELFFile>(FileNameArg.getValue()); bool All = AllHeadersSwitch.getValue(); if (HeaderSwitch.getValue() || All) { printHeader(pFile->getHeader(), std::cout); } if (SectionSwitch.getValue() || All) { printSectionTable(pFile, std::cout); } if (SegmentSwitch.getValue() || All) { printSegmentTable(pFile, std::cout); } if (SymbolSwitch.getValue()) { printSymbolSections(pFile, std::cout); } if (DynamicSwitch.getValue()) { printDynamicSection(pFile, std::cout); } if (NotesSwitch.getValue()) { printNotesSections(pFile, std::cout); } if (RelocSwitch.getValue()) { printRelocSections(pFile, std::cout); } } catch (const std::runtime_error& err) { std::cerr << "ERROR: Creation of file " << FileNameArg.getValue() << " failed: " << err.what() << "\n"; return 1; } } catch (TCLAP::ArgException& e) { std::cerr << "ERROR: " << e.error() << "\n"; return 1; } return 0; }<|endoftext|>
<commit_before>#include "rpc/protocol.hh" #include "rpc/thunk.hh" #include "rpc_server.hh" using namespace ten; using namespace msgpack::rpc; const size_t default_stacksize=256*1024; class rpc_client : public boost::noncopyable { public: rpc_client(const std::string &hostname, uint16_t port) : s(AF_INET, SOCK_STREAM), msgid(0) { if (s.dial(hostname.c_str(), port) != 0) { throw errorx("rpc client connection failed"); } } template <typename Result, typename ...Args> Result call(const std::string &method, Args ...args) { uint32_t mid = ++msgid; return rpcall<Result>(mid, method, args...); } protected: netsock s; uint32_t msgid; msgpack::unpacker pac; template <typename Result> Result rpcall(msgpack::packer<msgpack::sbuffer> &pk, msgpack::sbuffer &sbuf) { ssize_t nw = s.send(sbuf.data(), sbuf.size()); if (nw != (ssize_t)sbuf.size()) { throw errorx("rpc call failed to send"); } size_t bsize = 4096; for (;;) { pac.reserve_buffer(bsize); ssize_t nr = s.recv(pac.buffer(), bsize); if (nr <= 0) { throw errorx("rpc client lost connection"); } DVLOG(3) << "client recv: " << nr; pac.buffer_consumed(nr); msgpack::unpacked result; if (pac.next(&result)) { msgpack::object o = result.get(); DVLOG(3) << "client got: " << o; msg_response<msgpack::object, msgpack::object> resp; o.convert(&resp); if (resp.error.is_nil()) { return resp.result.as<Result>(); } else { LOG(ERROR) << "rpc error returned: " << resp.error; throw errorx(resp.error.as<std::string>()); } } } // shouldn't get here. throw errorx("rpc client unknown error"); } template <typename Result, typename Arg, typename ...Args> Result rpcall(msgpack::packer<msgpack::sbuffer> &pk, msgpack::sbuffer &sbuf, Arg arg, Args ...args) { pk.pack(arg); return rpcall<Result>(pk, sbuf, args...); } template <typename Result, typename ...Args> Result rpcall(uint32_t msgid, const std::string &method, Args ...args) { msgpack::sbuffer sbuf; msgpack::packer<msgpack::sbuffer> pk(&sbuf); pk.pack_array(4); pk.pack_uint8(0); // request message type pk.pack_uint32(msgid); pk.pack(method); pk.pack_array(sizeof...(args)); return rpcall<Result>(pk, sbuf, args...); } }; static void client_task() { rpc_client c("localhost", 5500); int status = c.call<int>("add2", 40, 2); LOG(INFO) << "status: " << status; } static int add2(int a, int b) { LOG(INFO) << "called add2(" << a << "," << b << ")"; return a + b; } static void startup() { rpc_server rpc; rpc.add_command("add2", thunk<int, int, int>(add2)); taskspawn(client_task); rpc.serve("0.0.0.0", 5500); } int main(int argc, char *argv[]) { procmain p; taskspawn(startup); return p.main(argc, argv); } <commit_msg>extend rpc example<commit_after>#include "rpc/protocol.hh" #include "rpc/thunk.hh" #include "rpc_server.hh" using namespace ten; using namespace msgpack::rpc; const size_t default_stacksize=256*1024; class rpc_client : public boost::noncopyable { public: rpc_client(const std::string &hostname, uint16_t port) : s(AF_INET, SOCK_STREAM), msgid(0) { if (s.dial(hostname.c_str(), port) != 0) { throw errorx("rpc client connection failed"); } } template <typename Result, typename ...Args> Result call(const std::string &method, Args ...args) { uint32_t mid = ++msgid; return rpcall<Result>(mid, method, args...); } protected: netsock s; uint32_t msgid; msgpack::unpacker pac; template <typename Result> Result rpcall(msgpack::packer<msgpack::sbuffer> &pk, msgpack::sbuffer &sbuf) { ssize_t nw = s.send(sbuf.data(), sbuf.size()); if (nw != (ssize_t)sbuf.size()) { throw errorx("rpc call failed to send"); } size_t bsize = 4096; for (;;) { pac.reserve_buffer(bsize); ssize_t nr = s.recv(pac.buffer(), bsize); if (nr <= 0) { throw errorx("rpc client lost connection"); } DVLOG(3) << "client recv: " << nr; pac.buffer_consumed(nr); msgpack::unpacked result; if (pac.next(&result)) { msgpack::object o = result.get(); DVLOG(3) << "client got: " << o; msg_response<msgpack::object, msgpack::object> resp; o.convert(&resp); if (resp.error.is_nil()) { return resp.result.as<Result>(); } else { LOG(ERROR) << "rpc error returned: " << resp.error; throw errorx(resp.error.as<std::string>()); } } } // shouldn't get here. throw errorx("rpc client unknown error"); } template <typename Result, typename Arg, typename ...Args> Result rpcall(msgpack::packer<msgpack::sbuffer> &pk, msgpack::sbuffer &sbuf, Arg arg, Args ...args) { pk.pack(arg); return rpcall<Result>(pk, sbuf, args...); } template <typename Result, typename ...Args> Result rpcall(uint32_t msgid, const std::string &method, Args ...args) { msgpack::sbuffer sbuf; msgpack::packer<msgpack::sbuffer> pk(&sbuf); pk.pack_array(4); pk.pack_uint8(0); // request message type pk.pack_uint32(msgid); pk.pack(method); pk.pack_array(sizeof...(args)); return rpcall<Result>(pk, sbuf, args...); } }; static void client_task() { rpc_client c("localhost", 5500); LOG(INFO) << "40+2=" << c.call<int>("add2", 40, 2); LOG(INFO) << "44-2=" << c.call<int>("subtract2", 44, 2); procshutdown(); } static int add2(int a, int b) { LOG(INFO) << "called add2(" << a << "," << b << ")"; return a + b; } static int subtract2(int a, int b) { return a - b; } static void startup() { rpc_server rpc; rpc.add_command("add2", thunk<int, int, int>(add2)); rpc.add_command("subtract2", thunk<int, int, int>(subtract2)); taskspawn(client_task); rpc.serve("0.0.0.0", 5500); } int main(int argc, char *argv[]) { procmain p; taskspawn(startup); return p.main(argc, argv); } <|endoftext|>
<commit_before> #include "../../../Include/Windows/ExtLibs.h" #include "../../../Include/Windows/Thread.h" using namespace A2D; // Set an instance of this. So it can call waitAll AbstractThread* Thread::aClassInstance = new Thread(NULL); // Intiialize the OrderedList OrderedList<HANDLE> Thread::aThreadHandles; Thread::Thread(Runnable * xRunnable) : AbstractThread(xRunnable) { // Default thread id is 0 until we get // an actual thread id from kernel aId = 0; } Thread::~Thread() { // Obviously check if it is alive then stop // Due to limitations in C++ code, we can't // do this in AbstractThread. But you should // do this in all children classes of AbstractThread if (isAlive()) { stop(); } // Call super deconstructor AbstractThread::~AbstractThread(); } bool Thread::start() { // Get thread via kernel level request aHThread = CreateThread(NULL, 0, &initThread, this, 0, &aId); // Set priority just because we can SetThreadPriority(aHThread, THREAD_PRIORITY_TIME_CRITICAL); // Get the handle from OrderedList and store it aListHandle = aThreadHandles.push_back(aHThread); // Increment parent activeCount AbstractThread::aActiveCount++; return (aHThread != NULL); } void Thread::interrupt() { // Check if thread exists if (aHThread) { SuspendThread(aHThread); // Decrement parent activeCount AbstractThread::aActiveCount--; } } int Thread::id() { //return an integer format of thread id return static_cast<int>(aId); } void Thread::resume() { if (aHThread) { int resumeCount = ResumeThread(aHThread); while (resumeCount > 1) { resumeCount = ResumeThread(aHThread); } // Increment parent activeCount AbstractThread::aActiveCount++; } } void Thread::stop() { if (aHThread) { TerminateThread( aHThread, 0 ); CloseHandle(aHThread); aHThread = NULL; // Request remove of the list handle aThreadHandles.remove_request(aListHandle); // Decrement parent activeCount AbstractThread::aActiveCount--; } } bool Thread::isAlive() { // Kernel level waiting to see if thread is still alive. // If it is alive, and the wait time is 0, then we know // that the WAIT has not been signaled (WAIT_OBJECT_0) // Another way to setting the wait time to something really // small like 1ms and then see if the signal has not been fired // i.e. WaitForSingleObject(aHThread, 0) == WAIT_TIMEOUT return ((aHThread != NULL) && (WaitForSingleObject(aHThread, 0) != WAIT_OBJECT_0)); } void Thread::waitAll() { // Use the kernel wait for every thread that has been created. WaitForMultipleObjects(aThreadHandles.size(), aThreadHandles.to_array(), true, INFINITE); } int Thread::getCurrentThreadId() { // returns the current thread from the kernel level return static_cast<int>(GetCurrentThreadId()); } // This static method is used as the logic loop behind // thread creation and starting every thread. Different // platforms have different techniques, Windows just happens // to do it this way. DWORD WINAPI Thread::initThread(void * xParam) { Thread * thread = reinterpret_cast<Thread*>(xParam); if (thread) { thread->fire(); return 0; } return -1; } LPCWSTR Thread::getClass() { return L"Thread"; } LPCWSTR Thread::toString() { return L"Thread"; }<commit_msg>Added one more important comment<commit_after> #include "../../../Include/Windows/ExtLibs.h" #include "../../../Include/Windows/Thread.h" using namespace A2D; // Set an instance of this. So it can call waitAll AbstractThread* Thread::aClassInstance = new Thread(NULL); // Intiialize the OrderedList OrderedList<HANDLE> Thread::aThreadHandles; Thread::Thread(Runnable * xRunnable) : AbstractThread(xRunnable) { // Default thread id is 0 until we get // an actual thread id from kernel aId = 0; } Thread::~Thread() { // Obviously check if it is alive then stop // Due to limitations in C++ code, we can't // do this in AbstractThread. But you should // do this in all children classes of AbstractThread if (isAlive()) { stop(); } // Call super deconstructor AbstractThread::~AbstractThread(); } bool Thread::start() { // Get thread via kernel level request aHThread = CreateThread(NULL, 0, &initThread, this, 0, &aId); // Set priority just because we can SetThreadPriority(aHThread, THREAD_PRIORITY_TIME_CRITICAL); // Get the handle from OrderedList and store it aListHandle = aThreadHandles.push_back(aHThread); // Increment parent activeCount AbstractThread::aActiveCount++; return (aHThread != NULL); } void Thread::interrupt() { // Check if thread exists if (aHThread) { SuspendThread(aHThread); // Decrement parent activeCount AbstractThread::aActiveCount--; } } int Thread::id() { //return an integer format of thread id return static_cast<int>(aId); } void Thread::resume() { if (aHThread) { int resumeCount = ResumeThread(aHThread); while (resumeCount > 1) { resumeCount = ResumeThread(aHThread); } // Increment parent activeCount AbstractThread::aActiveCount++; } } void Thread::stop() { if (aHThread) { TerminateThread( aHThread, 0 ); CloseHandle(aHThread); aHThread = NULL; // Request remove of the list handle aThreadHandles.remove_request(aListHandle); // Decrement parent activeCount AbstractThread::aActiveCount--; } } bool Thread::isAlive() { // Kernel level waiting to see if thread is still alive. // If it is alive, and the wait time is 0, then we know // that the WAIT has not been signaled (WAIT_OBJECT_0) // Another way to setting the wait time to something really // small like 1ms and then see if the signal has not been fired // i.e. WaitForSingleObject(aHThread, 0) == WAIT_TIMEOUT return ((aHThread != NULL) && (WaitForSingleObject(aHThread, 0) != WAIT_OBJECT_0)); } void Thread::waitAll() { // Use the kernel wait for every thread that has been created. WaitForMultipleObjects(aThreadHandles.size(), aThreadHandles.to_array(), true, INFINITE); } int Thread::getCurrentThreadId() { // returns the current thread from the kernel level return static_cast<int>(GetCurrentThreadId()); } // This static method is used as the logic loop behind // thread creation and starting every thread. Different // platforms have different techniques, Windows just happens // to do it this way. DWORD WINAPI Thread::initThread(void * xParam) { Thread * thread = reinterpret_cast<Thread*>(xParam); // If thread exists if (thread) { // Fire the thread which is defined in // super class : AbstracThread thread->fire(); return 0; } return -1; } LPCWSTR Thread::getClass() { return L"Thread"; } LPCWSTR Thread::toString() { return L"Thread"; }<|endoftext|>
<commit_before>/* * Copyright 2012 Google Inc. * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include "SkDataPixelRef.h" #include "SkData.h" SkDataPixelRef::SkDataPixelRef(SkData* data) : fData(data) { fData->ref(); this->setPreLocked(const_cast<void*>(fData->data()), NULL); } SkDataPixelRef::~SkDataPixelRef() { fData->unref(); } void* SkDataPixelRef::onLockPixels(SkColorTable** ct) { *ct = NULL; return const_cast<void*>(fData->data()); } void SkDataPixelRef::onUnlockPixels() { // nothing to do } void SkDataPixelRef::flatten(SkFlattenableWriteBuffer& buffer) const { this->INHERITED::flatten(buffer); buffer.writeFlattenable(fData); } SkDataPixelRef::SkDataPixelRef(SkFlattenableReadBuffer& buffer) : INHERITED(buffer, NULL) { fData = (SkData*)buffer.readFlattenable(); this->setPreLocked(const_cast<void*>(fData->data()), NULL); } SK_DEFINE_FLATTENABLE_REGISTRAR(SkDataPixelRef) <commit_msg>include SkFlatteningBuffer.h after restructure<commit_after>/* * Copyright 2012 Google Inc. * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include "SkDataPixelRef.h" #include "SkData.h" #include "SkFlattenableBuffers.h" SkDataPixelRef::SkDataPixelRef(SkData* data) : fData(data) { fData->ref(); this->setPreLocked(const_cast<void*>(fData->data()), NULL); } SkDataPixelRef::~SkDataPixelRef() { fData->unref(); } void* SkDataPixelRef::onLockPixels(SkColorTable** ct) { *ct = NULL; return const_cast<void*>(fData->data()); } void SkDataPixelRef::onUnlockPixels() { // nothing to do } void SkDataPixelRef::flatten(SkFlattenableWriteBuffer& buffer) const { this->INHERITED::flatten(buffer); buffer.writeFlattenable(fData); } SkDataPixelRef::SkDataPixelRef(SkFlattenableReadBuffer& buffer) : INHERITED(buffer, NULL) { fData = (SkData*)buffer.readFlattenable(); this->setPreLocked(const_cast<void*>(fData->data()), NULL); } SK_DEFINE_FLATTENABLE_REGISTRAR(SkDataPixelRef) <|endoftext|>
<commit_before>/* * Copyright (C) 2013 Google 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 Google 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. */ #include "config.h" #include "core/animation/AnimatableLength.h" #include "core/css/CSSPrimitiveValueMappings.h" #include "platform/CalculationValue.h" #include "platform/animation/AnimationUtilities.h" namespace WebCore { PassRefPtr<AnimatableLength> AnimatableLength::create(CSSValue* value) { ASSERT(canCreateFrom(value)); if (value->isPrimitiveValue()) { CSSPrimitiveValue* primitiveValue = WebCore::toCSSPrimitiveValue(value); const CSSCalcValue* calcValue = primitiveValue->cssCalcValue(); if (calcValue) return create(calcValue->expressionNode(), primitiveValue); NumberUnitType unitType = primitiveUnitToNumberType(primitiveValue->primitiveType()); ASSERT(unitType != UnitTypeInvalid); const double scale = CSSPrimitiveValue::conversionToCanonicalUnitsScaleFactor(primitiveValue->primitiveType()); return create(primitiveValue->getDoubleValue() * scale, unitType, primitiveValue); } if (value->isCalcValue()) return create(toCSSCalcValue(value)->expressionNode()); ASSERT_NOT_REACHED(); return 0; } bool AnimatableLength::canCreateFrom(const CSSValue* value) { ASSERT(value); if (value->isPrimitiveValue()) { const CSSPrimitiveValue* primitiveValue = WebCore::toCSSPrimitiveValue(value); if (primitiveValue->cssCalcValue()) return true; return primitiveUnitToNumberType(primitiveValue->primitiveType()) != UnitTypeInvalid; } return value->isCalcValue(); } PassRefPtr<CSSValue> AnimatableLength::toCSSValue(NumberRange range) const { return toCSSPrimitiveValue(range); } Length AnimatableLength::toLength(const RenderStyle* style, const RenderStyle* rootStyle, double zoom, NumberRange range) const { if (!m_isCalc) { // Avoid creating a CSSValue in the common cases if (m_unitType == UnitTypePixels) return Length(clampedNumber(range) * zoom, Fixed); if (m_unitType == UnitTypePercentage) return Length(clampedNumber(range), Percent); } return toCSSPrimitiveValue(range)->convertToLength<AnyConversion>(style, rootStyle, zoom); } PassRefPtr<AnimatableValue> AnimatableLength::interpolateTo(const AnimatableValue* value, double fraction) const { const AnimatableLength* length = toAnimatableLength(value); NumberUnitType type = commonUnitType(length); if (type != UnitTypeInvalid) return AnimatableLength::create(blend(m_number, length->m_number, fraction), type); return AnimatableLength::create(scale(1 - fraction).get(), length->scale(fraction).get()); } PassRefPtr<AnimatableValue> AnimatableLength::addWith(const AnimatableValue* value) const { // Optimization for adding with 0. if (isUnitlessZero()) return takeConstRef(value); const AnimatableLength* length = toAnimatableLength(value); if (length->isUnitlessZero()) return takeConstRef(this); NumberUnitType type = commonUnitType(length); if (type != UnitTypeInvalid) return AnimatableLength::create(m_number + length->m_number, type); return AnimatableLength::create(this, length); } bool AnimatableLength::equalTo(const AnimatableValue* value) const { const AnimatableLength* length = toAnimatableLength(value); if (m_isCalc != length->m_isCalc) return false; if (m_isCalc && length->m_isCalc) return m_calcExpression == length->m_calcExpression || m_calcExpression->equals(*length->m_calcExpression); return m_number == length->m_number && m_unitType == length->m_unitType; } PassRefPtr<CSSCalcExpressionNode> AnimatableLength::toCSSCalcExpressionNode() const { if (m_isCalc) return m_calcExpression; return CSSCalcValue::createExpressionNode(toCSSPrimitiveValue(AllValues), m_number == trunc(m_number)); } static bool isCompatibleWithRange(const CSSPrimitiveValue* primitiveValue, NumberRange range) { ASSERT(primitiveValue); if (range == AllValues) return true; if (primitiveValue->isCalculated()) return primitiveValue->cssCalcValue()->permittedValueRange() == ValueRangeNonNegative; return primitiveValue->getDoubleValue() >= 0; } PassRefPtr<CSSPrimitiveValue> AnimatableLength::toCSSPrimitiveValue(NumberRange range) const { ASSERT(m_unitType != UnitTypeInvalid); if (!m_cachedCSSPrimitiveValue || !isCompatibleWithRange(m_cachedCSSPrimitiveValue.get(), range)) { if (m_isCalc) m_cachedCSSPrimitiveValue = CSSPrimitiveValue::create(CSSCalcValue::create(m_calcExpression, range == AllValues ? ValueRangeAll : ValueRangeNonNegative)); else m_cachedCSSPrimitiveValue = CSSPrimitiveValue::create(clampedNumber(range), static_cast<CSSPrimitiveValue::UnitTypes>(numberTypeToPrimitiveUnit(m_unitType))); } return m_cachedCSSPrimitiveValue; } PassRefPtr<AnimatableLength> AnimatableLength::scale(double factor) const { if (m_isCalc) { return AnimatableLength::create(CSSCalcValue::createExpressionNode( m_calcExpression, CSSCalcValue::createExpressionNode(CSSPrimitiveValue::create(factor, CSSPrimitiveValue::CSS_NUMBER)), CalcMultiply)); } return AnimatableLength::create(m_number * factor, m_unitType); } AnimatableLength::NumberUnitType AnimatableLength::primitiveUnitToNumberType(unsigned short primitiveUnit) { switch (primitiveUnit) { case CSSPrimitiveValue::CSS_PX: case CSSPrimitiveValue::CSS_CM: case CSSPrimitiveValue::CSS_MM: case CSSPrimitiveValue::CSS_IN: case CSSPrimitiveValue::CSS_PT: case CSSPrimitiveValue::CSS_PC: return UnitTypePixels; case CSSPrimitiveValue::CSS_EMS: return UnitTypeFontSize; case CSSPrimitiveValue::CSS_EXS: return UnitTypeFontXSize; case CSSPrimitiveValue::CSS_REMS: return UnitTypeRootFontSize; case CSSPrimitiveValue::CSS_PERCENTAGE: return UnitTypePercentage; case CSSPrimitiveValue::CSS_VW: return UnitTypeViewportWidth; case CSSPrimitiveValue::CSS_VH: return UnitTypeViewportHeight; case CSSPrimitiveValue::CSS_VMIN: return UnitTypeViewportMin; case CSSPrimitiveValue::CSS_VMAX: return UnitTypeViewportMax; default: return UnitTypeInvalid; } } unsigned short AnimatableLength::numberTypeToPrimitiveUnit(NumberUnitType numberType) { switch (numberType) { case UnitTypePixels: return CSSPrimitiveValue::CSS_PX; case UnitTypeFontSize: return CSSPrimitiveValue::CSS_EMS; case UnitTypeFontXSize: return CSSPrimitiveValue::CSS_EXS; case UnitTypeRootFontSize: return CSSPrimitiveValue::CSS_REMS; case UnitTypePercentage: return CSSPrimitiveValue::CSS_PERCENTAGE; case UnitTypeViewportWidth: return CSSPrimitiveValue::CSS_VW; case UnitTypeViewportHeight: return CSSPrimitiveValue::CSS_VH; case UnitTypeViewportMin: return CSSPrimitiveValue::CSS_VMIN; case UnitTypeViewportMax: return CSSPrimitiveValue::CSS_VMAX; case UnitTypeInvalid: return CSSPrimitiveValue::CSS_UNKNOWN; } ASSERT_NOT_REACHED(); return CSSPrimitiveValue::CSS_UNKNOWN; } } // namespace WebCore <commit_msg>Web Animations CSS: Fix assertion in AnimatableLength::toCSSPrimitiveValue<commit_after>/* * Copyright (C) 2013 Google 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 Google 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. */ #include "config.h" #include "core/animation/AnimatableLength.h" #include "core/css/CSSPrimitiveValueMappings.h" #include "platform/CalculationValue.h" #include "platform/animation/AnimationUtilities.h" namespace WebCore { PassRefPtr<AnimatableLength> AnimatableLength::create(CSSValue* value) { ASSERT(canCreateFrom(value)); if (value->isPrimitiveValue()) { CSSPrimitiveValue* primitiveValue = WebCore::toCSSPrimitiveValue(value); const CSSCalcValue* calcValue = primitiveValue->cssCalcValue(); if (calcValue) return create(calcValue->expressionNode(), primitiveValue); NumberUnitType unitType = primitiveUnitToNumberType(primitiveValue->primitiveType()); ASSERT(unitType != UnitTypeInvalid); const double scale = CSSPrimitiveValue::conversionToCanonicalUnitsScaleFactor(primitiveValue->primitiveType()); return create(primitiveValue->getDoubleValue() * scale, unitType, primitiveValue); } if (value->isCalcValue()) return create(toCSSCalcValue(value)->expressionNode()); ASSERT_NOT_REACHED(); return 0; } bool AnimatableLength::canCreateFrom(const CSSValue* value) { ASSERT(value); if (value->isPrimitiveValue()) { const CSSPrimitiveValue* primitiveValue = WebCore::toCSSPrimitiveValue(value); if (primitiveValue->cssCalcValue()) return true; return primitiveUnitToNumberType(primitiveValue->primitiveType()) != UnitTypeInvalid; } return value->isCalcValue(); } PassRefPtr<CSSValue> AnimatableLength::toCSSValue(NumberRange range) const { return toCSSPrimitiveValue(range); } Length AnimatableLength::toLength(const RenderStyle* style, const RenderStyle* rootStyle, double zoom, NumberRange range) const { if (!m_isCalc) { // Avoid creating a CSSValue in the common cases if (m_unitType == UnitTypePixels) return Length(clampedNumber(range) * zoom, Fixed); if (m_unitType == UnitTypePercentage) return Length(clampedNumber(range), Percent); } return toCSSPrimitiveValue(range)->convertToLength<AnyConversion>(style, rootStyle, zoom); } PassRefPtr<AnimatableValue> AnimatableLength::interpolateTo(const AnimatableValue* value, double fraction) const { const AnimatableLength* length = toAnimatableLength(value); NumberUnitType type = commonUnitType(length); if (type != UnitTypeInvalid) return AnimatableLength::create(blend(m_number, length->m_number, fraction), type); return AnimatableLength::create(scale(1 - fraction).get(), length->scale(fraction).get()); } PassRefPtr<AnimatableValue> AnimatableLength::addWith(const AnimatableValue* value) const { // Optimization for adding with 0. if (isUnitlessZero()) return takeConstRef(value); const AnimatableLength* length = toAnimatableLength(value); if (length->isUnitlessZero()) return takeConstRef(this); NumberUnitType type = commonUnitType(length); if (type != UnitTypeInvalid) return AnimatableLength::create(m_number + length->m_number, type); return AnimatableLength::create(this, length); } bool AnimatableLength::equalTo(const AnimatableValue* value) const { const AnimatableLength* length = toAnimatableLength(value); if (m_isCalc != length->m_isCalc) return false; if (m_isCalc && length->m_isCalc) return m_calcExpression == length->m_calcExpression || m_calcExpression->equals(*length->m_calcExpression); return m_number == length->m_number && m_unitType == length->m_unitType; } PassRefPtr<CSSCalcExpressionNode> AnimatableLength::toCSSCalcExpressionNode() const { if (m_isCalc) return m_calcExpression; return CSSCalcValue::createExpressionNode(toCSSPrimitiveValue(AllValues), m_number == trunc(m_number)); } static bool isCompatibleWithRange(const CSSPrimitiveValue* primitiveValue, NumberRange range) { ASSERT(primitiveValue); if (range == AllValues) return true; if (primitiveValue->isCalculated()) return primitiveValue->cssCalcValue()->permittedValueRange() == ValueRangeNonNegative; return primitiveValue->getDoubleValue() >= 0; } PassRefPtr<CSSPrimitiveValue> AnimatableLength::toCSSPrimitiveValue(NumberRange range) const { ASSERT(m_isCalc || m_unitType != UnitTypeInvalid); if (!m_cachedCSSPrimitiveValue || !isCompatibleWithRange(m_cachedCSSPrimitiveValue.get(), range)) { if (m_isCalc) m_cachedCSSPrimitiveValue = CSSPrimitiveValue::create(CSSCalcValue::create(m_calcExpression, range == AllValues ? ValueRangeAll : ValueRangeNonNegative)); else m_cachedCSSPrimitiveValue = CSSPrimitiveValue::create(clampedNumber(range), static_cast<CSSPrimitiveValue::UnitTypes>(numberTypeToPrimitiveUnit(m_unitType))); } return m_cachedCSSPrimitiveValue; } PassRefPtr<AnimatableLength> AnimatableLength::scale(double factor) const { if (m_isCalc) { return AnimatableLength::create(CSSCalcValue::createExpressionNode( m_calcExpression, CSSCalcValue::createExpressionNode(CSSPrimitiveValue::create(factor, CSSPrimitiveValue::CSS_NUMBER)), CalcMultiply)); } return AnimatableLength::create(m_number * factor, m_unitType); } AnimatableLength::NumberUnitType AnimatableLength::primitiveUnitToNumberType(unsigned short primitiveUnit) { switch (primitiveUnit) { case CSSPrimitiveValue::CSS_PX: case CSSPrimitiveValue::CSS_CM: case CSSPrimitiveValue::CSS_MM: case CSSPrimitiveValue::CSS_IN: case CSSPrimitiveValue::CSS_PT: case CSSPrimitiveValue::CSS_PC: return UnitTypePixels; case CSSPrimitiveValue::CSS_EMS: return UnitTypeFontSize; case CSSPrimitiveValue::CSS_EXS: return UnitTypeFontXSize; case CSSPrimitiveValue::CSS_REMS: return UnitTypeRootFontSize; case CSSPrimitiveValue::CSS_PERCENTAGE: return UnitTypePercentage; case CSSPrimitiveValue::CSS_VW: return UnitTypeViewportWidth; case CSSPrimitiveValue::CSS_VH: return UnitTypeViewportHeight; case CSSPrimitiveValue::CSS_VMIN: return UnitTypeViewportMin; case CSSPrimitiveValue::CSS_VMAX: return UnitTypeViewportMax; default: return UnitTypeInvalid; } } unsigned short AnimatableLength::numberTypeToPrimitiveUnit(NumberUnitType numberType) { switch (numberType) { case UnitTypePixels: return CSSPrimitiveValue::CSS_PX; case UnitTypeFontSize: return CSSPrimitiveValue::CSS_EMS; case UnitTypeFontXSize: return CSSPrimitiveValue::CSS_EXS; case UnitTypeRootFontSize: return CSSPrimitiveValue::CSS_REMS; case UnitTypePercentage: return CSSPrimitiveValue::CSS_PERCENTAGE; case UnitTypeViewportWidth: return CSSPrimitiveValue::CSS_VW; case UnitTypeViewportHeight: return CSSPrimitiveValue::CSS_VH; case UnitTypeViewportMin: return CSSPrimitiveValue::CSS_VMIN; case UnitTypeViewportMax: return CSSPrimitiveValue::CSS_VMAX; case UnitTypeInvalid: return CSSPrimitiveValue::CSS_UNKNOWN; } ASSERT_NOT_REACHED(); return CSSPrimitiveValue::CSS_UNKNOWN; } } // namespace WebCore <|endoftext|>
<commit_before>// condor_mail.cpp : main project file. // compile with: /clr #using <mscorlib.dll> #using <System.dll> #using <System.Net.dll> #using <System.Security.dll> using namespace System; using namespace System::Net; using namespace System::Net::Mail; using namespace System::Security; using namespace System::Security::Cryptography; using namespace System::Text; using namespace System::Collections; using namespace System::Collections::Generic; using namespace Microsoft::Win32; void Usage(Int32 code) { Console::Error->WriteLine("usage: condor_mail [-f from] " "[-s subject] [-relay relayhost] " "[-savecred -u user@relayhost -p password] recipient ..."); Environment::Exit(code); } String^ Username() { String^ username = nullptr; username = Environment::GetEnvironmentVariable("CONDOR_MAIL_USER"); if (!String::IsNullOrEmpty(username)) { return username; } username = Environment::UserName; if (!String::IsNullOrEmpty(username)) { return username; } username = Environment::GetEnvironmentVariable("USER"); if (!String::IsNullOrEmpty(username)) { return username; } return "unknown"; } String^ Body() { return Console::In->ReadToEnd(); } String^ SmtpRelaysSubKey() { return "SOFTWARE\\condor\\SmtpRelays"; } void SaveCredentials(String^ relay, String^ login, String^ password) { try { RegistryKey^ key = Registry::LocalMachine->OpenSubKey( SmtpRelaysSubKey(), true); if (!key) { key = Registry::LocalMachine->CreateSubKey(SmtpRelaysSubKey()); } array<Byte>^ securePassword = ProtectedData::Protect( Encoding::UTF8->GetBytes(password), nullptr, DataProtectionScope::LocalMachine); String^ value = String::Format("{0} {1}", login, Convert::ToBase64String(securePassword)); key->SetValue(relay, value); key->Close(); } catch (Exception^ e) { Console::Error->WriteLine("error : " + e->Message); Usage(1); } } NetworkCredential^ FindCredentials(String^ relay) { try { RegistryKey^ key = Registry::LocalMachine->OpenSubKey( SmtpRelaysSubKey()); if (!key) { return nullptr; } String^ value = (String^) key->GetValue(relay); key->Close(); if (!value) { return nullptr; } array<String^>^ split = value->Split(); String^ login = split[0]; String^ password = Encoding::UTF8->GetString( ProtectedData::Unprotect(Convert::FromBase64String(split[1]), nullptr, DataProtectionScope::LocalMachine)); return gcnew NetworkCredential(login, password); } catch (Exception^ e) { Console::Error->WriteLine("error : " + e->Message); Usage(1); } return nullptr; } int main(array<String^>^ args) { List<MailAddress^>^ recipients = gcnew List<MailAddress^>(); String^ subject = ""; String^ from = Username() + "@" + Dns::GetHostName(); String^ relay = "127.0.0.1"; String^ login = ""; String^ password = ""; Boolean saveCred = false; try { for (int i = 0; i < args->Length; ++i) { if ("-s" == args[i]) { subject = args[++i]; } else if ("-f" == args[i]) { from = args[++i]; } else if ("-relay" == args[i]) { relay = args[++i]; } else if ("-savecred" == args[i]) { saveCred = true; } else if ("-u" == args[i]) { login = args[++i]; } else if ("-p" == args[i]) { password = args[++i]; } else { // this is a recipient recipients->Add(gcnew MailAddress(args[i])); } } } catch (Exception^ e) { Console::Error->WriteLine("error: " + e->Message); Usage(1); } if (!saveCred && (!String::IsNullOrEmpty(login) || !String::IsNullOrEmpty(password))) { Console::Error->WriteLine("error: -u or -p cannot be used " "without -savecred"); Usage(4); } if (saveCred) { if (String::IsNullOrEmpty(relay)) { Console::Error->WriteLine("error: -savecred cannot be used " "without -relay"); Usage(4); } else if ("127.0.0.1" == relay) { Console::WriteLine("warning: saving credential for 127.0.0.1"); } if (String::IsNullOrEmpty(login) || String::IsNullOrEmpty(password)) { Console::Error->WriteLine("error: -u and -p are required " "with -savecred"); Usage(4); } SaveCredentials(relay, login, password); Console::WriteLine("info: saved credential for {0} at relay {1}", login, relay); Environment::Exit(0); } if (!recipients->Count) { Console::Error->WriteLine("error: you must specify " "at least one recipient."); Usage(2); } try { SmtpClient^ client = gcnew SmtpClient(relay); MailMessage^ msg = gcnew MailMessage(); NetworkCredential^ credentials = FindCredentials(relay); if (credentials) { client->EnableSsl = true; client->Credentials = credentials; } msg->From = gcnew MailAddress(from); msg->Subject = subject; msg->Body = Body(); for (int i = 0; i < recipients->Count; ++i) { msg->To->Add(recipients[i]); } client->Send(msg); } catch (Exception^ e) { Console::Error->WriteLine("error: " + e->Message); Usage(3); } } <commit_msg>Use port 587 if using an authenticated relay<commit_after>// condor_mail.cpp : main project file. // compile with: /clr #using <mscorlib.dll> #using <System.dll> #using <System.Net.dll> #using <System.Security.dll> using namespace System; using namespace System::Net; using namespace System::Net::Mail; using namespace System::Security; using namespace System::Security::Cryptography; using namespace System::Text; using namespace System::Collections; using namespace System::Collections::Generic; using namespace Microsoft::Win32; void Usage(Int32 code) { Console::Error->WriteLine("usage: condor_mail [-f from] " "[-s subject] [-relay relayhost] " "[-savecred -u user@relayhost -p password] recipient ..."); Environment::Exit(code); } String^ Username() { String^ username = nullptr; username = Environment::GetEnvironmentVariable("CONDOR_MAIL_USER"); if (!String::IsNullOrEmpty(username)) { return username; } username = Environment::UserName; if (!String::IsNullOrEmpty(username)) { return username; } username = Environment::GetEnvironmentVariable("USER"); if (!String::IsNullOrEmpty(username)) { return username; } return "unknown"; } String^ Body() { return Console::In->ReadToEnd(); } String^ SmtpRelaysSubKey() { return "SOFTWARE\\condor\\SmtpRelays"; } void SaveCredentials(String^ relay, String^ login, String^ password) { try { RegistryKey^ key = Registry::LocalMachine->OpenSubKey( SmtpRelaysSubKey(), true); if (!key) { key = Registry::LocalMachine->CreateSubKey(SmtpRelaysSubKey()); } array<Byte>^ securePassword = ProtectedData::Protect( Encoding::UTF8->GetBytes(password), nullptr, DataProtectionScope::LocalMachine); String^ value = String::Format("{0} {1}", login, Convert::ToBase64String(securePassword)); key->SetValue(relay, value); key->Close(); } catch (Exception^ e) { Console::Error->WriteLine("error : " + e->Message); Usage(1); } } NetworkCredential^ FindCredentials(String^ relay) { try { RegistryKey^ key = Registry::LocalMachine->OpenSubKey( SmtpRelaysSubKey()); if (!key) { return nullptr; } String^ value = (String^) key->GetValue(relay); key->Close(); if (!value) { return nullptr; } array<String^>^ split = value->Split(); String^ login = split[0]; String^ password = Encoding::UTF8->GetString( ProtectedData::Unprotect(Convert::FromBase64String(split[1]), nullptr, DataProtectionScope::LocalMachine)); return gcnew NetworkCredential(login, password); } catch (Exception^ e) { Console::Error->WriteLine("error : " + e->Message); Usage(1); } return nullptr; } int main(array<String^>^ args) { List<MailAddress^>^ recipients = gcnew List<MailAddress^>(); String^ subject = ""; String^ from = Username() + "@" + Dns::GetHostName(); String^ relay = "127.0.0.1"; String^ login = ""; String^ password = ""; Boolean saveCred = false; try { for (int i = 0; i < args->Length; ++i) { if ("-s" == args[i]) { subject = args[++i]; } else if ("-f" == args[i]) { from = args[++i]; } else if ("-relay" == args[i]) { relay = args[++i]; } else if ("-savecred" == args[i]) { saveCred = true; } else if ("-u" == args[i]) { login = args[++i]; } else if ("-p" == args[i]) { password = args[++i]; } else { // this is a recipient recipients->Add(gcnew MailAddress(args[i])); } } } catch (Exception^ e) { Console::Error->WriteLine("error: " + e->Message); Usage(1); } if (!saveCred && (!String::IsNullOrEmpty(login) || !String::IsNullOrEmpty(password))) { Console::Error->WriteLine("error: -u or -p cannot be used " "without -savecred"); Usage(4); } if (saveCred) { if (String::IsNullOrEmpty(relay)) { Console::Error->WriteLine("error: -savecred cannot be used " "without -relay"); Usage(4); } else if ("127.0.0.1" == relay) { Console::WriteLine("warning: saving credential for 127.0.0.1"); } if (String::IsNullOrEmpty(login) || String::IsNullOrEmpty(password)) { Console::Error->WriteLine("error: -u and -p are required " "with -savecred"); Usage(4); } SaveCredentials(relay, login, password); Console::WriteLine("info: saved credential for {0} at relay {1}", login, relay); Environment::Exit(0); } if (!recipients->Count) { Console::Error->WriteLine("error: you must specify " "at least one recipient."); Usage(2); } try { SmtpClient^ client = gcnew SmtpClient(relay); MailMessage^ msg = gcnew MailMessage(); NetworkCredential^ credentials = FindCredentials(relay); if (credentials) { client->EnableSsl = true; client->Port = 587; client->Credentials = credentials; } msg->From = gcnew MailAddress(from); msg->Subject = subject; msg->Body = Body(); for (int i = 0; i < recipients->Count; ++i) { msg->To->Add(recipients[i]); } client->Send(msg); } catch (Exception^ e) { Console::Error->WriteLine("error: " + e->Message); Usage(3); } } <|endoftext|>
<commit_before>#include <boost/asio/io_service.hpp> #include "TcpServer.h" #include <exception> #include "ProcessMessageClientConnected.h" #include "ProcessMessageReceivePacket.h" #include "ProcessMessageSendPacket.h" #include "ProcessMessageSocketDisconnected.h" #include "ProcessMessageTerminate.h" #include "TcpCommunicationProcess.h" #include "TcpListenerProcess.h" #include "ProcessMessageAskForCommProcessInfo.h" #include "ProcessMessageCommProcessInfo.h" #define FORCE_VS_DBG_OUTPUT #include <DebugUtil.h> #include <ToString.h> TcpServer::TcpServer() { m_isListening = false; m_ioService = new boost::asio::io_service(); m_listenerProcess = NULL; m_uniqueBroadcastPacketIdentifier = 0; } TcpServer::~TcpServer() { shutdown(); } void TcpServer::shutdown() { stopListening(); for( unsigned int i=0; i<m_communicationProcesses.size(); i++ ) { m_communicationProcesses[i]->putMessage( new ProcessMessageTerminate() ); m_communicationProcesses[i]->stop(); delete m_communicationProcesses[i]; } m_communicationProcesses.clear(); delete m_ioService; m_ioService = NULL; } void TcpServer::startListening( int p_port ) { m_isListening = true; m_listenerProcess = new TcpListenerProcess( this, p_port, m_ioService ); m_listenerProcess->start(); } void TcpServer::stopListening() { m_isListening = false; if( m_listenerProcess ) { m_listenerProcess->putMessage( new ProcessMessageTerminate() ); m_listenerProcess->stop(); delete m_listenerProcess; m_listenerProcess = NULL; } } bool TcpServer::isListening() { return m_isListening; } bool TcpServer::hasNewConnections() { bool newConnect = false; if( m_newConnectionProcesses.size() > 0 ) newConnect = true; return newConnect; } unsigned int TcpServer::newConnectionsCount() { return m_newConnectionProcesses.size(); } unsigned int TcpServer::activeConnectionsCount() { return m_communicationProcesses.size(); } unsigned int TcpServer::newDisconnectionsCount() { return m_newDisconnectionProcesses.size(); } bool TcpServer::hasNewDisconnections() { bool newDisconnect = false; if( m_newDisconnectionProcesses.size() > 0 ) newDisconnect = true; return newDisconnect; } int TcpServer::popNewDisconnection() { int id = -1; if( m_newDisconnectionProcesses.size() > 0 ) { id = m_newDisconnectionProcesses.front(); m_newDisconnectionProcesses.pop(); } return id; } bool TcpServer::hasNewPackets() { bool newPacket = false; if( m_newPackets.size() > 0 ) newPacket = true; return newPacket; } unsigned int TcpServer::newPacketsCount() { return m_newPackets.size(); } Packet TcpServer::popNewPacket() { if ( !m_newPackets.empty() ) { Packet packet = m_newPackets.front(); m_newPackets.pop(); return packet; } else { throw domain_error( "Trying to pop from an empty packet queue!" ); } return NULL; } void TcpServer::processMessages() { queue< ProcessMessage* > messages; messages = checkoutMessageQueue(); while( messages.size() > 0 ) { ProcessMessage* message = messages.front(); messages.pop(); if( message->type == MessageType::CLIENT_CONNECTED ) { ProcessMessageClientConnected* messageClientConnected = static_cast<ProcessMessageClientConnected*>(message); m_communicationProcesses.push_back(new TcpCommunicationProcess( this, messageClientConnected->socket, m_ioService)); m_communicationProcesses.back()->start(); m_totalSentInCommProcesses.push_back(0); m_newConnectionProcesses.push( m_communicationProcesses.back()->getId() ); } else if( message->type == MessageType::SOCKET_DISCONNECTED ) { ProcessMessageSocketDisconnected* messageSocketDisconnected = static_cast< ProcessMessageSocketDisconnected* >(message); int processToBeDeleted = -1; for( unsigned int i=0; i<m_communicationProcesses.size(); i++ ) { if( messageSocketDisconnected->processId == m_communicationProcesses[i]->getId() ) { m_newDisconnectionProcesses.push( m_communicationProcesses[i]->getId() ); processToBeDeleted = i; break; } } if (processToBeDeleted != -1) { DEBUGPRINT(( (toString("Server terminated comprocess ") + toString(m_communicationProcesses[processToBeDeleted]->getId()) + toString("\n")).c_str() )); m_communicationProcesses[processToBeDeleted]->putMessage( new ProcessMessageTerminate() ); m_communicationProcesses[processToBeDeleted]->stop(); delete m_communicationProcesses[processToBeDeleted]; m_communicationProcesses.erase(m_communicationProcesses.begin() + processToBeDeleted); } else throw "Something is really knaaas"; } else if( message->type == MessageType::RECEIVE_PACKET ) { m_newPackets.push( static_cast< ProcessMessageReceivePacket* >(message)->packet ); } else if( message->type == MessageType::COMM_PROCESS_INFO ) { ProcessMessageCommProcessInfo* commInfoMessage = static_cast<ProcessMessageCommProcessInfo*>( message ); for(unsigned int i=0; i<m_communicationProcesses.size(); i++) { if(m_communicationProcesses[i] == commInfoMessage->sender ) { m_totalSentInCommProcesses[i] = commInfoMessage->totalPacketsSent; } } } delete message; } } void TcpServer::broadcastPacket( Packet& p_packet, int p_excludeClientId) { giveBroadcastPacketAUniqueIdentifier( &p_packet ); for( unsigned int i=0; i<m_communicationProcesses.size(); i++ ) { if (m_communicationProcesses[i]->getId()!=p_excludeClientId) { m_communicationProcesses[i]->putMessage( new ProcessMessageSendPacket( this, p_packet ) ); } } } void TcpServer::multicastPacket( vector<int> p_connectionIdentities, Packet& p_packet ) { for( unsigned int i=0; i<p_connectionIdentities.size(); i++ ) { unicastPacket( p_packet, p_connectionIdentities[i] ); } } void TcpServer::unicastPacket( Packet& p_packet, int p_clientId ) { // NOTE: this might be slow enough to do for individual packets for ( unsigned int i = 0; i < m_communicationProcesses.size(); i++ ) { if ( m_communicationProcesses[i]->getId() == p_clientId ) { m_communicationProcesses[i]->putMessage( new ProcessMessageSendPacket( this, p_packet ) ); break; } } } void TcpServer::unicastPacketQueue( queue<Packet> p_packets, int p_clientId ) { for ( unsigned int i = 0; i < m_communicationProcesses.size(); i++ ) { if ( m_communicationProcesses[i]->getId() == p_clientId ) { queue<ProcessMessage*> messages; while( !p_packets.empty() ) { Packet packet = p_packets.front(); p_packets.pop(); messages.push( new ProcessMessageSendPacket( this, packet ) ); } m_communicationProcesses[i]->putMessages( messages ); break; } } } int TcpServer::popNewConnection() { int id = -1; if( m_newConnectionProcesses.size() > 0 ) { id = m_newConnectionProcesses.front(); m_newConnectionProcesses.pop(); } return id; } vector< int > TcpServer::getActiveConnections() { vector< int > currentConnections; for( unsigned int i=0; i<m_communicationProcesses.size(); i++ ) { currentConnections.push_back( m_communicationProcesses[i]->getId() ); } return currentConnections; } void TcpServer::giveBroadcastPacketAUniqueIdentifier( Packet* p_packet ) { p_packet->setUniquePacketIdentifier( m_uniqueBroadcastPacketIdentifier ); m_uniqueBroadcastPacketIdentifier += 1; } const unsigned int& TcpServer::getTotalBroadcasts() { return m_uniqueBroadcastPacketIdentifier; } void TcpServer::askForCommProcessInfo() { for(unsigned int i=0; i<m_communicationProcesses.size(); i++) { m_communicationProcesses[i]->putMessage( new ProcessMessageAskForCommProcessInfo( this ) ); } } const unsigned int& TcpServer::totalSentInCommProcess( const unsigned int& p_processIdentity ) { return m_totalSentInCommProcesses[p_processIdentity]; } <commit_msg>Poo on you<commit_after>#include <boost/asio/io_service.hpp> #include "TcpServer.h" #include <exception> #include "ProcessMessageClientConnected.h" #include "ProcessMessageReceivePacket.h" #include "ProcessMessageSendPacket.h" #include "ProcessMessageSocketDisconnected.h" #include "ProcessMessageTerminate.h" #include "TcpCommunicationProcess.h" #include "TcpListenerProcess.h" #include "ProcessMessageAskForCommProcessInfo.h" #include "ProcessMessageCommProcessInfo.h" #define FORCE_VS_DBG_OUTPUT #include <DebugUtil.h> #include <ToString.h> TcpServer::TcpServer() { m_isListening = false; m_ioService = new boost::asio::io_service(); m_listenerProcess = NULL; m_uniqueBroadcastPacketIdentifier = 0; } TcpServer::~TcpServer() { shutdown(); } void TcpServer::shutdown() { stopListening(); for( unsigned int i=0; i<m_communicationProcesses.size(); i++ ) { m_communicationProcesses[i]->putMessage( new ProcessMessageTerminate() ); m_communicationProcesses[i]->stop(); delete m_communicationProcesses[i]; } m_communicationProcesses.clear(); delete m_ioService; m_ioService = NULL; } void TcpServer::startListening( int p_port ) { m_isListening = true; m_listenerProcess = new TcpListenerProcess( this, p_port, m_ioService ); m_listenerProcess->start(); } void TcpServer::stopListening() { m_isListening = false; if( m_listenerProcess ) { m_listenerProcess->putMessage( new ProcessMessageTerminate() ); m_listenerProcess->stop(); delete m_listenerProcess; m_listenerProcess = NULL; } } bool TcpServer::isListening() { return m_isListening; } bool TcpServer::hasNewConnections() { bool newConnect = false; if( m_newConnectionProcesses.size() > 0 ) newConnect = true; return newConnect; } unsigned int TcpServer::newConnectionsCount() { return m_newConnectionProcesses.size(); } unsigned int TcpServer::activeConnectionsCount() { return m_communicationProcesses.size(); } unsigned int TcpServer::newDisconnectionsCount() { return m_newDisconnectionProcesses.size(); } bool TcpServer::hasNewDisconnections() { bool newDisconnect = false; if( m_newDisconnectionProcesses.size() > 0 ) newDisconnect = true; return newDisconnect; } int TcpServer::popNewDisconnection() { int id = -1; if( m_newDisconnectionProcesses.size() > 0 ) { id = m_newDisconnectionProcesses.front(); m_newDisconnectionProcesses.pop(); } return id; } bool TcpServer::hasNewPackets() { bool newPacket = false; if( m_newPackets.size() > 0 ) newPacket = true; return newPacket; } unsigned int TcpServer::newPacketsCount() { return m_newPackets.size(); } Packet TcpServer::popNewPacket() { if ( !m_newPackets.empty() ) { Packet packet = m_newPackets.front(); m_newPackets.pop(); return packet; } else { throw domain_error( "Trying to pop from an empty packet queue!" ); } return NULL; } void TcpServer::processMessages() { queue< ProcessMessage* > messages; messages = checkoutMessageQueue(); while( messages.size() > 0 ) { ProcessMessage* message = messages.front(); messages.pop(); if( message->type == MessageType::CLIENT_CONNECTED ) { ProcessMessageClientConnected* messageClientConnected = static_cast<ProcessMessageClientConnected*>(message); m_communicationProcesses.push_back(new TcpCommunicationProcess( this, messageClientConnected->socket, m_ioService)); m_communicationProcesses.back()->start(); m_totalSentInCommProcesses.push_back(0); m_newConnectionProcesses.push( m_communicationProcesses.back()->getId() ); } else if( message->type == MessageType::SOCKET_DISCONNECTED ) { ProcessMessageSocketDisconnected* messageSocketDisconnected = static_cast< ProcessMessageSocketDisconnected* >(message); int processToBeDeleted = -1; for( unsigned int i=0; i<m_communicationProcesses.size(); i++ ) { if( messageSocketDisconnected->processId == m_communicationProcesses[i]->getId() ) { m_newDisconnectionProcesses.push( m_communicationProcesses[i]->getId() ); processToBeDeleted = i; break; } } if (processToBeDeleted != -1) { DEBUGPRINT(( (toString("Server terminated comprocess ") + toString(m_communicationProcesses[processToBeDeleted]->getId()) + toString("\n")).c_str() )); m_communicationProcesses[processToBeDeleted]->putMessage( new ProcessMessageTerminate() ); m_communicationProcesses[processToBeDeleted]->stop(); delete m_communicationProcesses[processToBeDeleted]; m_communicationProcesses.erase(m_communicationProcesses.begin() + processToBeDeleted); } else throw "Something is really knaaas"; } else if( message->type == MessageType::RECEIVE_PACKET ) { m_newPackets.push( static_cast< ProcessMessageReceivePacket* >(message)->packet ); } else if( message->type == MessageType::COMM_PROCESS_INFO ) { ProcessMessageCommProcessInfo* commInfoMessage = static_cast<ProcessMessageCommProcessInfo*>( message ); for(unsigned int i=0; i<m_communicationProcesses.size(); i++) { if(m_communicationProcesses[i] == commInfoMessage->sender ) { m_totalSentInCommProcesses[i] = commInfoMessage->totalPacketsSent; } } } delete message; } } void TcpServer::broadcastPacket( Packet& p_packet, int p_excludeClientId) { giveBroadcastPacketAUniqueIdentifier( &p_packet ); for( unsigned int i=0; i<m_communicationProcesses.size(); i++ ) { if (m_communicationProcesses[i]->getId()!=p_excludeClientId) { m_communicationProcesses[i]->putMessage( new ProcessMessageSendPacket( this, p_packet ) ); } } } void TcpServer::multicastPacket( vector<int> p_connectionIdentities, Packet& p_packet ) { for( unsigned int i=0; i<p_connectionIdentities.size(); i++ ) { unicastPacket( p_packet, p_connectionIdentities[i] ); } } void TcpServer::unicastPacket( Packet& p_packet, int p_clientId ) { // NOTE: this might be slow enough to do for individual packets for ( unsigned int i = 0; i < m_communicationProcesses.size(); i++ ) { if ( m_communicationProcesses[i]->getId() == p_clientId ) { m_communicationProcesses[i]->putMessage( new ProcessMessageSendPacket( this, p_packet ) ); break; } } } void TcpServer::unicastPacketQueue( queue<Packet> p_packets, int p_clientId ) { for ( unsigned int i = 0; i < m_communicationProcesses.size(); i++ ) { if ( m_communicationProcesses[i]->getId() == p_clientId ) { queue<ProcessMessage*> messages; while( !p_packets.empty() ) { Packet packet = p_packets.front(); p_packets.pop(); messages.push( new ProcessMessageSendPacket( this, packet ) ); } m_communicationProcesses[i]->putMessages( messages ); break; } } } int TcpServer::popNewConnection() { int id = -1; if( m_newConnectionProcesses.size() > 0 ) { id = m_newConnectionProcesses.front(); m_newConnectionProcesses.pop(); } return id; } vector< int > TcpServer::getActiveConnections() { vector< int > currentConnections; for( unsigned int i=0; i<m_communicationProcesses.size(); i++ ) { currentConnections.push_back( m_communicationProcesses[i]->getId() ); } return currentConnections; } void TcpServer::giveBroadcastPacketAUniqueIdentifier( Packet* p_packet ) { p_packet->setUniquePacketIdentifier( m_uniqueBroadcastPacketIdentifier ); m_uniqueBroadcastPacketIdentifier += 1; } const unsigned int& TcpServer::getTotalBroadcasts() { return m_uniqueBroadcastPacketIdentifier; } void TcpServer::askForCommProcessInfo() { for(unsigned int i=0; i<m_communicationProcesses.size(); i++) { m_communicationProcesses[i]->putMessage( new ProcessMessageAskForCommProcessInfo( this ) ); } } const unsigned int& TcpServer::totalSentInCommProcess( const unsigned int& p_processIdentity ) { return m_totalSentInCommProcesses[p_processIdentity]; } <|endoftext|>
<commit_before>/* * Copyright (C) 2011 Google 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 Google 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. */ #include "config.h" #include "core/inspector/PageRuntimeAgent.h" #include "bindings/v8/DOMWrapperWorld.h" #include "bindings/v8/ScriptController.h" #include "core/inspector/InjectedScript.h" #include "core/inspector/InjectedScriptManager.h" #include "core/inspector/InspectorPageAgent.h" #include "core/inspector/InspectorState.h" #include "core/inspector/InstrumentingAgents.h" #include "core/page/Frame.h" #include "core/page/Page.h" #include "core/page/PageConsole.h" #include "weborigin/SecurityOrigin.h" using WebCore::TypeBuilder::Runtime::ExecutionContextDescription; namespace WebCore { namespace PageRuntimeAgentState { static const char runtimeEnabled[] = "runtimeEnabled"; }; PageRuntimeAgent::PageRuntimeAgent(InstrumentingAgents* instrumentingAgents, InspectorCompositeState* state, InjectedScriptManager* injectedScriptManager, ScriptDebugServer* scriptDebugServer, Page* page, InspectorPageAgent* pageAgent) : InspectorRuntimeAgent(instrumentingAgents, state, injectedScriptManager, scriptDebugServer) , m_inspectedPage(page) , m_pageAgent(pageAgent) , m_frontend(0) , m_mainWorldContextCreated(false) { m_instrumentingAgents->setPageRuntimeAgent(this); } PageRuntimeAgent::~PageRuntimeAgent() { m_instrumentingAgents->setPageRuntimeAgent(0); } void PageRuntimeAgent::setFrontend(InspectorFrontend* frontend) { m_frontend = frontend->runtime(); } void PageRuntimeAgent::clearFrontend() { m_frontend = 0; String errorString; disable(&errorString); } void PageRuntimeAgent::restore() { if (m_state->getBoolean(PageRuntimeAgentState::runtimeEnabled)) { String error; enable(&error); } } void PageRuntimeAgent::enable(ErrorString* errorString) { if (m_enabled) return; InspectorRuntimeAgent::enable(errorString); m_state->setBoolean(PageRuntimeAgentState::runtimeEnabled, true); // Only report existing contexts if the page did commit load, otherwise we may // unintentionally initialize contexts in the frames which may trigger some listeners // that are expected to be triggered only after the load is committed, see http://crbug.com/131623 if (m_mainWorldContextCreated) reportExecutionContextCreation(); } void PageRuntimeAgent::disable(ErrorString* errorString) { if (!m_enabled) return; InspectorRuntimeAgent::disable(errorString); m_state->setBoolean(PageRuntimeAgentState::runtimeEnabled, false); } void PageRuntimeAgent::didClearWindowObjectInWorld(Frame* frame, DOMWrapperWorld* world) { if (world != mainThreadNormalWorld()) return; m_mainWorldContextCreated = true; if (!m_enabled) return; ASSERT(m_frontend); String frameId = m_pageAgent->frameId(frame); ScriptState* scriptState = mainWorldScriptState(frame); notifyContextCreated(frameId, scriptState, 0, true); } void PageRuntimeAgent::didCreateIsolatedContext(Frame* frame, ScriptState* scriptState, SecurityOrigin* origin) { if (!m_enabled) return; ASSERT(m_frontend); String frameId = m_pageAgent->frameId(frame); notifyContextCreated(frameId, scriptState, origin, false); } InjectedScript PageRuntimeAgent::injectedScriptForEval(ErrorString* errorString, const int* executionContextId) { if (!executionContextId) { // We shouldn't be able to create an injected script if the main // window shell not initialized. See crbug.com/263162. ScriptController* scriptController = m_inspectedPage->mainFrame()->script(); if (!scriptController->existingWindowShell(mainThreadNormalWorld())) { *errorString = "Window shell for main world not initialized yet."; return InjectedScript(); } ScriptState* scriptState = mainWorldScriptState(m_inspectedPage->mainFrame()); InjectedScript result = injectedScriptManager()->injectedScriptFor(scriptState); if (result.hasNoValue()) *errorString = "Internal error: main world execution context not found."; return result; } InjectedScript injectedScript = injectedScriptManager()->injectedScriptForId(*executionContextId); if (injectedScript.hasNoValue()) *errorString = "Execution context with given id not found."; return injectedScript; } void PageRuntimeAgent::muteConsole() { PageConsole::mute(); } void PageRuntimeAgent::unmuteConsole() { PageConsole::unmute(); } void PageRuntimeAgent::reportExecutionContextCreation() { Vector<std::pair<ScriptState*, SecurityOrigin*> > isolatedContexts; for (Frame* frame = m_inspectedPage->mainFrame(); frame; frame = frame->tree()->traverseNext()) { if (!frame->script()->canExecuteScripts(NotAboutToExecuteScript)) continue; String frameId = m_pageAgent->frameId(frame); ScriptState* scriptState = mainWorldScriptState(frame); notifyContextCreated(frameId, scriptState, 0, true); frame->script()->collectIsolatedContexts(isolatedContexts); if (isolatedContexts.isEmpty()) continue; for (size_t i = 0; i< isolatedContexts.size(); i++) notifyContextCreated(frameId, isolatedContexts[i].first, isolatedContexts[i].second, false); isolatedContexts.clear(); } } void PageRuntimeAgent::notifyContextCreated(const String& frameId, ScriptState* scriptState, SecurityOrigin* securityOrigin, bool isPageContext) { ASSERT(securityOrigin || isPageContext); int executionContextId = injectedScriptManager()->injectedScriptIdFor(scriptState); String name = securityOrigin ? securityOrigin->toRawString() : ""; m_frontend->executionContextCreated(ExecutionContextDescription::create() .setId(executionContextId) .setIsPageContext(isPageContext) .setName(name) .setFrameId(frameId) .release()); } } // namespace WebCore <commit_msg>Revert 158684 "Fix creating InjectedScript too early causing ext..."<commit_after>/* * Copyright (C) 2011 Google 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 Google 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. */ #include "config.h" #include "core/inspector/PageRuntimeAgent.h" #include "bindings/v8/DOMWrapperWorld.h" #include "bindings/v8/ScriptController.h" #include "core/inspector/InjectedScript.h" #include "core/inspector/InjectedScriptManager.h" #include "core/inspector/InspectorPageAgent.h" #include "core/inspector/InspectorState.h" #include "core/inspector/InstrumentingAgents.h" #include "core/page/Frame.h" #include "core/page/Page.h" #include "core/page/PageConsole.h" #include "weborigin/SecurityOrigin.h" using WebCore::TypeBuilder::Runtime::ExecutionContextDescription; namespace WebCore { namespace PageRuntimeAgentState { static const char runtimeEnabled[] = "runtimeEnabled"; }; PageRuntimeAgent::PageRuntimeAgent(InstrumentingAgents* instrumentingAgents, InspectorCompositeState* state, InjectedScriptManager* injectedScriptManager, ScriptDebugServer* scriptDebugServer, Page* page, InspectorPageAgent* pageAgent) : InspectorRuntimeAgent(instrumentingAgents, state, injectedScriptManager, scriptDebugServer) , m_inspectedPage(page) , m_pageAgent(pageAgent) , m_frontend(0) , m_mainWorldContextCreated(false) { m_instrumentingAgents->setPageRuntimeAgent(this); } PageRuntimeAgent::~PageRuntimeAgent() { m_instrumentingAgents->setPageRuntimeAgent(0); } void PageRuntimeAgent::setFrontend(InspectorFrontend* frontend) { m_frontend = frontend->runtime(); } void PageRuntimeAgent::clearFrontend() { m_frontend = 0; String errorString; disable(&errorString); } void PageRuntimeAgent::restore() { if (m_state->getBoolean(PageRuntimeAgentState::runtimeEnabled)) { String error; enable(&error); } } void PageRuntimeAgent::enable(ErrorString* errorString) { if (m_enabled) return; InspectorRuntimeAgent::enable(errorString); m_state->setBoolean(PageRuntimeAgentState::runtimeEnabled, true); // Only report existing contexts if the page did commit load, otherwise we may // unintentionally initialize contexts in the frames which may trigger some listeners // that are expected to be triggered only after the load is committed, see http://crbug.com/131623 if (m_mainWorldContextCreated) reportExecutionContextCreation(); } void PageRuntimeAgent::disable(ErrorString* errorString) { if (!m_enabled) return; InspectorRuntimeAgent::disable(errorString); m_state->setBoolean(PageRuntimeAgentState::runtimeEnabled, false); } void PageRuntimeAgent::didClearWindowObjectInWorld(Frame* frame, DOMWrapperWorld* world) { if (world != mainThreadNormalWorld()) return; m_mainWorldContextCreated = true; if (!m_enabled) return; ASSERT(m_frontend); String frameId = m_pageAgent->frameId(frame); ScriptState* scriptState = mainWorldScriptState(frame); notifyContextCreated(frameId, scriptState, 0, true); } void PageRuntimeAgent::didCreateIsolatedContext(Frame* frame, ScriptState* scriptState, SecurityOrigin* origin) { if (!m_enabled) return; ASSERT(m_frontend); String frameId = m_pageAgent->frameId(frame); notifyContextCreated(frameId, scriptState, origin, false); } InjectedScript PageRuntimeAgent::injectedScriptForEval(ErrorString* errorString, const int* executionContextId) { if (!executionContextId) { ScriptState* scriptState = mainWorldScriptState(m_inspectedPage->mainFrame()); InjectedScript result = injectedScriptManager()->injectedScriptFor(scriptState); if (result.hasNoValue()) *errorString = "Internal error: main world execution context not found."; return result; } InjectedScript injectedScript = injectedScriptManager()->injectedScriptForId(*executionContextId); if (injectedScript.hasNoValue()) *errorString = "Execution context with given id not found."; return injectedScript; } void PageRuntimeAgent::muteConsole() { PageConsole::mute(); } void PageRuntimeAgent::unmuteConsole() { PageConsole::unmute(); } void PageRuntimeAgent::reportExecutionContextCreation() { Vector<std::pair<ScriptState*, SecurityOrigin*> > isolatedContexts; for (Frame* frame = m_inspectedPage->mainFrame(); frame; frame = frame->tree()->traverseNext()) { if (!frame->script()->canExecuteScripts(NotAboutToExecuteScript)) continue; String frameId = m_pageAgent->frameId(frame); ScriptState* scriptState = mainWorldScriptState(frame); notifyContextCreated(frameId, scriptState, 0, true); frame->script()->collectIsolatedContexts(isolatedContexts); if (isolatedContexts.isEmpty()) continue; for (size_t i = 0; i< isolatedContexts.size(); i++) notifyContextCreated(frameId, isolatedContexts[i].first, isolatedContexts[i].second, false); isolatedContexts.clear(); } } void PageRuntimeAgent::notifyContextCreated(const String& frameId, ScriptState* scriptState, SecurityOrigin* securityOrigin, bool isPageContext) { ASSERT(securityOrigin || isPageContext); int executionContextId = injectedScriptManager()->injectedScriptIdFor(scriptState); String name = securityOrigin ? securityOrigin->toRawString() : ""; m_frontend->executionContextCreated(ExecutionContextDescription::create() .setId(executionContextId) .setIsPageContext(isPageContext) .setName(name) .setFrameId(frameId) .release()); } } // namespace WebCore <|endoftext|>
<commit_before>/* * Copyright (C) 2011 Google 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 Google 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. */ #include "config.h" #include "core/inspector/PageRuntimeAgent.h" #include "bindings/v8/DOMWrapperWorld.h" #include "bindings/v8/ScriptController.h" #include "core/inspector/InjectedScript.h" #include "core/inspector/InjectedScriptManager.h" #include "core/inspector/InspectorPageAgent.h" #include "core/inspector/InspectorState.h" #include "core/inspector/InstrumentingAgents.h" #include "core/page/Frame.h" #include "core/page/Page.h" #include "core/page/PageConsole.h" #include "weborigin/SecurityOrigin.h" using WebCore::TypeBuilder::Runtime::ExecutionContextDescription; namespace WebCore { namespace PageRuntimeAgentState { static const char runtimeEnabled[] = "runtimeEnabled"; }; PageRuntimeAgent::PageRuntimeAgent(InstrumentingAgents* instrumentingAgents, InspectorCompositeState* state, InjectedScriptManager* injectedScriptManager, ScriptDebugServer* scriptDebugServer, Page* page, InspectorPageAgent* pageAgent) : InspectorRuntimeAgent(instrumentingAgents, state, injectedScriptManager, scriptDebugServer) , m_inspectedPage(page) , m_pageAgent(pageAgent) , m_frontend(0) , m_mainWorldContextCreated(false) { m_instrumentingAgents->setPageRuntimeAgent(this); } PageRuntimeAgent::~PageRuntimeAgent() { m_instrumentingAgents->setPageRuntimeAgent(0); } void PageRuntimeAgent::setFrontend(InspectorFrontend* frontend) { m_frontend = frontend->runtime(); } void PageRuntimeAgent::clearFrontend() { m_frontend = 0; String errorString; disable(&errorString); } void PageRuntimeAgent::restore() { if (m_state->getBoolean(PageRuntimeAgentState::runtimeEnabled)) { String error; enable(&error); } } void PageRuntimeAgent::enable(ErrorString* errorString) { if (m_enabled) return; InspectorRuntimeAgent::enable(errorString); m_state->setBoolean(PageRuntimeAgentState::runtimeEnabled, true); // Only report existing contexts if the page did commit load, otherwise we may // unintentionally initialize contexts in the frames which may trigger some listeners // that are expected to be triggered only after the load is committed, see http://crbug.com/131623 if (m_mainWorldContextCreated) reportExecutionContextCreation(); } void PageRuntimeAgent::disable(ErrorString* errorString) { if (!m_enabled) return; InspectorRuntimeAgent::disable(errorString); m_state->setBoolean(PageRuntimeAgentState::runtimeEnabled, false); } void PageRuntimeAgent::didClearWindowObjectInWorld(Frame* frame, DOMWrapperWorld* world) { if (world != mainThreadNormalWorld()) return; m_mainWorldContextCreated = true; if (!m_enabled) return; ASSERT(m_frontend); String frameId = m_pageAgent->frameId(frame); ScriptState* scriptState = mainWorldScriptState(frame); notifyContextCreated(frameId, scriptState, 0, true); } void PageRuntimeAgent::didCreateIsolatedContext(Frame* frame, ScriptState* scriptState, SecurityOrigin* origin) { if (!m_enabled) return; ASSERT(m_frontend); String frameId = m_pageAgent->frameId(frame); notifyContextCreated(frameId, scriptState, origin, false); } InjectedScript PageRuntimeAgent::injectedScriptForEval(ErrorString* errorString, const int* executionContextId) { if (!executionContextId) { ScriptState* scriptState = mainWorldScriptState(m_inspectedPage->mainFrame()); InjectedScript result = injectedScriptManager()->injectedScriptFor(scriptState); if (result.hasNoValue()) *errorString = "Internal error: main world execution context not found."; return result; } InjectedScript injectedScript = injectedScriptManager()->injectedScriptForId(*executionContextId); if (injectedScript.hasNoValue()) *errorString = "Execution context with given id not found."; return injectedScript; } void PageRuntimeAgent::muteConsole() { PageConsole::mute(); } void PageRuntimeAgent::unmuteConsole() { PageConsole::unmute(); } void PageRuntimeAgent::reportExecutionContextCreation() { Vector<std::pair<ScriptState*, SecurityOrigin*> > isolatedContexts; for (Frame* frame = m_inspectedPage->mainFrame(); frame; frame = frame->tree()->traverseNext()) { if (!frame->script()->canExecuteScripts(NotAboutToExecuteScript)) continue; String frameId = m_pageAgent->frameId(frame); ScriptState* scriptState = mainWorldScriptState(frame); notifyContextCreated(frameId, scriptState, 0, true); frame->script()->collectIsolatedContexts(isolatedContexts); if (isolatedContexts.isEmpty()) continue; for (size_t i = 0; i< isolatedContexts.size(); i++) notifyContextCreated(frameId, isolatedContexts[i].first, isolatedContexts[i].second, false); isolatedContexts.clear(); } } void PageRuntimeAgent::notifyContextCreated(const String& frameId, ScriptState* scriptState, SecurityOrigin* securityOrigin, bool isPageContext) { ASSERT(securityOrigin || isPageContext); int executionContextId = injectedScriptManager()->injectedScriptIdFor(scriptState); String name = securityOrigin ? securityOrigin->toRawString() : ""; m_frontend->executionContextCreated(ExecutionContextDescription::create() .setId(executionContextId) .setIsPageContext(isPageContext) .setName(name) .setFrameId(frameId) .release()); } } // namespace WebCore <commit_msg>Fix creating InjectedScript too early causing extension bindings not to work.<commit_after>/* * Copyright (C) 2011 Google 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 Google 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. */ #include "config.h" #include "core/inspector/PageRuntimeAgent.h" #include "bindings/v8/DOMWrapperWorld.h" #include "bindings/v8/ScriptController.h" #include "core/inspector/InjectedScript.h" #include "core/inspector/InjectedScriptManager.h" #include "core/inspector/InspectorPageAgent.h" #include "core/inspector/InspectorState.h" #include "core/inspector/InstrumentingAgents.h" #include "core/page/Frame.h" #include "core/page/Page.h" #include "core/page/PageConsole.h" #include "weborigin/SecurityOrigin.h" using WebCore::TypeBuilder::Runtime::ExecutionContextDescription; namespace WebCore { namespace PageRuntimeAgentState { static const char runtimeEnabled[] = "runtimeEnabled"; }; PageRuntimeAgent::PageRuntimeAgent(InstrumentingAgents* instrumentingAgents, InspectorCompositeState* state, InjectedScriptManager* injectedScriptManager, ScriptDebugServer* scriptDebugServer, Page* page, InspectorPageAgent* pageAgent) : InspectorRuntimeAgent(instrumentingAgents, state, injectedScriptManager, scriptDebugServer) , m_inspectedPage(page) , m_pageAgent(pageAgent) , m_frontend(0) , m_mainWorldContextCreated(false) { m_instrumentingAgents->setPageRuntimeAgent(this); } PageRuntimeAgent::~PageRuntimeAgent() { m_instrumentingAgents->setPageRuntimeAgent(0); } void PageRuntimeAgent::setFrontend(InspectorFrontend* frontend) { m_frontend = frontend->runtime(); } void PageRuntimeAgent::clearFrontend() { m_frontend = 0; String errorString; disable(&errorString); } void PageRuntimeAgent::restore() { if (m_state->getBoolean(PageRuntimeAgentState::runtimeEnabled)) { String error; enable(&error); } } void PageRuntimeAgent::enable(ErrorString* errorString) { if (m_enabled) return; InspectorRuntimeAgent::enable(errorString); m_state->setBoolean(PageRuntimeAgentState::runtimeEnabled, true); // Only report existing contexts if the page did commit load, otherwise we may // unintentionally initialize contexts in the frames which may trigger some listeners // that are expected to be triggered only after the load is committed, see http://crbug.com/131623 if (m_mainWorldContextCreated) reportExecutionContextCreation(); } void PageRuntimeAgent::disable(ErrorString* errorString) { if (!m_enabled) return; InspectorRuntimeAgent::disable(errorString); m_state->setBoolean(PageRuntimeAgentState::runtimeEnabled, false); } void PageRuntimeAgent::didClearWindowObjectInWorld(Frame* frame, DOMWrapperWorld* world) { if (world != mainThreadNormalWorld()) return; m_mainWorldContextCreated = true; if (!m_enabled) return; ASSERT(m_frontend); String frameId = m_pageAgent->frameId(frame); ScriptState* scriptState = mainWorldScriptState(frame); notifyContextCreated(frameId, scriptState, 0, true); } void PageRuntimeAgent::didCreateIsolatedContext(Frame* frame, ScriptState* scriptState, SecurityOrigin* origin) { if (!m_enabled) return; ASSERT(m_frontend); String frameId = m_pageAgent->frameId(frame); notifyContextCreated(frameId, scriptState, origin, false); } InjectedScript PageRuntimeAgent::injectedScriptForEval(ErrorString* errorString, const int* executionContextId) { if (!executionContextId) { // We shouldn't be able to create an injected script if the main // window shell not initialized. See crbug.com/263162. ScriptController* scriptController = m_inspectedPage->mainFrame()->script(); if (!scriptController->existingWindowShell(mainThreadNormalWorld())) { *errorString = "Window shell for main world not initialized yet."; return InjectedScript(); } ScriptState* scriptState = mainWorldScriptState(m_inspectedPage->mainFrame()); InjectedScript result = injectedScriptManager()->injectedScriptFor(scriptState); if (result.hasNoValue()) *errorString = "Internal error: main world execution context not found."; return result; } InjectedScript injectedScript = injectedScriptManager()->injectedScriptForId(*executionContextId); if (injectedScript.hasNoValue()) *errorString = "Execution context with given id not found."; return injectedScript; } void PageRuntimeAgent::muteConsole() { PageConsole::mute(); } void PageRuntimeAgent::unmuteConsole() { PageConsole::unmute(); } void PageRuntimeAgent::reportExecutionContextCreation() { Vector<std::pair<ScriptState*, SecurityOrigin*> > isolatedContexts; for (Frame* frame = m_inspectedPage->mainFrame(); frame; frame = frame->tree()->traverseNext()) { if (!frame->script()->canExecuteScripts(NotAboutToExecuteScript)) continue; String frameId = m_pageAgent->frameId(frame); ScriptState* scriptState = mainWorldScriptState(frame); notifyContextCreated(frameId, scriptState, 0, true); frame->script()->collectIsolatedContexts(isolatedContexts); if (isolatedContexts.isEmpty()) continue; for (size_t i = 0; i< isolatedContexts.size(); i++) notifyContextCreated(frameId, isolatedContexts[i].first, isolatedContexts[i].second, false); isolatedContexts.clear(); } } void PageRuntimeAgent::notifyContextCreated(const String& frameId, ScriptState* scriptState, SecurityOrigin* securityOrigin, bool isPageContext) { ASSERT(securityOrigin || isPageContext); int executionContextId = injectedScriptManager()->injectedScriptIdFor(scriptState); String name = securityOrigin ? securityOrigin->toRawString() : ""; m_frontend->executionContextCreated(ExecutionContextDescription::create() .setId(executionContextId) .setIsPageContext(isPageContext) .setName(name) .setFrameId(frameId) .release()); } } // namespace WebCore <|endoftext|>
<commit_before>/* TyTools - public domain Niels Martignène <[email protected]> https://koromix.dev/tytools This software is in the public domain. Where that dedication is not recognized, you are granted a perpetual, irrevocable license to copy, distribute, and modify this file as you see fit. See the LICENSE file for more details. */ #include <QIdentityProxyModel> #include <QItemDelegate> #include <QPushButton> #include "board.hpp" #include "monitor.hpp" #include "selector_dialog.hpp" #include "tycommander.hpp" using namespace std; class SelectorDialogModel: public QIdentityProxyModel { public: SelectorDialogModel(QObject *parent = nullptr) : QIdentityProxyModel(parent) {} int columnCount(const QModelIndex &parent) const override; QVariant data(const QModelIndex &index, int role) const override; }; class SelectorDialogItemDelegate: public QItemDelegate { public: SelectorDialogItemDelegate(QObject *parent = nullptr) : QItemDelegate(parent) {} QSize sizeHint(const QStyleOptionViewItem &option, const QModelIndex &index) const override; }; int SelectorDialogModel::columnCount(const QModelIndex &parent) const { Q_UNUSED(parent); return 3; } QVariant SelectorDialogModel::data(const QModelIndex &index, int role) const { if (index.column() == Monitor::COLUMN_BOARD) { switch (role) { case Qt::TextAlignmentRole: return QVariant(Qt::AlignLeft | Qt::AlignVCenter); } } else if (index.column() == Monitor::COLUMN_MODEL) { switch (role) { case Qt::TextAlignmentRole: return QVariant(Qt::AlignLeft | Qt::AlignVCenter); } } else if (index.column() == Monitor::COLUMN_STATUS) { switch (role) { case Qt::TextAlignmentRole: return QVariant(Qt::AlignRight | Qt::AlignVCenter); case Qt::ForegroundRole: return QBrush(Qt::darkGray); } } return QIdentityProxyModel::data(index, role); } QSize SelectorDialogItemDelegate::sizeHint(const QStyleOptionViewItem &option, const QModelIndex &index) const { auto size = QItemDelegate::sizeHint(option, index); size.setHeight(24); return size; } SelectorDialog::SelectorDialog(QWidget *parent) : QDialog(parent), monitor_(tyCommander->monitor()) { setupUi(this); connect(buttonBox, &QDialogButtonBox::accepted, this, &SelectorDialog::accept); connect(buttonBox, &QDialogButtonBox::rejected, this, &SelectorDialog::reject); connect(tree, &QTreeView::doubleClicked, this, &SelectorDialog::accept); monitor_model_ = new SelectorDialogModel(this); monitor_model_->setSourceModel(monitor_); tree->setModel(monitor_model_); tree->setItemDelegate(new SelectorDialogItemDelegate(tree)); connect(tree->selectionModel(), &QItemSelectionModel::selectionChanged, this, &SelectorDialog::updateSelection); tree->header()->setStretchLastSection(false); tree->header()->setSectionResizeMode(0, QHeaderView::ResizeToContents); tree->header()->setSectionResizeMode(1, QHeaderView::ResizeToContents); tree->header()->setSectionResizeMode(2, QHeaderView::Stretch); auto first_board = Monitor::boardFromModel(monitor_model_, 0); if (first_board) { tree->setCurrentIndex(monitor_->index(0, 0)); } else { buttonBox->button(QDialogButtonBox::Ok)->setEnabled(false); } } void SelectorDialog::setExtendedSelection(bool extended) { tree->setSelectionMode(extended ? QAbstractItemView::ExtendedSelection : QAbstractItemView::SingleSelection); } void SelectorDialog::setAction(const QString &action) { action_ = action; setWindowTitle(QString("%1 | %2").arg(action, QCoreApplication::applicationName())); } void SelectorDialog::updateSelection() { selected_boards_.clear(); auto indexes = tree->selectionModel()->selectedIndexes(); qSort(indexes); for (auto &idx: indexes) { if (idx.column() == 0) selected_boards_.push_back(Monitor::boardFromModel(monitor_model_, idx)); } buttonBox->button(QDialogButtonBox::Ok)->setEnabled(!selected_boards_.empty()); emit selectionChanged(); } <commit_msg>Block secondary boards in board selection dialog<commit_after>/* TyTools - public domain Niels Martignène <[email protected]> https://koromix.dev/tytools This software is in the public domain. Where that dedication is not recognized, you are granted a perpetual, irrevocable license to copy, distribute, and modify this file as you see fit. See the LICENSE file for more details. */ #include <QIdentityProxyModel> #include <QItemDelegate> #include <QPushButton> #include "board.hpp" #include "monitor.hpp" #include "selector_dialog.hpp" #include "tycommander.hpp" using namespace std; class SelectorDialogModel: public QIdentityProxyModel { public: SelectorDialogModel(QObject *parent = nullptr) : QIdentityProxyModel(parent) {} int columnCount(const QModelIndex &parent) const override; QVariant data(const QModelIndex &index, int role) const override; Qt::ItemFlags flags(const QModelIndex &index) const override; }; class SelectorDialogItemDelegate: public QItemDelegate { public: SelectorDialogItemDelegate(QObject *parent = nullptr) : QItemDelegate(parent) {} QSize sizeHint(const QStyleOptionViewItem &option, const QModelIndex &index) const override; }; int SelectorDialogModel::columnCount(const QModelIndex &parent) const { Q_UNUSED(parent); return 3; } QVariant SelectorDialogModel::data(const QModelIndex &index, int role) const { if (index.column() == Monitor::COLUMN_BOARD) { switch (role) { case Qt::TextAlignmentRole: return QVariant(Qt::AlignLeft | Qt::AlignVCenter); } } else if (index.column() == Monitor::COLUMN_MODEL) { switch (role) { case Qt::TextAlignmentRole: return QVariant(Qt::AlignLeft | Qt::AlignVCenter); } } else if (index.column() == Monitor::COLUMN_STATUS) { switch (role) { case Qt::TextAlignmentRole: return QVariant(Qt::AlignRight | Qt::AlignVCenter); case Qt::ForegroundRole: return QBrush(Qt::darkGray); } } return QIdentityProxyModel::data(index, role); } Qt::ItemFlags SelectorDialogModel::flags(const QModelIndex &index) const { auto board = QIdentityProxyModel::data(index, Monitor::ROLE_BOARD).value<Board *>(); return board->isSecondary() ? 0 : QIdentityProxyModel::flags(index); } QSize SelectorDialogItemDelegate::sizeHint(const QStyleOptionViewItem &option, const QModelIndex &index) const { auto size = QItemDelegate::sizeHint(option, index); size.setHeight(24); return size; } SelectorDialog::SelectorDialog(QWidget *parent) : QDialog(parent), monitor_(tyCommander->monitor()) { setupUi(this); connect(buttonBox, &QDialogButtonBox::accepted, this, &SelectorDialog::accept); connect(buttonBox, &QDialogButtonBox::rejected, this, &SelectorDialog::reject); connect(tree, &QTreeView::doubleClicked, this, &SelectorDialog::accept); monitor_model_ = new SelectorDialogModel(this); monitor_model_->setSourceModel(monitor_); tree->setModel(monitor_model_); tree->setItemDelegate(new SelectorDialogItemDelegate(tree)); connect(tree->selectionModel(), &QItemSelectionModel::selectionChanged, this, &SelectorDialog::updateSelection); tree->header()->setStretchLastSection(false); tree->header()->setSectionResizeMode(0, QHeaderView::ResizeToContents); tree->header()->setSectionResizeMode(1, QHeaderView::ResizeToContents); tree->header()->setSectionResizeMode(2, QHeaderView::Stretch); auto first_board = Monitor::boardFromModel(monitor_model_, 0); if (first_board) { tree->setCurrentIndex(monitor_->index(0, 0)); } else { buttonBox->button(QDialogButtonBox::Ok)->setEnabled(false); } } void SelectorDialog::setExtendedSelection(bool extended) { tree->setSelectionMode(extended ? QAbstractItemView::ExtendedSelection : QAbstractItemView::SingleSelection); } void SelectorDialog::setAction(const QString &action) { action_ = action; setWindowTitle(QString("%1 | %2").arg(action, QCoreApplication::applicationName())); } void SelectorDialog::updateSelection() { selected_boards_.clear(); auto indexes = tree->selectionModel()->selectedIndexes(); qSort(indexes); for (auto &idx: indexes) { if (idx.column() == 0) selected_boards_.push_back(Monitor::boardFromModel(monitor_model_, idx)); } buttonBox->button(QDialogButtonBox::Ok)->setEnabled(!selected_boards_.empty()); emit selectionChanged(); } <|endoftext|>
<commit_before>/* * Convert any file descriptor to a pipe by splicing. * * author: Max Kellermann <[email protected]> */ #ifdef __linux #include "istream_pipe.hxx" #include "istream_internal.hxx" #include "fd_util.h" #include "direct.hxx" #include "pipe_stock.hxx" #include "stock.hxx" #include "gerrno.h" #include "pool.hxx" #include "util/Cast.hxx" #include <daemon/log.h> #include <assert.h> #include <errno.h> #include <string.h> #include <fcntl.h> #include <unistd.h> struct PipeIstream { struct istream output; struct istream *input; Stock *stock; StockItem *stock_item; int fds[2]; size_t piped; }; static void pipe_close(PipeIstream *p) { if (p->stock != nullptr) { if (p->stock_item != nullptr) /* reuse the pipe only if it's empty */ stock_put(*p->stock_item, p->piped > 0); } else { if (p->fds[0] >= 0) { close(p->fds[0]); p->fds[0] = -1; } if (p->fds[1] >= 0) { close(p->fds[1]); p->fds[1] = -1; } } } static void pipe_abort(PipeIstream *p, GError *error) { pipe_close(p); if (p->input != nullptr) istream_close_handler(p->input); istream_deinit_abort(&p->output, error); } static ssize_t pipe_consume(PipeIstream *p) { assert(p->fds[0] >= 0); assert(p->piped > 0); assert(p->stock_item != nullptr || p->stock == nullptr); ssize_t nbytes = istream_invoke_direct(&p->output, FdType::FD_PIPE, p->fds[0], p->piped); if (unlikely(nbytes == ISTREAM_RESULT_BLOCKING || nbytes == ISTREAM_RESULT_CLOSED)) /* handler blocks (-2) or pipe was closed (-3) */ return nbytes; if (unlikely(nbytes == ISTREAM_RESULT_ERRNO && errno != EAGAIN)) { GError *error = new_error_errno_msg("read from pipe failed"); pipe_abort(p, error); return ISTREAM_RESULT_CLOSED; } if (nbytes > 0) { assert((size_t)nbytes <= p->piped); p->piped -= (size_t)nbytes; if (p->piped == 0 && p->stock != nullptr) { /* if the pipe was drained, return it to the stock, to make it available to other streams */ stock_put(*p->stock_item, false); p->stock_item = nullptr; p->fds[0] = -1; p->fds[1] = -1; } if (p->piped == 0 && p->input == nullptr) { /* p->input has already reported EOF, and we have been waiting for the pipe buffer to become empty */ pipe_close(p); istream_deinit_eof(&p->output); return ISTREAM_RESULT_CLOSED; } } return nbytes; } /* * istream handler * */ static size_t pipe_input_data(const void *data, size_t length, void *ctx) { PipeIstream *p = (PipeIstream *)ctx; assert(p->output.handler != nullptr); if (p->piped > 0) { ssize_t nbytes = pipe_consume(p); if (nbytes == ISTREAM_RESULT_CLOSED) return 0; if (p->piped > 0 || p->output.handler == nullptr) return 0; } assert(p->piped == 0); return istream_invoke_data(&p->output, data, length); } static bool pipe_create(PipeIstream *p) { assert(p->fds[0] < 0); assert(p->fds[1] < 0); if (p->stock != nullptr) { assert(p->stock_item == nullptr); GError *error = nullptr; p->stock_item = stock_get_now(*p->stock, *p->output.pool, nullptr, &error); if (p->stock_item == nullptr) { daemon_log(1, "%s\n", error->message); g_error_free(error); return false; } pipe_stock_item_get(p->stock_item, p->fds); } else { if (pipe_cloexec_nonblock(p->fds) < 0) { daemon_log(1, "pipe() failed: %s\n", strerror(errno)); return false; } } return true; } static ssize_t pipe_input_direct(FdType type, int fd, size_t max_length, void *ctx) { PipeIstream *p = (PipeIstream *)ctx; assert(p->output.handler != nullptr); assert(p->output.handler->direct != nullptr); assert(istream_check_direct(&p->output, FdType::FD_PIPE)); if (p->piped > 0) { ssize_t nbytes = pipe_consume(p); if (nbytes <= 0) return nbytes; if (p->piped > 0) /* if the pipe still isn't empty, we can't start reading new input */ return ISTREAM_RESULT_BLOCKING; } if (istream_check_direct(&p->output, type)) /* already supported by handler (maybe already a pipe) - no need for wrapping it into a pipe */ return istream_invoke_direct(&p->output, type, fd, max_length); assert((type & ISTREAM_TO_PIPE) == type); if (p->fds[1] < 0 && !pipe_create(p)) return ISTREAM_RESULT_CLOSED; ssize_t nbytes = splice(fd, nullptr, p->fds[1], nullptr, max_length, SPLICE_F_NONBLOCK | SPLICE_F_MOVE); /* don't check EAGAIN here (and don't return -2). We assume that splicing to the pipe cannot possibly block, since we flushed the pipe; assume that it can only be the source file which is blocking */ if (nbytes <= 0) return nbytes; assert(p->piped == 0); p->piped = (size_t)nbytes; if (pipe_consume(p) == ISTREAM_RESULT_CLOSED) return ISTREAM_RESULT_CLOSED; return nbytes; } static void pipe_input_eof(void *ctx) { PipeIstream *p = (PipeIstream *)ctx; p->input = nullptr; if (p->stock == nullptr && p->fds[1] >= 0) { close(p->fds[1]); p->fds[1] = -1; } if (p->piped == 0) { pipe_close(p); istream_deinit_eof(&p->output); } } static void pipe_input_abort(GError *error, void *ctx) { PipeIstream *p = (PipeIstream *)ctx; pipe_close(p); p->input = nullptr; istream_deinit_abort(&p->output, error); } static const struct istream_handler pipe_input_handler = { .data = pipe_input_data, .direct = pipe_input_direct, .eof = pipe_input_eof, .abort = pipe_input_abort, }; /* * istream implementation * */ static inline PipeIstream * istream_to_pipe(struct istream *istream) { return &ContainerCast2(*istream, &PipeIstream::output); } static off_t istream_pipe_available(struct istream *istream, bool partial) { PipeIstream *p = istream_to_pipe(istream); if (likely(p->input != nullptr)) { off_t available = istream_available(p->input, partial); if (p->piped > 0) { if (available != -1) available += p->piped; else if (partial) available = p->piped; } return available; } else { assert(p->piped > 0); return p->piped; } } static void istream_pipe_read(struct istream *istream) { PipeIstream *p = istream_to_pipe(istream); if (p->piped > 0 && (pipe_consume(p) <= 0 || p->piped > 0)) return; /* at this point, the pipe must be flushed - if the pipe is flushed, this stream is either closed or there must be an input stream */ assert(p->input != nullptr); auto mask = p->output.handler_direct; if (mask & FdType::FD_PIPE) /* if the handler supports the pipe, we offer our services */ mask |= ISTREAM_TO_PIPE; istream_handler_set_direct(p->input, mask); istream_read(p->input); } static int istream_pipe_as_fd(struct istream *istream) { PipeIstream *p = istream_to_pipe(istream); if (p->piped > 0) /* need to flush the pipe buffer first */ return -1; int fd = istream_as_fd(p->input); if (fd >= 0) { pipe_close(p); istream_deinit(&p->output); } return fd; } static void istream_pipe_close(struct istream *istream) { PipeIstream *p = istream_to_pipe(istream); pipe_close(p); if (p->input != nullptr) istream_close_handler(p->input); istream_deinit(&p->output); } static const struct istream_class istream_pipe = { .available = istream_pipe_available, .read = istream_pipe_read, .as_fd = istream_pipe_as_fd, .close = istream_pipe_close, }; /* * constructor * */ struct istream * istream_pipe_new(struct pool *pool, struct istream *input, Stock *pipe_stock) { assert(input != nullptr); assert(!istream_has_handler(input)); auto *p = NewFromPool<PipeIstream>(*pool); istream_init(&p->output, &istream_pipe, pool); p->stock = pipe_stock; p->stock_item = nullptr; p->fds[0] = -1; p->fds[1] = -1; p->piped = 0; istream_assign_handler(&p->input, input, &pipe_input_handler, p, 0); return &p->output; } #endif <commit_msg>istream/pipe: move functions into the struct<commit_after>/* * Convert any file descriptor to a pipe by splicing. * * author: Max Kellermann <[email protected]> */ #ifdef __linux #include "istream_pipe.hxx" #include "istream_internal.hxx" #include "fd_util.h" #include "direct.hxx" #include "pipe_stock.hxx" #include "stock.hxx" #include "gerrno.h" #include "pool.hxx" #include "util/Cast.hxx" #include <daemon/log.h> #include <assert.h> #include <errno.h> #include <string.h> #include <fcntl.h> #include <unistd.h> struct PipeIstream { struct istream output; struct istream *input; Stock *stock; StockItem *stock_item; int fds[2]; size_t piped; void CloseInternal(); void Abort(GError *error); ssize_t Consume(); bool Create(); }; void PipeIstream::CloseInternal() { if (stock != nullptr) { if (stock_item != nullptr) /* reuse the pipe only if it's empty */ stock_put(*stock_item, piped > 0); } else { if (fds[0] >= 0) { close(fds[0]); fds[0] = -1; } if (fds[1] >= 0) { close(fds[1]); fds[1] = -1; } } } void PipeIstream::Abort(GError *error) { CloseInternal(); if (input != nullptr) istream_close_handler(input); istream_deinit_abort(&output, error); } ssize_t PipeIstream::Consume() { assert(fds[0] >= 0); assert(piped > 0); assert(stock_item != nullptr || stock == nullptr); ssize_t nbytes = istream_invoke_direct(&output, FdType::FD_PIPE, fds[0], piped); if (unlikely(nbytes == ISTREAM_RESULT_BLOCKING || nbytes == ISTREAM_RESULT_CLOSED)) /* handler blocks (-2) or pipe was closed (-3) */ return nbytes; if (unlikely(nbytes == ISTREAM_RESULT_ERRNO && errno != EAGAIN)) { GError *error = new_error_errno_msg("read from pipe failed"); Abort(error); return ISTREAM_RESULT_CLOSED; } if (nbytes > 0) { assert((size_t)nbytes <= piped); piped -= (size_t)nbytes; if (piped == 0 && stock != nullptr) { /* if the pipe was drained, return it to the stock, to make it available to other streams */ stock_put(*stock_item, false); stock_item = nullptr; fds[0] = -1; fds[1] = -1; } if (piped == 0 && input == nullptr) { /* our input has already reported EOF, and we have been waiting for the pipe buffer to become empty */ CloseInternal(); istream_deinit_eof(&output); return ISTREAM_RESULT_CLOSED; } } return nbytes; } /* * istream handler * */ static size_t pipe_input_data(const void *data, size_t length, void *ctx) { PipeIstream *p = (PipeIstream *)ctx; assert(p->output.handler != nullptr); if (p->piped > 0) { ssize_t nbytes = p->Consume(); if (nbytes == ISTREAM_RESULT_CLOSED) return 0; if (p->piped > 0 || p->output.handler == nullptr) return 0; } assert(p->piped == 0); return istream_invoke_data(&p->output, data, length); } inline bool PipeIstream::Create() { assert(fds[0] < 0); assert(fds[1] < 0); if (stock != nullptr) { assert(stock_item == nullptr); GError *error = nullptr; stock_item = stock_get_now(*stock, *output.pool, nullptr, &error); if (stock_item == nullptr) { daemon_log(1, "%s\n", error->message); g_error_free(error); return false; } pipe_stock_item_get(stock_item, fds); } else { if (pipe_cloexec_nonblock(fds) < 0) { daemon_log(1, "pipe() failed: %s\n", strerror(errno)); return false; } } return true; } static ssize_t pipe_input_direct(FdType type, int fd, size_t max_length, void *ctx) { PipeIstream *p = (PipeIstream *)ctx; assert(p->output.handler != nullptr); assert(p->output.handler->direct != nullptr); assert(istream_check_direct(&p->output, FdType::FD_PIPE)); if (p->piped > 0) { ssize_t nbytes = p->Consume(); if (nbytes <= 0) return nbytes; if (p->piped > 0) /* if the pipe still isn't empty, we can't start reading new input */ return ISTREAM_RESULT_BLOCKING; } if (istream_check_direct(&p->output, type)) /* already supported by handler (maybe already a pipe) - no need for wrapping it into a pipe */ return istream_invoke_direct(&p->output, type, fd, max_length); assert((type & ISTREAM_TO_PIPE) == type); if (p->fds[1] < 0 && !p->Create()) return ISTREAM_RESULT_CLOSED; ssize_t nbytes = splice(fd, nullptr, p->fds[1], nullptr, max_length, SPLICE_F_NONBLOCK | SPLICE_F_MOVE); /* don't check EAGAIN here (and don't return -2). We assume that splicing to the pipe cannot possibly block, since we flushed the pipe; assume that it can only be the source file which is blocking */ if (nbytes <= 0) return nbytes; assert(p->piped == 0); p->piped = (size_t)nbytes; if (p->Consume() == ISTREAM_RESULT_CLOSED) return ISTREAM_RESULT_CLOSED; return nbytes; } static void pipe_input_eof(void *ctx) { PipeIstream *p = (PipeIstream *)ctx; p->input = nullptr; if (p->stock == nullptr && p->fds[1] >= 0) { close(p->fds[1]); p->fds[1] = -1; } if (p->piped == 0) { p->CloseInternal(); istream_deinit_eof(&p->output); } } static void pipe_input_abort(GError *error, void *ctx) { PipeIstream *p = (PipeIstream *)ctx; p->CloseInternal(); p->input = nullptr; istream_deinit_abort(&p->output, error); } static const struct istream_handler pipe_input_handler = { .data = pipe_input_data, .direct = pipe_input_direct, .eof = pipe_input_eof, .abort = pipe_input_abort, }; /* * istream implementation * */ static inline PipeIstream * istream_to_pipe(struct istream *istream) { return &ContainerCast2(*istream, &PipeIstream::output); } static off_t istream_pipe_available(struct istream *istream, bool partial) { PipeIstream *p = istream_to_pipe(istream); if (likely(p->input != nullptr)) { off_t available = istream_available(p->input, partial); if (p->piped > 0) { if (available != -1) available += p->piped; else if (partial) available = p->piped; } return available; } else { assert(p->piped > 0); return p->piped; } } static void istream_pipe_read(struct istream *istream) { PipeIstream *p = istream_to_pipe(istream); if (p->piped > 0 && (p->Consume() <= 0 || p->piped > 0)) return; /* at this point, the pipe must be flushed - if the pipe is flushed, this stream is either closed or there must be an input stream */ assert(p->input != nullptr); auto mask = p->output.handler_direct; if (mask & FdType::FD_PIPE) /* if the handler supports the pipe, we offer our services */ mask |= ISTREAM_TO_PIPE; istream_handler_set_direct(p->input, mask); istream_read(p->input); } static int istream_pipe_as_fd(struct istream *istream) { PipeIstream *p = istream_to_pipe(istream); if (p->piped > 0) /* need to flush the pipe buffer first */ return -1; int fd = istream_as_fd(p->input); if (fd >= 0) { p->CloseInternal(); istream_deinit(&p->output); } return fd; } static void istream_pipe_close(struct istream *istream) { PipeIstream *p = istream_to_pipe(istream); p->CloseInternal(); if (p->input != nullptr) istream_close_handler(p->input); istream_deinit(&p->output); } static const struct istream_class istream_pipe = { .available = istream_pipe_available, .read = istream_pipe_read, .as_fd = istream_pipe_as_fd, .close = istream_pipe_close, }; /* * constructor * */ struct istream * istream_pipe_new(struct pool *pool, struct istream *input, Stock *pipe_stock) { assert(input != nullptr); assert(!istream_has_handler(input)); auto *p = NewFromPool<PipeIstream>(*pool); istream_init(&p->output, &istream_pipe, pool); p->stock = pipe_stock; p->stock_item = nullptr; p->fds[0] = -1; p->fds[1] = -1; p->piped = 0; istream_assign_handler(&p->input, input, &pipe_input_handler, p, 0); return &p->output; } #endif <|endoftext|>
<commit_before>/* * Copyright 2018 The WebRTC project authors. All Rights Reserved. * * Use of this source code is governed by a BSD-style license * that can be found in the LICENSE file in the root of the source * tree. An additional intellectual property rights grant can be found * in the file PATENTS. All contributing project authors may * be found in the AUTHORS file in the root of the source tree. */ #include "test/scenario/scenario.h" #include <atomic> #include "test/gtest.h" #include "test/logging/memory_log_writer.h" #include "test/scenario/stats_collection.h" namespace webrtc { namespace test { TEST(ScenarioTest, StartsAndStopsWithoutErrors) { std::atomic<bool> packet_received(false); std::atomic<bool> bitrate_changed(false); Scenario s; CallClientConfig call_client_config; call_client_config.transport.rates.start_rate = DataRate::KilobitsPerSec(300); auto* alice = s.CreateClient("alice", call_client_config); auto* bob = s.CreateClient("bob", call_client_config); NetworkSimulationConfig network_config; auto alice_net = s.CreateSimulationNode(network_config); auto bob_net = s.CreateSimulationNode(network_config); auto route = s.CreateRoutes(alice, {alice_net}, bob, {bob_net}); VideoStreamConfig video_stream_config; s.CreateVideoStream(route->forward(), video_stream_config); s.CreateVideoStream(route->reverse(), video_stream_config); AudioStreamConfig audio_stream_config; audio_stream_config.encoder.min_rate = DataRate::KilobitsPerSec(6); audio_stream_config.encoder.max_rate = DataRate::KilobitsPerSec(64); audio_stream_config.encoder.allocate_bitrate = true; audio_stream_config.stream.in_bandwidth_estimation = false; s.CreateAudioStream(route->forward(), audio_stream_config); s.CreateAudioStream(route->reverse(), audio_stream_config); RandomWalkConfig cross_traffic_config; s.net()->CreateRandomWalkCrossTraffic( s.net()->CreateTrafficRoute({alice_net}), cross_traffic_config); s.NetworkDelayedAction({alice_net, bob_net}, 100, [&packet_received] { packet_received = true; }); s.Every(TimeDelta::Millis(10), [alice, bob, &bitrate_changed] { if (alice->GetStats().send_bandwidth_bps != 300000 && bob->GetStats().send_bandwidth_bps != 300000) bitrate_changed = true; }); s.RunUntil(TimeDelta::Seconds(2), TimeDelta::Millis(5), [&bitrate_changed, &packet_received] { return packet_received && bitrate_changed; }); EXPECT_TRUE(packet_received); EXPECT_TRUE(bitrate_changed); } namespace { void SetupVideoCall(Scenario& s, VideoQualityAnalyzer* analyzer) { CallClientConfig call_config; auto* alice = s.CreateClient("alice", call_config); auto* bob = s.CreateClient("bob", call_config); NetworkSimulationConfig network_config; network_config.bandwidth = DataRate::KilobitsPerSec(1000); network_config.delay = TimeDelta::Millis(50); auto alice_net = s.CreateSimulationNode(network_config); auto bob_net = s.CreateSimulationNode(network_config); auto route = s.CreateRoutes(alice, {alice_net}, bob, {bob_net}); VideoStreamConfig video; if (analyzer) { video.source.capture = VideoStreamConfig::Source::Capture::kVideoFile; video.source.video_file.name = "foreman_cif"; video.source.video_file.width = 352; video.source.video_file.height = 288; video.source.framerate = 30; video.encoder.codec = VideoStreamConfig::Encoder::Codec::kVideoCodecVP8; video.encoder.implementation = VideoStreamConfig::Encoder::Implementation::kSoftware; video.hooks.frame_pair_handlers = {analyzer->Handler()}; } s.CreateVideoStream(route->forward(), video); s.CreateAudioStream(route->forward(), AudioStreamConfig()); } } // namespace TEST(ScenarioTest, SimTimeEncoding) { VideoQualityAnalyzerConfig analyzer_config; analyzer_config.psnr_coverage = 0.1; VideoQualityAnalyzer analyzer(analyzer_config); { Scenario s("scenario/encode_sim", false); SetupVideoCall(s, &analyzer); s.RunFor(TimeDelta::Seconds(2)); } // Regression tests based on previous runs. EXPECT_EQ(analyzer.stats().lost_count, 0); EXPECT_NEAR(analyzer.stats().psnr_with_freeze.Mean(), 38, 5); } // TODO(bugs.webrtc.org/10515): Remove this when performance has been improved. #if defined(WEBRTC_IOS) && defined(WEBRTC_ARCH_ARM64) && !defined(NDEBUG) #define MAYBE_RealTimeEncoding DISABLED_RealTimeEncoding #else #define MAYBE_RealTimeEncoding RealTimeEncoding #endif TEST(ScenarioTest, MAYBE_RealTimeEncoding) { VideoQualityAnalyzerConfig analyzer_config; analyzer_config.psnr_coverage = 0.1; VideoQualityAnalyzer analyzer(analyzer_config); { Scenario s("scenario/encode_real", true); SetupVideoCall(s, &analyzer); s.RunFor(TimeDelta::Seconds(2)); } // Regression tests based on previous runs. EXPECT_LT(analyzer.stats().lost_count, 2); // This far below expected but ensures that we get something. EXPECT_GT(analyzer.stats().psnr_with_freeze.Mean(), 10); } TEST(ScenarioTest, SimTimeFakeing) { Scenario s("scenario/encode_sim", false); SetupVideoCall(s, nullptr); s.RunFor(TimeDelta::Seconds(2)); } TEST(ScenarioTest, WritesToRtcEventLog) { MemoryLogStorage storage; { Scenario s(storage.CreateFactory(), false); SetupVideoCall(s, nullptr); s.RunFor(TimeDelta::Seconds(1)); } auto logs = storage.logs(); // We expect that a rtc event log has been created and that it has some data. EXPECT_GE(storage.logs().at("alice.rtc.dat").size(), 1u); } } // namespace test } // namespace webrtc <commit_msg>Adds test case that would have found potential dead-lock in pacer.<commit_after>/* * Copyright 2018 The WebRTC project authors. All Rights Reserved. * * Use of this source code is governed by a BSD-style license * that can be found in the LICENSE file in the root of the source * tree. An additional intellectual property rights grant can be found * in the file PATENTS. All contributing project authors may * be found in the AUTHORS file in the root of the source tree. */ #include "test/scenario/scenario.h" #include <atomic> #include "test/field_trial.h" #include "test/gtest.h" #include "test/logging/memory_log_writer.h" #include "test/scenario/stats_collection.h" namespace webrtc { namespace test { TEST(ScenarioTest, StartsAndStopsWithoutErrors) { std::atomic<bool> packet_received(false); std::atomic<bool> bitrate_changed(false); Scenario s; CallClientConfig call_client_config; call_client_config.transport.rates.start_rate = DataRate::KilobitsPerSec(300); auto* alice = s.CreateClient("alice", call_client_config); auto* bob = s.CreateClient("bob", call_client_config); NetworkSimulationConfig network_config; auto alice_net = s.CreateSimulationNode(network_config); auto bob_net = s.CreateSimulationNode(network_config); auto route = s.CreateRoutes(alice, {alice_net}, bob, {bob_net}); VideoStreamConfig video_stream_config; s.CreateVideoStream(route->forward(), video_stream_config); s.CreateVideoStream(route->reverse(), video_stream_config); AudioStreamConfig audio_stream_config; audio_stream_config.encoder.min_rate = DataRate::KilobitsPerSec(6); audio_stream_config.encoder.max_rate = DataRate::KilobitsPerSec(64); audio_stream_config.encoder.allocate_bitrate = true; audio_stream_config.stream.in_bandwidth_estimation = false; s.CreateAudioStream(route->forward(), audio_stream_config); s.CreateAudioStream(route->reverse(), audio_stream_config); RandomWalkConfig cross_traffic_config; s.net()->CreateRandomWalkCrossTraffic( s.net()->CreateTrafficRoute({alice_net}), cross_traffic_config); s.NetworkDelayedAction({alice_net, bob_net}, 100, [&packet_received] { packet_received = true; }); s.Every(TimeDelta::Millis(10), [alice, bob, &bitrate_changed] { if (alice->GetStats().send_bandwidth_bps != 300000 && bob->GetStats().send_bandwidth_bps != 300000) bitrate_changed = true; }); s.RunUntil(TimeDelta::Seconds(2), TimeDelta::Millis(5), [&bitrate_changed, &packet_received] { return packet_received && bitrate_changed; }); EXPECT_TRUE(packet_received); EXPECT_TRUE(bitrate_changed); } namespace { void SetupVideoCall(Scenario& s, VideoQualityAnalyzer* analyzer) { CallClientConfig call_config; auto* alice = s.CreateClient("alice", call_config); auto* bob = s.CreateClient("bob", call_config); NetworkSimulationConfig network_config; network_config.bandwidth = DataRate::KilobitsPerSec(1000); network_config.delay = TimeDelta::Millis(50); auto alice_net = s.CreateSimulationNode(network_config); auto bob_net = s.CreateSimulationNode(network_config); auto route = s.CreateRoutes(alice, {alice_net}, bob, {bob_net}); VideoStreamConfig video; if (analyzer) { video.source.capture = VideoStreamConfig::Source::Capture::kVideoFile; video.source.video_file.name = "foreman_cif"; video.source.video_file.width = 352; video.source.video_file.height = 288; video.source.framerate = 30; video.encoder.codec = VideoStreamConfig::Encoder::Codec::kVideoCodecVP8; video.encoder.implementation = VideoStreamConfig::Encoder::Implementation::kSoftware; video.hooks.frame_pair_handlers = {analyzer->Handler()}; } s.CreateVideoStream(route->forward(), video); s.CreateAudioStream(route->forward(), AudioStreamConfig()); } } // namespace TEST(ScenarioTest, SimTimeEncoding) { VideoQualityAnalyzerConfig analyzer_config; analyzer_config.psnr_coverage = 0.1; VideoQualityAnalyzer analyzer(analyzer_config); { Scenario s("scenario/encode_sim", false); SetupVideoCall(s, &analyzer); s.RunFor(TimeDelta::Seconds(2)); } // Regression tests based on previous runs. EXPECT_EQ(analyzer.stats().lost_count, 0); EXPECT_NEAR(analyzer.stats().psnr_with_freeze.Mean(), 38, 5); } // TODO(bugs.webrtc.org/10515): Remove this when performance has been improved. #if defined(WEBRTC_IOS) && defined(WEBRTC_ARCH_ARM64) && !defined(NDEBUG) #define MAYBE_RealTimeEncoding DISABLED_RealTimeEncoding #else #define MAYBE_RealTimeEncoding RealTimeEncoding #endif TEST(ScenarioTest, MAYBE_RealTimeEncoding) { VideoQualityAnalyzerConfig analyzer_config; analyzer_config.psnr_coverage = 0.1; VideoQualityAnalyzer analyzer(analyzer_config); { Scenario s("scenario/encode_real", true); SetupVideoCall(s, &analyzer); s.RunFor(TimeDelta::Seconds(2)); } // Regression tests based on previous runs. EXPECT_LT(analyzer.stats().lost_count, 2); // This far below expected but ensures that we get something. EXPECT_GT(analyzer.stats().psnr_with_freeze.Mean(), 10); } TEST(ScenarioTest, SimTimeFakeing) { Scenario s("scenario/encode_sim", false); SetupVideoCall(s, nullptr); s.RunFor(TimeDelta::Seconds(2)); } TEST(ScenarioTest, WritesToRtcEventLog) { MemoryLogStorage storage; { Scenario s(storage.CreateFactory(), false); SetupVideoCall(s, nullptr); s.RunFor(TimeDelta::Seconds(1)); } auto logs = storage.logs(); // We expect that a rtc event log has been created and that it has some data. EXPECT_GE(storage.logs().at("alice.rtc.dat").size(), 1u); } TEST(ScenarioTest, RetransmitsVideoPacketsInAudioAndVideoCallWithSendSideBweAndLoss) { // Make sure audio packets are included in transport feedback. test::ScopedFieldTrials override_field_trials( "WebRTC-Audio-SendSideBwe/Enabled/WebRTC-Audio-ABWENoTWCC/Disabled/"); Scenario s; CallClientConfig call_client_config; call_client_config.transport.rates.start_rate = DataRate::KilobitsPerSec(300); auto* alice = s.CreateClient("alice", call_client_config); auto* bob = s.CreateClient("bob", call_client_config); NetworkSimulationConfig network_config; // Add some loss and delay. network_config.delay = TimeDelta::Millis(200); network_config.loss_rate = 0.05; auto alice_net = s.CreateSimulationNode(network_config); auto bob_net = s.CreateSimulationNode(network_config); auto route = s.CreateRoutes(alice, {alice_net}, bob, {bob_net}); // First add an audio stream, then a video stream. // Needed to make sure audio RTP module is selected first when sending // transport feedback message. AudioStreamConfig audio_stream_config; audio_stream_config.encoder.min_rate = DataRate::KilobitsPerSec(6); audio_stream_config.encoder.max_rate = DataRate::KilobitsPerSec(64); audio_stream_config.encoder.allocate_bitrate = true; audio_stream_config.stream.in_bandwidth_estimation = true; s.CreateAudioStream(route->forward(), audio_stream_config); s.CreateAudioStream(route->reverse(), audio_stream_config); VideoStreamConfig video_stream_config; auto video = s.CreateVideoStream(route->forward(), video_stream_config); s.CreateVideoStream(route->reverse(), video_stream_config); // Run for 10 seconds. s.RunFor(TimeDelta::Seconds(10)); // Make sure retransmissions have happened. int retransmit_packets = 0; for (const auto& substream : video->send()->GetStats().substreams) { retransmit_packets += substream.second.rtp_stats.retransmitted.packets; } EXPECT_GT(retransmit_packets, 0); } } // namespace test } // namespace webrtc <|endoftext|>
<commit_before>/* This file is part of Magnum. Copyright © 2010, 2011, 2012, 2013 Vladimír Vondruš <[email protected]> Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #include "Sdl2Application.h" #include <Utility/utilities.h> #include "Context.h" #include "ExtensionWrangler.h" namespace Magnum { namespace Platform { namespace { /* * Fix up the modifiers -- we want >= operator to work properly on Shift, * Ctrl, Alt, but SDL generates different event for left / right keys, thus * (modifiers >= Shift) would pass only if both left and right were pressed, * which is usually not what the developers wants. */ Sdl2Application::InputEvent::Modifiers fixedModifiers(Uint16 mod) { Sdl2Application::InputEvent::Modifiers modifiers(static_cast<Sdl2Application::InputEvent::Modifier>(mod)); if(modifiers & Sdl2Application::InputEvent::Modifier::Shift) modifiers |= Sdl2Application::InputEvent::Modifier::Shift; if(modifiers & Sdl2Application::InputEvent::Modifier::Ctrl) modifiers |= Sdl2Application::InputEvent::Modifier::Ctrl; if(modifiers & Sdl2Application::InputEvent::Modifier::Alt) modifiers |= Sdl2Application::InputEvent::Modifier::Alt; return modifiers; } } Sdl2Application::Sdl2Application(const Arguments&): context(nullptr), flags(Flag::Redraw) { initialize(); createContext(new Configuration); } Sdl2Application::Sdl2Application(const Arguments&, Configuration* configuration): context(nullptr), flags(Flag::Redraw) { initialize(); if(configuration) createContext(configuration); } void Sdl2Application::initialize() { if(SDL_Init(SDL_INIT_VIDEO) < 0) { Error() << "Cannot initialize SDL."; std::exit(1); } } void Sdl2Application::createContext(Configuration* configuration) { if(!tryCreateContext(configuration)) { Error() << "Platform::Sdl2Application::createContext(): cannot create context:" << SDL_GetError(); delete configuration; std::exit(1); } else delete configuration; } bool Sdl2Application::tryCreateContext(Configuration* configuration) { CORRADE_ASSERT(!context, "Platform::Sdl2Application::tryCreateContext(): context already created", false); /* Enable double buffering and 24bt depth buffer */ SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1); SDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE, 24); /* Multisampling */ SDL_GL_SetAttribute(SDL_GL_MULTISAMPLEBUFFERS, configuration->sampleCount() > 1 ? 1 : 0); SDL_GL_SetAttribute(SDL_GL_MULTISAMPLESAMPLES, configuration->sampleCount()); /* Flags: if not hidden, set as shown */ Uint32 flags(configuration->flags()); if(!(configuration->flags() & Configuration::Flag::Hidden)) flags |= SDL_WINDOW_SHOWN; if(!(window = SDL_CreateWindow(configuration->title().c_str(), SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, configuration->size().x(), configuration->size().y(), SDL_WINDOW_OPENGL|flags))) { Error() << "Platform::Sdl2Application::tryCreateContext(): cannot create window:" << SDL_GetError(); std::exit(2); } if(!(context = SDL_GL_CreateContext(window))) { SDL_DestroyWindow(window); window = nullptr; return false; } /* This must be enabled, otherwise (on my NVidia) it crashes when creating VAO. WTF. */ ExtensionWrangler::initialize(ExtensionWrangler::ExperimentalFeatures::Enable); /* Push resize event, so viewportEvent() is called at startup */ SDL_Event* sizeEvent = new SDL_Event; sizeEvent->type = SDL_WINDOWEVENT; sizeEvent->window.event = SDL_WINDOWEVENT_RESIZED; sizeEvent->window.data1 = configuration->size().x(); sizeEvent->window.data2 = configuration->size().y(); SDL_PushEvent(sizeEvent); c = new Context; return true; } Sdl2Application::~Sdl2Application() { delete c; SDL_GL_DeleteContext(context); SDL_DestroyWindow(window); SDL_Quit(); } int Sdl2Application::exec() { while(!(flags & Flag::Exit)) { SDL_Event event; while(SDL_PollEvent(&event)) { switch(event.type) { case SDL_WINDOWEVENT: switch(event.window.event) { case SDL_WINDOWEVENT_RESIZED: viewportEvent({event.window.data1, event.window.data2}); flags |= Flag::Redraw; break; case SDL_WINDOWEVENT_EXPOSED: flags |= Flag::Redraw; break; } break; case SDL_KEYDOWN: case SDL_KEYUP: { KeyEvent e(static_cast<KeyEvent::Key>(event.key.keysym.sym), fixedModifiers(event.key.keysym.mod)); event.type == SDL_KEYDOWN ? keyPressEvent(e) : keyReleaseEvent(e); } break; case SDL_MOUSEBUTTONDOWN: case SDL_MOUSEBUTTONUP: { MouseEvent e(static_cast<MouseEvent::Button>(event.button.button), {event.button.x, event.button.y}); event.type == SDL_MOUSEBUTTONDOWN ? mousePressEvent(e) : mouseReleaseEvent(e); } break; case SDL_MOUSEWHEEL: if(event.wheel.y != 0) { MouseEvent e(event.wheel.y < 0 ? MouseEvent::Button::WheelUp : MouseEvent::Button::WheelDown, {event.wheel.x, event.wheel.y}); mousePressEvent(e); } break; case SDL_MOUSEMOTION: { MouseMoveEvent e({event.motion.x, event.motion.y}, {event.motion.xrel, event.motion.yrel}); mouseMoveEvent(e); break; } case SDL_QUIT: return 0; } } if(flags & Flag::Redraw) { flags &= ~Flag::Redraw; drawEvent(); } else Corrade::Utility::sleep(5); } return 0; } void Sdl2Application::setMouseLocked(bool enabled) { SDL_SetWindowGrab(window, enabled ? SDL_TRUE : SDL_FALSE); SDL_SetRelativeMouseMode(enabled ? SDL_TRUE : SDL_FALSE); } Sdl2Application::Configuration::Configuration(): _title("Magnum SDL2 Application"), _size(800, 600), _flags(Flag::Resizable), _sampleCount(0) {} Sdl2Application::Configuration::~Configuration() = default; Sdl2Application::InputEvent::Modifiers Sdl2Application::MouseEvent::modifiers() { if(modifiersLoaded) return _modifiers; modifiersLoaded = true; return _modifiers = fixedModifiers(SDL_GetModState()); } Sdl2Application::InputEvent::Modifiers Sdl2Application::MouseMoveEvent::modifiers() { if(modifiersLoaded) return _modifiers; modifiersLoaded = true; return _modifiers = fixedModifiers(SDL_GetModState()); } }} <commit_msg>Platform: fixed Sdl2Application::tryCreateContext().<commit_after>/* This file is part of Magnum. Copyright © 2010, 2011, 2012, 2013 Vladimír Vondruš <[email protected]> Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #include "Sdl2Application.h" #include <Utility/utilities.h> #include "Context.h" #include "ExtensionWrangler.h" namespace Magnum { namespace Platform { namespace { /* * Fix up the modifiers -- we want >= operator to work properly on Shift, * Ctrl, Alt, but SDL generates different event for left / right keys, thus * (modifiers >= Shift) would pass only if both left and right were pressed, * which is usually not what the developers wants. */ Sdl2Application::InputEvent::Modifiers fixedModifiers(Uint16 mod) { Sdl2Application::InputEvent::Modifiers modifiers(static_cast<Sdl2Application::InputEvent::Modifier>(mod)); if(modifiers & Sdl2Application::InputEvent::Modifier::Shift) modifiers |= Sdl2Application::InputEvent::Modifier::Shift; if(modifiers & Sdl2Application::InputEvent::Modifier::Ctrl) modifiers |= Sdl2Application::InputEvent::Modifier::Ctrl; if(modifiers & Sdl2Application::InputEvent::Modifier::Alt) modifiers |= Sdl2Application::InputEvent::Modifier::Alt; return modifiers; } } Sdl2Application::Sdl2Application(const Arguments&): context(nullptr), flags(Flag::Redraw) { initialize(); createContext(new Configuration); } Sdl2Application::Sdl2Application(const Arguments&, Configuration* configuration): context(nullptr), flags(Flag::Redraw) { initialize(); if(configuration) createContext(configuration); } void Sdl2Application::initialize() { if(SDL_Init(SDL_INIT_VIDEO) < 0) { Error() << "Cannot initialize SDL."; std::exit(1); } } void Sdl2Application::createContext(Configuration* configuration) { if(!tryCreateContext(configuration)) { Error() << "Platform::Sdl2Application::createContext(): cannot create context:" << SDL_GetError(); delete configuration; std::exit(1); } else delete configuration; } bool Sdl2Application::tryCreateContext(Configuration* configuration) { CORRADE_ASSERT(!context, "Platform::Sdl2Application::tryCreateContext(): context already created", false); /* Enable double buffering and 24bt depth buffer */ SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1); SDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE, 24); /* Multisampling */ SDL_GL_SetAttribute(SDL_GL_MULTISAMPLEBUFFERS, configuration->sampleCount() > 1 ? 1 : 0); SDL_GL_SetAttribute(SDL_GL_MULTISAMPLESAMPLES, configuration->sampleCount()); /* Flags: if not hidden, set as shown */ Uint32 flags(configuration->flags()); if(!(configuration->flags() & Configuration::Flag::Hidden)) flags |= SDL_WINDOW_SHOWN; if(!(window = SDL_CreateWindow(configuration->title().c_str(), SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, configuration->size().x(), configuration->size().y(), SDL_WINDOW_OPENGL|flags))) return false; if(!(context = SDL_GL_CreateContext(window))) { SDL_DestroyWindow(window); window = nullptr; return false; } /* This must be enabled, otherwise (on my NVidia) it crashes when creating VAO. WTF. */ ExtensionWrangler::initialize(ExtensionWrangler::ExperimentalFeatures::Enable); /* Push resize event, so viewportEvent() is called at startup */ SDL_Event* sizeEvent = new SDL_Event; sizeEvent->type = SDL_WINDOWEVENT; sizeEvent->window.event = SDL_WINDOWEVENT_RESIZED; sizeEvent->window.data1 = configuration->size().x(); sizeEvent->window.data2 = configuration->size().y(); SDL_PushEvent(sizeEvent); c = new Context; return true; } Sdl2Application::~Sdl2Application() { delete c; SDL_GL_DeleteContext(context); SDL_DestroyWindow(window); SDL_Quit(); } int Sdl2Application::exec() { while(!(flags & Flag::Exit)) { SDL_Event event; while(SDL_PollEvent(&event)) { switch(event.type) { case SDL_WINDOWEVENT: switch(event.window.event) { case SDL_WINDOWEVENT_RESIZED: viewportEvent({event.window.data1, event.window.data2}); flags |= Flag::Redraw; break; case SDL_WINDOWEVENT_EXPOSED: flags |= Flag::Redraw; break; } break; case SDL_KEYDOWN: case SDL_KEYUP: { KeyEvent e(static_cast<KeyEvent::Key>(event.key.keysym.sym), fixedModifiers(event.key.keysym.mod)); event.type == SDL_KEYDOWN ? keyPressEvent(e) : keyReleaseEvent(e); } break; case SDL_MOUSEBUTTONDOWN: case SDL_MOUSEBUTTONUP: { MouseEvent e(static_cast<MouseEvent::Button>(event.button.button), {event.button.x, event.button.y}); event.type == SDL_MOUSEBUTTONDOWN ? mousePressEvent(e) : mouseReleaseEvent(e); } break; case SDL_MOUSEWHEEL: if(event.wheel.y != 0) { MouseEvent e(event.wheel.y < 0 ? MouseEvent::Button::WheelUp : MouseEvent::Button::WheelDown, {event.wheel.x, event.wheel.y}); mousePressEvent(e); } break; case SDL_MOUSEMOTION: { MouseMoveEvent e({event.motion.x, event.motion.y}, {event.motion.xrel, event.motion.yrel}); mouseMoveEvent(e); break; } case SDL_QUIT: return 0; } } if(flags & Flag::Redraw) { flags &= ~Flag::Redraw; drawEvent(); } else Corrade::Utility::sleep(5); } return 0; } void Sdl2Application::setMouseLocked(bool enabled) { SDL_SetWindowGrab(window, enabled ? SDL_TRUE : SDL_FALSE); SDL_SetRelativeMouseMode(enabled ? SDL_TRUE : SDL_FALSE); } Sdl2Application::Configuration::Configuration(): _title("Magnum SDL2 Application"), _size(800, 600), _flags(Flag::Resizable), _sampleCount(0) {} Sdl2Application::Configuration::~Configuration() = default; Sdl2Application::InputEvent::Modifiers Sdl2Application::MouseEvent::modifiers() { if(modifiersLoaded) return _modifiers; modifiersLoaded = true; return _modifiers = fixedModifiers(SDL_GetModState()); } Sdl2Application::InputEvent::Modifiers Sdl2Application::MouseMoveEvent::modifiers() { if(modifiersLoaded) return _modifiers; modifiersLoaded = true; return _modifiers = fixedModifiers(SDL_GetModState()); } }} <|endoftext|>
<commit_before>/* Copyright 2012-2015 Alex Zhondin <[email protected]> Copyright 2015-2016 Alexandra Cherdantseva <[email protected]> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ #include "QObjectPropertySet.h" #include "PropertyCore.h" #include "PropertyGUI.h" #include "PropertyConnector.h" #include "MultiProperty.h" #include "IQtnPropertyStateProvider.h" #include "Config.h" #include <QCoreApplication> #include <QMetaObject> #include <QMetaProperty> #include <QMap> #include <QLocale> static QtnProperty *createRealNumberProperty( QObject *object, const QMetaProperty &metaProperty) { auto property = new QtnPropertyDoubleCallback(nullptr); switch (metaProperty.revision()) { case PERCENT_SUFFIX: { QtnPropertyDelegateInfo delegate; qtnInitPercentSpinBoxDelegate(delegate); property->setDelegate(delegate); property->setCallbackValueGet( [object, metaProperty]() -> qreal { return metaProperty.read(object).toDouble() * 100.0; }); property->setCallbackValueSet( [object, metaProperty](qreal value) { metaProperty.write(object, value / 100.0); }); property->setCallbackValueAccepted( [property](qreal) -> bool { return property->isEditableByUser(); }); return property; } case DEGREE_SUFFIX: { QtnPropertyDelegateInfo delegate; qtnInitDegreeSpinBoxDelegate(delegate); property->setDelegate(delegate); break; } } property->setCallbackValueGet( [object, metaProperty]() -> qreal { return metaProperty.read(object).toDouble(); }); property->setCallbackValueSet( [object, metaProperty](qreal value) { metaProperty.write(object, value); }); property->setCallbackValueAccepted( [property](qreal) -> bool { return property->isEditableByUser(); }); return property; } bool qtnRegisterDefaultMetaPropertyFactory() { qtnRegisterMetaPropertyFactory( QVariant::Bool, qtnCreateFactory<QtnPropertyBoolCallback>()); qtnRegisterMetaPropertyFactory( QVariant::String, qtnCreateFactory<QtnPropertyQStringCallback>()); qtnRegisterMetaPropertyFactory(QVariant::Double, createRealNumberProperty); qtnRegisterMetaPropertyFactory( QVariant::Int, qtnCreateFactory<QtnPropertyIntCallback>()); qtnRegisterMetaPropertyFactory( QVariant::UInt, qtnCreateFactory<QtnPropertyUIntCallback>()); qtnRegisterMetaPropertyFactory( QVariant::Point, qtnCreateFactory<QtnPropertyQPointCallback>()); qtnRegisterMetaPropertyFactory( QVariant::Rect, qtnCreateFactory<QtnPropertyQRectCallback>()); qtnRegisterMetaPropertyFactory( QVariant::Size, qtnCreateFactory<QtnPropertyQSizeCallback>()); qtnRegisterMetaPropertyFactory( QVariant::Color, qtnCreateFactory<QtnPropertyQColorCallback>()); qtnRegisterMetaPropertyFactory( QVariant::Font, qtnCreateFactory<QtnPropertyQFontCallback>()); return true; } static QMap<int, QtnMetaPropertyFactory_t> qtnFactoryMap; static bool success = qtnRegisterDefaultMetaPropertyFactory(); bool qtnRegisterMetaPropertyFactory( int metaPropertyType, const QtnMetaPropertyFactory_t &factory, bool force) { Q_ASSERT(factory); if (!force && qtnFactoryMap.contains(metaPropertyType)) return false; qtnFactoryMap.insert(metaPropertyType, factory); return true; } QtnPropertyState qtnPropertyStateToAdd(const QMetaProperty &metaProperty) { QtnPropertyState toAdd; if (!metaProperty.isDesignable()) toAdd |= QtnPropertyStateInvisible; if (metaProperty.isConstant() || (!metaProperty.isWritable() && !metaProperty.isResettable())) { toAdd |= QtnPropertyStateImmutable; } return toAdd; } void qtnUpdatePropertyState( QtnPropertyBase *property, const QMetaProperty &metaProperty) { property->addState(qtnPropertyStateToAdd(metaProperty)); } QtnProperty *qtnCreateQObjectProperty( QObject *object, const QMetaProperty &metaProperty, bool connect, const char *className) { if (!object) return nullptr; auto it = qtnFactoryMap.find(metaProperty.type()); if (it == qtnFactoryMap.end()) it = qtnFactoryMap.find(metaProperty.userType()); if (it == qtnFactoryMap.end()) return nullptr; if (!metaProperty.isDesignable(object) || !metaProperty.isReadable()) return nullptr; QtnProperty *property = it.value() (object, metaProperty); if (!property) return property; property->setName( (nullptr != className) ? QCoreApplication::translate(className, metaProperty.name()) : metaProperty.name()); auto stateProvider = dynamic_cast<IQtnPropertyStateProvider *>(object); if (nullptr != stateProvider) { auto state = stateProvider->getPropertyState(metaProperty); property->setState(state); } qtnUpdatePropertyState(property, metaProperty); if (connect && metaProperty.hasNotifySignal()) { auto connector = new QtnPropertyConnector(property); connector->connectProperty(object, metaProperty); } return property; } QtnProperty *qtnCreateQObjectProperty( QObject *object, const char *propertyName, bool connect) { if (!object) return nullptr; const QMetaObject *metaObject = object->metaObject(); int propertyIndex = -1; while (metaObject) { propertyIndex = object->metaObject()->indexOfProperty(propertyName); if (propertyIndex != -1) break; metaObject = metaObject->superClass(); } if (!metaObject) return nullptr; if (propertyIndex == -1) return nullptr; Q_ASSERT(propertyIndex >= 0 && propertyIndex < metaObject->propertyCount()); return qtnCreateQObjectProperty( object, metaObject->property(propertyIndex), connect); } QtnPropertySet *qtnCreateQObjectPropertySet(QObject *object) { if (!object) return nullptr; // collect property sets by object's classes QStringList classNames; std::map<QString, QtnPropertySet *> propertySetsByClass; auto metaObject = object->metaObject(); while (nullptr != metaObject) { if (metaObject->propertyCount() > 0) { QList<QtnProperty *> properties; for (int propertyIndex = metaObject->propertyOffset(), n = metaObject->propertyCount(); propertyIndex < n; ++propertyIndex) { auto metaProperty = metaObject->property(propertyIndex); auto property = qtnCreateQObjectProperty( object, metaProperty, true, metaObject->className()); if (nullptr != property) properties.append(property); } if (!properties.isEmpty()) { auto className = QCoreApplication::translate( "ClassName", metaObject->className()); auto it = propertySetsByClass.find(className); QtnPropertySet *propertySetByClass; if (it != propertySetsByClass.end()) propertySetByClass = it->second; else { propertySetByClass = new QtnPropertySet(nullptr); propertySetByClass->setName(className); propertySetsByClass[className] = propertySetByClass; classNames.push_back(className); } for (auto property : properties) { propertySetByClass->addChildProperty(property); } } } // move up in class hierarchy metaObject = metaObject->superClass(); } if (propertySetsByClass.empty()) return nullptr; // move collected property sets to object's property set auto propertySet = new QtnPropertySet(nullptr); propertySet->setName(object->objectName()); for (auto &class_name : classNames) { propertySet->addChildProperty(propertySetsByClass[class_name]); } return propertySet; } QtnPropertySet *qtnCreateQObjectMultiPropertySet( const std::set<QObject *> &objects) { if (objects.empty()) return nullptr; auto result = new QtnPropertySet(nullptr); auto &subSets = result->childProperties(); for (auto object : objects) { auto propertySet = qtnCreateQObjectPropertySet(object); if (nullptr == propertySet) continue; for (int i = propertySet->childProperties().count() - 1; i >= 0; i--) { auto property = propertySet->childProperties().at(i); auto subSet = dynamic_cast<QtnPropertySet *>(property); Q_ASSERT(nullptr != subSet); auto it = std::find_if( subSets.begin(), subSets.end(), [subSet](const QtnPropertyBase *set) -> bool { return (subSet->name() == set->name()); }); QtnPropertySet *multiSet; if (it == subSets.end()) { multiSet = new QtnPropertySet(nullptr); multiSet->setName(subSet->name()); multiSet->setDescription(subSet->description()); multiSet->setId(subSet->id()); multiSet->setState(subSet->stateLocal()); result->addChildProperty(multiSet, true, 0); } else { multiSet = dynamic_cast<QtnPropertySet *>(*it); } auto &ncp = multiSet->childProperties(); for (auto subProp : subSet->childProperties()) { auto propIt = std::find_if( ncp.begin(), ncp.end(), [subProp](QtnPropertyBase *p) -> bool { return p->name() == subProp->name(); }); QtnMultiProperty *multiProperty; if (propIt == ncp.end()) { multiProperty = new QtnMultiProperty(subProp->metaObject()); multiProperty->setName(subProp->name()); multiProperty->setDescription(subProp->description()); multiProperty->setId(subProp->id()); multiSet->addChildProperty(multiProperty); } else { multiProperty = dynamic_cast<QtnMultiProperty *>(*propIt); } multiProperty->addProperty( dynamic_cast<QtnProperty *>(subProp)); } } delete propertySet; } return result; } void qtnInitPercentSpinBoxDelegate(QtnPropertyDelegateInfo &delegate) { delegate.name = "SpinBox"; delegate.attributes["suffix"] = QLocale().percent(); } void qtnInitDegreeSpinBoxDelegate(QtnPropertyDelegateInfo &delegate) { delegate.name = "SpinBox"; delegate.attributes["suffix"] = QString::fromUtf8("º"); } <commit_msg>QObject property create with class name<commit_after>/* Copyright 2012-2015 Alex Zhondin <[email protected]> Copyright 2015-2016 Alexandra Cherdantseva <[email protected]> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ #include "QObjectPropertySet.h" #include "PropertyCore.h" #include "PropertyGUI.h" #include "PropertyConnector.h" #include "MultiProperty.h" #include "IQtnPropertyStateProvider.h" #include "Config.h" #include <QCoreApplication> #include <QMetaObject> #include <QMetaProperty> #include <QMap> #include <QLocale> static QtnProperty *createRealNumberProperty( QObject *object, const QMetaProperty &metaProperty) { auto property = new QtnPropertyDoubleCallback(nullptr); switch (metaProperty.revision()) { case PERCENT_SUFFIX: { QtnPropertyDelegateInfo delegate; qtnInitPercentSpinBoxDelegate(delegate); property->setDelegate(delegate); property->setCallbackValueGet( [object, metaProperty]() -> qreal { return metaProperty.read(object).toDouble() * 100.0; }); property->setCallbackValueSet( [object, metaProperty](qreal value) { metaProperty.write(object, value / 100.0); }); property->setCallbackValueAccepted( [property](qreal) -> bool { return property->isEditableByUser(); }); return property; } case DEGREE_SUFFIX: { QtnPropertyDelegateInfo delegate; qtnInitDegreeSpinBoxDelegate(delegate); property->setDelegate(delegate); break; } } property->setCallbackValueGet( [object, metaProperty]() -> qreal { return metaProperty.read(object).toDouble(); }); property->setCallbackValueSet( [object, metaProperty](qreal value) { metaProperty.write(object, value); }); property->setCallbackValueAccepted( [property](qreal) -> bool { return property->isEditableByUser(); }); return property; } bool qtnRegisterDefaultMetaPropertyFactory() { qtnRegisterMetaPropertyFactory( QVariant::Bool, qtnCreateFactory<QtnPropertyBoolCallback>()); qtnRegisterMetaPropertyFactory( QVariant::String, qtnCreateFactory<QtnPropertyQStringCallback>()); qtnRegisterMetaPropertyFactory(QVariant::Double, createRealNumberProperty); qtnRegisterMetaPropertyFactory( QVariant::Int, qtnCreateFactory<QtnPropertyIntCallback>()); qtnRegisterMetaPropertyFactory( QVariant::UInt, qtnCreateFactory<QtnPropertyUIntCallback>()); qtnRegisterMetaPropertyFactory( QVariant::Point, qtnCreateFactory<QtnPropertyQPointCallback>()); qtnRegisterMetaPropertyFactory( QVariant::Rect, qtnCreateFactory<QtnPropertyQRectCallback>()); qtnRegisterMetaPropertyFactory( QVariant::Size, qtnCreateFactory<QtnPropertyQSizeCallback>()); qtnRegisterMetaPropertyFactory( QVariant::Color, qtnCreateFactory<QtnPropertyQColorCallback>()); qtnRegisterMetaPropertyFactory( QVariant::Font, qtnCreateFactory<QtnPropertyQFontCallback>()); return true; } static QMap<int, QtnMetaPropertyFactory_t> qtnFactoryMap; static bool success = qtnRegisterDefaultMetaPropertyFactory(); bool qtnRegisterMetaPropertyFactory( int metaPropertyType, const QtnMetaPropertyFactory_t &factory, bool force) { Q_ASSERT(factory); if (!force && qtnFactoryMap.contains(metaPropertyType)) return false; qtnFactoryMap.insert(metaPropertyType, factory); return true; } QtnPropertyState qtnPropertyStateToAdd(const QMetaProperty &metaProperty) { QtnPropertyState toAdd; if (!metaProperty.isDesignable()) toAdd |= QtnPropertyStateInvisible; if (metaProperty.isConstant() || (!metaProperty.isWritable() && !metaProperty.isResettable())) { toAdd |= QtnPropertyStateImmutable; } return toAdd; } void qtnUpdatePropertyState( QtnPropertyBase *property, const QMetaProperty &metaProperty) { property->addState(qtnPropertyStateToAdd(metaProperty)); } QtnProperty *qtnCreateQObjectProperty( QObject *object, const QMetaProperty &metaProperty, bool connect, const char *className) { if (!object) return nullptr; auto it = qtnFactoryMap.find(metaProperty.type()); if (it == qtnFactoryMap.end()) it = qtnFactoryMap.find(metaProperty.userType()); if (it == qtnFactoryMap.end()) return nullptr; if (!metaProperty.isDesignable(object) || !metaProperty.isReadable()) return nullptr; QtnProperty *property = it.value() (object, metaProperty); if (!property) return property; property->setName( (nullptr != className) ? QCoreApplication::translate(className, metaProperty.name()) : metaProperty.name()); auto stateProvider = dynamic_cast<IQtnPropertyStateProvider *>(object); if (nullptr != stateProvider) { auto state = stateProvider->getPropertyState(metaProperty); property->setState(state); } qtnUpdatePropertyState(property, metaProperty); if (connect && metaProperty.hasNotifySignal()) { auto connector = new QtnPropertyConnector(property); connector->connectProperty(object, metaProperty); } return property; } QtnProperty *qtnCreateQObjectProperty( QObject *object, const char *propertyName, bool connect) { if (!object) return nullptr; const QMetaObject *metaObject = object->metaObject(); int propertyIndex = -1; while (metaObject) { propertyIndex = object->metaObject()->indexOfProperty(propertyName); if (propertyIndex != -1) break; metaObject = metaObject->superClass(); } if (!metaObject) return nullptr; if (propertyIndex == -1) return nullptr; Q_ASSERT(propertyIndex >= 0 && propertyIndex < metaObject->propertyCount()); return qtnCreateQObjectProperty( object, metaObject->property(propertyIndex), connect, metaObject->className()); } QtnPropertySet *qtnCreateQObjectPropertySet(QObject *object) { if (!object) return nullptr; // collect property sets by object's classes QStringList classNames; std::map<QString, QtnPropertySet *> propertySetsByClass; auto metaObject = object->metaObject(); while (nullptr != metaObject) { if (metaObject->propertyCount() > 0) { QList<QtnProperty *> properties; for (int propertyIndex = metaObject->propertyOffset(), n = metaObject->propertyCount(); propertyIndex < n; ++propertyIndex) { auto metaProperty = metaObject->property(propertyIndex); auto property = qtnCreateQObjectProperty( object, metaProperty, true, metaObject->className()); if (nullptr != property) properties.append(property); } if (!properties.isEmpty()) { auto className = QCoreApplication::translate( "ClassName", metaObject->className()); auto it = propertySetsByClass.find(className); QtnPropertySet *propertySetByClass; if (it != propertySetsByClass.end()) propertySetByClass = it->second; else { propertySetByClass = new QtnPropertySet(nullptr); propertySetByClass->setName(className); propertySetsByClass[className] = propertySetByClass; classNames.push_back(className); } for (auto property : properties) { propertySetByClass->addChildProperty(property); } } } // move up in class hierarchy metaObject = metaObject->superClass(); } if (propertySetsByClass.empty()) return nullptr; // move collected property sets to object's property set auto propertySet = new QtnPropertySet(nullptr); propertySet->setName(object->objectName()); for (auto &class_name : classNames) { propertySet->addChildProperty(propertySetsByClass[class_name]); } return propertySet; } QtnPropertySet *qtnCreateQObjectMultiPropertySet( const std::set<QObject *> &objects) { if (objects.empty()) return nullptr; auto result = new QtnPropertySet(nullptr); auto &subSets = result->childProperties(); for (auto object : objects) { auto propertySet = qtnCreateQObjectPropertySet(object); if (nullptr == propertySet) continue; for (int i = propertySet->childProperties().count() - 1; i >= 0; i--) { auto property = propertySet->childProperties().at(i); auto subSet = dynamic_cast<QtnPropertySet *>(property); Q_ASSERT(nullptr != subSet); auto it = std::find_if( subSets.begin(), subSets.end(), [subSet](const QtnPropertyBase *set) -> bool { return (subSet->name() == set->name()); }); QtnPropertySet *multiSet; if (it == subSets.end()) { multiSet = new QtnPropertySet(nullptr); multiSet->setName(subSet->name()); multiSet->setDescription(subSet->description()); multiSet->setId(subSet->id()); multiSet->setState(subSet->stateLocal()); result->addChildProperty(multiSet, true, 0); } else { multiSet = dynamic_cast<QtnPropertySet *>(*it); } auto &ncp = multiSet->childProperties(); for (auto subProp : subSet->childProperties()) { auto propIt = std::find_if( ncp.begin(), ncp.end(), [subProp](QtnPropertyBase *p) -> bool { return p->name() == subProp->name(); }); QtnMultiProperty *multiProperty; if (propIt == ncp.end()) { multiProperty = new QtnMultiProperty(subProp->metaObject()); multiProperty->setName(subProp->name()); multiProperty->setDescription(subProp->description()); multiProperty->setId(subProp->id()); multiSet->addChildProperty(multiProperty); } else { multiProperty = dynamic_cast<QtnMultiProperty *>(*propIt); } multiProperty->addProperty( dynamic_cast<QtnProperty *>(subProp)); } } delete propertySet; } return result; } void qtnInitPercentSpinBoxDelegate(QtnPropertyDelegateInfo &delegate) { delegate.name = "SpinBox"; delegate.attributes["suffix"] = QLocale().percent(); } void qtnInitDegreeSpinBoxDelegate(QtnPropertyDelegateInfo &delegate) { delegate.name = "SpinBox"; delegate.attributes["suffix"] = QString::fromUtf8("º"); } <|endoftext|>
<commit_before>// The libMesh Finite Element Library. // Copyright (C) 2002-2012 Benjamin S. Kirk, John W. Peterson, Roy H. Stogner // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // Lesser General Public License for more details. // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // C++ includes // Local includes #include "nonlinear_implicit_system.h" #include "diff_solver.h" #include "equation_systems.h" #include "libmesh_logging.h" #include "nonlinear_solver.h" #include "sparse_matrix.h" namespace libMesh { // ------------------------------------------------------------ // NonlinearImplicitSystem implementation NonlinearImplicitSystem::NonlinearImplicitSystem (EquationSystems& es, const std::string& name, const unsigned int number) : Parent (es, name, number), nonlinear_solver (NonlinearSolver<Number>::build(*this)), diff_solver (NULL), _n_nonlinear_iterations (0), _final_nonlinear_residual (1.e20) { // Set default parameters // These were chosen to match the Petsc defaults es.parameters.set<Real> ("linear solver tolerance") = 1e-5; es.parameters.set<Real> ("linear solver minimum tolerance") = 1e-5; es.parameters.set<unsigned int>("linear solver maximum iterations") = 10000; es.parameters.set<unsigned int>("nonlinear solver maximum iterations") = 50; es.parameters.set<unsigned int>("nonlinear solver maximum function evaluations") = 10000; es.parameters.set<Real>("nonlinear solver absolute residual tolerance") = 1e-50; es.parameters.set<Real>("nonlinear solver relative residual tolerance") = 1e-8; es.parameters.set<Real>("nonlinear solver absolute step tolerance") = 1e-8; es.parameters.set<Real>("nonlinear solver relative step tolerance") = 1e-8; } NonlinearImplicitSystem::~NonlinearImplicitSystem () { // Clear data this->clear(); } void NonlinearImplicitSystem::clear () { // clear the nonlinear solver nonlinear_solver->clear(); // clear the parent data Parent::clear(); } void NonlinearImplicitSystem::reinit () { // re-initialize the nonlinear solver interface nonlinear_solver->clear(); if (diff_solver.get()) diff_solver->reinit(); // initialize parent data Parent::reinit(); } void NonlinearImplicitSystem::set_solver_parameters () { // Get a reference to the EquationSystems const EquationSystems& es = this->get_equation_systems(); // Get the user-specifiied nonlinear solver tolerances const unsigned int maxits = es.parameters.get<unsigned int>("nonlinear solver maximum iterations"); const unsigned int maxfuncs = es.parameters.get<unsigned int>("nonlinear solver maximum function evaluations"); const Real abs_resid_tol = es.parameters.get<Real>("nonlinear solver absolute residual tolerance"); const Real rel_resid_tol = es.parameters.get<Real>("nonlinear solver relative residual tolerance"); const Real abs_step_tol = es.parameters.get<Real>("nonlinear solver absolute step tolerance"); const Real rel_step_tol = es.parameters.get<Real>("nonlinear solver relative step tolerance"); // Get the user-specified linear solver toleranaces const unsigned int maxlinearits = es.parameters.get<unsigned int>("linear solver maximum iterations"); const Real linear_tol = es.parameters.get<Real>("linear solver tolerance"); const Real linear_min_tol = es.parameters.get<Real>("linear solver minimum tolerance"); // Set all the parameters on the NonlinearSolver nonlinear_solver->max_nonlinear_iterations = maxits; nonlinear_solver->max_function_evaluations = maxfuncs; nonlinear_solver->absolute_residual_tolerance = abs_resid_tol; nonlinear_solver->relative_residual_tolerance = rel_resid_tol; nonlinear_solver->absolute_step_tolerance = abs_step_tol; nonlinear_solver->relative_step_tolerance = rel_step_tol; nonlinear_solver->max_linear_iterations = maxlinearits; nonlinear_solver->initial_linear_tolerance = linear_tol; nonlinear_solver->minimum_linear_tolerance = linear_min_tol; if (diff_solver.get()) { diff_solver->max_nonlinear_iterations = maxits; diff_solver->absolute_residual_tolerance = abs_resid_tol; diff_solver->relative_residual_tolerance = rel_resid_tol; diff_solver->absolute_step_tolerance = abs_step_tol; diff_solver->relative_step_tolerance = rel_step_tol; diff_solver->max_linear_iterations = maxlinearits; diff_solver->initial_linear_tolerance = linear_tol; diff_solver->minimum_linear_tolerance = linear_min_tol; } } void NonlinearImplicitSystem::solve () { // Log how long the nonlinear solve takes. START_LOG("solve()", "System"); this->set_solver_parameters(); if (diff_solver.get()) { diff_solver->solve(); // Store the number of nonlinear iterations required to // solve and the final residual. _n_nonlinear_iterations = diff_solver->total_outer_iterations(); _final_nonlinear_residual = 0.; // FIXME - support this! } else { // Solve the nonlinear system. const std::pair<unsigned int, Real> rval = nonlinear_solver->solve (*matrix, *solution, *rhs, nonlinear_solver->relative_residual_tolerance, nonlinear_solver->max_linear_iterations); // Store the number of nonlinear iterations required to // solve and the final residual. _n_nonlinear_iterations = rval.first; _final_nonlinear_residual = rval.second; } // Stop logging the nonlinear solve STOP_LOG("solve()", "System"); // Update the system after the solve this->update(); } std::pair<unsigned int, Real> NonlinearImplicitSystem::get_linear_solve_parameters() const { if (diff_solver.get()) return std::make_pair(this->diff_solver->max_linear_iterations, this->diff_solver->relative_residual_tolerance); return std::make_pair(this->nonlinear_solver->max_linear_iterations, this->nonlinear_solver->relative_residual_tolerance); } void NonlinearImplicitSystem::assembly(bool get_residual, bool get_jacobian) { // Get current_local_solution in sync this->update(); //----------------------------------------------------------------------------- // if the user has provided both function pointers and objects only the pointer // will be used, so catch that as an error if (nonlinear_solver->jacobian && nonlinear_solver->jacobian_object) { libMesh::err << "ERROR: cannot specifiy both a function and object to compute the Jacobian!" << std::endl; libmesh_error(); } if (nonlinear_solver->residual && nonlinear_solver->residual_object) { libMesh::err << "ERROR: cannot specifiy both a function and object to compute the Residual!" << std::endl; libmesh_error(); } if (nonlinear_solver->matvec && nonlinear_solver->residual_and_jacobian_object) { libMesh::err << "ERROR: cannot specifiy both a function and object to compute the combined Residual & Jacobian!" << std::endl; libmesh_error(); } //----------------------------------------------------------------------------- if (get_jacobian) { if (nonlinear_solver->jacobian != NULL) nonlinear_solver->jacobian (*current_local_solution.get(), *matrix, *this); else if (nonlinear_solver->jacobian_object != NULL) nonlinear_solver->jacobian_object->jacobian (*current_local_solution.get(), *matrix, *this); else if (nonlinear_solver->matvec != NULL) nonlinear_solver->matvec (*current_local_solution.get(), get_residual?rhs:NULL, matrix, *this); else if (nonlinear_solver->residual_and_jacobian_object != NULL) nonlinear_solver->residual_and_jacobian_object->residual_and_jacobian (*current_local_solution.get(), get_residual?rhs:NULL, matrix, *this); else libmesh_error(); } if (get_residual) { if (nonlinear_solver->residual != NULL) nonlinear_solver->residual (*current_local_solution.get(), *rhs, *this); else if (nonlinear_solver->residual_object != NULL) nonlinear_solver->residual_object->residual (*current_local_solution.get(), *rhs, *this); else if (nonlinear_solver->matvec != NULL) { // we might have already grabbed the residual and jacobian together if (!get_jacobian) nonlinear_solver->matvec (*current_local_solution.get(), rhs, NULL, *this); } else if (nonlinear_solver->residual_and_jacobian_object != NULL) { // we might have already grabbed the residual and jacobian together if (!get_jacobian) nonlinear_solver->residual_and_jacobian_object->residual_and_jacobian (*current_local_solution.get(), rhs, NULL, *this); } else libmesh_error(); } else libmesh_assert(get_jacobian); // I can't believe you really wanted to assemble *nothing* } unsigned NonlinearImplicitSystem::get_current_nonlinear_iteration_number() const { return nonlinear_solver->get_current_nonlinear_iteration_number(); } } // namespace libMesh <commit_msg>Avoid underflow with Real==float<commit_after>// The libMesh Finite Element Library. // Copyright (C) 2002-2012 Benjamin S. Kirk, John W. Peterson, Roy H. Stogner // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // Lesser General Public License for more details. // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // C++ includes // Local includes #include "nonlinear_implicit_system.h" #include "diff_solver.h" #include "equation_systems.h" #include "libmesh_logging.h" #include "nonlinear_solver.h" #include "sparse_matrix.h" namespace libMesh { // ------------------------------------------------------------ // NonlinearImplicitSystem implementation NonlinearImplicitSystem::NonlinearImplicitSystem (EquationSystems& es, const std::string& name, const unsigned int number) : Parent (es, name, number), nonlinear_solver (NonlinearSolver<Number>::build(*this)), diff_solver (NULL), _n_nonlinear_iterations (0), _final_nonlinear_residual (1.e20) { // Set default parameters // These were chosen to match the Petsc defaults es.parameters.set<Real> ("linear solver tolerance") = 1e-5; es.parameters.set<Real> ("linear solver minimum tolerance") = 1e-5; es.parameters.set<unsigned int>("linear solver maximum iterations") = 10000; es.parameters.set<unsigned int>("nonlinear solver maximum iterations") = 50; es.parameters.set<unsigned int>("nonlinear solver maximum function evaluations") = 10000; es.parameters.set<Real>("nonlinear solver absolute residual tolerance") = 1e-35; es.parameters.set<Real>("nonlinear solver relative residual tolerance") = 1e-8; es.parameters.set<Real>("nonlinear solver absolute step tolerance") = 1e-8; es.parameters.set<Real>("nonlinear solver relative step tolerance") = 1e-8; } NonlinearImplicitSystem::~NonlinearImplicitSystem () { // Clear data this->clear(); } void NonlinearImplicitSystem::clear () { // clear the nonlinear solver nonlinear_solver->clear(); // clear the parent data Parent::clear(); } void NonlinearImplicitSystem::reinit () { // re-initialize the nonlinear solver interface nonlinear_solver->clear(); if (diff_solver.get()) diff_solver->reinit(); // initialize parent data Parent::reinit(); } void NonlinearImplicitSystem::set_solver_parameters () { // Get a reference to the EquationSystems const EquationSystems& es = this->get_equation_systems(); // Get the user-specifiied nonlinear solver tolerances const unsigned int maxits = es.parameters.get<unsigned int>("nonlinear solver maximum iterations"); const unsigned int maxfuncs = es.parameters.get<unsigned int>("nonlinear solver maximum function evaluations"); const Real abs_resid_tol = es.parameters.get<Real>("nonlinear solver absolute residual tolerance"); const Real rel_resid_tol = es.parameters.get<Real>("nonlinear solver relative residual tolerance"); const Real abs_step_tol = es.parameters.get<Real>("nonlinear solver absolute step tolerance"); const Real rel_step_tol = es.parameters.get<Real>("nonlinear solver relative step tolerance"); // Get the user-specified linear solver toleranaces const unsigned int maxlinearits = es.parameters.get<unsigned int>("linear solver maximum iterations"); const Real linear_tol = es.parameters.get<Real>("linear solver tolerance"); const Real linear_min_tol = es.parameters.get<Real>("linear solver minimum tolerance"); // Set all the parameters on the NonlinearSolver nonlinear_solver->max_nonlinear_iterations = maxits; nonlinear_solver->max_function_evaluations = maxfuncs; nonlinear_solver->absolute_residual_tolerance = abs_resid_tol; nonlinear_solver->relative_residual_tolerance = rel_resid_tol; nonlinear_solver->absolute_step_tolerance = abs_step_tol; nonlinear_solver->relative_step_tolerance = rel_step_tol; nonlinear_solver->max_linear_iterations = maxlinearits; nonlinear_solver->initial_linear_tolerance = linear_tol; nonlinear_solver->minimum_linear_tolerance = linear_min_tol; if (diff_solver.get()) { diff_solver->max_nonlinear_iterations = maxits; diff_solver->absolute_residual_tolerance = abs_resid_tol; diff_solver->relative_residual_tolerance = rel_resid_tol; diff_solver->absolute_step_tolerance = abs_step_tol; diff_solver->relative_step_tolerance = rel_step_tol; diff_solver->max_linear_iterations = maxlinearits; diff_solver->initial_linear_tolerance = linear_tol; diff_solver->minimum_linear_tolerance = linear_min_tol; } } void NonlinearImplicitSystem::solve () { // Log how long the nonlinear solve takes. START_LOG("solve()", "System"); this->set_solver_parameters(); if (diff_solver.get()) { diff_solver->solve(); // Store the number of nonlinear iterations required to // solve and the final residual. _n_nonlinear_iterations = diff_solver->total_outer_iterations(); _final_nonlinear_residual = 0.; // FIXME - support this! } else { // Solve the nonlinear system. const std::pair<unsigned int, Real> rval = nonlinear_solver->solve (*matrix, *solution, *rhs, nonlinear_solver->relative_residual_tolerance, nonlinear_solver->max_linear_iterations); // Store the number of nonlinear iterations required to // solve and the final residual. _n_nonlinear_iterations = rval.first; _final_nonlinear_residual = rval.second; } // Stop logging the nonlinear solve STOP_LOG("solve()", "System"); // Update the system after the solve this->update(); } std::pair<unsigned int, Real> NonlinearImplicitSystem::get_linear_solve_parameters() const { if (diff_solver.get()) return std::make_pair(this->diff_solver->max_linear_iterations, this->diff_solver->relative_residual_tolerance); return std::make_pair(this->nonlinear_solver->max_linear_iterations, this->nonlinear_solver->relative_residual_tolerance); } void NonlinearImplicitSystem::assembly(bool get_residual, bool get_jacobian) { // Get current_local_solution in sync this->update(); //----------------------------------------------------------------------------- // if the user has provided both function pointers and objects only the pointer // will be used, so catch that as an error if (nonlinear_solver->jacobian && nonlinear_solver->jacobian_object) { libMesh::err << "ERROR: cannot specifiy both a function and object to compute the Jacobian!" << std::endl; libmesh_error(); } if (nonlinear_solver->residual && nonlinear_solver->residual_object) { libMesh::err << "ERROR: cannot specifiy both a function and object to compute the Residual!" << std::endl; libmesh_error(); } if (nonlinear_solver->matvec && nonlinear_solver->residual_and_jacobian_object) { libMesh::err << "ERROR: cannot specifiy both a function and object to compute the combined Residual & Jacobian!" << std::endl; libmesh_error(); } //----------------------------------------------------------------------------- if (get_jacobian) { if (nonlinear_solver->jacobian != NULL) nonlinear_solver->jacobian (*current_local_solution.get(), *matrix, *this); else if (nonlinear_solver->jacobian_object != NULL) nonlinear_solver->jacobian_object->jacobian (*current_local_solution.get(), *matrix, *this); else if (nonlinear_solver->matvec != NULL) nonlinear_solver->matvec (*current_local_solution.get(), get_residual?rhs:NULL, matrix, *this); else if (nonlinear_solver->residual_and_jacobian_object != NULL) nonlinear_solver->residual_and_jacobian_object->residual_and_jacobian (*current_local_solution.get(), get_residual?rhs:NULL, matrix, *this); else libmesh_error(); } if (get_residual) { if (nonlinear_solver->residual != NULL) nonlinear_solver->residual (*current_local_solution.get(), *rhs, *this); else if (nonlinear_solver->residual_object != NULL) nonlinear_solver->residual_object->residual (*current_local_solution.get(), *rhs, *this); else if (nonlinear_solver->matvec != NULL) { // we might have already grabbed the residual and jacobian together if (!get_jacobian) nonlinear_solver->matvec (*current_local_solution.get(), rhs, NULL, *this); } else if (nonlinear_solver->residual_and_jacobian_object != NULL) { // we might have already grabbed the residual and jacobian together if (!get_jacobian) nonlinear_solver->residual_and_jacobian_object->residual_and_jacobian (*current_local_solution.get(), rhs, NULL, *this); } else libmesh_error(); } else libmesh_assert(get_jacobian); // I can't believe you really wanted to assemble *nothing* } unsigned NonlinearImplicitSystem::get_current_nonlinear_iteration_number() const { return nonlinear_solver->get_current_nonlinear_iteration_number(); } } // namespace libMesh <|endoftext|>
<commit_before>// Copyright 2016 The SwiftShader Authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include "ExecutableMemory.hpp" #include "Debug.hpp" #if defined(_WIN32) # ifndef WIN32_LEAN_AND_MEAN # define WIN32_LEAN_AND_MEAN # endif # include <Windows.h> # include <intrin.h> #elif defined(__Fuchsia__) # include <unistd.h> # include <zircon/process.h> # include <zircon/syscalls.h> #else # include <errno.h> # include <sys/mman.h> # include <stdlib.h> # include <unistd.h> #endif #include <memory.h> #undef allocate #undef deallocate #if(defined(__i386__) || defined(_M_IX86) || defined(__x86_64__) || defined(_M_X64)) && !defined(__x86__) # define __x86__ #endif #define STRINGIFY(x) #x #define MACRO_STRINGIFY(x) STRINGIFY(x) namespace rr { namespace { struct Allocation { // size_t bytes; unsigned char *block; }; void *allocateRaw(size_t bytes, size_t alignment) { ASSERT((alignment & (alignment - 1)) == 0); // Power of 2 alignment. #if defined(REACTOR_ANONYMOUS_MMAP_NAME) if(alignment < sizeof(void *)) { return malloc(bytes); } else { void *allocation; int result = posix_memalign(&allocation, alignment, bytes); if(result != 0) { errno = result; allocation = nullptr; } return allocation; } #else unsigned char *block = new unsigned char[bytes + sizeof(Allocation) + alignment]; unsigned char *aligned = nullptr; if(block) { aligned = (unsigned char *)((uintptr_t)(block + sizeof(Allocation) + alignment - 1) & -(intptr_t)alignment); Allocation *allocation = (Allocation *)(aligned - sizeof(Allocation)); // allocation->bytes = bytes; allocation->block = block; } return aligned; #endif } #if defined(_WIN32) DWORD permissionsToProtectMode(int permissions) { switch(permissions) { case PERMISSION_READ: return PAGE_READONLY; case PERMISSION_EXECUTE: return PAGE_EXECUTE; case PERMISSION_READ | PERMISSION_WRITE: return PAGE_READWRITE; case PERMISSION_READ | PERMISSION_EXECUTE: return PAGE_EXECUTE_READ; case PERMISSION_READ | PERMISSION_WRITE | PERMISSION_EXECUTE: return PAGE_EXECUTE_READWRITE; } return PAGE_NOACCESS; } #endif #if !defined(_WIN32) && !defined(__Fuchsia__) int permissionsToMmapProt(int permissions) { int result = 0; if(permissions & PERMISSION_READ) { result |= PROT_READ; } if(permissions & PERMISSION_WRITE) { result |= PROT_WRITE; } if(permissions & PERMISSION_EXECUTE) { result |= PROT_EXEC; } return result; } #endif // !defined(_WIN32) && !defined(__Fuchsia__) #if defined(REACTOR_ANONYMOUS_MMAP_NAME) // Create a file descriptor for anonymous memory with the given // name. Returns -1 on failure. // TODO: remove once libc wrapper exists. static int memfd_create(const char *name, unsigned int flags) { # if __aarch64__ # define __NR_memfd_create 279 # elif __arm__ # define __NR_memfd_create 279 # elif __powerpc64__ # define __NR_memfd_create 360 # elif __i386__ # define __NR_memfd_create 356 # elif __x86_64__ # define __NR_memfd_create 319 # endif /* __NR_memfd_create__ */ # ifdef __NR_memfd_create // In the event of no system call this returns -1 with errno set // as ENOSYS. return syscall(__NR_memfd_create, name, flags); # else return -1; # endif } // Returns a file descriptor for use with an anonymous mmap, if // memfd_create fails, -1 is returned. Note, the mappings should be // MAP_PRIVATE so that underlying pages aren't shared. int anonymousFd() { static int fd = memfd_create(MACRO_STRINGIFY(REACTOR_ANONYMOUS_MMAP_NAME), 0); return fd; } // Ensure there is enough space in the "anonymous" fd for length. void ensureAnonFileSize(int anonFd, size_t length) { static size_t fileSize = 0; if(length > fileSize) { ftruncate(anonFd, length); fileSize = length; } } #endif // defined(REACTOR_ANONYMOUS_MMAP_NAME) #if defined(__Fuchsia__) zx_vm_option_t permissionsToZxVmOptions(int permissions) { zx_vm_option_t result = 0; if(permissions & PERMISSION_READ) { result |= ZX_VM_PERM_READ; } if(permissions & PERMISSION_WRITE) { result |= ZX_VM_PERM_WRITE; } if(permissions & PERMISSION_EXECUTE) { result |= ZX_VM_PERM_EXECUTE; } return result; } #endif // defined(__Fuchsia__) } // anonymous namespace size_t memoryPageSize() { static int pageSize = [] { #if defined(_WIN32) SYSTEM_INFO systemInfo; GetSystemInfo(&systemInfo); return systemInfo.dwPageSize; #else return sysconf(_SC_PAGESIZE); #endif }(); return pageSize; } void *allocate(size_t bytes, size_t alignment) { void *memory = allocateRaw(bytes, alignment); if(memory) { memset(memory, 0, bytes); } return memory; } void deallocate(void *memory) { #if defined(REACTOR_ANONYMOUS_MMAP_NAME) free(memory); #else if(memory) { unsigned char *aligned = (unsigned char *)memory; Allocation *allocation = (Allocation *)(aligned - sizeof(Allocation)); delete[] allocation->block; } #endif } // Rounds |x| up to a multiple of |m|, where |m| is a power of 2. inline uintptr_t roundUp(uintptr_t x, uintptr_t m) { ASSERT(m > 0 && (m & (m - 1)) == 0); // |m| must be a power of 2. return (x + m - 1) & ~(m - 1); } void *allocateMemoryPages(size_t bytes, int permissions, bool need_exec) { size_t pageSize = memoryPageSize(); size_t length = roundUp(bytes, pageSize); void *mapping = nullptr; #if defined(REACTOR_ANONYMOUS_MMAP_NAME) int flags = MAP_PRIVATE; // Try to name the memory region for the executable code, // to aid profilers. int anonFd = anonymousFd(); if(anonFd == -1) { flags |= MAP_ANONYMOUS; } else { ensureAnonFileSize(anonFd, length); } mapping = mmap( nullptr, length, permissionsToMmapProt(permissions), flags, anonFd, 0); if(mapping == MAP_FAILED) { mapping = nullptr; } #elif defined(__Fuchsia__) zx_handle_t vmo; if(zx_vmo_create(length, 0, &vmo) != ZX_OK) { return nullptr; } if(need_exec && zx_vmo_replace_as_executable(vmo, ZX_HANDLE_INVALID, &vmo) != ZX_OK) { return nullptr; } zx_vaddr_t reservation; zx_status_t status = zx_vmar_map( zx_vmar_root_self(), permissionsToZxVmOptions(permissions), 0, vmo, 0, length, &reservation); zx_handle_close(vmo); if(status != ZX_OK) { return nullptr; } // zx_vmar_map() returns page-aligned address. ASSERT(roundUp(reservation, pageSize) == reservation); mapping = reinterpret_cast<void *>(reservation); #elif defined(__APPLE__) int prot = permissionsToMmapProt(permissions); int flags = MAP_PRIVATE | MAP_ANONYMOUS; // On macOS 10.14 and higher, executables that are code signed with the // "runtime" option cannot execute writable memory by default. They can opt // into this capability by specifying the "com.apple.security.cs.allow-jit" // code signing entitlement and allocating the region with the MAP_JIT flag. mapping = mmap(nullptr, length, prot, flags | MAP_JIT, -1, 0); if(mapping == MAP_FAILED) { // Retry without MAP_JIT (for older macOS versions). mapping = mmap(nullptr, length, prot, flags, -1, 0); } if(mapping == MAP_FAILED) { mapping = nullptr; } #else mapping = allocate(length, pageSize); protectMemoryPages(mapping, length, permissions); #endif return mapping; } void protectMemoryPages(void *memory, size_t bytes, int permissions) { if(bytes == 0) { return; } bytes = roundUp(bytes, memoryPageSize()); #if defined(_WIN32) unsigned long oldProtection; BOOL result = VirtualProtect(memory, bytes, permissionsToProtectMode(permissions), &oldProtection); ASSERT(result); #elif defined(__Fuchsia__) zx_status_t status = zx_vmar_protect( zx_vmar_root_self(), permissionsToZxVmOptions(permissions), reinterpret_cast<zx_vaddr_t>(memory), bytes); ASSERT(status == ZX_OK); #else int result = mprotect(memory, bytes, permissionsToMmapProt(permissions)); ASSERT(result == 0); #endif } void deallocateMemoryPages(void *memory, size_t bytes) { #if defined(_WIN32) unsigned long oldProtection; BOOL result = VirtualProtect(memory, bytes, PAGE_READWRITE, &oldProtection); ASSERT(result); deallocate(memory); #elif defined(__APPLE__) || defined(REACTOR_ANONYMOUS_MMAP_NAME) size_t pageSize = memoryPageSize(); size_t length = (bytes + pageSize - 1) & ~(pageSize - 1); int result = munmap(memory, length); ASSERT(result == 0); #elif defined(__Fuchsia__) size_t pageSize = memoryPageSize(); size_t length = roundUp(bytes, pageSize); zx_status_t status = zx_vmar_unmap( zx_vmar_root_self(), reinterpret_cast<zx_vaddr_t>(memory), length); ASSERT(status == ZX_OK); #else int result = mprotect(memory, bytes, PROT_READ | PROT_WRITE); ASSERT(result == 0); deallocate(memory); #endif } } // namespace rr <commit_msg>Only enable naming anonymous mmap on Linux<commit_after>// Copyright 2016 The SwiftShader Authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include "ExecutableMemory.hpp" #include "Debug.hpp" #if defined(_WIN32) # ifndef WIN32_LEAN_AND_MEAN # define WIN32_LEAN_AND_MEAN # endif # include <Windows.h> # include <intrin.h> #elif defined(__Fuchsia__) # include <unistd.h> # include <zircon/process.h> # include <zircon/syscalls.h> #else # include <errno.h> # include <sys/mman.h> # include <stdlib.h> # include <unistd.h> #endif #include <memory.h> #undef allocate #undef deallocate #if(defined(__i386__) || defined(_M_IX86) || defined(__x86_64__) || defined(_M_X64)) && !defined(__x86__) # define __x86__ #endif #define STRINGIFY(x) #x #define MACRO_STRINGIFY(x) STRINGIFY(x) namespace rr { namespace { struct Allocation { // size_t bytes; unsigned char *block; }; void *allocateRaw(size_t bytes, size_t alignment) { ASSERT((alignment & (alignment - 1)) == 0); // Power of 2 alignment. #if defined(__linux__) && defined(REACTOR_ANONYMOUS_MMAP_NAME) if(alignment < sizeof(void *)) { return malloc(bytes); } else { void *allocation; int result = posix_memalign(&allocation, alignment, bytes); if(result != 0) { errno = result; allocation = nullptr; } return allocation; } #else unsigned char *block = new unsigned char[bytes + sizeof(Allocation) + alignment]; unsigned char *aligned = nullptr; if(block) { aligned = (unsigned char *)((uintptr_t)(block + sizeof(Allocation) + alignment - 1) & -(intptr_t)alignment); Allocation *allocation = (Allocation *)(aligned - sizeof(Allocation)); // allocation->bytes = bytes; allocation->block = block; } return aligned; #endif } #if defined(_WIN32) DWORD permissionsToProtectMode(int permissions) { switch(permissions) { case PERMISSION_READ: return PAGE_READONLY; case PERMISSION_EXECUTE: return PAGE_EXECUTE; case PERMISSION_READ | PERMISSION_WRITE: return PAGE_READWRITE; case PERMISSION_READ | PERMISSION_EXECUTE: return PAGE_EXECUTE_READ; case PERMISSION_READ | PERMISSION_WRITE | PERMISSION_EXECUTE: return PAGE_EXECUTE_READWRITE; } return PAGE_NOACCESS; } #endif #if !defined(_WIN32) && !defined(__Fuchsia__) int permissionsToMmapProt(int permissions) { int result = 0; if(permissions & PERMISSION_READ) { result |= PROT_READ; } if(permissions & PERMISSION_WRITE) { result |= PROT_WRITE; } if(permissions & PERMISSION_EXECUTE) { result |= PROT_EXEC; } return result; } #endif // !defined(_WIN32) && !defined(__Fuchsia__) #if defined(__linux__) && defined(REACTOR_ANONYMOUS_MMAP_NAME) // Create a file descriptor for anonymous memory with the given // name. Returns -1 on failure. // TODO: remove once libc wrapper exists. static int memfd_create(const char *name, unsigned int flags) { # if __aarch64__ # define __NR_memfd_create 279 # elif __arm__ # define __NR_memfd_create 279 # elif __powerpc64__ # define __NR_memfd_create 360 # elif __i386__ # define __NR_memfd_create 356 # elif __x86_64__ # define __NR_memfd_create 319 # endif /* __NR_memfd_create__ */ # ifdef __NR_memfd_create // In the event of no system call this returns -1 with errno set // as ENOSYS. return syscall(__NR_memfd_create, name, flags); # else return -1; # endif } // Returns a file descriptor for use with an anonymous mmap, if // memfd_create fails, -1 is returned. Note, the mappings should be // MAP_PRIVATE so that underlying pages aren't shared. int anonymousFd() { static int fd = memfd_create(MACRO_STRINGIFY(REACTOR_ANONYMOUS_MMAP_NAME), 0); return fd; } // Ensure there is enough space in the "anonymous" fd for length. void ensureAnonFileSize(int anonFd, size_t length) { static size_t fileSize = 0; if(length > fileSize) { ftruncate(anonFd, length); fileSize = length; } } #endif // defined(__linux__) && defined(REACTOR_ANONYMOUS_MMAP_NAME) #if defined(__Fuchsia__) zx_vm_option_t permissionsToZxVmOptions(int permissions) { zx_vm_option_t result = 0; if(permissions & PERMISSION_READ) { result |= ZX_VM_PERM_READ; } if(permissions & PERMISSION_WRITE) { result |= ZX_VM_PERM_WRITE; } if(permissions & PERMISSION_EXECUTE) { result |= ZX_VM_PERM_EXECUTE; } return result; } #endif // defined(__Fuchsia__) } // anonymous namespace size_t memoryPageSize() { static int pageSize = [] { #if defined(_WIN32) SYSTEM_INFO systemInfo; GetSystemInfo(&systemInfo); return systemInfo.dwPageSize; #else return sysconf(_SC_PAGESIZE); #endif }(); return pageSize; } void *allocate(size_t bytes, size_t alignment) { void *memory = allocateRaw(bytes, alignment); if(memory) { memset(memory, 0, bytes); } return memory; } void deallocate(void *memory) { #if defined(__linux__) && defined(REACTOR_ANONYMOUS_MMAP_NAME) free(memory); #else if(memory) { unsigned char *aligned = (unsigned char *)memory; Allocation *allocation = (Allocation *)(aligned - sizeof(Allocation)); delete[] allocation->block; } #endif } // Rounds |x| up to a multiple of |m|, where |m| is a power of 2. inline uintptr_t roundUp(uintptr_t x, uintptr_t m) { ASSERT(m > 0 && (m & (m - 1)) == 0); // |m| must be a power of 2. return (x + m - 1) & ~(m - 1); } void *allocateMemoryPages(size_t bytes, int permissions, bool need_exec) { size_t pageSize = memoryPageSize(); size_t length = roundUp(bytes, pageSize); void *mapping = nullptr; #if defined(__linux__) && defined(REACTOR_ANONYMOUS_MMAP_NAME) int flags = MAP_PRIVATE; // Try to name the memory region for the executable code, // to aid profilers. int anonFd = anonymousFd(); if(anonFd == -1) { flags |= MAP_ANONYMOUS; } else { ensureAnonFileSize(anonFd, length); } mapping = mmap( nullptr, length, permissionsToMmapProt(permissions), flags, anonFd, 0); if(mapping == MAP_FAILED) { mapping = nullptr; } #elif defined(__Fuchsia__) zx_handle_t vmo; if(zx_vmo_create(length, 0, &vmo) != ZX_OK) { return nullptr; } if(need_exec && zx_vmo_replace_as_executable(vmo, ZX_HANDLE_INVALID, &vmo) != ZX_OK) { return nullptr; } zx_vaddr_t reservation; zx_status_t status = zx_vmar_map( zx_vmar_root_self(), permissionsToZxVmOptions(permissions), 0, vmo, 0, length, &reservation); zx_handle_close(vmo); if(status != ZX_OK) { return nullptr; } // zx_vmar_map() returns page-aligned address. ASSERT(roundUp(reservation, pageSize) == reservation); mapping = reinterpret_cast<void *>(reservation); #elif defined(__APPLE__) int prot = permissionsToMmapProt(permissions); int flags = MAP_PRIVATE | MAP_ANONYMOUS; // On macOS 10.14 and higher, executables that are code signed with the // "runtime" option cannot execute writable memory by default. They can opt // into this capability by specifying the "com.apple.security.cs.allow-jit" // code signing entitlement and allocating the region with the MAP_JIT flag. mapping = mmap(nullptr, length, prot, flags | MAP_JIT, -1, 0); if(mapping == MAP_FAILED) { // Retry without MAP_JIT (for older macOS versions). mapping = mmap(nullptr, length, prot, flags, -1, 0); } if(mapping == MAP_FAILED) { mapping = nullptr; } #else mapping = allocate(length, pageSize); protectMemoryPages(mapping, length, permissions); #endif return mapping; } void protectMemoryPages(void *memory, size_t bytes, int permissions) { if(bytes == 0) { return; } bytes = roundUp(bytes, memoryPageSize()); #if defined(_WIN32) unsigned long oldProtection; BOOL result = VirtualProtect(memory, bytes, permissionsToProtectMode(permissions), &oldProtection); ASSERT(result); #elif defined(__Fuchsia__) zx_status_t status = zx_vmar_protect( zx_vmar_root_self(), permissionsToZxVmOptions(permissions), reinterpret_cast<zx_vaddr_t>(memory), bytes); ASSERT(status == ZX_OK); #else int result = mprotect(memory, bytes, permissionsToMmapProt(permissions)); ASSERT(result == 0); #endif } void deallocateMemoryPages(void *memory, size_t bytes) { #if defined(_WIN32) unsigned long oldProtection; BOOL result = VirtualProtect(memory, bytes, PAGE_READWRITE, &oldProtection); ASSERT(result); deallocate(memory); #elif defined(__APPLE__) || (defined(__linux__) && defined(REACTOR_ANONYMOUS_MMAP_NAME)) size_t pageSize = memoryPageSize(); size_t length = (bytes + pageSize - 1) & ~(pageSize - 1); int result = munmap(memory, length); ASSERT(result == 0); #elif defined(__Fuchsia__) size_t pageSize = memoryPageSize(); size_t length = roundUp(bytes, pageSize); zx_status_t status = zx_vmar_unmap( zx_vmar_root_self(), reinterpret_cast<zx_vaddr_t>(memory), length); ASSERT(status == ZX_OK); #else int result = mprotect(memory, bytes, PROT_READ | PROT_WRITE); ASSERT(result == 0); deallocate(memory); #endif } } // namespace rr <|endoftext|>
<commit_before>/** ** \file libport/perror.cc ** \brief perror: implements file libport/perror.hh */ #include <cstdio> #include <iostream> #include "libport/cstring" namespace libport { void perror (const char* s) { #ifndef WIN32 ::perror(s); #else int errnum; const char* errstring; const char* colon; errnum = WSAGetLastError(); errstring = strerror(errnum); if (s == NULL || *s == '\0') s = colon = ""; else colon = ": "; std::cerr << s << colon << errstring << std::endl; #endif } } <commit_msg>Add missing header for windows.<commit_after>/** ** \file libport/perror.cc ** \brief perror: implements file libport/perror.hh */ #include <cstdio> #include <iostream> #include "libport/windows.hh" #include "libport/cstring" namespace libport { void perror (const char* s) { #ifndef WIN32 ::perror(s); #else int errnum; const char* errstring; const char* colon; errnum = WSAGetLastError(); errstring = strerror(errnum); if (s == NULL || *s == '\0') s = colon = ""; else colon = ": "; std::cerr << s << colon << errstring << std::endl; #endif } } <|endoftext|>
<commit_before>// Copyright 2016 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 "gpu_surface_gl.h" #include "flutter/fml/arraysize.h" #include "flutter/fml/logging.h" #include "flutter/fml/trace_event.h" #include "flutter/shell/common/persistent_cache.h" #include "third_party/skia/include/core/SkColorFilter.h" #include "third_party/skia/include/core/SkSurface.h" #include "third_party/skia/include/gpu/GrBackendSurface.h" #include "third_party/skia/include/gpu/GrContextOptions.h" #include "third_party/skia/include/gpu/gl/GrGLAssembleInterface.h" #include "third_party/skia/include/gpu/gl/GrGLInterface.h" // These are common defines present on all OpenGL headers. However, we don't // want to perform GL header reasolution on each platform we support. So just // define these upfront. It is unlikely we will need more. But, if we do, we can // add the same here. #define GPU_GL_RGBA8 0x8058 #define GPU_GL_RGBA4 0x8056 #define GPU_GL_RGB565 0x8D62 #define GPU_GL_VERSION 0x1F02 namespace shell { // Default maximum number of budgeted resources in the cache. static const int kGrCacheMaxCount = 8192; // Default maximum number of bytes of GPU memory of budgeted resources in the // cache. static const size_t kGrCacheMaxByteSize = 512 * (1 << 20); // Version string prefix that identifies an OpenGL ES implementation. static const char kGLESVersionPrefix[] = "OpenGL ES"; GPUSurfaceGL::GPUSurfaceGL(GPUSurfaceGLDelegate* delegate) : delegate_(delegate), weak_factory_(this) { if (!delegate_->GLContextMakeCurrent()) { FML_LOG(ERROR) << "Could not make the context current to setup the gr context."; return; } proc_resolver_ = delegate_->GetGLProcResolver(); GrContextOptions options; options.fPersistentCache = PersistentCache::GetCacheForProcess(); options.fAvoidStencilBuffers = true; // To get video playback on the widest range of devices, we limit Skia to // ES2 shading language when the ES3 external image extension is missing. options.fPreferExternalImagesOverES3 = true; sk_sp<const GrGLInterface> interface; if (proc_resolver_ == nullptr) { interface = GrGLMakeNativeInterface(); } else { auto gl_get_proc = [](void* context, const char gl_proc_name[]) -> GrGLFuncPtr { return reinterpret_cast<GrGLFuncPtr>( reinterpret_cast<GPUSurfaceGL*>(context)->proc_resolver_( gl_proc_name)); }; if (IsProcResolverOpenGLES()) { interface = GrGLMakeAssembledGLESInterface(this, gl_get_proc); } else { interface = GrGLMakeAssembledGLInterface(this, gl_get_proc); } } auto context = GrContext::MakeGL(interface, options); if (context == nullptr) { FML_LOG(ERROR) << "Failed to setup Skia Gr context."; return; } context_ = std::move(context); context_->setResourceCacheLimits(kGrCacheMaxCount, kGrCacheMaxByteSize); delegate_->GLContextClearCurrent(); valid_ = true; } GPUSurfaceGL::~GPUSurfaceGL() { if (!valid_) { return; } if (!delegate_->GLContextMakeCurrent()) { FML_LOG(ERROR) << "Could not make the context current to destroy the " "GrContext resources."; return; } onscreen_surface_ = nullptr; context_->releaseResourcesAndAbandonContext(); context_ = nullptr; delegate_->GLContextClearCurrent(); } bool GPUSurfaceGL::IsProcResolverOpenGLES() { using GLGetStringProc = const char* (*)(uint32_t); GLGetStringProc gl_get_string = reinterpret_cast<GLGetStringProc>(proc_resolver_("glGetString")); FML_CHECK(gl_get_string) << "The GL proc resolver could not resolve glGetString"; const char* gl_version_string = gl_get_string(GPU_GL_VERSION); FML_CHECK(gl_version_string) << "The GL proc resolver's glGetString(GL_VERSION) failed"; return strncmp(gl_version_string, kGLESVersionPrefix, strlen(kGLESVersionPrefix)) == 0; } // |shell::Surface| bool GPUSurfaceGL::IsValid() { return valid_; } static SkColorType FirstSupportedColorType(GrContext* context, GrGLenum* format) { #define RETURN_IF_RENDERABLE(x, y) \ if (context->colorTypeSupportedAsSurface((x))) { \ *format = (y); \ return (x); \ } RETURN_IF_RENDERABLE(kRGBA_8888_SkColorType, GPU_GL_RGBA8); RETURN_IF_RENDERABLE(kARGB_4444_SkColorType, GPU_GL_RGBA4); RETURN_IF_RENDERABLE(kRGB_565_SkColorType, GPU_GL_RGB565); return kUnknown_SkColorType; } static sk_sp<SkSurface> WrapOnscreenSurface(GrContext* context, const SkISize& size, intptr_t fbo) { GrGLenum format; const SkColorType color_type = FirstSupportedColorType(context, &format); GrGLFramebufferInfo framebuffer_info = {}; framebuffer_info.fFBOID = static_cast<GrGLuint>(fbo); framebuffer_info.fFormat = format; GrBackendRenderTarget render_target(size.width(), // width size.height(), // height 0, // sample count 0, // stencil bits (TODO) framebuffer_info // framebuffer info ); sk_sp<SkColorSpace> colorspace = nullptr; SkSurfaceProps surface_props( SkSurfaceProps::InitType::kLegacyFontHost_InitType); return SkSurface::MakeFromBackendRenderTarget( context, // gr context render_target, // render target GrSurfaceOrigin::kBottomLeft_GrSurfaceOrigin, // origin color_type, // color type colorspace, // colorspace &surface_props // surface properties ); } static sk_sp<SkSurface> CreateOffscreenSurface(GrContext* context, const SkISize& size) { const SkImageInfo image_info = SkImageInfo::MakeN32(size.fWidth, size.fHeight, kOpaque_SkAlphaType); const SkSurfaceProps surface_props( SkSurfaceProps::InitType::kLegacyFontHost_InitType); return SkSurface::MakeRenderTarget(context, SkBudgeted::kNo, image_info, 0, kBottomLeft_GrSurfaceOrigin, &surface_props); } bool GPUSurfaceGL::CreateOrUpdateSurfaces(const SkISize& size) { if (onscreen_surface_ != nullptr && size == SkISize::Make(onscreen_surface_->width(), onscreen_surface_->height())) { // Surface size appears unchanged. So bail. return true; } // We need to do some updates. TRACE_EVENT0("flutter", "UpdateSurfacesSize"); // Either way, we need to get rid of previous surface. onscreen_surface_ = nullptr; offscreen_surface_ = nullptr; if (size.isEmpty()) { FML_LOG(ERROR) << "Cannot create surfaces of empty size."; return false; } sk_sp<SkSurface> onscreen_surface, offscreen_surface; onscreen_surface = WrapOnscreenSurface(context_.get(), // GL context size, // root surface size delegate_->GLContextFBO() // window FBO ID ); if (onscreen_surface == nullptr) { // If the onscreen surface could not be wrapped. There is absolutely no // point in moving forward. FML_LOG(ERROR) << "Could not wrap onscreen surface."; return false; } if (delegate_->UseOffscreenSurface()) { offscreen_surface = CreateOffscreenSurface(context_.get(), size); if (offscreen_surface == nullptr) { FML_LOG(ERROR) << "Could not create offscreen surface."; return false; } } onscreen_surface_ = std::move(onscreen_surface); offscreen_surface_ = std::move(offscreen_surface); return true; } // |shell::Surface| SkMatrix GPUSurfaceGL::GetRootTransformation() const { return delegate_->GLContextSurfaceTransformation(); } // |shell::Surface| std::unique_ptr<SurfaceFrame> GPUSurfaceGL::AcquireFrame(const SkISize& size) { if (delegate_ == nullptr) { return nullptr; } if (!delegate_->GLContextMakeCurrent()) { FML_LOG(ERROR) << "Could not make the context current to acquire the frame."; return nullptr; } const auto root_surface_transformation = GetRootTransformation(); sk_sp<SkSurface> surface = AcquireRenderSurface(size, root_surface_transformation); if (surface == nullptr) { return nullptr; } surface->getCanvas()->setMatrix(root_surface_transformation); SurfaceFrame::SubmitCallback submit_callback = [weak = weak_factory_.GetWeakPtr()](const SurfaceFrame& surface_frame, SkCanvas* canvas) { return weak ? weak->PresentSurface(canvas) : false; }; return std::make_unique<SurfaceFrame>(surface, submit_callback); } bool GPUSurfaceGL::PresentSurface(SkCanvas* canvas) { if (delegate_ == nullptr || canvas == nullptr || context_ == nullptr) { return false; } if (offscreen_surface_ != nullptr) { TRACE_EVENT0("flutter", "CopyTextureOnscreen"); SkPaint paint; onscreen_surface_->getCanvas()->drawImage( offscreen_surface_->makeImageSnapshot(), 0, 0, &paint); } { TRACE_EVENT0("flutter", "SkCanvas::Flush"); onscreen_surface_->getCanvas()->flush(); } if (!delegate_->GLContextPresent()) { return false; } if (delegate_->GLContextFBOResetAfterPresent()) { auto current_size = SkISize::Make(onscreen_surface_->width(), onscreen_surface_->height()); // The FBO has changed, ask the delegate for the new FBO and do a surface // re-wrap. auto new_onscreen_surface = WrapOnscreenSurface(context_.get(), // GL context current_size, // root surface size delegate_->GLContextFBO() // window FBO ID ); if (!new_onscreen_surface) { return false; } onscreen_surface_ = std::move(new_onscreen_surface); } return true; } sk_sp<SkSurface> GPUSurfaceGL::AcquireRenderSurface( const SkISize& untransformed_size, const SkMatrix& root_surface_transformation) { const auto transformed_rect = root_surface_transformation.mapRect( SkRect::MakeWH(untransformed_size.width(), untransformed_size.height())); const auto transformed_size = SkISize::Make(transformed_rect.width(), transformed_rect.height()); if (!CreateOrUpdateSurfaces(transformed_size)) { return nullptr; } return offscreen_surface_ != nullptr ? offscreen_surface_ : onscreen_surface_; } // |shell::Surface| GrContext* GPUSurfaceGL::GetContext() { return context_.get(); } // |shell::Surface| flow::ExternalViewEmbedder* GPUSurfaceGL::GetExternalViewEmbedder() { return delegate_->GetExternalViewEmbedder(); } } // namespace shell <commit_msg>Clear the on-screen surface every frame. (#6753)<commit_after>// Copyright 2016 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 "gpu_surface_gl.h" #include "flutter/fml/arraysize.h" #include "flutter/fml/logging.h" #include "flutter/fml/trace_event.h" #include "flutter/shell/common/persistent_cache.h" #include "third_party/skia/include/core/SkColorFilter.h" #include "third_party/skia/include/core/SkSurface.h" #include "third_party/skia/include/gpu/GrBackendSurface.h" #include "third_party/skia/include/gpu/GrContextOptions.h" #include "third_party/skia/include/gpu/gl/GrGLAssembleInterface.h" #include "third_party/skia/include/gpu/gl/GrGLInterface.h" // These are common defines present on all OpenGL headers. However, we don't // want to perform GL header reasolution on each platform we support. So just // define these upfront. It is unlikely we will need more. But, if we do, we can // add the same here. #define GPU_GL_RGBA8 0x8058 #define GPU_GL_RGBA4 0x8056 #define GPU_GL_RGB565 0x8D62 #define GPU_GL_VERSION 0x1F02 namespace shell { // Default maximum number of budgeted resources in the cache. static const int kGrCacheMaxCount = 8192; // Default maximum number of bytes of GPU memory of budgeted resources in the // cache. static const size_t kGrCacheMaxByteSize = 512 * (1 << 20); // Version string prefix that identifies an OpenGL ES implementation. static const char kGLESVersionPrefix[] = "OpenGL ES"; GPUSurfaceGL::GPUSurfaceGL(GPUSurfaceGLDelegate* delegate) : delegate_(delegate), weak_factory_(this) { if (!delegate_->GLContextMakeCurrent()) { FML_LOG(ERROR) << "Could not make the context current to setup the gr context."; return; } proc_resolver_ = delegate_->GetGLProcResolver(); GrContextOptions options; options.fPersistentCache = PersistentCache::GetCacheForProcess(); options.fAvoidStencilBuffers = true; // To get video playback on the widest range of devices, we limit Skia to // ES2 shading language when the ES3 external image extension is missing. options.fPreferExternalImagesOverES3 = true; sk_sp<const GrGLInterface> interface; if (proc_resolver_ == nullptr) { interface = GrGLMakeNativeInterface(); } else { auto gl_get_proc = [](void* context, const char gl_proc_name[]) -> GrGLFuncPtr { return reinterpret_cast<GrGLFuncPtr>( reinterpret_cast<GPUSurfaceGL*>(context)->proc_resolver_( gl_proc_name)); }; if (IsProcResolverOpenGLES()) { interface = GrGLMakeAssembledGLESInterface(this, gl_get_proc); } else { interface = GrGLMakeAssembledGLInterface(this, gl_get_proc); } } auto context = GrContext::MakeGL(interface, options); if (context == nullptr) { FML_LOG(ERROR) << "Failed to setup Skia Gr context."; return; } context_ = std::move(context); context_->setResourceCacheLimits(kGrCacheMaxCount, kGrCacheMaxByteSize); delegate_->GLContextClearCurrent(); valid_ = true; } GPUSurfaceGL::~GPUSurfaceGL() { if (!valid_) { return; } if (!delegate_->GLContextMakeCurrent()) { FML_LOG(ERROR) << "Could not make the context current to destroy the " "GrContext resources."; return; } onscreen_surface_ = nullptr; context_->releaseResourcesAndAbandonContext(); context_ = nullptr; delegate_->GLContextClearCurrent(); } bool GPUSurfaceGL::IsProcResolverOpenGLES() { using GLGetStringProc = const char* (*)(uint32_t); GLGetStringProc gl_get_string = reinterpret_cast<GLGetStringProc>(proc_resolver_("glGetString")); FML_CHECK(gl_get_string) << "The GL proc resolver could not resolve glGetString"; const char* gl_version_string = gl_get_string(GPU_GL_VERSION); FML_CHECK(gl_version_string) << "The GL proc resolver's glGetString(GL_VERSION) failed"; return strncmp(gl_version_string, kGLESVersionPrefix, strlen(kGLESVersionPrefix)) == 0; } // |shell::Surface| bool GPUSurfaceGL::IsValid() { return valid_; } static SkColorType FirstSupportedColorType(GrContext* context, GrGLenum* format) { #define RETURN_IF_RENDERABLE(x, y) \ if (context->colorTypeSupportedAsSurface((x))) { \ *format = (y); \ return (x); \ } RETURN_IF_RENDERABLE(kRGBA_8888_SkColorType, GPU_GL_RGBA8); RETURN_IF_RENDERABLE(kARGB_4444_SkColorType, GPU_GL_RGBA4); RETURN_IF_RENDERABLE(kRGB_565_SkColorType, GPU_GL_RGB565); return kUnknown_SkColorType; } static sk_sp<SkSurface> WrapOnscreenSurface(GrContext* context, const SkISize& size, intptr_t fbo) { GrGLenum format; const SkColorType color_type = FirstSupportedColorType(context, &format); GrGLFramebufferInfo framebuffer_info = {}; framebuffer_info.fFBOID = static_cast<GrGLuint>(fbo); framebuffer_info.fFormat = format; GrBackendRenderTarget render_target(size.width(), // width size.height(), // height 0, // sample count 0, // stencil bits (TODO) framebuffer_info // framebuffer info ); sk_sp<SkColorSpace> colorspace = nullptr; SkSurfaceProps surface_props( SkSurfaceProps::InitType::kLegacyFontHost_InitType); return SkSurface::MakeFromBackendRenderTarget( context, // gr context render_target, // render target GrSurfaceOrigin::kBottomLeft_GrSurfaceOrigin, // origin color_type, // color type colorspace, // colorspace &surface_props // surface properties ); } static sk_sp<SkSurface> CreateOffscreenSurface(GrContext* context, const SkISize& size) { const SkImageInfo image_info = SkImageInfo::MakeN32(size.fWidth, size.fHeight, kOpaque_SkAlphaType); const SkSurfaceProps surface_props( SkSurfaceProps::InitType::kLegacyFontHost_InitType); return SkSurface::MakeRenderTarget(context, SkBudgeted::kNo, image_info, 0, kBottomLeft_GrSurfaceOrigin, &surface_props); } bool GPUSurfaceGL::CreateOrUpdateSurfaces(const SkISize& size) { if (onscreen_surface_ != nullptr && size == SkISize::Make(onscreen_surface_->width(), onscreen_surface_->height())) { // Surface size appears unchanged. So bail. return true; } // We need to do some updates. TRACE_EVENT0("flutter", "UpdateSurfacesSize"); // Either way, we need to get rid of previous surface. onscreen_surface_ = nullptr; offscreen_surface_ = nullptr; if (size.isEmpty()) { FML_LOG(ERROR) << "Cannot create surfaces of empty size."; return false; } sk_sp<SkSurface> onscreen_surface, offscreen_surface; onscreen_surface = WrapOnscreenSurface(context_.get(), // GL context size, // root surface size delegate_->GLContextFBO() // window FBO ID ); if (onscreen_surface == nullptr) { // If the onscreen surface could not be wrapped. There is absolutely no // point in moving forward. FML_LOG(ERROR) << "Could not wrap onscreen surface."; return false; } if (delegate_->UseOffscreenSurface()) { offscreen_surface = CreateOffscreenSurface(context_.get(), size); if (offscreen_surface == nullptr) { FML_LOG(ERROR) << "Could not create offscreen surface."; return false; } } onscreen_surface_ = std::move(onscreen_surface); offscreen_surface_ = std::move(offscreen_surface); return true; } // |shell::Surface| SkMatrix GPUSurfaceGL::GetRootTransformation() const { return delegate_->GLContextSurfaceTransformation(); } // |shell::Surface| std::unique_ptr<SurfaceFrame> GPUSurfaceGL::AcquireFrame(const SkISize& size) { if (delegate_ == nullptr) { return nullptr; } if (!delegate_->GLContextMakeCurrent()) { FML_LOG(ERROR) << "Could not make the context current to acquire the frame."; return nullptr; } const auto root_surface_transformation = GetRootTransformation(); sk_sp<SkSurface> surface = AcquireRenderSurface(size, root_surface_transformation); if (surface == nullptr) { return nullptr; } surface->getCanvas()->setMatrix(root_surface_transformation); SurfaceFrame::SubmitCallback submit_callback = [weak = weak_factory_.GetWeakPtr()](const SurfaceFrame& surface_frame, SkCanvas* canvas) { return weak ? weak->PresentSurface(canvas) : false; }; return std::make_unique<SurfaceFrame>(surface, submit_callback); } bool GPUSurfaceGL::PresentSurface(SkCanvas* canvas) { if (delegate_ == nullptr || canvas == nullptr || context_ == nullptr) { return false; } if (offscreen_surface_ != nullptr) { TRACE_EVENT0("flutter", "CopyTextureOnscreen"); SkPaint paint; SkCanvas* onscreen_canvas = onscreen_surface_->getCanvas(); onscreen_canvas->clear(SK_ColorTRANSPARENT); onscreen_canvas->drawImage(offscreen_surface_->makeImageSnapshot(), 0, 0, &paint); } { TRACE_EVENT0("flutter", "SkCanvas::Flush"); onscreen_surface_->getCanvas()->flush(); } if (!delegate_->GLContextPresent()) { return false; } if (delegate_->GLContextFBOResetAfterPresent()) { auto current_size = SkISize::Make(onscreen_surface_->width(), onscreen_surface_->height()); // The FBO has changed, ask the delegate for the new FBO and do a surface // re-wrap. auto new_onscreen_surface = WrapOnscreenSurface(context_.get(), // GL context current_size, // root surface size delegate_->GLContextFBO() // window FBO ID ); if (!new_onscreen_surface) { return false; } onscreen_surface_ = std::move(new_onscreen_surface); } return true; } sk_sp<SkSurface> GPUSurfaceGL::AcquireRenderSurface( const SkISize& untransformed_size, const SkMatrix& root_surface_transformation) { const auto transformed_rect = root_surface_transformation.mapRect( SkRect::MakeWH(untransformed_size.width(), untransformed_size.height())); const auto transformed_size = SkISize::Make(transformed_rect.width(), transformed_rect.height()); if (!CreateOrUpdateSurfaces(transformed_size)) { return nullptr; } return offscreen_surface_ != nullptr ? offscreen_surface_ : onscreen_surface_; } // |shell::Surface| GrContext* GPUSurfaceGL::GetContext() { return context_.get(); } // |shell::Surface| flow::ExternalViewEmbedder* GPUSurfaceGL::GetExternalViewEmbedder() { return delegate_->GetExternalViewEmbedder(); } } // namespace shell <|endoftext|>
<commit_before>#include "Runtime/MP1/World/CAtomicAlpha.hpp" #include <array> #include "Runtime/CStateManager.hpp" #include "Runtime/Weapon/CPlayerGun.hpp" #include "Runtime/World/CGameArea.hpp" #include "Runtime/World/CPatternedInfo.hpp" #include "Runtime/World/CPlayer.hpp" #include "Runtime/World/CWorld.hpp" namespace urde::MP1 { constexpr std::array skBombLocators{ "bomb1_LCTR"sv, "bomb2_LCTR"sv, "bomb3_LCTR"sv, "bomb4_LCTR"sv, }; CAtomicAlpha::CAtomicAlpha(TUniqueId uid, std::string_view name, const CEntityInfo& info, const zeus::CTransform& xf, CModelData&& mData, const CActorParameters& actParms, const CPatternedInfo& pInfo, CAssetId bombWeapon, const CDamageInfo& bombDamage, float bombDropDelay, float f2, float f3, CAssetId cmdl, bool invisible, bool b2) : CPatterned(ECharacter::AtomicAlpha, uid, name, EFlavorType::Zero, info, xf, std::move(mData), pInfo, EMovementType::Flyer, EColliderType::One, EBodyType::Flyer, actParms, EKnockBackVariant::Medium) , x568_24_inRange(false) , x568_25_invisible(invisible) , x568_26_applyBeamAttraction(b2) , x56c_bomdDropDelay(bombDropDelay) , x570_bombReappearDelay(f2) , x574_bombRappearTime(f3) , x580_pathFind(nullptr, 3, pInfo.GetPathfindingIndex(), 1.f, 1.f) , x668_bombProjectile(bombWeapon, bombDamage) , x690_bombModel(CStaticRes(cmdl, GetModelData()->GetScale())) { x668_bombProjectile.Token().Lock(); for (u32 i = 0; i < skBombCount; ++i) { x6dc_bombLocators.push_back( SBomb(skBombLocators[i], pas::ELocomotionType(u32(pas::ELocomotionType::Internal10) + i))); } } void CAtomicAlpha::AcceptScriptMsg(EScriptObjectMessage msg, TUniqueId uid, CStateManager& mgr) { CPatterned::AcceptScriptMsg(msg, uid, mgr); if (msg == EScriptObjectMessage::InitializedInArea) { x580_pathFind.SetArea(mgr.GetWorld()->GetAreaAlways(GetAreaIdAlways())->GetPostConstructed()->x10bc_pathArea); } else if (msg == EScriptObjectMessage::Registered) { x450_bodyController->Activate(mgr); } else if (msg == EScriptObjectMessage::AddSplashInhabitant) { if (x400_25_alive) x401_30_pendingDeath = true; } } void CAtomicAlpha::Render(const CStateManager& mgr) const { if (mgr.GetPlayerState()->GetActiveVisor(mgr) != CPlayerState::EPlayerVisor::XRay && x568_25_invisible) return; CPatterned::Render(mgr); for (const SBomb& bomb : x6dc_bombLocators) { zeus::CTransform locatorXf = GetTransform() * GetScaledLocatorTransform(bomb.x0_locatorName) * zeus::CTransform::Scale( std::min(1.f, std::max(0.f, bomb.x14_scaleTime - x570_bombReappearDelay) / x570_bombReappearDelay)); CModelFlags flags; flags.x2_flags = 1 | 2; flags.x4_color = zeus::skWhite; x690_bombModel.Render(mgr, locatorXf, x90_actorLights.get(), flags); } } void CAtomicAlpha::AddToRenderer(const zeus::CFrustum& frustum, const CStateManager& mgr) const { if (mgr.GetPlayerState()->GetActiveVisor(mgr) != CPlayerState::EPlayerVisor::XRay && x568_25_invisible) return; CPatterned::AddToRenderer(frustum, mgr); } void CAtomicAlpha::Think(float dt, CStateManager& mgr) { CPatterned::Think(dt, mgr); if (!GetActive()) return; x578_bombTime += dt; for (SBomb& bomb : x6dc_bombLocators) { bomb.x14_scaleTime += dt; } } void CAtomicAlpha::DoUserAnimEvent(CStateManager& mgr, const CInt32POINode& node, EUserEventType type, float dt) { if (type == EUserEventType::Projectile) { zeus::CVector3f origin = GetLctrTransform(node.GetLocatorName()).origin; zeus::CTransform xf = zeus::lookAt(origin, origin + zeus::skDown, zeus::skUp); LaunchProjectile(xf, mgr, 4, EProjectileAttrib::None, false, {}, 0xFFFF, false, zeus::CVector3f(1.f)); x578_bombTime = 0.f; x57c_curBomb = (x57c_curBomb + 1) & (x6dc_bombLocators.size() - 1); } else CPatterned::DoUserAnimEvent(mgr, node, type, dt); } bool CAtomicAlpha::Leash(CStateManager& mgr, float) { if ((mgr.GetPlayer().GetTranslation() - GetTranslation()).magSquared() <= x3cc_playerLeashRadius * x3cc_playerLeashRadius) return false; return x3d4_curPlayerLeashTime > x3d0_playerLeashTime; } bool CAtomicAlpha::AggressionCheck(CStateManager& mgr, float) { const CPlayerGun* playerGun = mgr.GetPlayer().GetPlayerGun(); float factor = 0.f; if (x568_26_applyBeamAttraction && playerGun->IsCharging()) factor = playerGun->GetChargeBeamFactor(); return factor > 0.1f; } void CAtomicAlpha::CollidedWith(TUniqueId uid, const CCollisionInfoList& list, CStateManager& mgr) { if (IsAlive()) { if (TCastToConstPtr<CPlayer> pl = mgr.GetObjectById(uid)) { if (x420_curDamageRemTime <= 0.f) { mgr.GetPlayerState()->GetStaticInterference().AddSource(GetUniqueId(), 0.5f, 0.25f); for (SBomb& bomb : x6dc_bombLocators) { bomb.x14_scaleTime = 0.f; } } } } CPatterned::CollidedWith(uid, list, mgr); } void CAtomicAlpha::Patrol(CStateManager& mgr, EStateMsg msg, float arg) { CPatterned::Patrol(mgr, msg, arg); if (msg == EStateMsg::Activate) { x578_bombTime = 0.f; } else if (msg == EStateMsg::Update) { if (x568_24_inRange) { if (x578_bombTime >= x56c_bomdDropDelay && x6dc_bombLocators[0].x14_scaleTime > (x570_bombReappearDelay + x574_bombRappearTime)) { x450_bodyController->SetLocomotionType(x6dc_bombLocators[x57c_curBomb].x10_locomotionType); } else { x450_bodyController->SetLocomotionType(pas::ELocomotionType::Relaxed); } if (Leash(mgr, arg)) x568_24_inRange = false; } else { x450_bodyController->SetLocomotionType(pas::ELocomotionType::Relaxed); if (InMaxRange(mgr, arg)) x568_24_inRange = true; } } else if (msg == EStateMsg::Deactivate) { x568_24_inRange = false; } } void CAtomicAlpha::Attack(CStateManager& mgr, EStateMsg msg, float) { if (msg == EStateMsg::Activate) { x450_bodyController->SetLocomotionType(pas::ELocomotionType::Internal8); } else if (msg == EStateMsg::Update) { zeus::CVector3f seekVec = x664_steeringBehaviors.Seek(*this, mgr.GetPlayer().GetEyePosition()); x450_bodyController->GetCommandMgr().DeliverCmd(CBCLocomotionCmd(seekVec, {}, 1.f)); } else if (msg == EStateMsg::Deactivate) { x450_bodyController->SetLocomotionType(pas::ELocomotionType::Relaxed); } } } // namespace urde::MP1 <commit_msg>CAtomicAlpha: Use emplace_back where applicable<commit_after>#include "Runtime/MP1/World/CAtomicAlpha.hpp" #include <array> #include "Runtime/CStateManager.hpp" #include "Runtime/Weapon/CPlayerGun.hpp" #include "Runtime/World/CGameArea.hpp" #include "Runtime/World/CPatternedInfo.hpp" #include "Runtime/World/CPlayer.hpp" #include "Runtime/World/CWorld.hpp" namespace urde::MP1 { constexpr std::array skBombLocators{ "bomb1_LCTR"sv, "bomb2_LCTR"sv, "bomb3_LCTR"sv, "bomb4_LCTR"sv, }; CAtomicAlpha::CAtomicAlpha(TUniqueId uid, std::string_view name, const CEntityInfo& info, const zeus::CTransform& xf, CModelData&& mData, const CActorParameters& actParms, const CPatternedInfo& pInfo, CAssetId bombWeapon, const CDamageInfo& bombDamage, float bombDropDelay, float f2, float f3, CAssetId cmdl, bool invisible, bool b2) : CPatterned(ECharacter::AtomicAlpha, uid, name, EFlavorType::Zero, info, xf, std::move(mData), pInfo, EMovementType::Flyer, EColliderType::One, EBodyType::Flyer, actParms, EKnockBackVariant::Medium) , x568_24_inRange(false) , x568_25_invisible(invisible) , x568_26_applyBeamAttraction(b2) , x56c_bomdDropDelay(bombDropDelay) , x570_bombReappearDelay(f2) , x574_bombRappearTime(f3) , x580_pathFind(nullptr, 3, pInfo.GetPathfindingIndex(), 1.f, 1.f) , x668_bombProjectile(bombWeapon, bombDamage) , x690_bombModel(CStaticRes(cmdl, GetModelData()->GetScale())) { x668_bombProjectile.Token().Lock(); for (u32 i = 0; i < skBombCount; ++i) { x6dc_bombLocators.emplace_back(skBombLocators[i], pas::ELocomotionType(u32(pas::ELocomotionType::Internal10) + i)); } } void CAtomicAlpha::AcceptScriptMsg(EScriptObjectMessage msg, TUniqueId uid, CStateManager& mgr) { CPatterned::AcceptScriptMsg(msg, uid, mgr); if (msg == EScriptObjectMessage::InitializedInArea) { x580_pathFind.SetArea(mgr.GetWorld()->GetAreaAlways(GetAreaIdAlways())->GetPostConstructed()->x10bc_pathArea); } else if (msg == EScriptObjectMessage::Registered) { x450_bodyController->Activate(mgr); } else if (msg == EScriptObjectMessage::AddSplashInhabitant) { if (x400_25_alive) x401_30_pendingDeath = true; } } void CAtomicAlpha::Render(const CStateManager& mgr) const { if (mgr.GetPlayerState()->GetActiveVisor(mgr) != CPlayerState::EPlayerVisor::XRay && x568_25_invisible) return; CPatterned::Render(mgr); for (const SBomb& bomb : x6dc_bombLocators) { zeus::CTransform locatorXf = GetTransform() * GetScaledLocatorTransform(bomb.x0_locatorName) * zeus::CTransform::Scale( std::min(1.f, std::max(0.f, bomb.x14_scaleTime - x570_bombReappearDelay) / x570_bombReappearDelay)); CModelFlags flags; flags.x2_flags = 1 | 2; flags.x4_color = zeus::skWhite; x690_bombModel.Render(mgr, locatorXf, x90_actorLights.get(), flags); } } void CAtomicAlpha::AddToRenderer(const zeus::CFrustum& frustum, const CStateManager& mgr) const { if (mgr.GetPlayerState()->GetActiveVisor(mgr) != CPlayerState::EPlayerVisor::XRay && x568_25_invisible) return; CPatterned::AddToRenderer(frustum, mgr); } void CAtomicAlpha::Think(float dt, CStateManager& mgr) { CPatterned::Think(dt, mgr); if (!GetActive()) return; x578_bombTime += dt; for (SBomb& bomb : x6dc_bombLocators) { bomb.x14_scaleTime += dt; } } void CAtomicAlpha::DoUserAnimEvent(CStateManager& mgr, const CInt32POINode& node, EUserEventType type, float dt) { if (type == EUserEventType::Projectile) { zeus::CVector3f origin = GetLctrTransform(node.GetLocatorName()).origin; zeus::CTransform xf = zeus::lookAt(origin, origin + zeus::skDown, zeus::skUp); LaunchProjectile(xf, mgr, 4, EProjectileAttrib::None, false, {}, 0xFFFF, false, zeus::CVector3f(1.f)); x578_bombTime = 0.f; x57c_curBomb = (x57c_curBomb + 1) & (x6dc_bombLocators.size() - 1); } else CPatterned::DoUserAnimEvent(mgr, node, type, dt); } bool CAtomicAlpha::Leash(CStateManager& mgr, float) { if ((mgr.GetPlayer().GetTranslation() - GetTranslation()).magSquared() <= x3cc_playerLeashRadius * x3cc_playerLeashRadius) return false; return x3d4_curPlayerLeashTime > x3d0_playerLeashTime; } bool CAtomicAlpha::AggressionCheck(CStateManager& mgr, float) { const CPlayerGun* playerGun = mgr.GetPlayer().GetPlayerGun(); float factor = 0.f; if (x568_26_applyBeamAttraction && playerGun->IsCharging()) factor = playerGun->GetChargeBeamFactor(); return factor > 0.1f; } void CAtomicAlpha::CollidedWith(TUniqueId uid, const CCollisionInfoList& list, CStateManager& mgr) { if (IsAlive()) { if (TCastToConstPtr<CPlayer> pl = mgr.GetObjectById(uid)) { if (x420_curDamageRemTime <= 0.f) { mgr.GetPlayerState()->GetStaticInterference().AddSource(GetUniqueId(), 0.5f, 0.25f); for (SBomb& bomb : x6dc_bombLocators) { bomb.x14_scaleTime = 0.f; } } } } CPatterned::CollidedWith(uid, list, mgr); } void CAtomicAlpha::Patrol(CStateManager& mgr, EStateMsg msg, float arg) { CPatterned::Patrol(mgr, msg, arg); if (msg == EStateMsg::Activate) { x578_bombTime = 0.f; } else if (msg == EStateMsg::Update) { if (x568_24_inRange) { if (x578_bombTime >= x56c_bomdDropDelay && x6dc_bombLocators[0].x14_scaleTime > (x570_bombReappearDelay + x574_bombRappearTime)) { x450_bodyController->SetLocomotionType(x6dc_bombLocators[x57c_curBomb].x10_locomotionType); } else { x450_bodyController->SetLocomotionType(pas::ELocomotionType::Relaxed); } if (Leash(mgr, arg)) x568_24_inRange = false; } else { x450_bodyController->SetLocomotionType(pas::ELocomotionType::Relaxed); if (InMaxRange(mgr, arg)) x568_24_inRange = true; } } else if (msg == EStateMsg::Deactivate) { x568_24_inRange = false; } } void CAtomicAlpha::Attack(CStateManager& mgr, EStateMsg msg, float) { if (msg == EStateMsg::Activate) { x450_bodyController->SetLocomotionType(pas::ELocomotionType::Internal8); } else if (msg == EStateMsg::Update) { zeus::CVector3f seekVec = x664_steeringBehaviors.Seek(*this, mgr.GetPlayer().GetEyePosition()); x450_bodyController->GetCommandMgr().DeliverCmd(CBCLocomotionCmd(seekVec, {}, 1.f)); } else if (msg == EStateMsg::Deactivate) { x450_bodyController->SetLocomotionType(pas::ELocomotionType::Relaxed); } } } // namespace urde::MP1 <|endoftext|>
<commit_before>/* * yosys -- Yosys Open SYnthesis Suite * * Copyright (C) 2012 Clifford Wolf <[email protected]> * * Permission to use, copy, modify, and/or distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. * * --- * * The Verilog frontend. * * This frontend is using the AST frontend library (see frontends/ast/). * Thus this frontend does not generate RTLIL code directly but creates an * AST directly from the Verilog parse tree and then passes this AST to * the AST frontend library. * * --- * * Ad-hoc implementation of a Verilog preprocessor. The directives `define, * `include, `ifdef, `ifndef, `else and `endif are handled here. All other * directives are handled by the lexer (see lexer.l). * */ #include "verilog_frontend.h" #include "kernel/log.h" #include <stdarg.h> #include <stdio.h> #include <string.h> YOSYS_NAMESPACE_BEGIN static std::list<std::string> output_code; static std::list<std::string> input_buffer; static size_t input_buffer_charp; static void return_char(char ch) { if (input_buffer_charp == 0) input_buffer.push_front(std::string() + ch); else input_buffer.front()[--input_buffer_charp] = ch; } static void insert_input(std::string str) { if (input_buffer_charp != 0) { input_buffer.front() = input_buffer.front().substr(input_buffer_charp); input_buffer_charp = 0; } input_buffer.push_front(str); } static char next_char() { if (input_buffer.empty()) return 0; log_assert(input_buffer_charp <= input_buffer.front().size()); if (input_buffer_charp == input_buffer.front().size()) { input_buffer_charp = 0; input_buffer.pop_front(); return next_char(); } char ch = input_buffer.front()[input_buffer_charp++]; return ch == '\r' ? next_char() : ch; } static std::string skip_spaces() { std::string spaces; while (1) { char ch = next_char(); if (ch == 0) break; if (ch != ' ' && ch != '\t') { return_char(ch); break; } spaces += ch; } return spaces; } static std::string next_token(bool pass_newline = false) { std::string token; char ch = next_char(); if (ch == 0) return token; token += ch; if (ch == '\n') { if (pass_newline) { output_code.push_back(token); return ""; } return token; } if (ch == ' ' || ch == '\t') { while ((ch = next_char()) != 0) { if (ch != ' ' && ch != '\t') { return_char(ch); break; } token += ch; } } else if (ch == '"') { while ((ch = next_char()) != 0) { token += ch; if (ch == '"') break; if (ch == '\\') { if ((ch = next_char()) != 0) token += ch; } } if (token == "\"\"" && (ch = next_char()) != 0) { if (ch == '"') token += ch; else return_char(ch); } } else if (ch == '/') { if ((ch = next_char()) != 0) { if (ch == '/') { token += '*'; char last_ch = 0; while ((ch = next_char()) != 0) { if (ch == '\n') { return_char(ch); break; } if (last_ch != '*' || ch != '/') { token += ch; last_ch = ch; } } token += " */"; } else if (ch == '*') { token += '*'; int newline_count = 0; char last_ch = 0; while ((ch = next_char()) != 0) { if (ch == '\n') { newline_count++; token += ' '; } else token += ch; if (last_ch == '*' && ch == '/') break; last_ch = ch; } while (newline_count-- > 0) return_char('\n'); } else return_char(ch); } } else { const char *ok = "abcdefghijklmnopqrstuvwxyz_ABCDEFGHIJKLMNOPQRSTUVWXYZ$0123456789"; if (ch == '`' || strchr(ok, ch) != NULL) while ((ch = next_char()) != 0) { if (strchr(ok, ch) == NULL) { return_char(ch); break; } token += ch; } } return token; } static void input_file(FILE *f, std::string filename) { char buffer[513]; int rc; insert_input(""); auto it = input_buffer.begin(); input_buffer.insert(it, "`file_push " + filename + "\n"); while ((rc = fread(buffer, 1, sizeof(buffer)-1, f)) > 0) { buffer[rc] = 0; input_buffer.insert(it, buffer); } input_buffer.insert(it, "\n`file_pop\n"); } std::string frontend_verilog_preproc(FILE *f, std::string filename, const std::map<std::string, std::string> pre_defines_map, const std::list<std::string> include_dirs) { std::set<std::string> defines_with_args; std::map<std::string, std::string> defines_map(pre_defines_map); int ifdef_fail_level = 0; bool in_elseif = false; output_code.clear(); input_buffer.clear(); input_buffer_charp = 0; input_file(f, filename); defines_map["__YOSYS__"] = "1"; while (!input_buffer.empty()) { std::string tok = next_token(); // printf("token: >>%s<<\n", tok != "\n" ? tok.c_str() : "NEWLINE"); if (tok == "`endif") { if (ifdef_fail_level > 0) ifdef_fail_level--; if (ifdef_fail_level == 0) in_elseif = false; continue; } if (tok == "`else") { if (ifdef_fail_level == 0) ifdef_fail_level = 1; else if (ifdef_fail_level == 1 && !in_elseif) ifdef_fail_level = 0; continue; } if (tok == "`elsif") { skip_spaces(); std::string name = next_token(true); if (ifdef_fail_level == 0) ifdef_fail_level = 1, in_elseif = true; else if (ifdef_fail_level == 1 && defines_map.count(name) != 0) ifdef_fail_level = 0, in_elseif = true; continue; } if (tok == "`ifdef") { skip_spaces(); std::string name = next_token(true); if (ifdef_fail_level > 0 || defines_map.count(name) == 0) ifdef_fail_level++; continue; } if (tok == "`ifndef") { skip_spaces(); std::string name = next_token(true); if (ifdef_fail_level > 0 || defines_map.count(name) != 0) ifdef_fail_level++; continue; } if (ifdef_fail_level > 0) { if (tok == "\n") output_code.push_back(tok); continue; } if (tok == "`include") { skip_spaces(); std::string fn = next_token(true); while (1) { size_t pos = fn.find('"'); if (pos == std::string::npos) break; if (pos == 0) fn = fn.substr(1); else fn = fn.substr(0, pos) + fn.substr(pos+1); } FILE *fp = fopen(fn.c_str(), "r"); if (fp == NULL && fn.size() > 0 && fn[0] != '/' && filename.find('/') != std::string::npos) { // if the include file was not found, it is not given with an absolute path, and the // currently read file is given with a path, then try again relative to its directory std::string fn2 = filename.substr(0, filename.rfind('/')+1) + fn; fp = fopen(fn2.c_str(), "r"); } if (fp == NULL && fn.size() > 0 && fn[0] != '/') { // if the include file was not found and it is not given with an absolute path, then // search it in the include path for (auto incdir : include_dirs) { std::string fn2 = incdir + '/' + fn; fp = fopen(fn2.c_str(), "r"); if (fp != NULL) break; } } if (fp != NULL) { input_file(fp, fn); fclose(fp); } else output_code.push_back("`file_notfound " + fn); continue; } if (tok == "`define") { std::string name, value; std::map<std::string, int> args; skip_spaces(); name = next_token(true); bool here_doc_mode = false; int newline_count = 0; int state = 0; if (skip_spaces() != "") state = 3; while (!tok.empty()) { tok = next_token(); if (tok == "\"\"\"") { here_doc_mode = !here_doc_mode; continue; } if (state == 0 && tok == "(") { state = 1; skip_spaces(); } else if (state == 1) { if (tok == ")") state = 2; else if (tok != ",") { int arg_idx = args.size()+1; args[tok] = arg_idx; } skip_spaces(); } else { if (state != 2) state = 3; if (tok == "\n" && !here_doc_mode) { return_char('\n'); break; } if (tok == "\\") { char ch = next_char(); if (ch == '\n') { value += " "; newline_count++; } else { value += std::string("\\"); return_char(ch); } } else if (args.count(tok) > 0) value += stringf("`macro_%s_arg%d", name.c_str(), args.at(tok)); else value += tok; } } while (newline_count-- > 0) return_char('\n'); // printf("define: >>%s<< -> >>%s<<\n", name.c_str(), value.c_str()); defines_map[name] = value; if (state == 2) defines_with_args.insert(name); else defines_with_args.erase(name); continue; } if (tok == "`undef") { std::string name; skip_spaces(); name = next_token(true); // printf("undef: >>%s<<\n", name.c_str()); defines_map.erase(name); defines_with_args.erase(name); continue; } if (tok == "`timescale") { skip_spaces(); while (!tok.empty() && tok != "\n") tok = next_token(true); if (tok == "\n") return_char('\n'); continue; } if (tok.size() > 1 && tok[0] == '`' && defines_map.count(tok.substr(1)) > 0) { std::string name = tok.substr(1); // printf("expand: >>%s<< -> >>%s<<\n", name.c_str(), defines_map[name].c_str()); std::string skipped_spaces = skip_spaces(); tok = next_token(false); if (tok == "(" && defines_with_args.count(name) > 0) { int level = 1; std::vector<std::string> args; args.push_back(std::string()); while (1) { tok = next_token(true); if (tok == ")" || tok == "}" || tok == "]") level--; if (level == 0) break; if (level == 1 && tok == ",") args.push_back(std::string()); else args.back() += tok; if (tok == "(" || tok == "{" || tok == "[") level++; } for (size_t i = 0; i < args.size(); i++) defines_map[stringf("macro_%s_arg%d", name.c_str(), i+1)] = args[i]; } else { insert_input(tok); insert_input(skipped_spaces); } insert_input(defines_map[name]); continue; } output_code.push_back(tok); } std::string output; for (auto &str : output_code) output += str; output_code.clear(); input_buffer.clear(); input_buffer_charp = 0; return output; } YOSYS_NAMESPACE_END <commit_msg>Fixed line numbers when using here-doc macros<commit_after>/* * yosys -- Yosys Open SYnthesis Suite * * Copyright (C) 2012 Clifford Wolf <[email protected]> * * Permission to use, copy, modify, and/or distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. * * --- * * The Verilog frontend. * * This frontend is using the AST frontend library (see frontends/ast/). * Thus this frontend does not generate RTLIL code directly but creates an * AST directly from the Verilog parse tree and then passes this AST to * the AST frontend library. * * --- * * Ad-hoc implementation of a Verilog preprocessor. The directives `define, * `include, `ifdef, `ifndef, `else and `endif are handled here. All other * directives are handled by the lexer (see lexer.l). * */ #include "verilog_frontend.h" #include "kernel/log.h" #include <stdarg.h> #include <stdio.h> #include <string.h> YOSYS_NAMESPACE_BEGIN static std::list<std::string> output_code; static std::list<std::string> input_buffer; static size_t input_buffer_charp; static void return_char(char ch) { if (input_buffer_charp == 0) input_buffer.push_front(std::string() + ch); else input_buffer.front()[--input_buffer_charp] = ch; } static void insert_input(std::string str) { if (input_buffer_charp != 0) { input_buffer.front() = input_buffer.front().substr(input_buffer_charp); input_buffer_charp = 0; } input_buffer.push_front(str); } static char next_char() { if (input_buffer.empty()) return 0; log_assert(input_buffer_charp <= input_buffer.front().size()); if (input_buffer_charp == input_buffer.front().size()) { input_buffer_charp = 0; input_buffer.pop_front(); return next_char(); } char ch = input_buffer.front()[input_buffer_charp++]; return ch == '\r' ? next_char() : ch; } static std::string skip_spaces() { std::string spaces; while (1) { char ch = next_char(); if (ch == 0) break; if (ch != ' ' && ch != '\t') { return_char(ch); break; } spaces += ch; } return spaces; } static std::string next_token(bool pass_newline = false) { std::string token; char ch = next_char(); if (ch == 0) return token; token += ch; if (ch == '\n') { if (pass_newline) { output_code.push_back(token); return ""; } return token; } if (ch == ' ' || ch == '\t') { while ((ch = next_char()) != 0) { if (ch != ' ' && ch != '\t') { return_char(ch); break; } token += ch; } } else if (ch == '"') { while ((ch = next_char()) != 0) { token += ch; if (ch == '"') break; if (ch == '\\') { if ((ch = next_char()) != 0) token += ch; } } if (token == "\"\"" && (ch = next_char()) != 0) { if (ch == '"') token += ch; else return_char(ch); } } else if (ch == '/') { if ((ch = next_char()) != 0) { if (ch == '/') { token += '*'; char last_ch = 0; while ((ch = next_char()) != 0) { if (ch == '\n') { return_char(ch); break; } if (last_ch != '*' || ch != '/') { token += ch; last_ch = ch; } } token += " */"; } else if (ch == '*') { token += '*'; int newline_count = 0; char last_ch = 0; while ((ch = next_char()) != 0) { if (ch == '\n') { newline_count++; token += ' '; } else token += ch; if (last_ch == '*' && ch == '/') break; last_ch = ch; } while (newline_count-- > 0) return_char('\n'); } else return_char(ch); } } else { const char *ok = "abcdefghijklmnopqrstuvwxyz_ABCDEFGHIJKLMNOPQRSTUVWXYZ$0123456789"; if (ch == '`' || strchr(ok, ch) != NULL) while ((ch = next_char()) != 0) { if (strchr(ok, ch) == NULL) { return_char(ch); break; } token += ch; } } return token; } static void input_file(FILE *f, std::string filename) { char buffer[513]; int rc; insert_input(""); auto it = input_buffer.begin(); input_buffer.insert(it, "`file_push " + filename + "\n"); while ((rc = fread(buffer, 1, sizeof(buffer)-1, f)) > 0) { buffer[rc] = 0; input_buffer.insert(it, buffer); } input_buffer.insert(it, "\n`file_pop\n"); } std::string frontend_verilog_preproc(FILE *f, std::string filename, const std::map<std::string, std::string> pre_defines_map, const std::list<std::string> include_dirs) { std::set<std::string> defines_with_args; std::map<std::string, std::string> defines_map(pre_defines_map); int ifdef_fail_level = 0; bool in_elseif = false; output_code.clear(); input_buffer.clear(); input_buffer_charp = 0; input_file(f, filename); defines_map["__YOSYS__"] = "1"; while (!input_buffer.empty()) { std::string tok = next_token(); // printf("token: >>%s<<\n", tok != "\n" ? tok.c_str() : "NEWLINE"); if (tok == "`endif") { if (ifdef_fail_level > 0) ifdef_fail_level--; if (ifdef_fail_level == 0) in_elseif = false; continue; } if (tok == "`else") { if (ifdef_fail_level == 0) ifdef_fail_level = 1; else if (ifdef_fail_level == 1 && !in_elseif) ifdef_fail_level = 0; continue; } if (tok == "`elsif") { skip_spaces(); std::string name = next_token(true); if (ifdef_fail_level == 0) ifdef_fail_level = 1, in_elseif = true; else if (ifdef_fail_level == 1 && defines_map.count(name) != 0) ifdef_fail_level = 0, in_elseif = true; continue; } if (tok == "`ifdef") { skip_spaces(); std::string name = next_token(true); if (ifdef_fail_level > 0 || defines_map.count(name) == 0) ifdef_fail_level++; continue; } if (tok == "`ifndef") { skip_spaces(); std::string name = next_token(true); if (ifdef_fail_level > 0 || defines_map.count(name) != 0) ifdef_fail_level++; continue; } if (ifdef_fail_level > 0) { if (tok == "\n") output_code.push_back(tok); continue; } if (tok == "`include") { skip_spaces(); std::string fn = next_token(true); while (1) { size_t pos = fn.find('"'); if (pos == std::string::npos) break; if (pos == 0) fn = fn.substr(1); else fn = fn.substr(0, pos) + fn.substr(pos+1); } FILE *fp = fopen(fn.c_str(), "r"); if (fp == NULL && fn.size() > 0 && fn[0] != '/' && filename.find('/') != std::string::npos) { // if the include file was not found, it is not given with an absolute path, and the // currently read file is given with a path, then try again relative to its directory std::string fn2 = filename.substr(0, filename.rfind('/')+1) + fn; fp = fopen(fn2.c_str(), "r"); } if (fp == NULL && fn.size() > 0 && fn[0] != '/') { // if the include file was not found and it is not given with an absolute path, then // search it in the include path for (auto incdir : include_dirs) { std::string fn2 = incdir + '/' + fn; fp = fopen(fn2.c_str(), "r"); if (fp != NULL) break; } } if (fp != NULL) { input_file(fp, fn); fclose(fp); } else output_code.push_back("`file_notfound " + fn); continue; } if (tok == "`define") { std::string name, value; std::map<std::string, int> args; skip_spaces(); name = next_token(true); bool here_doc_mode = false; int newline_count = 0; int state = 0; if (skip_spaces() != "") state = 3; while (!tok.empty()) { tok = next_token(); if (tok == "\"\"\"") { here_doc_mode = !here_doc_mode; continue; } if (state == 0 && tok == "(") { state = 1; skip_spaces(); } else if (state == 1) { if (tok == ")") state = 2; else if (tok != ",") { int arg_idx = args.size()+1; args[tok] = arg_idx; } skip_spaces(); } else { if (state != 2) state = 3; if (tok == "\n") { if (here_doc_mode) { value += " "; newline_count++; } else { return_char('\n'); break; } } else if (tok == "\\") { char ch = next_char(); if (ch == '\n') { value += " "; newline_count++; } else { value += std::string("\\"); return_char(ch); } } else if (args.count(tok) > 0) value += stringf("`macro_%s_arg%d", name.c_str(), args.at(tok)); else value += tok; } } while (newline_count-- > 0) return_char('\n'); // printf("define: >>%s<< -> >>%s<<\n", name.c_str(), value.c_str()); defines_map[name] = value; if (state == 2) defines_with_args.insert(name); else defines_with_args.erase(name); continue; } if (tok == "`undef") { std::string name; skip_spaces(); name = next_token(true); // printf("undef: >>%s<<\n", name.c_str()); defines_map.erase(name); defines_with_args.erase(name); continue; } if (tok == "`timescale") { skip_spaces(); while (!tok.empty() && tok != "\n") tok = next_token(true); if (tok == "\n") return_char('\n'); continue; } if (tok.size() > 1 && tok[0] == '`' && defines_map.count(tok.substr(1)) > 0) { std::string name = tok.substr(1); // printf("expand: >>%s<< -> >>%s<<\n", name.c_str(), defines_map[name].c_str()); std::string skipped_spaces = skip_spaces(); tok = next_token(false); if (tok == "(" && defines_with_args.count(name) > 0) { int level = 1; std::vector<std::string> args; args.push_back(std::string()); while (1) { tok = next_token(true); if (tok == ")" || tok == "}" || tok == "]") level--; if (level == 0) break; if (level == 1 && tok == ",") args.push_back(std::string()); else args.back() += tok; if (tok == "(" || tok == "{" || tok == "[") level++; } for (size_t i = 0; i < args.size(); i++) defines_map[stringf("macro_%s_arg%d", name.c_str(), i+1)] = args[i]; } else { insert_input(tok); insert_input(skipped_spaces); } insert_input(defines_map[name]); continue; } output_code.push_back(tok); } std::string output; for (auto &str : output_code) output += str; output_code.clear(); input_buffer.clear(); input_buffer_charp = 0; return output; } YOSYS_NAMESPACE_END <|endoftext|>
<commit_before>// // This file is part of the Marble Desktop Globe. // // This program is free software licensed under the GNU LGPL. You can // find a copy of this license in LICENSE.txt in the top directory of // the source code. // // Copyright 2011 Konstantin Oblaukhov <[email protected]> // #include "GeoGraphicsScene.h" #include "GeoDataLatLonAltBox.h" #include "GeoGraphicsItem.h" #include "TileId.h" #include "TileCoordsPyramid.h" #include "MarbleDebug.h" #include <QtCore/QMap> namespace Marble { bool zValueLessThan( GeoGraphicsItem* i1, GeoGraphicsItem* i2 ) { return i1->zValue() < i2->zValue(); } int GeoGraphicsScene::s_tileZoomLevel = 14; class GeoGraphicsScenePrivate { public: TileId coordToTileId( const GeoDataCoordinates& coord, int popularity ) const { if ( popularity < 0 ) { return TileId(); } int maxLat = 90000000; int maxLon = 180000000; int lat = coord.latitude( GeoDataCoordinates::Degree ) * 1000000; int lon = coord.longitude( GeoDataCoordinates::Degree ) * 1000000; int deltaLat, deltaLon; int x = 0; int y = 0; for( int i=0; i<popularity; ++i ) { deltaLat = maxLat >> i; if( lat < ( maxLat - deltaLat )) { y += 1<<(popularity-i-1); lat += deltaLat; } deltaLon = maxLon >> i; if( lon >= ( maxLon - deltaLon )) { x += 1<<(popularity-i-1); } else { lon += deltaLon; } } return TileId( "", popularity, x, y ); } QMap<TileId, QList<GeoGraphicsItem*> > m_items; }; GeoGraphicsScene::GeoGraphicsScene( QObject* parent ): QObject( parent ), d( new GeoGraphicsScenePrivate() ) { } GeoGraphicsScene::~GeoGraphicsScene() { delete d; } QList< GeoGraphicsItem* > GeoGraphicsScene::items() const { //TODO: insert items return QList< GeoGraphicsItem* >(); //return d->m_items; } QList< GeoGraphicsItem* > GeoGraphicsScene::items( const Marble::GeoDataLatLonAltBox& box ) const { QList< GeoGraphicsItem* > result; QRect rect; qreal north, south, east, west; box.boundaries( north, south, east, west ); TileId key; key = d->coordToTileId( GeoDataCoordinates(west, north, 0), s_tileZoomLevel ); rect.setLeft( key.x() ); rect.setTop( key.y() ); key = d->coordToTileId( GeoDataCoordinates(east, south, 0), s_tileZoomLevel ); rect.setRight( key.x() ); rect.setBottom( key.y() ); TileCoordsPyramid pyramid( 0, s_tileZoomLevel ); pyramid.setBottomLevelCoords( rect ); for ( int level = pyramid.topLevel(); level <= pyramid.bottomLevel(); ++level ) { QRect const coords = pyramid.coords( level ); int x1, y1, x2, y2; coords.getCoords( &x1, &y1, &x2, &y2 ); for ( int x = x1; x <= x2; ++x ) { for ( int y = y1; y <= y2; ++y ) { TileId const tileId( "", level, x, y ); result += d->m_items.value(tileId); } } } //TODO: Even quicksort isn't fast enouth... qSort( result.begin(), result.end(), zValueLessThan ); return result; } void GeoGraphicsScene::removeItem( GeoGraphicsItem* item ) { //TODO: Remove one item //d->m_items.removeOne( item ); } void GeoGraphicsScene::clear() { d->m_items.clear(); } void GeoGraphicsScene::addIdem( GeoGraphicsItem* item ) { // Select zoom level so that the object fit in single tile int zoomLevel; qreal north, south, east, west; item->latLonAltBox().boundaries( north, south, east, west ); for(zoomLevel = s_tileZoomLevel; zoomLevel >= 0; zoomLevel--) { if( d->coordToTileId( GeoDataCoordinates(west, north, 0), zoomLevel ) == d->coordToTileId( GeoDataCoordinates(east, south, 0), zoomLevel ) ) break; } int tnorth, tsouth, teast, twest; TileId key; key = d->coordToTileId( GeoDataCoordinates(west, north, 0), zoomLevel ); twest = key.x(); tnorth = key.y(); key = d->coordToTileId( GeoDataCoordinates(east, south, 0), zoomLevel ); teast = key.x(); tsouth = key.y(); for( int i = twest; i <= teast; i++ ) { for( int j = tsouth; j <= tnorth; j++ ) { QList< GeoGraphicsItem* >& tileList = d->m_items[TileId( "", zoomLevel, i, j )]; QList< GeoGraphicsItem* >::iterator position = qLowerBound( tileList.begin(), tileList.end(), item, zValueLessThan ); tileList.insert( position, item ); } } } }; #include "GeoGraphicsScene.moc" <commit_msg>New way to build object list in GeoGraphicsScene::items.<commit_after>// // This file is part of the Marble Desktop Globe. // // This program is free software licensed under the GNU LGPL. You can // find a copy of this license in LICENSE.txt in the top directory of // the source code. // // Copyright 2011 Konstantin Oblaukhov <[email protected]> // #include "GeoGraphicsScene.h" #include "GeoDataLatLonAltBox.h" #include "GeoGraphicsItem.h" #include "TileId.h" #include "TileCoordsPyramid.h" #include "MarbleDebug.h" #include <QtCore/QMap> namespace Marble { bool zValueLessThan( GeoGraphicsItem* i1, GeoGraphicsItem* i2 ) { return i1->zValue() < i2->zValue(); } int GeoGraphicsScene::s_tileZoomLevel = 14; class GeoGraphicsScenePrivate { public: TileId coordToTileId( const GeoDataCoordinates& coord, int popularity ) const { if ( popularity < 0 ) { return TileId(); } int maxLat = 90000000; int maxLon = 180000000; int lat = coord.latitude( GeoDataCoordinates::Degree ) * 1000000; int lon = coord.longitude( GeoDataCoordinates::Degree ) * 1000000; int deltaLat, deltaLon; int x = 0; int y = 0; for( int i=0; i<popularity; ++i ) { deltaLat = maxLat >> i; if( lat < ( maxLat - deltaLat )) { y += 1<<(popularity-i-1); lat += deltaLat; } deltaLon = maxLon >> i; if( lon >= ( maxLon - deltaLon )) { x += 1<<(popularity-i-1); } else { lon += deltaLon; } } return TileId( "", popularity, x, y ); } QMap<TileId, QList<GeoGraphicsItem*> > m_items; }; GeoGraphicsScene::GeoGraphicsScene( QObject* parent ): QObject( parent ), d( new GeoGraphicsScenePrivate() ) { } GeoGraphicsScene::~GeoGraphicsScene() { delete d; } QList< GeoGraphicsItem* > GeoGraphicsScene::items() const { //TODO: insert items return QList< GeoGraphicsItem* >(); //return d->m_items; } QList< GeoGraphicsItem* > GeoGraphicsScene::items( const Marble::GeoDataLatLonAltBox& box ) const { QList< GeoGraphicsItem* > result; QRect rect; qreal north, south, east, west; box.boundaries( north, south, east, west ); TileId key; key = d->coordToTileId( GeoDataCoordinates(west, north, 0), s_tileZoomLevel ); rect.setLeft( key.x() ); rect.setTop( key.y() ); key = d->coordToTileId( GeoDataCoordinates(east, south, 0), s_tileZoomLevel ); rect.setRight( key.x() ); rect.setBottom( key.y() ); TileCoordsPyramid pyramid( 0, s_tileZoomLevel ); pyramid.setBottomLevelCoords( rect ); for ( int level = pyramid.topLevel(); level <= pyramid.bottomLevel(); ++level ) { QRect const coords = pyramid.coords( level ); int x1, y1, x2, y2; coords.getCoords( &x1, &y1, &x2, &y2 ); for ( int x = x1; x <= x2; ++x ) { for ( int y = y1; y <= y2; ++y ) { TileId const tileId( "", level, x, y ); const QList< GeoGraphicsItem* > &objects = d->m_items.value(tileId); QList< GeoGraphicsItem* >::iterator before = result.begin(); QList< GeoGraphicsItem* >::const_iterator currentItem = objects.constBegin(); while( currentItem != objects.end() ) { while( ( currentItem != objects.end() ) && ( ( before == result.end() ) || ( (*currentItem)->zValue() < (*before)->zValue() ) ) ) { before = result.insert( before, *currentItem ); currentItem++; } if ( before != result.end() ) before++; } } } } return result; } void GeoGraphicsScene::removeItem( GeoGraphicsItem* item ) { //TODO: Remove one item //d->m_items.removeOne( item ); } void GeoGraphicsScene::clear() { d->m_items.clear(); } void GeoGraphicsScene::addIdem( GeoGraphicsItem* item ) { // Select zoom level so that the object fit in single tile int zoomLevel; qreal north, south, east, west; item->latLonAltBox().boundaries( north, south, east, west ); for(zoomLevel = s_tileZoomLevel; zoomLevel >= 0; zoomLevel--) { if( d->coordToTileId( GeoDataCoordinates(west, north, 0), zoomLevel ) == d->coordToTileId( GeoDataCoordinates(east, south, 0), zoomLevel ) ) break; } int tnorth, tsouth, teast, twest; TileId key; key = d->coordToTileId( GeoDataCoordinates(west, north, 0), zoomLevel ); twest = key.x(); tnorth = key.y(); key = d->coordToTileId( GeoDataCoordinates(east, south, 0), zoomLevel ); teast = key.x(); tsouth = key.y(); for( int i = twest; i <= teast; i++ ) { for( int j = tsouth; j <= tnorth; j++ ) { QList< GeoGraphicsItem* >& tileList = d->m_items[TileId( "", zoomLevel, i, j )]; QList< GeoGraphicsItem* >::iterator position = qLowerBound( tileList.begin(), tileList.end(), item, zValueLessThan ); tileList.insert( position, item ); } } } }; #include "GeoGraphicsScene.moc" <|endoftext|>
<commit_before>#include <cstdio> #include <cwctype> #include <algorithm> #include "../vendor/hunspell/src/hunspell/hunspell.hxx" #include "../vendor/hunspell/src/hunspell/csutil.hxx" #include "spellchecker_hunspell.h" namespace spellchecker { HunspellSpellchecker::HunspellSpellchecker() : hunspell(NULL) { } HunspellSpellchecker::~HunspellSpellchecker() { if (hunspell) { delete hunspell; } } bool HunspellSpellchecker::SetDictionary(const std::string& language, const std::string& dirname) { if (hunspell) { delete hunspell; hunspell = NULL; } // NB: Hunspell uses underscore to separate language and locale, and Win8 uses // dash - if they use the wrong one, just silently replace it for them std::string lang = language; std::replace(lang.begin(), lang.end(), '-', '_'); std::string affixpath = dirname + "/" + lang + ".aff"; std::string dpath = dirname + "/" + lang + ".dic"; // TODO: This code is almost certainly jacked on Win32 for non-ASCII paths FILE* handle = fopen(dpath.c_str(), "r"); if (!handle) { return false; } fclose(handle); hunspell = new Hunspell(affixpath.c_str(), dpath.c_str()); return true; } std::vector<std::string> HunspellSpellchecker::GetAvailableDictionaries(const std::string& path) { return std::vector<std::string>(); } bool HunspellSpellchecker::IsMisspelled(const std::string& word) { if (!hunspell) { return false; } return hunspell->spell(word.c_str()) == 0; } std::vector<MisspelledRange> HunspellSpellchecker::CheckSpelling(const uint16_t *utf16_text, size_t utf16_length) { std::vector<MisspelledRange> result; return result; } void HunspellSpellchecker::Add(const std::string& word) { if (hunspell) { hunspell->add(word.c_str()); } } std::vector<std::string> HunspellSpellchecker::GetCorrectionsForMisspelling(const std::string& word) { std::vector<std::string> corrections; if (hunspell) { char** slist; int size = hunspell->suggest(&slist, word.c_str()); corrections.reserve(size); for (int i = 0; i < size; ++i) { corrections.push_back(slist[i]); } hunspell->free_list(&slist, size); } return corrections; } } // namespace spellchecker <commit_msg>Add real hunspell impl for bulk spell-checking function<commit_after>#include <cstdio> #include <cwctype> #include <algorithm> #include "../vendor/hunspell/src/hunspell/hunspell.hxx" #include "../vendor/hunspell/src/hunspell/csutil.hxx" #include "spellchecker_hunspell.h" namespace spellchecker { HunspellSpellchecker::HunspellSpellchecker() : hunspell(NULL) { } HunspellSpellchecker::~HunspellSpellchecker() { if (hunspell) { delete hunspell; } } bool HunspellSpellchecker::SetDictionary(const std::string& language, const std::string& dirname) { if (hunspell) { delete hunspell; hunspell = NULL; } // NB: Hunspell uses underscore to separate language and locale, and Win8 uses // dash - if they use the wrong one, just silently replace it for them std::string lang = language; std::replace(lang.begin(), lang.end(), '-', '_'); std::string affixpath = dirname + "/" + lang + ".aff"; std::string dpath = dirname + "/" + lang + ".dic"; // TODO: This code is almost certainly jacked on Win32 for non-ASCII paths FILE* handle = fopen(dpath.c_str(), "r"); if (!handle) { return false; } fclose(handle); hunspell = new Hunspell(affixpath.c_str(), dpath.c_str()); return true; } std::vector<std::string> HunspellSpellchecker::GetAvailableDictionaries(const std::string& path) { return std::vector<std::string>(); } bool HunspellSpellchecker::IsMisspelled(const std::string& word) { if (!hunspell) { return false; } return hunspell->spell(word.c_str()) == 0; } std::vector<MisspelledRange> HunspellSpellchecker::CheckSpelling(const uint16_t *utf16_text, size_t utf16_length) { std::vector<MisspelledRange> result; if (!hunspell) { return result; } std::vector<char> utf8_buffer(256); char *utf8_word = utf8_buffer.data(); bool within_word = false; size_t word_start = 0; for (size_t i = 0; i <= utf16_length; i++) { bool is_alpha = i < utf16_length && std::iswalpha(utf16_text[i]); if (within_word) { if (!is_alpha) { within_word = false; const w_char *utf16_word = reinterpret_cast<const w_char *>(utf16_text + word_start); u16_u8(utf8_word, utf8_buffer.size(), utf16_word, i - word_start); if (hunspell->spell(utf8_word) == 0) { MisspelledRange range; range.start = word_start; range.end = i; result.push_back(range); } } } else if (is_alpha) { word_start = i; within_word = true; } } return result; } void HunspellSpellchecker::Add(const std::string& word) { if (hunspell) { hunspell->add(word.c_str()); } } std::vector<std::string> HunspellSpellchecker::GetCorrectionsForMisspelling(const std::string& word) { std::vector<std::string> corrections; if (hunspell) { char** slist; int size = hunspell->suggest(&slist, word.c_str()); corrections.reserve(size); for (int i = 0; i < size; ++i) { corrections.push_back(slist[i]); } hunspell->free_list(&slist, size); } return corrections; } } // namespace spellchecker <|endoftext|>
<commit_before>/* * GameKeeper Framework * * Copyright (C) 2013 Karol Herbst <[email protected]> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include "pch.h" #include <algorithm> #include <chrono> #include <iostream> #include <iterator> #include <sstream> #include <vector> #include <std_compat/thread> #include <gamekeeper/core/curlfiledownloader.h> #include <gamekeeper/core/logger.h> #include <gamekeeper/core/loggerFactory.h> #include <gamekeeper/core/loggerStream.h> #include <boost/algorithm/string/classification.hpp> #include <boost/algorithm/string/replace.hpp> #include <boost/algorithm/string/split.hpp> #include <boost/filesystem/fstream.hpp> #include <boost/filesystem/operations.hpp> #include <boost/filesystem/path.hpp> #include <boost/iostreams/device/array.hpp> #include <boost/iostreams/stream.hpp> #include <curl/curl.h> namespace algo = boost::algorithm; namespace fs = boost::filesystem; GAMEKEEPER_NAMESPACE_START(core) class PRIVATE_API CurlFileDownloadInfo { public: PRIVATE_API CurlFileDownloadInfo(const FileDownloader::DownloadCallback * _func, uint64_t _maxBufferSize, const fs::path & _path) : maxBufferSize(_maxBufferSize), func(_func), path(_path){} PRIVATE_API uint64_t bytesDownloaded(); PRIVATE_API bool addData(void * const buffer, uint64_t bytes); PRIVATE_API void callback(); private: const uint64_t maxBufferSize; const FileDownloader::DownloadCallback * func; const fs::path path; std::vector<gkbyte_t> dataBuffer; uint64_t _bytesDownloaded = 0; }; uint64_t CurlFileDownloadInfo::bytesDownloaded() { return this->_bytesDownloaded; } bool CurlFileDownloadInfo::addData(void * const buffer, uint64_t bytes) { gkbyte_t * newData = static_cast<gkbyte_t *>(buffer); // check amount of downloaded bytes to know if we use a file or buffer stream if(this->bytesDownloaded() <= (this->maxBufferSize * 1024)) { // the buffer might be too small for the new data, so check it before if((this->dataBuffer.size() + bytes) > (this->maxBufferSize * 1024)) { // first create directories if(!fs::exists(this->path.parent_path())) { fs::create_directories(this->path.parent_path()); } fs::basic_ofstream<gkbyte_t> ofs(this->path, std::ios_base::trunc | std::ios_base::binary); ofs.write(this->dataBuffer.data(), this->dataBuffer.size()); ofs.write(newData, bytes); ofs.close(); // clear internal buffer this->dataBuffer.clear(); } else { this->dataBuffer.insert(this->dataBuffer.end(), newData, &newData[bytes]); } } else { fs::basic_ofstream<gkbyte_t> ofs(this->path, std::ios_base::app | std::ios_base::binary); ofs.write(newData, bytes); } this->_bytesDownloaded += bytes; return true; } void CurlFileDownloadInfo::callback() { if(bytesDownloaded() <= (this->maxBufferSize * 1024)) { namespace bio = boost::iostreams; bio::stream<bio::basic_array_source<gkbyte_t>> stream(this->dataBuffer.data(), this->dataBuffer.size()); stream.peek(); (*this->func)(stream); } else { fs::basic_ifstream<gkbyte_t> ifs(this->path); (*this->func)(ifs); ifs.close(); fs::remove(this->path); } } class PRIVATE_API CURLPrivateData { public: PRIVATE_API CURLPrivateData(const char * const url, const std::string & userAgent, std::shared_ptr<PropertyResolver>); PRIVATE_API ~CURLPrivateData(); CURL * handle; std::string postData; CurlFileDownloadInfo * downloadInfo = nullptr; uint16_t resolveFailed = 0; uint16_t connectFailed = 0; }; CURLPrivateData::CURLPrivateData(const char * const url, const std::string & userAgent, std::shared_ptr<PropertyResolver> pr) : handle(curl_easy_init()) { curl_easy_setopt(this->handle, CURLOPT_URL, url); curl_easy_setopt(this->handle, CURLOPT_NOSIGNAL, 1); curl_easy_setopt(this->handle, CURLOPT_USERAGENT, userAgent.c_str()); curl_easy_setopt(this->handle, CURLOPT_CONNECTTIMEOUT_MS, pr->get<uint16_t>("network.connection.timeout")); } CURLPrivateData::~CURLPrivateData() { if(this->downloadInfo != nullptr) { delete downloadInfo; } curl_easy_cleanup(this->handle); } static uint64_t curlFileDownloadCallback(void * const buffer, size_t size, size_t nrMem, CURLPrivateData * data) { uint64_t sizeInBytes = size * nrMem; CurlFileDownloadInfo * info = data->downloadInfo; if(!info->addData(buffer, sizeInBytes)) { return -1; } return sizeInBytes; } static uint64_t emptyCurlFileDownloadCallback(void * const, size_t size, size_t nrMem, void *) { return size * nrMem; } static std::string buildUserAgentString(const boost::any & configValue) { if(configValue.empty()) { return std::string("GameKeeper/0.1 libcurl/") + curl_version_info(CURLVERSION_NOW)->version; } return boost::any_cast<std::string>(configValue); } const std::unordered_set<std::string> CurlFileDownloader::supportedProtocols = {"http", "https", "ftp", "ftps", "sftp"}; CurlFileDownloader::CurlFileDownloader(std::shared_ptr<LoggerFactory> loggerFactory, std::shared_ptr<PropertyResolver> _propertyResolver, std::shared_ptr<OSPaths> _ospaths) : propertyResolver(_propertyResolver), ospaths(_ospaths), logger(loggerFactory->getComponentLogger("IO.curl")), userAgent(buildUserAgentString(_propertyResolver->get("network.user_agent"))) { logger << LogLevel::Debug << "init curl with user-agent: " << this->userAgent << endl; curl_global_init(CURL_GLOBAL_SSL); } CurlFileDownloader::~CurlFileDownloader() { curl_global_cleanup(); } void CurlFileDownloader::handleFileDownload(CURLPrivateData & curl, FileDownloader::DownloadCallback * func, const char * const url) { boost::filesystem::path downloadPath = this->resolveDownloadPath(url); this->logger << LogLevel::Debug << "try to download file from: " << url << " at: " << downloadPath.string() << endl; curl.downloadInfo = new CurlFileDownloadInfo(func, this->propertyResolver->get<uint32_t>("network.download.max_buffer_size"), downloadPath); curl_easy_setopt(curl.handle, CURLOPT_WRITEFUNCTION, &curlFileDownloadCallback); curl_easy_setopt(curl.handle, CURLOPT_WRITEDATA, &curl); this->performCurl(curl); curl.downloadInfo->callback(); } static void addCookiesToCurl(const HttpFileDownloader::CookieBuket& cookies, CURLPrivateData & curl) { if(!cookies.empty()) { std::ostringstream cookieLineBuilder; for (const HttpFileDownloader::Cookie cookie : cookies) { cookieLineBuilder << cookie.first << '=' << cookie.second << ";"; } std::string cookieLine = cookieLineBuilder.str(); curl_easy_setopt(curl.handle, CURLOPT_COOKIE, cookieLine.c_str()); } } static HttpFileDownloader::CookieBuket getCookies(CURLPrivateData & curl) { struct curl_slist * list; HttpFileDownloader::CookieBuket result; curl_easy_getinfo(curl.handle, CURLINFO_COOKIELIST, &list); while(list != nullptr) { std::vector<std::string> strings; boost::split(strings, list->data, boost::is_any_of("\t")); result[strings[5]] = strings[6]; list = list->next; } curl_slist_free_all(list); return result; } static void addFormToCurl(const HttpFileDownloader::Form& form, CURLPrivateData & curl) { if(!form.empty()) { std::ostringstream cookieLineBuilder; for (const HttpFileDownloader::FormField formField : form) { cookieLineBuilder << formField.first << '=' << formField.second << '&'; } curl.postData = cookieLineBuilder.str(); curl_easy_setopt(curl.handle, CURLOPT_POSTFIELDS, curl.postData.c_str()); } } bool CurlFileDownloader::supportsProtocol(const char * const protocolName) { return supportedProtocols.find(protocolName) != supportedProtocols.end(); } void CurlFileDownloader::downloadFile(const char * const url, DownloadCallback callback) { CURLPrivateData curl(url, this->userAgent, this->propertyResolver); this->handleFileDownload(curl, &callback, url); } void CurlFileDownloader::downloadFileWithCookies(const char * const url, DownloadCallback callback, const CookieBuket& cookies) { CURLPrivateData curl(url, this->userAgent, this->propertyResolver); addCookiesToCurl(cookies, curl); this->handleFileDownload(curl, &callback, url); } CurlFileDownloader::CookieBuket CurlFileDownloader::doPostRequestForCookies(const char * const url, const Form& form) { this->logger << LogLevel::Debug << "try to fetch cookies at: " << url << endl; CURLPrivateData curl(url, this->userAgent, this->propertyResolver); curl_easy_setopt(curl.handle, CURLOPT_WRITEFUNCTION, &emptyCurlFileDownloadCallback); curl_easy_setopt(curl.handle, CURLOPT_COOKIEJAR, nullptr); addFormToCurl(form, curl); this->performCurl(curl); CurlFileDownloader::CookieBuket result = getCookies(curl); return result; } void CurlFileDownloader::performCurl(CURLPrivateData & curl, uint32_t timeout) { if(timeout > 0) { std::this_thread::sleep_for(std::chrono::milliseconds(timeout)); } CURLcode code = curl_easy_perform(curl.handle); switch (code) { case CURLE_OK: // 0 // everything okay this->logger << LogLevel::Trace << "CURL returned without errors" << endl; break; case CURLE_COULDNT_RESOLVE_HOST: // 6 curl.resolveFailed++; if(curl.resolveFailed < this->propertyResolver->get<uint16_t>("network.resolve.retries")) { this->logger << LogLevel::Warn << "CURL couldn't resolve host, retrying" << endl; this->performCurl(curl, this->propertyResolver->get<uint16_t>("network.time_between_retries")); } else { this->logger << LogLevel::Error << "CURL couldn't resolve host after " << curl.resolveFailed << " retries" << endl; } break; case CURLE_COULDNT_CONNECT: // 7 curl.connectFailed++; if(curl.connectFailed < this->propertyResolver->get<uint16_t>("network.connection.retries")) { this->logger << LogLevel::Warn << "CURL couldn't connect to host, retrying" << endl; this->performCurl(curl, this->propertyResolver->get<uint16_t>("network.time_between_retries")); } else { this->logger << LogLevel::Error << "CURL couldn't connect to host after " << curl.connectFailed << " retries" << endl; } break; default: // unhandled error this->logger << LogLevel::Fatal << "CURL error \"" << curl_easy_strerror(code) << "\" (" << code << ") unhandled, please report a bug" << endl; break; } } boost::filesystem::path CurlFileDownloader::resolveDownloadPath(const char * const url) { std::string uri = url; // frist cut the protocoll size_t pos = uri.find("://"); uri.erase(0, pos + 3); // now replace some unsupported characters algo::replace_all(uri, ":", "_"); return this->ospaths->getCacheFile(std::string("downloads/" + uri)); } GAMEKEEPER_NAMESPACE_END(core) <commit_msg>core/curl: also add ssl and libz information in the generated user-agent string<commit_after>/* * GameKeeper Framework * * Copyright (C) 2013 Karol Herbst <[email protected]> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include "pch.h" #include <algorithm> #include <chrono> #include <iostream> #include <iterator> #include <sstream> #include <vector> #include <std_compat/thread> #include <gamekeeper/core/curlfiledownloader.h> #include <gamekeeper/core/logger.h> #include <gamekeeper/core/loggerFactory.h> #include <gamekeeper/core/loggerStream.h> #include <boost/algorithm/string/classification.hpp> #include <boost/algorithm/string/replace.hpp> #include <boost/algorithm/string/split.hpp> #include <boost/filesystem/fstream.hpp> #include <boost/filesystem/operations.hpp> #include <boost/filesystem/path.hpp> #include <boost/iostreams/device/array.hpp> #include <boost/iostreams/stream.hpp> #include <curl/curl.h> namespace algo = boost::algorithm; namespace fs = boost::filesystem; GAMEKEEPER_NAMESPACE_START(core) class PRIVATE_API CurlFileDownloadInfo { public: PRIVATE_API CurlFileDownloadInfo(const FileDownloader::DownloadCallback * _func, uint64_t _maxBufferSize, const fs::path & _path) : maxBufferSize(_maxBufferSize), func(_func), path(_path){} PRIVATE_API uint64_t bytesDownloaded(); PRIVATE_API bool addData(void * const buffer, uint64_t bytes); PRIVATE_API void callback(); private: const uint64_t maxBufferSize; const FileDownloader::DownloadCallback * func; const fs::path path; std::vector<gkbyte_t> dataBuffer; uint64_t _bytesDownloaded = 0; }; uint64_t CurlFileDownloadInfo::bytesDownloaded() { return this->_bytesDownloaded; } bool CurlFileDownloadInfo::addData(void * const buffer, uint64_t bytes) { gkbyte_t * newData = static_cast<gkbyte_t *>(buffer); // check amount of downloaded bytes to know if we use a file or buffer stream if(this->bytesDownloaded() <= (this->maxBufferSize * 1024)) { // the buffer might be too small for the new data, so check it before if((this->dataBuffer.size() + bytes) > (this->maxBufferSize * 1024)) { // first create directories if(!fs::exists(this->path.parent_path())) { fs::create_directories(this->path.parent_path()); } fs::basic_ofstream<gkbyte_t> ofs(this->path, std::ios_base::trunc | std::ios_base::binary); ofs.write(this->dataBuffer.data(), this->dataBuffer.size()); ofs.write(newData, bytes); ofs.close(); // clear internal buffer this->dataBuffer.clear(); } else { this->dataBuffer.insert(this->dataBuffer.end(), newData, &newData[bytes]); } } else { fs::basic_ofstream<gkbyte_t> ofs(this->path, std::ios_base::app | std::ios_base::binary); ofs.write(newData, bytes); } this->_bytesDownloaded += bytes; return true; } void CurlFileDownloadInfo::callback() { if(bytesDownloaded() <= (this->maxBufferSize * 1024)) { namespace bio = boost::iostreams; bio::stream<bio::basic_array_source<gkbyte_t>> stream(this->dataBuffer.data(), this->dataBuffer.size()); stream.peek(); (*this->func)(stream); } else { fs::basic_ifstream<gkbyte_t> ifs(this->path); (*this->func)(ifs); ifs.close(); fs::remove(this->path); } } class PRIVATE_API CURLPrivateData { public: PRIVATE_API CURLPrivateData(const char * const url, const std::string & userAgent, std::shared_ptr<PropertyResolver>); PRIVATE_API ~CURLPrivateData(); CURL * handle; std::string postData; CurlFileDownloadInfo * downloadInfo = nullptr; uint16_t resolveFailed = 0; uint16_t connectFailed = 0; }; CURLPrivateData::CURLPrivateData(const char * const url, const std::string & userAgent, std::shared_ptr<PropertyResolver> pr) : handle(curl_easy_init()) { curl_easy_setopt(this->handle, CURLOPT_URL, url); curl_easy_setopt(this->handle, CURLOPT_NOSIGNAL, 1); curl_easy_setopt(this->handle, CURLOPT_USERAGENT, userAgent.c_str()); curl_easy_setopt(this->handle, CURLOPT_CONNECTTIMEOUT_MS, pr->get<uint16_t>("network.connection.timeout")); } CURLPrivateData::~CURLPrivateData() { if(this->downloadInfo != nullptr) { delete downloadInfo; } curl_easy_cleanup(this->handle); } static uint64_t curlFileDownloadCallback(void * const buffer, size_t size, size_t nrMem, CURLPrivateData * data) { uint64_t sizeInBytes = size * nrMem; CurlFileDownloadInfo * info = data->downloadInfo; if(!info->addData(buffer, sizeInBytes)) { return -1; } return sizeInBytes; } static uint64_t emptyCurlFileDownloadCallback(void * const, size_t size, size_t nrMem, void *) { return size * nrMem; } static std::string buildUserAgentString(const boost::any & configValue) { if(configValue.empty()) { curl_version_info_data * data = curl_version_info(CURLVERSION_NOW); return std::string("GameKeeper/0.1 libcurl/") + data->version + ' ' + data->ssl_version + " zlib/" + data->libz_version; } return boost::any_cast<std::string>(configValue); } const std::unordered_set<std::string> CurlFileDownloader::supportedProtocols = {"http", "https", "ftp", "ftps", "sftp"}; CurlFileDownloader::CurlFileDownloader(std::shared_ptr<LoggerFactory> loggerFactory, std::shared_ptr<PropertyResolver> _propertyResolver, std::shared_ptr<OSPaths> _ospaths) : propertyResolver(_propertyResolver), ospaths(_ospaths), logger(loggerFactory->getComponentLogger("IO.curl")), userAgent(buildUserAgentString(_propertyResolver->get("network.user_agent"))) { logger << LogLevel::Debug << "init curl with user-agent: " << this->userAgent << endl; curl_global_init(CURL_GLOBAL_SSL); } CurlFileDownloader::~CurlFileDownloader() { curl_global_cleanup(); } void CurlFileDownloader::handleFileDownload(CURLPrivateData & curl, FileDownloader::DownloadCallback * func, const char * const url) { boost::filesystem::path downloadPath = this->resolveDownloadPath(url); this->logger << LogLevel::Debug << "try to download file from: " << url << " at: " << downloadPath.string() << endl; curl.downloadInfo = new CurlFileDownloadInfo(func, this->propertyResolver->get<uint32_t>("network.download.max_buffer_size"), downloadPath); curl_easy_setopt(curl.handle, CURLOPT_WRITEFUNCTION, &curlFileDownloadCallback); curl_easy_setopt(curl.handle, CURLOPT_WRITEDATA, &curl); this->performCurl(curl); curl.downloadInfo->callback(); } static void addCookiesToCurl(const HttpFileDownloader::CookieBuket& cookies, CURLPrivateData & curl) { if(!cookies.empty()) { std::ostringstream cookieLineBuilder; for (const HttpFileDownloader::Cookie cookie : cookies) { cookieLineBuilder << cookie.first << '=' << cookie.second << ";"; } std::string cookieLine = cookieLineBuilder.str(); curl_easy_setopt(curl.handle, CURLOPT_COOKIE, cookieLine.c_str()); } } static HttpFileDownloader::CookieBuket getCookies(CURLPrivateData & curl) { struct curl_slist * list; HttpFileDownloader::CookieBuket result; curl_easy_getinfo(curl.handle, CURLINFO_COOKIELIST, &list); while(list != nullptr) { std::vector<std::string> strings; boost::split(strings, list->data, boost::is_any_of("\t")); result[strings[5]] = strings[6]; list = list->next; } curl_slist_free_all(list); return result; } static void addFormToCurl(const HttpFileDownloader::Form& form, CURLPrivateData & curl) { if(!form.empty()) { std::ostringstream cookieLineBuilder; for (const HttpFileDownloader::FormField formField : form) { cookieLineBuilder << formField.first << '=' << formField.second << '&'; } curl.postData = cookieLineBuilder.str(); curl_easy_setopt(curl.handle, CURLOPT_POSTFIELDS, curl.postData.c_str()); } } bool CurlFileDownloader::supportsProtocol(const char * const protocolName) { return supportedProtocols.find(protocolName) != supportedProtocols.end(); } void CurlFileDownloader::downloadFile(const char * const url, DownloadCallback callback) { CURLPrivateData curl(url, this->userAgent, this->propertyResolver); this->handleFileDownload(curl, &callback, url); } void CurlFileDownloader::downloadFileWithCookies(const char * const url, DownloadCallback callback, const CookieBuket& cookies) { CURLPrivateData curl(url, this->userAgent, this->propertyResolver); addCookiesToCurl(cookies, curl); this->handleFileDownload(curl, &callback, url); } CurlFileDownloader::CookieBuket CurlFileDownloader::doPostRequestForCookies(const char * const url, const Form& form) { this->logger << LogLevel::Debug << "try to fetch cookies at: " << url << endl; CURLPrivateData curl(url, this->userAgent, this->propertyResolver); curl_easy_setopt(curl.handle, CURLOPT_WRITEFUNCTION, &emptyCurlFileDownloadCallback); curl_easy_setopt(curl.handle, CURLOPT_COOKIEJAR, nullptr); addFormToCurl(form, curl); this->performCurl(curl); CurlFileDownloader::CookieBuket result = getCookies(curl); return result; } void CurlFileDownloader::performCurl(CURLPrivateData & curl, uint32_t timeout) { if(timeout > 0) { std::this_thread::sleep_for(std::chrono::milliseconds(timeout)); } CURLcode code = curl_easy_perform(curl.handle); switch (code) { case CURLE_OK: // 0 // everything okay this->logger << LogLevel::Trace << "CURL returned without errors" << endl; break; case CURLE_COULDNT_RESOLVE_HOST: // 6 curl.resolveFailed++; if(curl.resolveFailed < this->propertyResolver->get<uint16_t>("network.resolve.retries")) { this->logger << LogLevel::Warn << "CURL couldn't resolve host, retrying" << endl; this->performCurl(curl, this->propertyResolver->get<uint16_t>("network.time_between_retries")); } else { this->logger << LogLevel::Error << "CURL couldn't resolve host after " << curl.resolveFailed << " retries" << endl; } break; case CURLE_COULDNT_CONNECT: // 7 curl.connectFailed++; if(curl.connectFailed < this->propertyResolver->get<uint16_t>("network.connection.retries")) { this->logger << LogLevel::Warn << "CURL couldn't connect to host, retrying" << endl; this->performCurl(curl, this->propertyResolver->get<uint16_t>("network.time_between_retries")); } else { this->logger << LogLevel::Error << "CURL couldn't connect to host after " << curl.connectFailed << " retries" << endl; } break; default: // unhandled error this->logger << LogLevel::Fatal << "CURL error \"" << curl_easy_strerror(code) << "\" (" << code << ") unhandled, please report a bug" << endl; break; } } boost::filesystem::path CurlFileDownloader::resolveDownloadPath(const char * const url) { std::string uri = url; // frist cut the protocoll size_t pos = uri.find("://"); uri.erase(0, pos + 3); // now replace some unsupported characters algo::replace_all(uri, ":", "_"); return this->ospaths->getCacheFile(std::string("downloads/" + uri)); } GAMEKEEPER_NAMESPACE_END(core) <|endoftext|>
<commit_before>/********************************************************************************* * * Inviwo - Interactive Visualization Workshop * * Copyright (c) 2016 Inviwo Foundation * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT 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. * *********************************************************************************/ #include <inviwo/core/util/sharedlibrary.h> #include <inviwo/core/util/filesystem.h> #include <inviwo/core/util/stringconversion.h> // splitString #include <codecvt> #include <locale> #if WIN32 #define NOMINMAX #define WIN32_LEAN_AND_MEAN #include <windows.h> #else #include <dlfcn.h> #endif namespace inviwo { SharedLibrary::SharedLibrary(std::string filePath) : filePath_(filePath) { #if WIN32 // Search for dlls in directories specified by the path environment variable // Need to be done since we are using a non-standard call to LoadLibrary static auto addDirectoriesInPath = []() { // Lambda executed once std::wstring_convert<std::codecvt_utf8_utf16<wchar_t>> converter; const char* environmentPath = std::getenv("PATH"); if (environmentPath && GetProcAddress(GetModuleHandle(TEXT("kernel32.dll")), "AddDllDirectory")) { auto elems = splitString(std::string(environmentPath), ';'); for (auto path : elems) { std::wstring dd; //std::string narrow = converter.to_bytes(wide_utf16_source_string); std::wstring wide = converter.from_bytes(path); AddDllDirectory(converter.from_bytes(path).c_str()); } return true; } else { return false; } }(); // Load library and search for dependencies in // 1. The directory that contains the DLL (LOAD_LIBRARY_SEARCH_DLL_LOAD_DIR). // 2. Paths explicitly added with the AddDllDirectory function (LOAD_LIBRARY_SEARCH_USER_DIRS) // or the SetDllDirectory function. If more than one path has been added, the order in which the // paths are searched is unspecified. // 3. The System directory (LOAD_LIBRARY_SEARCH_SYSTEM32) // // Note 1: The directory containing the application executable is not searched filePath is in // that directory. This enables us to use a temporary directory when loading dlls and thereby // allow the original ones to be overwritten while the application is running. // Note 2: LOAD_LIBRARY_SEARCH_DLL_LOAD_DIR and LOAD_LIBRARY_SEARCH_USER_DIRS requires KB2533623 // to be installed. // Note 3: Not supported on Windows XP and Server 2003 if (GetProcAddress(GetModuleHandle(TEXT("kernel32.dll")), "AddDllDirectory")) { handle_ = LoadLibraryExA(filePath.c_str(), nullptr, LOAD_LIBRARY_SEARCH_DLL_LOAD_DIR | LOAD_LIBRARY_SEARCH_SYSTEM32 | LOAD_LIBRARY_SEARCH_USER_DIRS); } else { // LOAD_LIBRARY_SEARCH_* flags are not supported // Fall back to LoadLibrary handle_ = LoadLibraryA(filePath.c_str()); } if (!handle_) { auto error = GetLastError(); std::ostringstream errorStream; LPVOID errorText; auto outputSize = FormatMessage( // use system message tables to retrieve error text FORMAT_MESSAGE_FROM_SYSTEM // allocate buffer on local heap for error text | FORMAT_MESSAGE_ALLOCATE_BUFFER // Important! will fail otherwise, since we're not // (and CANNOT) pass insertion parameters | FORMAT_MESSAGE_IGNORE_INSERTS, NULL, error, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (LPTSTR)&errorText, 0, NULL); if (errorText != nullptr) { std::string errorString(static_cast<const char *>(errorText), outputSize + 1); errorStream << errorString; //errorStream << static_cast<const char *>(errorText); // release memory allocated by FormatMessage() LocalFree(errorText); } throw Exception("Failed to load library: " + filePath + "\n Error: " + errorStream.str()); } #else handle_ = dlopen(filePath.c_str(), RTLD_NOW | RTLD_GLOBAL); if (!handle_) { throw Exception("Failed to load library: " + filePath); } #endif } SharedLibrary::~SharedLibrary() { #if WIN32 FreeLibrary(handle_); #else dlclose(handle_); #endif } void* SharedLibrary::findSymbol(std::string name) { #if WIN32 return GetProcAddress(handle_, "createModule"); #else return dlsym(handle_, name.c_str()); #endif } } // namespace <commit_msg>Core: inviwo/inviwo-dev#1364 Added minor comments in SharedLibrary and removed RTLD_NOW since, as far as I know, we do not need it.<commit_after>/********************************************************************************* * * Inviwo - Interactive Visualization Workshop * * Copyright (c) 2016 Inviwo Foundation * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT 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. * *********************************************************************************/ #include <inviwo/core/util/sharedlibrary.h> #include <inviwo/core/util/filesystem.h> #include <inviwo/core/util/stringconversion.h> // splitString #include <codecvt> #include <locale> #if WIN32 #define NOMINMAX #define WIN32_LEAN_AND_MEAN #include <windows.h> #else #include <dlfcn.h> #endif namespace inviwo { SharedLibrary::SharedLibrary(std::string filePath) : filePath_(filePath) { #if WIN32 // Search for dlls in directories specified by the path environment variable // Need to be done since we are using a non-standard call to LoadLibrary static auto addDirectoriesInPath = []() { // Lambda executed once std::wstring_convert<std::codecvt_utf8_utf16<wchar_t>> converter; const char* environmentPath = std::getenv("PATH"); if (environmentPath && GetProcAddress(GetModuleHandle(TEXT("kernel32.dll")), "AddDllDirectory")) { auto elems = splitString(std::string(environmentPath), ';'); for (auto path : elems) { std::wstring dd; //std::string narrow = converter.to_bytes(wide_utf16_source_string); std::wstring wide = converter.from_bytes(path); AddDllDirectory(converter.from_bytes(path).c_str()); } return true; } else { return false; } }(); // Load library and search for dependencies in // 1. The directory that contains the DLL (LOAD_LIBRARY_SEARCH_DLL_LOAD_DIR). // 2. Paths explicitly added with the AddDllDirectory function (LOAD_LIBRARY_SEARCH_USER_DIRS) // or the SetDllDirectory function. If more than one path has been added, the order in which the // paths are searched is unspecified. // 3. The System directory (LOAD_LIBRARY_SEARCH_SYSTEM32) // // Note 1: The directory containing the application executable is not searched filePath is in // that directory. This enables us to use a temporary directory when loading dlls and thereby // allow the original ones to be overwritten while the application is running. // Note 2: LOAD_LIBRARY_SEARCH_DLL_LOAD_DIR and LOAD_LIBRARY_SEARCH_USER_DIRS requires KB2533623 // to be installed. // Note 3: Not supported on Windows XP and Server 2003 if (GetProcAddress(GetModuleHandle(TEXT("kernel32.dll")), "AddDllDirectory")) { handle_ = LoadLibraryExA(filePath.c_str(), nullptr, LOAD_LIBRARY_SEARCH_DLL_LOAD_DIR | LOAD_LIBRARY_SEARCH_SYSTEM32 | LOAD_LIBRARY_SEARCH_USER_DIRS); } else { // LOAD_LIBRARY_SEARCH_* flags are not supported // Fall back to LoadLibrary handle_ = LoadLibraryA(filePath.c_str()); } if (!handle_) { auto error = GetLastError(); std::ostringstream errorStream; LPVOID errorText; auto outputSize = FormatMessage( // use system message tables to retrieve error text FORMAT_MESSAGE_FROM_SYSTEM // allocate buffer on local heap for error text | FORMAT_MESSAGE_ALLOCATE_BUFFER // Important! will fail otherwise, since we're not // (and CANNOT) pass insertion parameters | FORMAT_MESSAGE_IGNORE_INSERTS, NULL, error, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (LPTSTR)&errorText, 0, NULL); if (errorText != nullptr) { std::string errorString(static_cast<const char *>(errorText), outputSize + 1); errorStream << errorString; //errorStream << static_cast<const char *>(errorText); // release memory allocated by FormatMessage() LocalFree(errorText); } throw Exception("Failed to load library: " + filePath + "\n Error: " + errorStream.str()); } #else // RTLD_GLOBAL gives all other loaded libraries access to library // RTLD_LOCAL is preferred but would require each module to // explicitly load its dependent libraries as well. handle_ = dlopen(filePath.c_str(), RTLD_GLOBAL); if (!handle_) { throw Exception("Failed to load library: " + filePath); } #endif } SharedLibrary::~SharedLibrary() { #if WIN32 FreeLibrary(handle_); #else dlclose(handle_); #endif } void* SharedLibrary::findSymbol(std::string name) { #if WIN32 return GetProcAddress(handle_, "createModule"); #else return dlsym(handle_, name.c_str()); #endif } } // namespace <|endoftext|>
<commit_before>/* * Copyright (C) 1994-2017 Altair Engineering, Inc. * For more information, contact Altair at www.altair.com. * * This file is part of the PBS Professional ("PBS Pro") software. * * Open Source License Information: * * PBS Pro is free software. You can redistribute it and/or modify it under the * terms of the GNU Affero General Public License as published by the Free * Software Foundation, either version 3 of the License, or (at your option) any * later version. * * PBS Pro is distributed in the hope that it will be useful, but WITHOUT ANY * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A * PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License along * with this program. If not, see <http://www.gnu.org/licenses/>. * * Commercial License Information: * * The PBS Pro software is licensed under the terms of the GNU Affero General * Public License agreement ("AGPL"), except where a separate commercial license * agreement for PBS Pro version 14 or later has been executed in writing with Altair. * * Altair’s dual-license business model allows companies, individuals, and * organizations to create proprietary derivative works of PBS Pro and distribute * them - whether embedded or bundled with other software - under a commercial * license agreement. * * Use of Altair’s trademarks, including but not limited to "PBS™", * "PBS Professional®", and "PBS Pro™" and Altair’s logos is subject to Altair's * trademark licensing policies. * */ #include <cppunit/extensions/AutoRegisterSuite.h> #include <cppunit/extensions/HelperMacros.h> #include <cppunit/TestAssert.h> #include <ConnectionPool.h> #include <testdrmaa.h> #include <pbs_ifl.h> using namespace std; CPPUNIT_TEST_SUITE_REGISTRATION(TestDrmaa); void TestDrmaa::TestConnectionPool() { int connfd[22], i = 0, prevfd = 0, x = 0; ConnPool* tmp= ConnPool::getInstance(); connfd[i] = tmp->getConnectionFromPool(pbs_default()); prevfd = connfd[i]; //printf("\nIndex [%d] Fd [%d]", i, connfd[i]); i++; tmp->returnConnectionToPool(connfd[0]); connfd[i] = tmp->getConnectionFromPool(pbs_default()); //printf("\nIndex [%d] Fd [%d]", i, connfd[i]); CPPUNIT_ASSERT_EQUAL(prevfd, connfd[i]); i++; connfd[i] = tmp->getConnectionFromPool(pbs_default()); //printf("\nIndex [%d] Fd [%d]", i, connfd[i]); i++; connfd[i] = tmp->getConnectionFromPool(pbs_default()); //printf("\nIndex [%d] Fd [%d]", i, connfd[i]); i++; connfd[i] = tmp->getConnectionFromPool(pbs_default()); //printf("\nIndex [%d] Fd [%d]", i, connfd[i]); prevfd = connfd[i]; connfd[i] = tmp->reestablishConnection(connfd[i]); //printf("\nIndex [%d] Fd [%d]", i, connfd[i]); CPPUNIT_ASSERT(prevfd == connfd[i]); i++; for(x = i; x < 22; x++) { connfd[x] = tmp->getConnectionFromPool(pbs_default()); //printf("\nIndex [%d] Fd [%d]", x, connfd[x]); } CPPUNIT_ASSERT(connfd[21] == -1); } <commit_msg>Outsider commit (#1)<commit_after>/* * Copyright (C) 1994-2017 Altair Engineering, Inc. * For more information, contact Altair at www.altair.com. * * This file is part of the PBS Professional ("PBS Pro") software. * * Open Source License Information: * * PBS Pro is free software. You can redistribute it and/or modify it under the * terms of the GNU Affero General Public License as published by the Free * Software Foundation, either version 3 of the License, or (at your option) any * later version. * * PBS Pro is distributed in the hope that it will be useful, but WITHOUT ANY * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A * PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License along * with this program. If not, see <http://www.gnu.org/licenses/>. * * Commercial License Information: * * The PBS Pro software is licensed under the terms of the GNU Affero General * Public License agreement ("AGPL"), except where a separate commercial license * agreement for PBS Pro version 14 or later has been executed in writing with Altair. * * Altair’s dual-license business model allows companies, individuals, and * organizations to create proprietary derivative works of PBS Pro and distribute * them - whether embedded or bundled with other software - under a commercial * license agreement. * * Use of Altair’s trademarks, including but not limited to "PBS™", * "PBS Professional®", and "PBS Pro™" and Altair’s logos is subject to Altair's * trademark licensing policies. * */ #include <cppunit/extensions/AutoRegisterSuite.h> #include <cppunit/extensions/HelperMacros.h> #include <cppunit/TestAssert.h> #include <ConnectionPool.h> #include <testdrmaa.h> #include <pbs_ifl.h> using namespace std; CPPUNIT_TEST_SUITE_REGISTRATION(TestDrmaa); void TestDrmaa::TestConnectionPool() { int connfd[22], i = 0, prevfd = 0, x = 0; ConnPool* tmp= ConnPool::getInstance(); connfd[i] = tmp->getConnectionFromPool(pbs_default()); prevfd = connfd[i]; //printf("\nIndex [%d] Fd [%d]", i, connfd[i]); i++; tmp->returnConnectionToPool(connfd[0]); connfd[i] = tmp->getConnectionFromPool(pbs_default()); //printf("\nIndex [%d] Fd [%d]", i, connfd[i]); CPPUNIT_ASSERT_EQUAL(prevfd, connfd[i]); i++; connfd[i] = tmp->getConnectionFromPool(pbs_default()); //printf("\nIndex [%d] Fd [%d]", i, connfd[i]); i++; connfd[i] = tmp->getConnectionFromPool(pbs_default()); //printf("\nIndex [%d] Fd [%d]", i, connfd[i]); i++; connfd[i] = tmp->getConnectionFromPool(pbs_default()); //printf("\nIndex [%d] Fd [%d]", i, connfd[i]); prevfd = connfd[i]; connfd[i] = tmp->reestablishConnection(connfd[i]); //printf("\nIndex [%d] Fd [%d]", i, connfd[i]); CPPUNIT_ASSERT(prevfd != connfd[i]); i++; for(x = i; x < 22; x++) { connfd[x] = tmp->getConnectionFromPool(pbs_default()); //printf("\nIndex [%d] Fd [%d]", x, connfd[x]); } CPPUNIT_ASSERT(connfd[21] == -1); } <|endoftext|>
<commit_before>//============================================================================== // CellMLAnnotationView plugin //============================================================================== #include "cellmlannotationviewcellmldetailswidget.h" #include "cellmlannotationviewdetailswidget.h" #include "cellmlannotationviewlistswidget.h" #include "cellmlannotationviewplugin.h" #include "cellmlannotationviewwidget.h" #include "cellmlfilemanager.h" #include "coreutils.h" //============================================================================== #include <QApplication> #include <QDesktopWidget> #include <QMainWindow> #include <QSettings> //============================================================================== namespace OpenCOR { namespace CellMLAnnotationView { //============================================================================== PLUGININFO_FUNC CellMLAnnotationViewPluginInfo() { Descriptions descriptions; descriptions.insert("en", "A plugin to annotate CellML files"); descriptions.insert("fr", "Une extension pour annoter des fichiers CellML"); return new PluginInfo(PluginInfo::V001, PluginInfo::Gui, PluginInfo::Editing, true, QStringList() << "CoreCellMLEditing" << "QJson" << "RICORDOSupport", descriptions); } //============================================================================== Q_EXPORT_PLUGIN2(CellMLAnnotationView, CellMLAnnotationViewPlugin) //============================================================================== CellMLAnnotationViewPlugin::CellMLAnnotationViewPlugin() : mSizes(QList<int>()), mListsWidgetSizes(QList<int>()), mCellmlDetailsWidgetSizes(QList<int>()), mViewWidgets(QMap<QString, CellmlAnnotationViewWidget *>()) { // Set our settings mGuiSettings->setView(GuiViewSettings::Editing); } //============================================================================== CellMLAnnotationViewPlugin::~CellMLAnnotationViewPlugin() { // Delete our view widgets foreach (QWidget *viewWidget, mViewWidgets) delete viewWidget; } //============================================================================== static const QString SettingsCellmlAnnotationWidget = "CellmlAnnotationWidget"; static const QString SettingsCellmlAnnotationWidgetSizesCount = "SizesCount"; static const QString SettingsCellmlAnnotationWidgetSizes = "Sizes%1"; static const QString SettingsCellmlAnnotationWidgetListsWidgetSizesCount = "ListsWidgetSizesCount"; static const QString SettingsCellmlAnnotationWidgetListsWidgetSizes = "ListsWidgetSizes%1"; static const QString SettingsCellmlAnnotationWidgetCellmlDetailsWidgetSizesCount = "CellmlDetailsWidgetSizesCount"; static const QString SettingsCellmlAnnotationWidgetCellmlDetailsWidgetSizes = "CellmlDetailsWidgetSizes%1"; //============================================================================== void CellMLAnnotationViewPlugin::loadSettings(QSettings *pSettings) { // Retrieve the size of the different items that make up our splitters // Note: we would normally do this in CellmlAnnotationViewWidget, but we // have one instance of it per CellML file and we want to share some // information between the different instances, so we have to do it // here instead... pSettings->beginGroup(SettingsCellmlAnnotationWidget); // Sizes int sizesCount = pSettings->value(SettingsCellmlAnnotationWidgetSizesCount, 0).toInt(); if (!sizesCount) { // There are no previous sizes, so get some default ones mSizes << 0.25*qApp->desktop()->screenGeometry().width() << 0.75*qApp->desktop()->screenGeometry().width(); } else { // There are previous sizes, so use them to initialise mSizes for (int i = 0; i < sizesCount; ++i) mSizes << pSettings->value(SettingsCellmlAnnotationWidgetSizes.arg(QString::number(i))).toInt(); } // View widget sizes int listsWidgetSizesCount = pSettings->value(SettingsCellmlAnnotationWidgetListsWidgetSizesCount, 0).toInt(); if (!listsWidgetSizesCount) { // There are no previous view widget sizes, so get some default ones mListsWidgetSizes << 0.75*qApp->desktop()->screenGeometry().height() << 0.25*qApp->desktop()->screenGeometry().height(); } else { // There are previous view widget sizes, so use them to initialise // mListsWidgetSizes for (int i = 0; i < listsWidgetSizesCount; ++i) mListsWidgetSizes << pSettings->value(SettingsCellmlAnnotationWidgetListsWidgetSizes.arg(QString::number(i))).toInt(); } // CellML details view widget sizes int cellmlDetailsWidgetSizesCount = pSettings->value(SettingsCellmlAnnotationWidgetCellmlDetailsWidgetSizesCount, 0).toInt(); if (!cellmlDetailsWidgetSizesCount) { // There are no previous view widget sizes, so get some default ones mCellmlDetailsWidgetSizes << 0.25*qApp->desktop()->screenGeometry().height() << 0.25*qApp->desktop()->screenGeometry().height() << 0.50*qApp->desktop()->screenGeometry().height(); } else { // There are previous view widget sizes, so use them to initialise // mCellmlDetailsWidgetSizes for (int i = 0; i < cellmlDetailsWidgetSizesCount; ++i) mCellmlDetailsWidgetSizes << pSettings->value(SettingsCellmlAnnotationWidgetCellmlDetailsWidgetSizes.arg(QString::number(i))).toInt(); } pSettings->endGroup(); } //============================================================================== void CellMLAnnotationViewPlugin::saveSettings(QSettings *pSettings) const { // Keep track of the tree view's and CellML annotation's width // Note: we must also keep track of the CellML annotation's width because // when loading our settings (see above), the view widget doesn't yet // have a 'proper' width, so we couldn't simply assume that the Cellml // annotation's initial width is this view widget's width minus the // tree view's initial width, so... pSettings->beginGroup(SettingsCellmlAnnotationWidget); // Sizes pSettings->setValue(SettingsCellmlAnnotationWidgetSizesCount, mSizes.count()); for (int i = 0, iMax = mSizes.count(); i < iMax; ++i) pSettings->setValue(SettingsCellmlAnnotationWidgetSizes.arg(QString::number(i)), mSizes[i]); // View widget sizes pSettings->setValue(SettingsCellmlAnnotationWidgetListsWidgetSizesCount, mListsWidgetSizes.count()); for (int i = 0, iMax = mListsWidgetSizes.count(); i < iMax; ++i) pSettings->setValue(SettingsCellmlAnnotationWidgetListsWidgetSizes.arg(QString::number(i)), mListsWidgetSizes[i]); // CellML details view widget sizes pSettings->setValue(SettingsCellmlAnnotationWidgetCellmlDetailsWidgetSizesCount, mCellmlDetailsWidgetSizes.count()); for (int i = 0, iMax = mCellmlDetailsWidgetSizes.count(); i < iMax; ++i) pSettings->setValue(SettingsCellmlAnnotationWidgetCellmlDetailsWidgetSizes.arg(QString::number(i)), mCellmlDetailsWidgetSizes[i]); pSettings->endGroup(); } //============================================================================== QWidget * CellMLAnnotationViewPlugin::viewWidget(const QString &pFileName) { // Check that we are dealing with a CellML file if (!CellMLSupport::CellmlFileManager::instance()->cellmlFile(pFileName)) // We are not dealing with a CellML file, so... return 0; // Retrieve from our list the view widget associated with the file name CellmlAnnotationViewWidget *res = mViewWidgets.value(pFileName); // Create a new view widget, if none could be retrieved if (!res) { res = new CellmlAnnotationViewWidget(mMainWindow, this, pFileName); // Initialise our new view widget's sizes res->setSizes(mSizes); res->listsWidget()->setSizes(mListsWidgetSizes); res->detailsWidget()->cellmlDetails()->setSizes(mCellmlDetailsWidgetSizes); // Keep track of the splitter move in our new view widget connect(res, SIGNAL(splitterMoved(const QList<int> &)), this, SLOT(splitterMoved(const QList<int> &))); connect(res->listsWidget(), SIGNAL(splitterMoved(const QList<int> &)), this, SLOT(listsWidgetSplitterMoved(const QList<int> &))); connect(res->detailsWidget()->cellmlDetails(), SIGNAL(splitterMoved(const QList<int> &)), this, SLOT(cellmlDetailsWidgetSplitterMoved(const QList<int> &))); // Some other connections to handle splitter moves between our view // widgets foreach (CellmlAnnotationViewWidget *viewWidget, mViewWidgets) { // Make sur that our new view widget is aware of any splitter move // occuring in the other view widget connect(res, SIGNAL(splitterMoved(const QList<int> &)), viewWidget, SLOT(updateSizes(const QList<int> &))); connect(res->listsWidget(), SIGNAL(splitterMoved(const QList<int> &)), viewWidget->listsWidget(), SLOT(updateSizes(const QList<int> &))); connect(res->detailsWidget()->cellmlDetails(), SIGNAL(splitterMoved(const QList<int> &)), viewWidget->detailsWidget()->cellmlDetails(), SLOT(updateSizes(const QList<int> &))); // Make sur that the other view widget is aware of any splitter move // occuring in our new view widget connect(viewWidget, SIGNAL(splitterMoved(const QList<int> &)), res, SLOT(updateSizes(const QList<int> &))); connect(viewWidget->listsWidget(), SIGNAL(splitterMoved(const QList<int> &)), res->listsWidget(), SLOT(updateSizes(const QList<int> &))); connect(viewWidget->detailsWidget()->cellmlDetails(), SIGNAL(splitterMoved(const QList<int> &)), res->detailsWidget()->cellmlDetails(), SLOT(updateSizes(const QList<int> &))); } // Keep track of our new view widget mViewWidgets.insert(pFileName, res); } // Return our view widget return res; } //============================================================================== bool CellMLAnnotationViewPlugin::hasViewWidget(const QString &pFileName) const { // Return whether a view widget exists or not for the given file name return mViewWidgets.value(pFileName); } //============================================================================== void CellMLAnnotationViewPlugin::deleteViewWidget(const QString &pFileName) { // Remove the view widget from our list, should there be one for the given // file name CellmlAnnotationViewWidget *viewWidget = mViewWidgets.value(pFileName); if (viewWidget) { // There is a view widget for the given file name, so delete it and // remove it from our list delete viewWidget; mViewWidgets.remove(pFileName); } } //============================================================================== QString CellMLAnnotationViewPlugin::viewName() { // Return our CellML annotation view's name return tr("CellML Annotation"); } //============================================================================== void CellMLAnnotationViewPlugin::retranslateUi() { // Retranslate all of our CellML annotation view widgets foreach (CellmlAnnotationViewWidget *viewWidget, mViewWidgets) viewWidget->retranslateUi(); } //============================================================================== void CellMLAnnotationViewPlugin::splitterMoved(const QList<int> &pSizes) { // The splitter of one of our CellML annotation view widgets has been moved, // so update things mSizes = pSizes; } //============================================================================== void CellMLAnnotationViewPlugin::listsWidgetSplitterMoved(const QList<int> &pSizes) { // The splitter of one of our CellML annotation view's lists widgets has // been moved, so update things mListsWidgetSizes = pSizes; } //============================================================================== void CellMLAnnotationViewPlugin::cellmlDetailsWidgetSplitterMoved(const QList<int> &pSizes) { // The splitter of one of our CellML annotation view's CellML details // widgets has been moved, so update things mCellmlDetailsWidgetSizes = pSizes; } //============================================================================== } // namespace CellMLAnnotationView } // namespace OpenCOR //============================================================================== // End of file //============================================================================== <commit_msg>Minor GUI update as a result of our work on the CellML Annotation view (#78).<commit_after>//============================================================================== // CellMLAnnotationView plugin //============================================================================== #include "cellmlannotationviewcellmldetailswidget.h" #include "cellmlannotationviewdetailswidget.h" #include "cellmlannotationviewlistswidget.h" #include "cellmlannotationviewplugin.h" #include "cellmlannotationviewwidget.h" #include "cellmlfilemanager.h" #include "coreutils.h" //============================================================================== #include <QApplication> #include <QDesktopWidget> #include <QMainWindow> #include <QSettings> //============================================================================== namespace OpenCOR { namespace CellMLAnnotationView { //============================================================================== PLUGININFO_FUNC CellMLAnnotationViewPluginInfo() { Descriptions descriptions; descriptions.insert("en", "A plugin to annotate CellML files"); descriptions.insert("fr", "Une extension pour annoter des fichiers CellML"); return new PluginInfo(PluginInfo::V001, PluginInfo::Gui, PluginInfo::Editing, true, QStringList() << "CoreCellMLEditing" << "QJson" << "RICORDOSupport", descriptions); } //============================================================================== Q_EXPORT_PLUGIN2(CellMLAnnotationView, CellMLAnnotationViewPlugin) //============================================================================== CellMLAnnotationViewPlugin::CellMLAnnotationViewPlugin() : mSizes(QList<int>()), mListsWidgetSizes(QList<int>()), mCellmlDetailsWidgetSizes(QList<int>()), mViewWidgets(QMap<QString, CellmlAnnotationViewWidget *>()) { // Set our settings mGuiSettings->setView(GuiViewSettings::Editing); } //============================================================================== CellMLAnnotationViewPlugin::~CellMLAnnotationViewPlugin() { // Delete our view widgets foreach (QWidget *viewWidget, mViewWidgets) delete viewWidget; } //============================================================================== static const QString SettingsCellmlAnnotationWidget = "CellmlAnnotationWidget"; static const QString SettingsCellmlAnnotationWidgetSizesCount = "SizesCount"; static const QString SettingsCellmlAnnotationWidgetSizes = "Sizes%1"; static const QString SettingsCellmlAnnotationWidgetListsWidgetSizesCount = "ListsWidgetSizesCount"; static const QString SettingsCellmlAnnotationWidgetListsWidgetSizes = "ListsWidgetSizes%1"; static const QString SettingsCellmlAnnotationWidgetCellmlDetailsWidgetSizesCount = "CellmlDetailsWidgetSizesCount"; static const QString SettingsCellmlAnnotationWidgetCellmlDetailsWidgetSizes = "CellmlDetailsWidgetSizes%1"; //============================================================================== void CellMLAnnotationViewPlugin::loadSettings(QSettings *pSettings) { // Retrieve the size of the different items that make up our splitters // Note: we would normally do this in CellmlAnnotationViewWidget, but we // have one instance of it per CellML file and we want to share some // information between the different instances, so we have to do it // here instead... pSettings->beginGroup(SettingsCellmlAnnotationWidget); // Sizes int sizesCount = pSettings->value(SettingsCellmlAnnotationWidgetSizesCount, 0).toInt(); if (!sizesCount) { // There are no previous sizes, so get some default ones mSizes << 0.25*qApp->desktop()->screenGeometry().width() << 0.75*qApp->desktop()->screenGeometry().width(); } else { // There are previous sizes, so use them to initialise mSizes for (int i = 0; i < sizesCount; ++i) mSizes << pSettings->value(SettingsCellmlAnnotationWidgetSizes.arg(QString::number(i))).toInt(); } // View widget sizes int listsWidgetSizesCount = pSettings->value(SettingsCellmlAnnotationWidgetListsWidgetSizesCount, 0).toInt(); if (!listsWidgetSizesCount) { // There are no previous view widget sizes, so get some default ones mListsWidgetSizes << 0.65*qApp->desktop()->screenGeometry().height() << 0.35*qApp->desktop()->screenGeometry().height(); } else { // There are previous view widget sizes, so use them to initialise // mListsWidgetSizes for (int i = 0; i < listsWidgetSizesCount; ++i) mListsWidgetSizes << pSettings->value(SettingsCellmlAnnotationWidgetListsWidgetSizes.arg(QString::number(i))).toInt(); } // CellML details view widget sizes int cellmlDetailsWidgetSizesCount = pSettings->value(SettingsCellmlAnnotationWidgetCellmlDetailsWidgetSizesCount, 0).toInt(); if (!cellmlDetailsWidgetSizesCount) { // There are no previous view widget sizes, so get some default ones mCellmlDetailsWidgetSizes << 0.25*qApp->desktop()->screenGeometry().height() << 0.25*qApp->desktop()->screenGeometry().height() << 0.50*qApp->desktop()->screenGeometry().height(); } else { // There are previous view widget sizes, so use them to initialise // mCellmlDetailsWidgetSizes for (int i = 0; i < cellmlDetailsWidgetSizesCount; ++i) mCellmlDetailsWidgetSizes << pSettings->value(SettingsCellmlAnnotationWidgetCellmlDetailsWidgetSizes.arg(QString::number(i))).toInt(); } pSettings->endGroup(); } //============================================================================== void CellMLAnnotationViewPlugin::saveSettings(QSettings *pSettings) const { // Keep track of the tree view's and CellML annotation's width // Note: we must also keep track of the CellML annotation's width because // when loading our settings (see above), the view widget doesn't yet // have a 'proper' width, so we couldn't simply assume that the Cellml // annotation's initial width is this view widget's width minus the // tree view's initial width, so... pSettings->beginGroup(SettingsCellmlAnnotationWidget); // Sizes pSettings->setValue(SettingsCellmlAnnotationWidgetSizesCount, mSizes.count()); for (int i = 0, iMax = mSizes.count(); i < iMax; ++i) pSettings->setValue(SettingsCellmlAnnotationWidgetSizes.arg(QString::number(i)), mSizes[i]); // View widget sizes pSettings->setValue(SettingsCellmlAnnotationWidgetListsWidgetSizesCount, mListsWidgetSizes.count()); for (int i = 0, iMax = mListsWidgetSizes.count(); i < iMax; ++i) pSettings->setValue(SettingsCellmlAnnotationWidgetListsWidgetSizes.arg(QString::number(i)), mListsWidgetSizes[i]); // CellML details view widget sizes pSettings->setValue(SettingsCellmlAnnotationWidgetCellmlDetailsWidgetSizesCount, mCellmlDetailsWidgetSizes.count()); for (int i = 0, iMax = mCellmlDetailsWidgetSizes.count(); i < iMax; ++i) pSettings->setValue(SettingsCellmlAnnotationWidgetCellmlDetailsWidgetSizes.arg(QString::number(i)), mCellmlDetailsWidgetSizes[i]); pSettings->endGroup(); } //============================================================================== QWidget * CellMLAnnotationViewPlugin::viewWidget(const QString &pFileName) { // Check that we are dealing with a CellML file if (!CellMLSupport::CellmlFileManager::instance()->cellmlFile(pFileName)) // We are not dealing with a CellML file, so... return 0; // Retrieve from our list the view widget associated with the file name CellmlAnnotationViewWidget *res = mViewWidgets.value(pFileName); // Create a new view widget, if none could be retrieved if (!res) { res = new CellmlAnnotationViewWidget(mMainWindow, this, pFileName); // Initialise our new view widget's sizes res->setSizes(mSizes); res->listsWidget()->setSizes(mListsWidgetSizes); res->detailsWidget()->cellmlDetails()->setSizes(mCellmlDetailsWidgetSizes); // Keep track of the splitter move in our new view widget connect(res, SIGNAL(splitterMoved(const QList<int> &)), this, SLOT(splitterMoved(const QList<int> &))); connect(res->listsWidget(), SIGNAL(splitterMoved(const QList<int> &)), this, SLOT(listsWidgetSplitterMoved(const QList<int> &))); connect(res->detailsWidget()->cellmlDetails(), SIGNAL(splitterMoved(const QList<int> &)), this, SLOT(cellmlDetailsWidgetSplitterMoved(const QList<int> &))); // Some other connections to handle splitter moves between our view // widgets foreach (CellmlAnnotationViewWidget *viewWidget, mViewWidgets) { // Make sur that our new view widget is aware of any splitter move // occuring in the other view widget connect(res, SIGNAL(splitterMoved(const QList<int> &)), viewWidget, SLOT(updateSizes(const QList<int> &))); connect(res->listsWidget(), SIGNAL(splitterMoved(const QList<int> &)), viewWidget->listsWidget(), SLOT(updateSizes(const QList<int> &))); connect(res->detailsWidget()->cellmlDetails(), SIGNAL(splitterMoved(const QList<int> &)), viewWidget->detailsWidget()->cellmlDetails(), SLOT(updateSizes(const QList<int> &))); // Make sur that the other view widget is aware of any splitter move // occuring in our new view widget connect(viewWidget, SIGNAL(splitterMoved(const QList<int> &)), res, SLOT(updateSizes(const QList<int> &))); connect(viewWidget->listsWidget(), SIGNAL(splitterMoved(const QList<int> &)), res->listsWidget(), SLOT(updateSizes(const QList<int> &))); connect(viewWidget->detailsWidget()->cellmlDetails(), SIGNAL(splitterMoved(const QList<int> &)), res->detailsWidget()->cellmlDetails(), SLOT(updateSizes(const QList<int> &))); } // Keep track of our new view widget mViewWidgets.insert(pFileName, res); } // Return our view widget return res; } //============================================================================== bool CellMLAnnotationViewPlugin::hasViewWidget(const QString &pFileName) const { // Return whether a view widget exists or not for the given file name return mViewWidgets.value(pFileName); } //============================================================================== void CellMLAnnotationViewPlugin::deleteViewWidget(const QString &pFileName) { // Remove the view widget from our list, should there be one for the given // file name CellmlAnnotationViewWidget *viewWidget = mViewWidgets.value(pFileName); if (viewWidget) { // There is a view widget for the given file name, so delete it and // remove it from our list delete viewWidget; mViewWidgets.remove(pFileName); } } //============================================================================== QString CellMLAnnotationViewPlugin::viewName() { // Return our CellML annotation view's name return tr("CellML Annotation"); } //============================================================================== void CellMLAnnotationViewPlugin::retranslateUi() { // Retranslate all of our CellML annotation view widgets foreach (CellmlAnnotationViewWidget *viewWidget, mViewWidgets) viewWidget->retranslateUi(); } //============================================================================== void CellMLAnnotationViewPlugin::splitterMoved(const QList<int> &pSizes) { // The splitter of one of our CellML annotation view widgets has been moved, // so update things mSizes = pSizes; } //============================================================================== void CellMLAnnotationViewPlugin::listsWidgetSplitterMoved(const QList<int> &pSizes) { // The splitter of one of our CellML annotation view's lists widgets has // been moved, so update things mListsWidgetSizes = pSizes; } //============================================================================== void CellMLAnnotationViewPlugin::cellmlDetailsWidgetSplitterMoved(const QList<int> &pSizes) { // The splitter of one of our CellML annotation view's CellML details // widgets has been moved, so update things mCellmlDetailsWidgetSizes = pSizes; } //============================================================================== } // namespace CellMLAnnotationView } // namespace OpenCOR //============================================================================== // End of file //============================================================================== <|endoftext|>
<commit_before>// Copyright 2015 Open Source Robotics Foundation, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include <atomic> #include <stdexcept> #include "gtest/gtest.h" #include "rclcpp/rclcpp.hpp" #ifdef RMW_IMPLEMENTATION # define CLASSNAME_(NAME, SUFFIX) NAME ## __ ## SUFFIX # define CLASSNAME(NAME, SUFFIX) CLASSNAME_(NAME, SUFFIX) #else # define CLASSNAME(NAME, SUFFIX) NAME #endif TEST(CLASSNAME(test_executor, RMW_IMPLEMENTATION), recursive_spin_call) { rclcpp::executors::SingleThreadedExecutor executor; auto node = rclcpp::Node::make_shared("recursive_spin_call"); auto timer = node->create_wall_timer(0_s, [&executor]() { ASSERT_THROW(executor.spin_some(), std::runtime_error); ASSERT_THROW(executor.spin_once(), std::runtime_error); ASSERT_THROW(executor.spin(), std::runtime_error); executor.cancel(); }); executor.add_node(node); executor.spin(); } TEST(CLASSNAME(test_executor, RMW_IMPLEMENTATION), multithreaded_spin_call) { rclcpp::executors::SingleThreadedExecutor executor; auto node = rclcpp::Node::make_shared("multithreaded_spin_call"); std::mutex m; bool ready = false; std::condition_variable cv; std::thread t([&executor, &m, &cv, &ready]() { std::unique_lock<std::mutex> lock(m); cv.wait(lock, [&ready] {return ready; }); ASSERT_THROW(executor.spin_some(), std::runtime_error); ASSERT_THROW(executor.spin_once(), std::runtime_error); ASSERT_THROW(executor.spin(), std::runtime_error); executor.cancel(); }); auto timer = node->create_wall_timer(0_s, [&m, &cv, &ready]() { if (!ready) { { std::lock_guard<std::mutex> lock(m); ready = true; } cv.notify_one(); } }); executor.add_node(node); executor.spin(); t.join(); } // Try spinning 2 single-threaded executors in two separate threads. TEST(CLASSNAME(test_executor, RMW_IMPLEMENTATION), multiple_executors) { std::atomic_uint counter; counter = 0; const uint32_t counter_goal = 20; // Initialize executor 1. rclcpp::executors::SingleThreadedExecutor executor1; auto callback1 = [&counter, &counter_goal, &executor1]() { if (counter == counter_goal) { executor1.cancel(); return; } ++counter; }; auto node1 = rclcpp::Node::make_shared("multiple_executors_1"); auto timer1 = node1->create_wall_timer(1_ms, callback1); executor1.add_node(node1); // Initialize executor 2. rclcpp::executors::SingleThreadedExecutor executor2; auto callback2 = [&counter, &counter_goal, &executor2]() { if (counter == counter_goal) { executor2.cancel(); return; } ++counter; }; auto node2 = rclcpp::Node::make_shared("multiple_executors_2"); auto timer2 = node2->create_wall_timer(1_ms, callback2); executor2.add_node(node2); auto spin_executor2 = [&executor2]() { executor2.spin(); }; // Launch both executors std::thread execution_thread(spin_executor2); executor1.spin(); execution_thread.join(); EXPECT_EQ(counter.load(), counter_goal); // Try to add node1 to executor2. It should throw, since node1 was already added to executor1. ASSERT_THROW(executor2.add_node(node1), std::runtime_error); } int main(int argc, char ** argv) { rclcpp::init(argc, argv); ::testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); } <commit_msg>use separate counter for each thread<commit_after>// Copyright 2015 Open Source Robotics Foundation, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include <atomic> #include <stdexcept> #include "gtest/gtest.h" #include "rclcpp/rclcpp.hpp" #ifdef RMW_IMPLEMENTATION # define CLASSNAME_(NAME, SUFFIX) NAME ## __ ## SUFFIX # define CLASSNAME(NAME, SUFFIX) CLASSNAME_(NAME, SUFFIX) #else # define CLASSNAME(NAME, SUFFIX) NAME #endif TEST(CLASSNAME(test_executor, RMW_IMPLEMENTATION), recursive_spin_call) { rclcpp::executors::SingleThreadedExecutor executor; auto node = rclcpp::Node::make_shared("recursive_spin_call"); auto timer = node->create_wall_timer(0_s, [&executor]() { ASSERT_THROW(executor.spin_some(), std::runtime_error); ASSERT_THROW(executor.spin_once(), std::runtime_error); ASSERT_THROW(executor.spin(), std::runtime_error); executor.cancel(); }); executor.add_node(node); executor.spin(); } TEST(CLASSNAME(test_executor, RMW_IMPLEMENTATION), multithreaded_spin_call) { rclcpp::executors::SingleThreadedExecutor executor; auto node = rclcpp::Node::make_shared("multithreaded_spin_call"); std::mutex m; bool ready = false; std::condition_variable cv; std::thread t([&executor, &m, &cv, &ready]() { std::unique_lock<std::mutex> lock(m); cv.wait(lock, [&ready] {return ready; }); ASSERT_THROW(executor.spin_some(), std::runtime_error); ASSERT_THROW(executor.spin_once(), std::runtime_error); ASSERT_THROW(executor.spin(), std::runtime_error); executor.cancel(); }); auto timer = node->create_wall_timer(0_s, [&m, &cv, &ready]() { if (!ready) { { std::lock_guard<std::mutex> lock(m); ready = true; } cv.notify_one(); } }); executor.add_node(node); executor.spin(); t.join(); } // Try spinning 2 single-threaded executors in two separate threads. TEST(CLASSNAME(test_executor, RMW_IMPLEMENTATION), multiple_executors) { std::atomic_uint counter1; counter1 = 0; std::atomic_uint counter2; counter2 = 0; const uint32_t counter_goal = 20; // Initialize executor 1. rclcpp::executors::SingleThreadedExecutor executor1; auto callback1 = [&counter1, &counter_goal, &executor1]() { if (counter1 == counter_goal) { executor1.cancel(); return; } ++counter1; }; auto node1 = rclcpp::Node::make_shared("multiple_executors_1"); auto timer1 = node1->create_wall_timer(1_ms, callback1); executor1.add_node(node1); // Initialize executor 2. rclcpp::executors::SingleThreadedExecutor executor2; auto callback2 = [&counter2, &counter_goal, &executor2]() { if (counter2 == counter_goal) { executor2.cancel(); return; } ++counter2; }; auto node2 = rclcpp::Node::make_shared("multiple_executors_2"); auto timer2 = node2->create_wall_timer(1_ms, callback2); executor2.add_node(node2); auto spin_executor2 = [&executor2]() { executor2.spin(); }; // Launch both executors std::thread execution_thread(spin_executor2); executor1.spin(); execution_thread.join(); EXPECT_EQ(counter1.load(), counter_goal); EXPECT_EQ(counter2.load(), counter_goal); // Try to add node1 to executor2. It should throw, since node1 was already added to executor1. ASSERT_THROW(executor2.add_node(node1), std::runtime_error); } int main(int argc, char ** argv) { rclcpp::init(argc, argv); ::testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); } <|endoftext|>
<commit_before>// Copyright 2017 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include <gtest/gtest.h> #include <algorithm> #include <cstdlib> #include <string> #include "ccomptr.h" #include "custom_binary_reader.h" #include "dbg_breakpoint.h" #include "dbg_object.h" #include "i_cor_debug_mocks.h" #include "i_dbg_object_factory_mock.h" #include "i_dbg_stack_frame_mock.h" #include "i_eval_coordinator_mock.h" #include "i_portable_pdb_mocks.h" #include "i_stack_frame_collection_mock.h" using google::cloud::diagnostics::debug::Breakpoint; using google_cloud_debugger::CComPtr; using google_cloud_debugger::DbgBreakpoint; using google_cloud_debugger_portable_pdb::IDocumentIndex; using google_cloud_debugger_portable_pdb::MethodInfo; using google_cloud_debugger_portable_pdb::SequencePoint; using std::max; using std::string; using std::unique_ptr; using std::vector; using ::testing::_; using ::testing::Const; using ::testing::Return; using ::testing::ReturnRef; using ::testing::SetArgPointee; namespace google_cloud_debugger_test { // Test Fixture for DbgBreakpoint // Sets up a default DbgBreakpoint for the test. class DbgBreakpointTest : public ::testing::Test { protected: virtual void SetUpBreakpoint() { breakpoint_.Initialize(file_name_, id_, line_, column_, condition_, expressions_); // Gives the PDB file the same file name as this breakpoint's file name. pdb_file_fixture_.first_doc_.file_name_ = file_name_; pdb_file_fixture_.SetUpIPortablePDBFile(&file_mock_); } // ICorDebugBreakpoint associated with this breakpoint. ICorDebugBreakpointMock cordebug_breakpoint_; // Breakpoint. DbgBreakpoint breakpoint_; // File name of the breakpoint. string file_name_ = "My file"; // Lower case of the file name of the breakpoint. string lower_case_file_name_ = "my file"; string condition_; std::vector<string> expressions_; // Id of the breakpoint. string id_ = "My ID"; // Line number of breakpoint. uint32_t line_ = 32; // Column of the breakpoint. uint32_t column_ = 64; // Mock object for Portable PDB file. IPortablePdbFileMock file_mock_; // Fixture for the PDB File. PortablePDBFileFixture pdb_file_fixture_; // Mock stackframe, eval coordinator and object factory. IDbgStackFrameMock dbg_stack_frame_; IEvalCoordinatorMock eval_coordinator_mock_; IDbgObjectFactoryMock object_factory_; // Mock active debug frame. ICorDebugILFrameMock active_frame_mock_; }; // Tests that the Initialize function sets up the correct fields. TEST_F(DbgBreakpointTest, Initialize) { SetUpBreakpoint(); // The names stored should be lower case. EXPECT_EQ(breakpoint_.GetFileName(), lower_case_file_name_); EXPECT_EQ(breakpoint_.GetId(), id_); EXPECT_EQ(breakpoint_.GetLine(), line_); EXPECT_EQ(breakpoint_.GetColumn(), column_); // Now we use the other Initialize function, // file name, ID, line and column should be copied over. DbgBreakpoint breakpoint2; breakpoint2.Initialize(breakpoint_); EXPECT_EQ(breakpoint2.GetFileName(), breakpoint_.GetFileName()); EXPECT_EQ(breakpoint2.GetId(), breakpoint_.GetId()); EXPECT_EQ(breakpoint2.GetLine(), breakpoint_.GetLine()); EXPECT_EQ(breakpoint2.GetColumn(), breakpoint_.GetColumn()); } // Tests that the Set/GetMethodToken function sets up the correct fields. TEST_F(DbgBreakpointTest, SetGetMethodToken) { mdMethodDef method_token = 10; SetUpBreakpoint(); breakpoint_.SetMethodToken(method_token); EXPECT_EQ(breakpoint_.GetMethodToken(), method_token); } // Tests that Set/GetICorDebugBreakpoint function works. TEST_F(DbgBreakpointTest, SetGetICorDebugBreakpoint) { SetUpBreakpoint(); breakpoint_.SetCorDebugBreakpoint(&cordebug_breakpoint_); CComPtr<ICorDebugBreakpoint> cordebug_breakpoint2; HRESULT hr = breakpoint_.GetCorDebugBreakpoint(&cordebug_breakpoint2); EXPECT_TRUE(SUCCEEDED(hr)) << "Failed with hr: " << hr; } // Tests the error cases of Set/GetICorDebugBreakpoint function. TEST_F(DbgBreakpointTest, SetGetICorDebugBreakpointError) { SetUpBreakpoint(); // Null argument. EXPECT_EQ(breakpoint_.GetCorDebugBreakpoint(nullptr), E_INVALIDARG); // Calls without setting the breakpoint. CComPtr<ICorDebugBreakpoint> cordebug_breakpoint2; EXPECT_EQ(breakpoint_.GetCorDebugBreakpoint(&cordebug_breakpoint2), E_FAIL); } // Returns a method that contains a sequence point // thats contains breakpoint_line. Also sets the method // def to method_def and the IL Offset of the matching // sequence point to il_offset. MethodInfo MakeMatchingMethod(uint32_t breakpoint_line, uint32_t method_first_line, uint32_t method_def, uint32_t il_offset) { assert(method_first_line < breakpoint_line); // Minimum amount of lines from breakpoint to last line. uint32_t min_line = 10; // This method's first line is less than the breakpoint's line // and its last line is greater than the breakpoint's line, // so the TrySetBreakpoint method should be able to use this method. MethodInfo method; method.first_line = method_first_line; method.last_line = breakpoint_line + max(breakpoint_line, min_line); method.method_def = method_def; // Puts a sequence point that does not match the line of the breakpoint. SequencePoint seq_point; seq_point.start_line = method.first_line; // End line is between the start line of the method and breakpoint_line. seq_point.end_line = method.first_line + (rand() % (breakpoint_line - method.first_line)); seq_point.il_offset = rand() % il_offset; method.sequence_points.push_back(seq_point); assert(seq_point.end_line < breakpoint_line); // Puts in another sequence point that matches the line of the breakpoint. SequencePoint seq_point2; seq_point2.start_line = breakpoint_line; seq_point2.end_line = breakpoint_line + 1; seq_point2.il_offset = il_offset; method.sequence_points.push_back(seq_point2); // Puts a sequence point that does not match the line of the breakpoint. SequencePoint seq_point3; seq_point3.start_line = seq_point2.end_line + 1; // End line is between the start line of the method and breakpoint_line. seq_point3.end_line = seq_point3.end_line + 2; seq_point3.il_offset = il_offset + 10; method.sequence_points.push_back(seq_point3); assert(seq_point3.end_line < method.last_line); return method; } // Test the TrySetBreakpoint function of DbgBreakpoint. TEST_F(DbgBreakpointTest, TrySetBreakpoint) { SetUpBreakpoint(); // Gets a method that matches the breakpoint. uint32_t method_first_line = rand() % line_; uint32_t method_def = 100; uint32_t il_offset = 99; MethodInfo method = MakeMatchingMethod(line_, method_first_line, method_def, il_offset); // Gets another method that does not match the breakpoint. MethodInfo method2 = MakeMatchingMethod(line_ * 2, line_ + 1, method_def * 2, il_offset * 2); // Push the methods into the method vector that // the document index matching this Breakpoint will return. pdb_file_fixture_.first_doc_.methods_.push_back(method); pdb_file_fixture_.first_doc_.methods_.push_back(method2); EXPECT_TRUE(breakpoint_.TrySetBreakpoint(&file_mock_)); EXPECT_EQ(breakpoint_.GetILOffset(), il_offset); EXPECT_EQ(breakpoint_.GetMethodDef(), method_def); } // Test the TrySetBreakpoint function of DbgBreakpoint // when there are multiple methods in the Document Index. TEST_F(DbgBreakpointTest, TrySetBreakpointWithMultipleMethods) { SetUpBreakpoint(); // Gets a method that matches the breakpoint. uint32_t method_first_line = line_ - 10; uint32_t method_def = 100; uint32_t il_offset = 99; MethodInfo method = MakeMatchingMethod(line_, method_first_line, method_def, il_offset); // Gets another method that does not match the breakpoint. uint32_t method2_first_line = line_ + 100; uint32_t method2_def = method_def * 2; uint32_t il_offset_2 = il_offset * 2; MethodInfo method2 = MakeMatchingMethod(line_ + 120, method2_first_line, method2_def, il_offset_2); // Makes another the method that match the breakpoint // but has start line greater than the first method (so // this method should be selected since it is a better match). uint32_t method3_first_line = line_ - 5; uint32_t method3_def = method_def * 3; uint32_t il_offset_3 = 130; MethodInfo method3 = MakeMatchingMethod(line_, method3_first_line, method3_def, il_offset_3); // Push the methods into the method vector that // the document index matching this Breakpoint will return. pdb_file_fixture_.first_doc_.methods_.push_back(method); pdb_file_fixture_.first_doc_.methods_.push_back(method2); pdb_file_fixture_.first_doc_.methods_.push_back(method3); EXPECT_TRUE(breakpoint_.TrySetBreakpoint(&file_mock_)); EXPECT_EQ(breakpoint_.GetILOffset(), il_offset_3); EXPECT_EQ(breakpoint_.GetMethodDef(), method3_def); } // Tests the case where no matching methods are found. TEST_F(DbgBreakpointTest, TrySetBreakpointWithNoMatching) { SetUpBreakpoint(); // Gets a method that does not match the breakpoint. uint32_t method_first_line = line_ + 5; uint32_t method_def = 100; uint32_t il_offset = 99; MethodInfo method = MakeMatchingMethod(line_ + 10, method_first_line, method_def, il_offset); // Gets another method that does not match the breakpoint. uint32_t method2_first_line = line_ + 100; uint32_t method2_def = method_def * 2; uint32_t il_offset_2 = il_offset * 2; MethodInfo method2 = MakeMatchingMethod(line_ + 120, method2_first_line, method2_def, il_offset_2); // Push the methods into the method vector that // the document index matching this Breakpoint will return. pdb_file_fixture_.first_doc_.methods_.push_back(method); pdb_file_fixture_.first_doc_.methods_.push_back(method2); EXPECT_FALSE(breakpoint_.TrySetBreakpoint(&file_mock_)); } // Tests the PopulateBreakpoint function of DbgBreakpoint. TEST_F(DbgBreakpointTest, PopulateBreakpoint) { SetUpBreakpoint(); Breakpoint proto_breakpoint; IStackFrameCollectionMock stackframe_collection_mock; EXPECT_CALL( stackframe_collection_mock, PopulateStackFrames(&proto_breakpoint, &eval_coordinator_mock_)) .Times(1) .WillRepeatedly(Return(S_OK)); HRESULT hr = breakpoint_.PopulateBreakpoint( &proto_breakpoint, &stackframe_collection_mock, &eval_coordinator_mock_); EXPECT_TRUE(SUCCEEDED(hr)) << "Failed with hr: " << hr; // Checks that the proto breakpoint's properties are set. EXPECT_EQ(proto_breakpoint.location().line(), line_); EXPECT_EQ(proto_breakpoint.location().path(), lower_case_file_name_); EXPECT_EQ(proto_breakpoint.id(), id_); } // Tests the error cases of PopulateBreakpoint function of DbgBreakpoint. TEST_F(DbgBreakpointTest, PopulateBreakpointError) { SetUpBreakpoint(); Breakpoint proto_breakpoint; IStackFrameCollectionMock stackframe_collection_mock; // Checks for null error. EXPECT_EQ(breakpoint_.PopulateBreakpoint(nullptr, &stackframe_collection_mock, &eval_coordinator_mock_), E_INVALIDARG); EXPECT_EQ(breakpoint_.PopulateBreakpoint(&proto_breakpoint, nullptr, &eval_coordinator_mock_), E_INVALIDARG); EXPECT_EQ(breakpoint_.PopulateBreakpoint( &proto_breakpoint, &stackframe_collection_mock, nullptr), E_INVALIDARG); // Makes PopulateStackFrames returns error. EXPECT_CALL( stackframe_collection_mock, PopulateStackFrames(&proto_breakpoint, &eval_coordinator_mock_)) .Times(1) .WillRepeatedly(Return(CORDBG_E_BAD_REFERENCE_VALUE)); EXPECT_EQ(breakpoint_.PopulateBreakpoint(&proto_breakpoint, &stackframe_collection_mock, &eval_coordinator_mock_), CORDBG_E_BAD_REFERENCE_VALUE); } // Tests the EvaluateExpressions function of DbgBreakpoint. TEST_F(DbgBreakpointTest, EvaluateExpressions) { expressions_ = { "1", "2" }; SetUpBreakpoint(); EXPECT_CALL(eval_coordinator_mock_, GetActiveDebugFrame(_)) .Times(expressions_.size()) .WillOnce(DoAll(SetArgPointee<0>(&active_frame_mock_), Return(S_OK))); HRESULT hr = breakpoint_.EvaluateExpressions(&dbg_stack_frame_, &eval_coordinator_mock_, &object_factory_); EXPECT_TRUE(SUCCEEDED(hr)) << "Failed with hr: " << hr; } // Tests that after EvaluateExpressions is called, PopulateBreakpoint // populates breakpoint proto with expressions. TEST_F(DbgBreakpointTest, PopulateBreakpointExpression) { expressions_ = { "1", "2" }; SetUpBreakpoint(); EXPECT_CALL(eval_coordinator_mock_, GetActiveDebugFrame(_)) .Times(expressions_.size()) .WillOnce(DoAll(SetArgPointee<0>(&active_frame_mock_), Return(S_OK))); HRESULT hr = breakpoint_.EvaluateExpressions(&dbg_stack_frame_, &eval_coordinator_mock_, &object_factory_); EXPECT_TRUE(SUCCEEDED(hr)) << "Failed with hr: " << hr; Breakpoint proto_breakpoint; IStackFrameCollectionMock stackframe_collection_mock; EXPECT_CALL( stackframe_collection_mock, PopulateStackFrames(&proto_breakpoint, &eval_coordinator_mock_)) .Times(1) .WillRepeatedly(Return(S_OK)); hr = breakpoint_.PopulateBreakpoint( &proto_breakpoint, &stackframe_collection_mock, &eval_coordinator_mock_); EXPECT_TRUE(SUCCEEDED(hr)) << "Failed with hr: " << hr; EXPECT_EQ(proto_breakpoint.evaluated_expressions_size(), 2); EXPECT_EQ(proto_breakpoint.evaluated_expressions(0).name(), "1"); EXPECT_EQ(proto_breakpoint.evaluated_expressions(0).value(), "1"); EXPECT_EQ(proto_breakpoint.evaluated_expressions(1).name(), "2"); EXPECT_EQ(proto_breakpoint.evaluated_expressions(1).value(), "2"); } } // namespace google_cloud_debugger_test <commit_msg>Fix tests<commit_after>// Copyright 2017 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include <gtest/gtest.h> #include <algorithm> #include <cstdlib> #include <string> #include "ccomptr.h" #include "custom_binary_reader.h" #include "dbg_breakpoint.h" #include "dbg_object.h" #include "i_cor_debug_mocks.h" #include "i_dbg_object_factory_mock.h" #include "i_dbg_stack_frame_mock.h" #include "i_eval_coordinator_mock.h" #include "i_portable_pdb_mocks.h" #include "i_stack_frame_collection_mock.h" using google::cloud::diagnostics::debug::Breakpoint; using google_cloud_debugger::CComPtr; using google_cloud_debugger::DbgBreakpoint; using google_cloud_debugger_portable_pdb::IDocumentIndex; using google_cloud_debugger_portable_pdb::MethodInfo; using google_cloud_debugger_portable_pdb::SequencePoint; using std::max; using std::string; using std::unique_ptr; using std::vector; using ::testing::_; using ::testing::Const; using ::testing::Return; using ::testing::ReturnRef; using ::testing::SetArgPointee; namespace google_cloud_debugger_test { // Test Fixture for DbgBreakpoint // Sets up a default DbgBreakpoint for the test. class DbgBreakpointTest : public ::testing::Test { protected: virtual void SetUpBreakpoint() { breakpoint_.Initialize(file_name_, id_, line_, column_, condition_, expressions_); // Gives the PDB file the same file name as this breakpoint's file name. pdb_file_fixture_.first_doc_.file_name_ = file_name_; pdb_file_fixture_.SetUpIPortablePDBFile(&file_mock_); } // ICorDebugBreakpoint associated with this breakpoint. ICorDebugBreakpointMock cordebug_breakpoint_; // Breakpoint. DbgBreakpoint breakpoint_; // File name of the breakpoint. string file_name_ = "My file"; // Lower case of the file name of the breakpoint. string lower_case_file_name_ = "my file"; string condition_; std::vector<string> expressions_; // Id of the breakpoint. string id_ = "My ID"; // Line number of breakpoint. uint32_t line_ = 32; // Column of the breakpoint. uint32_t column_ = 64; // Mock object for Portable PDB file. IPortablePdbFileMock file_mock_; // Fixture for the PDB File. PortablePDBFileFixture pdb_file_fixture_; // Mock stackframe, eval coordinator and object factory. IDbgStackFrameMock dbg_stack_frame_; IEvalCoordinatorMock eval_coordinator_mock_; IDbgObjectFactoryMock object_factory_; // Mock active debug frame. ICorDebugILFrameMock active_frame_mock_; }; // Tests that the Initialize function sets up the correct fields. TEST_F(DbgBreakpointTest, Initialize) { SetUpBreakpoint(); // The names stored should be lower case. EXPECT_EQ(breakpoint_.GetFileName(), lower_case_file_name_); EXPECT_EQ(breakpoint_.GetId(), id_); EXPECT_EQ(breakpoint_.GetLine(), line_); EXPECT_EQ(breakpoint_.GetColumn(), column_); // Now we use the other Initialize function, // file name, ID, line and column should be copied over. DbgBreakpoint breakpoint2; breakpoint2.Initialize(breakpoint_); EXPECT_EQ(breakpoint2.GetFileName(), breakpoint_.GetFileName()); EXPECT_EQ(breakpoint2.GetId(), breakpoint_.GetId()); EXPECT_EQ(breakpoint2.GetLine(), breakpoint_.GetLine()); EXPECT_EQ(breakpoint2.GetColumn(), breakpoint_.GetColumn()); } // Tests that the Set/GetMethodToken function sets up the correct fields. TEST_F(DbgBreakpointTest, SetGetMethodToken) { mdMethodDef method_token = 10; SetUpBreakpoint(); breakpoint_.SetMethodToken(method_token); EXPECT_EQ(breakpoint_.GetMethodToken(), method_token); } // Tests that Set/GetICorDebugBreakpoint function works. TEST_F(DbgBreakpointTest, SetGetICorDebugBreakpoint) { SetUpBreakpoint(); breakpoint_.SetCorDebugBreakpoint(&cordebug_breakpoint_); CComPtr<ICorDebugBreakpoint> cordebug_breakpoint2; HRESULT hr = breakpoint_.GetCorDebugBreakpoint(&cordebug_breakpoint2); EXPECT_TRUE(SUCCEEDED(hr)) << "Failed with hr: " << hr; } // Tests the error cases of Set/GetICorDebugBreakpoint function. TEST_F(DbgBreakpointTest, SetGetICorDebugBreakpointError) { SetUpBreakpoint(); // Null argument. EXPECT_EQ(breakpoint_.GetCorDebugBreakpoint(nullptr), E_INVALIDARG); // Calls without setting the breakpoint. CComPtr<ICorDebugBreakpoint> cordebug_breakpoint2; EXPECT_EQ(breakpoint_.GetCorDebugBreakpoint(&cordebug_breakpoint2), E_FAIL); } // Returns a method that contains a sequence point // thats contains breakpoint_line. Also sets the method // def to method_def and the IL Offset of the matching // sequence point to il_offset. MethodInfo MakeMatchingMethod(uint32_t breakpoint_line, uint32_t method_first_line, uint32_t method_def, uint32_t il_offset) { assert(method_first_line < breakpoint_line); // Minimum amount of lines from breakpoint to last line. uint32_t min_line = 10; // This method's first line is less than the breakpoint's line // and its last line is greater than the breakpoint's line, // so the TrySetBreakpoint method should be able to use this method. MethodInfo method; method.first_line = method_first_line; method.last_line = breakpoint_line + max(breakpoint_line, min_line); method.method_def = method_def; // Puts a sequence point that does not match the line of the breakpoint. SequencePoint seq_point; seq_point.start_line = method.first_line; // End line is between the start line of the method and breakpoint_line. seq_point.end_line = method.first_line + (rand() % (breakpoint_line - method.first_line)); seq_point.il_offset = rand() % il_offset; method.sequence_points.push_back(seq_point); assert(seq_point.end_line < breakpoint_line); // Puts in another sequence point that matches the line of the breakpoint. SequencePoint seq_point2; seq_point2.start_line = breakpoint_line; seq_point2.end_line = breakpoint_line + 1; seq_point2.il_offset = il_offset; method.sequence_points.push_back(seq_point2); // Puts a sequence point that does not match the line of the breakpoint. SequencePoint seq_point3; seq_point3.start_line = seq_point2.end_line + 1; // End line is between the start line of the method and breakpoint_line. seq_point3.end_line = seq_point3.end_line + 2; seq_point3.il_offset = il_offset + 10; method.sequence_points.push_back(seq_point3); assert(seq_point3.end_line < method.last_line); return method; } // Test the TrySetBreakpoint function of DbgBreakpoint. TEST_F(DbgBreakpointTest, TrySetBreakpoint) { SetUpBreakpoint(); // Gets a method that matches the breakpoint. uint32_t method_first_line = rand() % line_; uint32_t method_def = 100; uint32_t il_offset = 99; MethodInfo method = MakeMatchingMethod(line_, method_first_line, method_def, il_offset); // Gets another method that does not match the breakpoint. MethodInfo method2 = MakeMatchingMethod(line_ * 2, line_ + 1, method_def * 2, il_offset * 2); // Push the methods into the method vector that // the document index matching this Breakpoint will return. pdb_file_fixture_.first_doc_.methods_.push_back(method); pdb_file_fixture_.first_doc_.methods_.push_back(method2); EXPECT_TRUE(breakpoint_.TrySetBreakpoint(&file_mock_)); EXPECT_EQ(breakpoint_.GetILOffset(), il_offset); EXPECT_EQ(breakpoint_.GetMethodDef(), method_def); } // Test the TrySetBreakpoint function of DbgBreakpoint // when there are multiple methods in the Document Index. TEST_F(DbgBreakpointTest, TrySetBreakpointWithMultipleMethods) { SetUpBreakpoint(); // Gets a method that matches the breakpoint. uint32_t method_first_line = line_ - 10; uint32_t method_def = 100; uint32_t il_offset = 99; MethodInfo method = MakeMatchingMethod(line_, method_first_line, method_def, il_offset); // Gets another method that does not match the breakpoint. uint32_t method2_first_line = line_ + 100; uint32_t method2_def = method_def * 2; uint32_t il_offset_2 = il_offset * 2; MethodInfo method2 = MakeMatchingMethod(line_ + 120, method2_first_line, method2_def, il_offset_2); // Makes another the method that match the breakpoint // but has start line greater than the first method (so // this method should be selected since it is a better match). uint32_t method3_first_line = line_ - 5; uint32_t method3_def = method_def * 3; uint32_t il_offset_3 = 130; MethodInfo method3 = MakeMatchingMethod(line_, method3_first_line, method3_def, il_offset_3); // Push the methods into the method vector that // the document index matching this Breakpoint will return. pdb_file_fixture_.first_doc_.methods_.push_back(method); pdb_file_fixture_.first_doc_.methods_.push_back(method2); pdb_file_fixture_.first_doc_.methods_.push_back(method3); EXPECT_TRUE(breakpoint_.TrySetBreakpoint(&file_mock_)); EXPECT_EQ(breakpoint_.GetILOffset(), il_offset_3); EXPECT_EQ(breakpoint_.GetMethodDef(), method3_def); } // Tests the case where no matching methods are found. TEST_F(DbgBreakpointTest, TrySetBreakpointWithNoMatching) { SetUpBreakpoint(); // Gets a method that does not match the breakpoint. uint32_t method_first_line = line_ + 5; uint32_t method_def = 100; uint32_t il_offset = 99; MethodInfo method = MakeMatchingMethod(line_ + 10, method_first_line, method_def, il_offset); // Gets another method that does not match the breakpoint. uint32_t method2_first_line = line_ + 100; uint32_t method2_def = method_def * 2; uint32_t il_offset_2 = il_offset * 2; MethodInfo method2 = MakeMatchingMethod(line_ + 120, method2_first_line, method2_def, il_offset_2); // Push the methods into the method vector that // the document index matching this Breakpoint will return. pdb_file_fixture_.first_doc_.methods_.push_back(method); pdb_file_fixture_.first_doc_.methods_.push_back(method2); EXPECT_FALSE(breakpoint_.TrySetBreakpoint(&file_mock_)); } // Tests the PopulateBreakpoint function of DbgBreakpoint. TEST_F(DbgBreakpointTest, PopulateBreakpoint) { SetUpBreakpoint(); Breakpoint proto_breakpoint; IStackFrameCollectionMock stackframe_collection_mock; EXPECT_CALL( stackframe_collection_mock, PopulateStackFrames(&proto_breakpoint, &eval_coordinator_mock_)) .Times(1) .WillRepeatedly(Return(S_OK)); HRESULT hr = breakpoint_.PopulateBreakpoint( &proto_breakpoint, &stackframe_collection_mock, &eval_coordinator_mock_); EXPECT_TRUE(SUCCEEDED(hr)) << "Failed with hr: " << hr; // Checks that the proto breakpoint's properties are set. EXPECT_EQ(proto_breakpoint.location().line(), line_); EXPECT_EQ(proto_breakpoint.location().path(), lower_case_file_name_); EXPECT_EQ(proto_breakpoint.id(), id_); } // Tests the error cases of PopulateBreakpoint function of DbgBreakpoint. TEST_F(DbgBreakpointTest, PopulateBreakpointError) { SetUpBreakpoint(); Breakpoint proto_breakpoint; IStackFrameCollectionMock stackframe_collection_mock; // Checks for null error. EXPECT_EQ(breakpoint_.PopulateBreakpoint(nullptr, &stackframe_collection_mock, &eval_coordinator_mock_), E_INVALIDARG); EXPECT_EQ(breakpoint_.PopulateBreakpoint(&proto_breakpoint, nullptr, &eval_coordinator_mock_), E_INVALIDARG); EXPECT_EQ(breakpoint_.PopulateBreakpoint( &proto_breakpoint, &stackframe_collection_mock, nullptr), E_INVALIDARG); // Makes PopulateStackFrames returns error. EXPECT_CALL( stackframe_collection_mock, PopulateStackFrames(&proto_breakpoint, &eval_coordinator_mock_)) .Times(1) .WillRepeatedly(Return(CORDBG_E_BAD_REFERENCE_VALUE)); EXPECT_EQ(breakpoint_.PopulateBreakpoint(&proto_breakpoint, &stackframe_collection_mock, &eval_coordinator_mock_), CORDBG_E_BAD_REFERENCE_VALUE); } // Tests the EvaluateExpressions function of DbgBreakpoint. TEST_F(DbgBreakpointTest, EvaluateExpressions) { expressions_ = { "1", "2" }; SetUpBreakpoint(); EXPECT_CALL(eval_coordinator_mock_, GetActiveDebugFrame(_)) .Times(expressions_.size()) .WillOnce(DoAll(SetArgPointee<0>(&active_frame_mock_), Return(S_OK))); HRESULT hr = breakpoint_.EvaluateExpressions(&dbg_stack_frame_, &eval_coordinator_mock_, &object_factory_); EXPECT_TRUE(SUCCEEDED(hr)) << "Failed with hr: " << hr; } // Tests that after EvaluateExpressions is called, PopulateBreakpoint // populates breakpoint proto with expressions. TEST_F(DbgBreakpointTest, PopulateBreakpointExpression) { expressions_ = { "1", "2" }; SetUpBreakpoint(); EXPECT_CALL(eval_coordinator_mock_, GetActiveDebugFrame(_)) .Times(expressions_.size()) .WillRepeatedly(DoAll(SetArgPointee<0>(&active_frame_mock_), Return(S_OK))); HRESULT hr = breakpoint_.EvaluateExpressions(&dbg_stack_frame_, &eval_coordinator_mock_, &object_factory_); EXPECT_TRUE(SUCCEEDED(hr)) << "Failed with hr: " << hr; Breakpoint proto_breakpoint; IStackFrameCollectionMock stackframe_collection_mock; EXPECT_CALL( stackframe_collection_mock, PopulateStackFrames(&proto_breakpoint, &eval_coordinator_mock_)) .Times(1) .WillRepeatedly(Return(S_OK)); hr = breakpoint_.PopulateBreakpoint( &proto_breakpoint, &stackframe_collection_mock, &eval_coordinator_mock_); EXPECT_TRUE(SUCCEEDED(hr)) << "Failed with hr: " << hr; EXPECT_EQ(proto_breakpoint.evaluated_expressions_size(), 2); EXPECT_EQ(proto_breakpoint.evaluated_expressions(0).name(), "1"); EXPECT_EQ(proto_breakpoint.evaluated_expressions(0).value(), "1"); EXPECT_EQ(proto_breakpoint.evaluated_expressions(1).name(), "2"); EXPECT_EQ(proto_breakpoint.evaluated_expressions(1).value(), "2"); } } // namespace google_cloud_debugger_test <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: sreg.cxx,v $ * * $Revision: 1.7 $ * * last change: $Author: ihi $ $Date: 2007-09-13 18:06:40 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_lingucomponent.hxx" #include <cppuhelper/factory.hxx> // helper for factories #ifndef _RTL_STRING_HXX_ #include <rtl/string.hxx> #endif #include <com/sun/star/registry/XRegistryKey.hpp> using namespace rtl; using namespace com::sun::star::lang; using namespace com::sun::star::registry; //////////////////////////////////////// // declaration of external RegEntry-functions defined by the service objects // extern sal_Bool SAL_CALL SpellChecker_writeInfo( void * /*pServiceManager*/, XRegistryKey * pRegistryKey ); extern void * SAL_CALL SpellChecker_getFactory( const sal_Char * pImplName, XMultiServiceFactory * pServiceManager, void * /*pRegistryKey*/ ); //////////////////////////////////////// // definition of the two functions that are used to provide the services // extern "C" { sal_Bool SAL_CALL component_writeInfo( void * pServiceManager, XRegistryKey * pRegistryKey ) { return SpellChecker_writeInfo( pServiceManager, pRegistryKey ); } void SAL_CALL component_getImplementationEnvironment( const sal_Char ** ppEnvTypeName, uno_Environment ** /*ppEnv*/ ) { *ppEnvTypeName = CPPU_CURRENT_LANGUAGE_BINDING_NAME; } void * SAL_CALL component_getFactory( const sal_Char * pImplName, void * pServiceManager, void * pRegistryKey ) { void * pRet = NULL; pRet = SpellChecker_getFactory( pImplName, reinterpret_cast< XMultiServiceFactory * >( pServiceManager ), pRegistryKey ); return pRet; } } /////////////////////////////////////////////////////////////////////////// <commit_msg>INTEGRATION: CWS changefileheader (1.7.46); FILE MERGED 2008/04/01 15:21:14 thb 1.7.46.2: #i85898# Stripping all external header guards 2008/03/31 16:25:05 rt 1.7.46.1: #i87441# Change license header to LPGL v3.<commit_after>/************************************************************************* * * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * Copyright 2008 by Sun Microsystems, Inc. * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: sreg.cxx,v $ * $Revision: 1.8 $ * * This file is part of OpenOffice.org. * * OpenOffice.org is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License version 3 * only, as published by the Free Software Foundation. * * OpenOffice.org is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License version 3 for more details * (a copy is included in the LICENSE file that accompanied this code). * * You should have received a copy of the GNU Lesser General Public License * version 3 along with OpenOffice.org. If not, see * <http://www.openoffice.org/license.html> * for a copy of the LGPLv3 License. * ************************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_lingucomponent.hxx" #include <cppuhelper/factory.hxx> // helper for factories #include <rtl/string.hxx> #include <com/sun/star/registry/XRegistryKey.hpp> using namespace rtl; using namespace com::sun::star::lang; using namespace com::sun::star::registry; //////////////////////////////////////// // declaration of external RegEntry-functions defined by the service objects // extern sal_Bool SAL_CALL SpellChecker_writeInfo( void * /*pServiceManager*/, XRegistryKey * pRegistryKey ); extern void * SAL_CALL SpellChecker_getFactory( const sal_Char * pImplName, XMultiServiceFactory * pServiceManager, void * /*pRegistryKey*/ ); //////////////////////////////////////// // definition of the two functions that are used to provide the services // extern "C" { sal_Bool SAL_CALL component_writeInfo( void * pServiceManager, XRegistryKey * pRegistryKey ) { return SpellChecker_writeInfo( pServiceManager, pRegistryKey ); } void SAL_CALL component_getImplementationEnvironment( const sal_Char ** ppEnvTypeName, uno_Environment ** /*ppEnv*/ ) { *ppEnvTypeName = CPPU_CURRENT_LANGUAGE_BINDING_NAME; } void * SAL_CALL component_getFactory( const sal_Char * pImplName, void * pServiceManager, void * pRegistryKey ) { void * pRet = NULL; pRet = SpellChecker_getFactory( pImplName, reinterpret_cast< XMultiServiceFactory * >( pServiceManager ), pRegistryKey ); return pRet; } } /////////////////////////////////////////////////////////////////////////// <|endoftext|>
<commit_before>/******************************************************************************* * ALMA - Atacama Large Millimiter Array * (c) European Southern Observatory, 2011 * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * "@(#) $Id: bdNT32ReceiversTest.cpp,v 1.1 2011/11/30 15:47:32 bjeram Exp $" * * who when what * -------- -------- ---------------------------------------------- * bjeram 2011-04-19 created */ #include "bulkDataNTReceiverStream.h" #include "bulkDataNTCallback.h" #include <iostream> #include <ace/Get_Opt.h> #include <ace/Tokenizer_T.h> using namespace std; class TestCB: public BulkDataNTCallback { public: int cbStart(unsigned char* userParam_p, unsigned int size) { std::cout << "cbStart: got " << size << " :"; for(unsigned int i=0; i<size; i++) { std::cout << *(char*)(userParam_p+i); } std::cout << std::endl; return 0; } int cbReceive(unsigned char* data, unsigned int size) { // std::cout << "cbReceive: got " << size << " :"; /* for(unsigned int i=0; i<frame_p->length(); i++) { std::cout << *(char*)(frame_p->base()+i); } */ //std::cout << std::endl; return 0; } int cbStop() { std::cout << "cbStop" << std::endl; return 0; } }; int main(int argc, char *argv[]) { char c; unsigned int sleepPeriod=0; ReceiverFlowConfiguration cfg; //just LoggingProxy m_logger(0, 0, 31, 0); LoggingProxy::init (&m_logger); ACS_CHECK_LOGGER; char buf[]="00"; AcsBulkdata::BulkDataNTReceiverStream<TestCB>* receiverStreams[32]; for (int i=0; i<32; i++) { sprintf(buf, "%d", i); std::string streamName("Stream"); streamName += buf; std::cout << "Going to create stream: " << streamName << std::endl; receiverStreams[i] = new AcsBulkdata::BulkDataNTReceiverStream<TestCB>(streamName.c_str()); std::cout << "Stream: " << streamName << " has been created. Going to create a flow inside the stream" << std::endl; receiverStreams[i]->createFlow("00"); } getchar(); for (int i=0; i<32; i++) { std::cout << "Going to destroy stream: " << receiverStreams[i]->getName() << std::endl; delete receiverStreams[i]; } } <commit_msg>removed<commit_after><|endoftext|>
<commit_before>/* * Copyright (c) 2017, The OpenThread Authors. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. Neither the name of the copyright holder 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 HOLDER 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. */ /** * @file * This file implements the web server of border router */ #define OTBR_LOG_TAG "WEB" #include "web/web-service/web_server.hpp" #define BOOST_NO_CXX11_SCOPED_ENUMS #include <boost/filesystem.hpp> #undef BOOST_NO_CXX11_SCOPED_ENUMS #include <server_http.hpp> #include "common/code_utils.hpp" #include "common/logging.hpp" #define OT_ADD_PREFIX_PATH "^/add_prefix" #define OT_AVAILABLE_NETWORK_PATH "^/available_network$" #define OT_DELETE_PREFIX_PATH "^/delete_prefix" #define OT_FORM_NETWORK_PATH "^/form_network$" #define OT_GET_NETWORK_PATH "^/get_properties$" #define OT_JOIN_NETWORK_PATH "^/join_network$" #define OT_GET_QRCODE_PATH "^/get_qrcode$" #define OT_SET_NETWORK_PATH "^/settings$" #define OT_COMMISSIONER_START_PATH "^/commission$" #define OT_REQUEST_METHOD_GET "GET" #define OT_REQUEST_METHOD_POST "POST" #define OT_RESPONSE_SUCCESS_STATUS "HTTP/1.1 200 OK\r\n" #define OT_RESPONSE_HEADER_LENGTH "Content-Length: " #define OT_RESPONSE_HEADER_CSS_TYPE "\r\nContent-Type: text/css" #define OT_RESPONSE_HEADER_TYPE "Content-Type: application/json\r\n charset=utf-8" #define OT_RESPONSE_PLACEHOLD "\r\n\r\n" #define OT_RESPONSE_FAILURE_STATUS "HTTP/1.1 400 Bad Request\r\n" #define OT_BUFFER_SIZE 1024 namespace otbr { namespace Web { static void EscapeHtml(std::string &content) { std::string output; output.reserve(content.size()); for (char c : content) { switch (c) { case '&': output.append("&amp;"); break; case '<': output.append("&lt;"); break; case '>': output.append("&gt;"); break; case '"': output.append("&quot;"); break; case '\'': output.append("&apos;"); break; default: output.push_back(c); break; } } output.swap(content); } WebServer::WebServer(void) : mServer(new HttpServer()) { } WebServer::~WebServer(void) { delete mServer; } void WebServer::Init() { std::string networkName, extPanId; if (mWpanService.GetWpanServiceStatus(networkName, extPanId) > 0) { return; } } void WebServer::StartWebServer(const char *aIfName, const char *aListenAddr, uint16_t aPort) { if (aListenAddr != nullptr) { mServer->config.address = aListenAddr; } mServer->config.port = aPort; mWpanService.SetInterfaceName(aIfName); Init(); ResponseGetQRCode(); ResponseJoinNetwork(); ResponseFormNetwork(); ResponseAddOnMeshPrefix(); ResponseDeleteOnMeshPrefix(); ResponseGetStatus(); ResponseGetAvailableNetwork(); ResponseCommission(); DefaultHttpResponse(); try { mServer->start(); } catch (const std::exception &e) { otbrLogCrit("failed to start web server: %s", e.what()); abort(); } } void WebServer::StopWebServer(void) { try { mServer->stop(); } catch (const std::exception &e) { otbrLogCrit("failed to stop web server: %s", e.what()); } } void WebServer::HandleHttpRequest(const char *aUrl, const char *aMethod, HttpRequestCallback aCallback) { mServer->resource[aUrl][aMethod] = [aCallback, this](std::shared_ptr<HttpServer::Response> response, std::shared_ptr<HttpServer::Request> request) { try { std::string httpResponse; if (aCallback != nullptr) { httpResponse = aCallback(request->content.string(), this); } *response << OT_RESPONSE_SUCCESS_STATUS << OT_RESPONSE_HEADER_LENGTH << httpResponse.length() << OT_RESPONSE_PLACEHOLD << httpResponse; } catch (std::exception &e) { std::string content = e.what(); EscapeHtml(content); *response << OT_RESPONSE_FAILURE_STATUS << OT_RESPONSE_HEADER_LENGTH << strlen(e.what()) << OT_RESPONSE_PLACEHOLD << content; } }; } void DefaultResourceSend(const HttpServer & aServer, const std::shared_ptr<HttpServer::Response> &aResponse, const std::shared_ptr<std::ifstream> & aIfStream) { static std::vector<char> buffer(OT_BUFFER_SIZE); // Safe when server is running on one thread std::streamsize readLength; if ((readLength = aIfStream->read(&buffer[0], buffer.size()).gcount()) > 0) { aResponse->write(&buffer[0], readLength); if (readLength == static_cast<std::streamsize>(buffer.size())) { aServer.send(aResponse, [&aServer, aResponse, aIfStream](const boost::system::error_code &ec) { if (!ec) { DefaultResourceSend(aServer, aResponse, aIfStream); } else { std::cerr << "Connection interrupted" << std::endl; } }); } } } void WebServer::DefaultHttpResponse(void) { mServer->default_resource[OT_REQUEST_METHOD_GET] = [this](std::shared_ptr<HttpServer::Response> response, std::shared_ptr<HttpServer::Request> request) { try { auto webRootPath = boost::filesystem::canonical(WEB_FILE_PATH); auto path = boost::filesystem::canonical(webRootPath / request->path); // Check if path is within webRootPath if (std::distance(webRootPath.begin(), webRootPath.end()) > std::distance(path.begin(), path.end()) || !std::equal(webRootPath.begin(), webRootPath.end(), path.begin())) { throw std::invalid_argument("path must be within root path"); } if (boost::filesystem::is_directory(path)) { path /= "index.html"; } if (!(boost::filesystem::exists(path) && boost::filesystem::is_regular_file(path))) { throw std::invalid_argument("file does not exist"); } std::string cacheControl, etag; auto ifs = std::make_shared<std::ifstream>(); ifs->open(path.string(), std::ifstream::in | std::ios::binary | std::ios::ate); std::string extension = boost::filesystem::extension(path.string()); std::string style = ""; if (extension == ".css") { style = OT_RESPONSE_HEADER_CSS_TYPE; } if (*ifs) { auto length = ifs->tellg(); ifs->seekg(0, std::ios::beg); *response << OT_RESPONSE_SUCCESS_STATUS << cacheControl << etag << OT_RESPONSE_HEADER_LENGTH << length << style << OT_RESPONSE_PLACEHOLD; DefaultResourceSend(*mServer, response, ifs); } else { throw std::invalid_argument("could not read file"); } } catch (const std::exception &e) { std::string content = "Could not open path `" + request->path + "`: " + e.what(); EscapeHtml(content); *response << OT_RESPONSE_FAILURE_STATUS << OT_RESPONSE_HEADER_LENGTH << content.length() << OT_RESPONSE_PLACEHOLD << content; } }; } std::string WebServer::HandleJoinNetworkRequest(const std::string &aJoinRequest, void *aUserData) { WebServer *webServer = static_cast<WebServer *>(aUserData); return webServer->HandleJoinNetworkRequest(aJoinRequest); } std::string WebServer::HandleGetQRCodeRequest(const std::string &aGetQRCodeRequest, void *aUserData) { WebServer *webServer = static_cast<WebServer *>(aUserData); return webServer->HandleGetQRCodeRequest(aGetQRCodeRequest); } std::string WebServer::HandleFormNetworkRequest(const std::string &aFormRequest, void *aUserData) { WebServer *webServer = static_cast<WebServer *>(aUserData); return webServer->HandleFormNetworkRequest(aFormRequest); } std::string WebServer::HandleAddPrefixRequest(const std::string &aAddPrefixRequest, void *aUserData) { WebServer *webServer = static_cast<WebServer *>(aUserData); return webServer->HandleAddPrefixRequest(aAddPrefixRequest); } std::string WebServer::HandleDeletePrefixRequest(const std::string &aDeletePrefixRequest, void *aUserData) { WebServer *webServer = static_cast<WebServer *>(aUserData); return webServer->HandleDeletePrefixRequest(aDeletePrefixRequest); } std::string WebServer::HandleGetStatusRequest(const std::string &aGetStatusRequest, void *aUserData) { WebServer *webServer = static_cast<WebServer *>(aUserData); return webServer->HandleGetStatusRequest(aGetStatusRequest); } std::string WebServer::HandleGetAvailableNetworkResponse(const std::string &aGetAvailableNetworkRequest, void * aUserData) { WebServer *webServer = static_cast<WebServer *>(aUserData); return webServer->HandleGetAvailableNetworkResponse(aGetAvailableNetworkRequest); } std::string WebServer::HandleCommission(const std::string &aCommissionRequest, void *aUserData) { WebServer *webServer = static_cast<WebServer *>(aUserData); return webServer->HandleCommission(aCommissionRequest); } void WebServer::ResponseJoinNetwork(void) { HandleHttpRequest(OT_JOIN_NETWORK_PATH, OT_REQUEST_METHOD_POST, HandleJoinNetworkRequest); } void WebServer::ResponseGetQRCode(void) { HandleHttpRequest(OT_GET_QRCODE_PATH, OT_REQUEST_METHOD_GET, HandleGetQRCodeRequest); } void WebServer::ResponseFormNetwork(void) { HandleHttpRequest(OT_FORM_NETWORK_PATH, OT_REQUEST_METHOD_POST, HandleFormNetworkRequest); } void WebServer::ResponseAddOnMeshPrefix(void) { HandleHttpRequest(OT_ADD_PREFIX_PATH, OT_REQUEST_METHOD_POST, HandleAddPrefixRequest); } void WebServer::ResponseDeleteOnMeshPrefix(void) { HandleHttpRequest(OT_DELETE_PREFIX_PATH, OT_REQUEST_METHOD_POST, HandleDeletePrefixRequest); } void WebServer::ResponseGetStatus(void) { HandleHttpRequest(OT_GET_NETWORK_PATH, OT_REQUEST_METHOD_GET, HandleGetStatusRequest); } void WebServer::ResponseGetAvailableNetwork(void) { HandleHttpRequest(OT_AVAILABLE_NETWORK_PATH, OT_REQUEST_METHOD_GET, HandleGetAvailableNetworkResponse); } void WebServer::ResponseCommission(void) { HandleHttpRequest(OT_COMMISSIONER_START_PATH, OT_REQUEST_METHOD_POST, HandleCommission); } std::string WebServer::HandleJoinNetworkRequest(const std::string &aJoinRequest) { return mWpanService.HandleJoinNetworkRequest(aJoinRequest); } std::string WebServer::HandleGetQRCodeRequest(const std::string &aGetQRCodeRequest) { OTBR_UNUSED_VARIABLE(aGetQRCodeRequest); return mWpanService.HandleGetQRCodeRequest(); } std::string WebServer::HandleFormNetworkRequest(const std::string &aFormRequest) { return mWpanService.HandleFormNetworkRequest(aFormRequest); } std::string WebServer::HandleAddPrefixRequest(const std::string &aAddPrefixRequest) { return mWpanService.HandleAddPrefixRequest(aAddPrefixRequest); } std::string WebServer::HandleDeletePrefixRequest(const std::string &aDeletePrefixRequest) { return mWpanService.HandleDeletePrefixRequest(aDeletePrefixRequest); } std::string WebServer::HandleGetStatusRequest(const std::string &aGetStatusRequest) { OTBR_UNUSED_VARIABLE(aGetStatusRequest); return mWpanService.HandleStatusRequest(); } std::string WebServer::HandleGetAvailableNetworkResponse(const std::string &aGetAvailableNetworkRequest) { OTBR_UNUSED_VARIABLE(aGetAvailableNetworkRequest); return mWpanService.HandleAvailableNetworkRequest(); } std::string WebServer::HandleCommission(const std::string &aCommissionRequest) { return mWpanService.HandleCommission(aCommissionRequest); } } // namespace Web } // namespace otbr <commit_msg>[web] set text/html Content-Type for html files (#1261)<commit_after>/* * Copyright (c) 2017, The OpenThread Authors. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. Neither the name of the copyright holder 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 HOLDER 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. */ /** * @file * This file implements the web server of border router */ #define OTBR_LOG_TAG "WEB" #include "web/web-service/web_server.hpp" #define BOOST_NO_CXX11_SCOPED_ENUMS #include <boost/filesystem.hpp> #undef BOOST_NO_CXX11_SCOPED_ENUMS #include <server_http.hpp> #include "common/code_utils.hpp" #include "common/logging.hpp" #define OT_ADD_PREFIX_PATH "^/add_prefix" #define OT_AVAILABLE_NETWORK_PATH "^/available_network$" #define OT_DELETE_PREFIX_PATH "^/delete_prefix" #define OT_FORM_NETWORK_PATH "^/form_network$" #define OT_GET_NETWORK_PATH "^/get_properties$" #define OT_JOIN_NETWORK_PATH "^/join_network$" #define OT_GET_QRCODE_PATH "^/get_qrcode$" #define OT_SET_NETWORK_PATH "^/settings$" #define OT_COMMISSIONER_START_PATH "^/commission$" #define OT_REQUEST_METHOD_GET "GET" #define OT_REQUEST_METHOD_POST "POST" #define OT_RESPONSE_SUCCESS_STATUS "HTTP/1.1 200 OK\r\n" #define OT_RESPONSE_HEADER_LENGTH "Content-Length: " #define OT_RESPONSE_HEADER_CSS_TYPE "\r\nContent-Type: text/css" #define OT_RESPONSE_HEADER_TEXT_HTML_TYPE "\r\nContent-Type: text/html; charset=utf-8" #define OT_RESPONSE_HEADER_TYPE "Content-Type: application/json\r\n charset=utf-8" #define OT_RESPONSE_PLACEHOLD "\r\n\r\n" #define OT_RESPONSE_FAILURE_STATUS "HTTP/1.1 400 Bad Request\r\n" #define OT_BUFFER_SIZE 1024 namespace otbr { namespace Web { static void EscapeHtml(std::string &content) { std::string output; output.reserve(content.size()); for (char c : content) { switch (c) { case '&': output.append("&amp;"); break; case '<': output.append("&lt;"); break; case '>': output.append("&gt;"); break; case '"': output.append("&quot;"); break; case '\'': output.append("&apos;"); break; default: output.push_back(c); break; } } output.swap(content); } WebServer::WebServer(void) : mServer(new HttpServer()) { } WebServer::~WebServer(void) { delete mServer; } void WebServer::Init() { std::string networkName, extPanId; if (mWpanService.GetWpanServiceStatus(networkName, extPanId) > 0) { return; } } void WebServer::StartWebServer(const char *aIfName, const char *aListenAddr, uint16_t aPort) { if (aListenAddr != nullptr) { mServer->config.address = aListenAddr; } mServer->config.port = aPort; mWpanService.SetInterfaceName(aIfName); Init(); ResponseGetQRCode(); ResponseJoinNetwork(); ResponseFormNetwork(); ResponseAddOnMeshPrefix(); ResponseDeleteOnMeshPrefix(); ResponseGetStatus(); ResponseGetAvailableNetwork(); ResponseCommission(); DefaultHttpResponse(); try { mServer->start(); } catch (const std::exception &e) { otbrLogCrit("failed to start web server: %s", e.what()); abort(); } } void WebServer::StopWebServer(void) { try { mServer->stop(); } catch (const std::exception &e) { otbrLogCrit("failed to stop web server: %s", e.what()); } } void WebServer::HandleHttpRequest(const char *aUrl, const char *aMethod, HttpRequestCallback aCallback) { mServer->resource[aUrl][aMethod] = [aCallback, this](std::shared_ptr<HttpServer::Response> response, std::shared_ptr<HttpServer::Request> request) { try { std::string httpResponse; if (aCallback != nullptr) { httpResponse = aCallback(request->content.string(), this); } *response << OT_RESPONSE_SUCCESS_STATUS << OT_RESPONSE_HEADER_LENGTH << httpResponse.length() << OT_RESPONSE_PLACEHOLD << httpResponse; } catch (std::exception &e) { std::string content = e.what(); EscapeHtml(content); *response << OT_RESPONSE_FAILURE_STATUS << OT_RESPONSE_HEADER_LENGTH << strlen(e.what()) << OT_RESPONSE_PLACEHOLD << content; } }; } void DefaultResourceSend(const HttpServer & aServer, const std::shared_ptr<HttpServer::Response> &aResponse, const std::shared_ptr<std::ifstream> & aIfStream) { static std::vector<char> buffer(OT_BUFFER_SIZE); // Safe when server is running on one thread std::streamsize readLength; if ((readLength = aIfStream->read(&buffer[0], buffer.size()).gcount()) > 0) { aResponse->write(&buffer[0], readLength); if (readLength == static_cast<std::streamsize>(buffer.size())) { aServer.send(aResponse, [&aServer, aResponse, aIfStream](const boost::system::error_code &ec) { if (!ec) { DefaultResourceSend(aServer, aResponse, aIfStream); } else { std::cerr << "Connection interrupted" << std::endl; } }); } } } void WebServer::DefaultHttpResponse(void) { mServer->default_resource[OT_REQUEST_METHOD_GET] = [this](std::shared_ptr<HttpServer::Response> response, std::shared_ptr<HttpServer::Request> request) { try { auto webRootPath = boost::filesystem::canonical(WEB_FILE_PATH); auto path = boost::filesystem::canonical(webRootPath / request->path); // Check if path is within webRootPath if (std::distance(webRootPath.begin(), webRootPath.end()) > std::distance(path.begin(), path.end()) || !std::equal(webRootPath.begin(), webRootPath.end(), path.begin())) { throw std::invalid_argument("path must be within root path"); } if (boost::filesystem::is_directory(path)) { path /= "index.html"; } if (!(boost::filesystem::exists(path) && boost::filesystem::is_regular_file(path))) { throw std::invalid_argument("file does not exist"); } std::string cacheControl, etag; auto ifs = std::make_shared<std::ifstream>(); ifs->open(path.string(), std::ifstream::in | std::ios::binary | std::ios::ate); std::string extension = boost::filesystem::extension(path.string()); std::string header = ""; if (extension == ".css") { header = OT_RESPONSE_HEADER_CSS_TYPE; } else if (extension == ".html") { header = OT_RESPONSE_HEADER_TEXT_HTML_TYPE; } if (*ifs) { auto length = ifs->tellg(); ifs->seekg(0, std::ios::beg); *response << OT_RESPONSE_SUCCESS_STATUS << cacheControl << etag << OT_RESPONSE_HEADER_LENGTH << length << header << OT_RESPONSE_PLACEHOLD; DefaultResourceSend(*mServer, response, ifs); } else { throw std::invalid_argument("could not read file"); } } catch (const std::exception &e) { std::string content = "Could not open path `" + request->path + "`: " + e.what(); EscapeHtml(content); *response << OT_RESPONSE_FAILURE_STATUS << OT_RESPONSE_HEADER_LENGTH << content.length() << OT_RESPONSE_PLACEHOLD << content; } }; } std::string WebServer::HandleJoinNetworkRequest(const std::string &aJoinRequest, void *aUserData) { WebServer *webServer = static_cast<WebServer *>(aUserData); return webServer->HandleJoinNetworkRequest(aJoinRequest); } std::string WebServer::HandleGetQRCodeRequest(const std::string &aGetQRCodeRequest, void *aUserData) { WebServer *webServer = static_cast<WebServer *>(aUserData); return webServer->HandleGetQRCodeRequest(aGetQRCodeRequest); } std::string WebServer::HandleFormNetworkRequest(const std::string &aFormRequest, void *aUserData) { WebServer *webServer = static_cast<WebServer *>(aUserData); return webServer->HandleFormNetworkRequest(aFormRequest); } std::string WebServer::HandleAddPrefixRequest(const std::string &aAddPrefixRequest, void *aUserData) { WebServer *webServer = static_cast<WebServer *>(aUserData); return webServer->HandleAddPrefixRequest(aAddPrefixRequest); } std::string WebServer::HandleDeletePrefixRequest(const std::string &aDeletePrefixRequest, void *aUserData) { WebServer *webServer = static_cast<WebServer *>(aUserData); return webServer->HandleDeletePrefixRequest(aDeletePrefixRequest); } std::string WebServer::HandleGetStatusRequest(const std::string &aGetStatusRequest, void *aUserData) { WebServer *webServer = static_cast<WebServer *>(aUserData); return webServer->HandleGetStatusRequest(aGetStatusRequest); } std::string WebServer::HandleGetAvailableNetworkResponse(const std::string &aGetAvailableNetworkRequest, void * aUserData) { WebServer *webServer = static_cast<WebServer *>(aUserData); return webServer->HandleGetAvailableNetworkResponse(aGetAvailableNetworkRequest); } std::string WebServer::HandleCommission(const std::string &aCommissionRequest, void *aUserData) { WebServer *webServer = static_cast<WebServer *>(aUserData); return webServer->HandleCommission(aCommissionRequest); } void WebServer::ResponseJoinNetwork(void) { HandleHttpRequest(OT_JOIN_NETWORK_PATH, OT_REQUEST_METHOD_POST, HandleJoinNetworkRequest); } void WebServer::ResponseGetQRCode(void) { HandleHttpRequest(OT_GET_QRCODE_PATH, OT_REQUEST_METHOD_GET, HandleGetQRCodeRequest); } void WebServer::ResponseFormNetwork(void) { HandleHttpRequest(OT_FORM_NETWORK_PATH, OT_REQUEST_METHOD_POST, HandleFormNetworkRequest); } void WebServer::ResponseAddOnMeshPrefix(void) { HandleHttpRequest(OT_ADD_PREFIX_PATH, OT_REQUEST_METHOD_POST, HandleAddPrefixRequest); } void WebServer::ResponseDeleteOnMeshPrefix(void) { HandleHttpRequest(OT_DELETE_PREFIX_PATH, OT_REQUEST_METHOD_POST, HandleDeletePrefixRequest); } void WebServer::ResponseGetStatus(void) { HandleHttpRequest(OT_GET_NETWORK_PATH, OT_REQUEST_METHOD_GET, HandleGetStatusRequest); } void WebServer::ResponseGetAvailableNetwork(void) { HandleHttpRequest(OT_AVAILABLE_NETWORK_PATH, OT_REQUEST_METHOD_GET, HandleGetAvailableNetworkResponse); } void WebServer::ResponseCommission(void) { HandleHttpRequest(OT_COMMISSIONER_START_PATH, OT_REQUEST_METHOD_POST, HandleCommission); } std::string WebServer::HandleJoinNetworkRequest(const std::string &aJoinRequest) { return mWpanService.HandleJoinNetworkRequest(aJoinRequest); } std::string WebServer::HandleGetQRCodeRequest(const std::string &aGetQRCodeRequest) { OTBR_UNUSED_VARIABLE(aGetQRCodeRequest); return mWpanService.HandleGetQRCodeRequest(); } std::string WebServer::HandleFormNetworkRequest(const std::string &aFormRequest) { return mWpanService.HandleFormNetworkRequest(aFormRequest); } std::string WebServer::HandleAddPrefixRequest(const std::string &aAddPrefixRequest) { return mWpanService.HandleAddPrefixRequest(aAddPrefixRequest); } std::string WebServer::HandleDeletePrefixRequest(const std::string &aDeletePrefixRequest) { return mWpanService.HandleDeletePrefixRequest(aDeletePrefixRequest); } std::string WebServer::HandleGetStatusRequest(const std::string &aGetStatusRequest) { OTBR_UNUSED_VARIABLE(aGetStatusRequest); return mWpanService.HandleStatusRequest(); } std::string WebServer::HandleGetAvailableNetworkResponse(const std::string &aGetAvailableNetworkRequest) { OTBR_UNUSED_VARIABLE(aGetAvailableNetworkRequest); return mWpanService.HandleAvailableNetworkRequest(); } std::string WebServer::HandleCommission(const std::string &aCommissionRequest) { return mWpanService.HandleCommission(aCommissionRequest); } } // namespace Web } // namespace otbr <|endoftext|>
<commit_before>// This file is part of SWGANH which is released under the MIT license. // See file LICENSE or go to http://swganh.com/LICENSE #ifndef WIN32 #include <Python.h> #endif #include "swganh/app/swganh_app.h" #include <algorithm> #include <exception> #include <fstream> #include <iostream> #ifdef WIN32 #include <regex> #else #include <boost/regex.hpp> #endif #include <boost/date_time/posix_time/posix_time.hpp> #include <boost/program_options.hpp> #include "swganh/logger.h" #include "swganh/database/database_manager_interface.h" #include "swganh/event_dispatcher.h" #include "swganh/plugin/plugin_manager.h" #include "swganh/service/datastore.h" #include "swganh/service/service_manager.h" #include "swganh/app/swganh_kernel.h" #include "swganh/combat/combat_service_interface.h" #include "swganh/chat/chat_service_interface.h" #include "swganh/character/character_service_interface.h" #include "swganh/login/login_service_interface.h" #include "swganh/connection/connection_service_interface.h" #include "swganh/simulation/simulation_service_interface.h" #include "swganh/scripting/utilities.h" #include "version.h" using namespace boost::asio; using namespace boost::program_options; using namespace std; using namespace swganh; using namespace swganh::app; using namespace swganh::chat; using namespace swganh::login; using namespace swganh::character; using namespace swganh::connection; using namespace swganh::simulation; using namespace swganh::galaxy; using swganh::plugin::RegistrationMap; #ifdef WIN32 using std::regex; using std::smatch; using std::regex_match; #else using boost::regex; using boost::smatch; using boost::regex_match; #endif options_description AppConfig::BuildConfigDescription() { options_description desc; desc.add_options() ("help,h", "Display help message and config options") ("server_mode", boost::program_options::value<std::string>(&server_mode)->default_value("all"), "Specifies the service configuration mode to run the server in.") ("plugin,p", boost::program_options::value<std::vector<std::string>>(&plugins), "Only used when single_server_mode is disabled, loads a module of the specified name") ("plugin_directory", value<string>(&plugin_directory)->default_value("plugins/"), "Directory containing the application plugins") ("script_directory", value<string>(&script_directory)->default_value("scripts"), "Directory containing the application scripts") ("tre_config", boost::program_options::value<std::string>(&tre_config), "File containing the tre configuration (live.cfg)") ("galaxy_name", boost::program_options::value<std::string>(&galaxy_name), "Name of the galaxy (cluster) to this process should run") ("resource_cache_size", boost::program_options::value<uint32_t>(&resource_cache_size), "Available cache size for the resource manager (in Megabytes)") ("db.galaxy_manager.host", boost::program_options::value<std::string>(&galaxy_manager_db.host), "Host address for the galaxy_manager datastore") ("db.galaxy_manager.schema", boost::program_options::value<std::string>(&galaxy_manager_db.schema), "Schema name for the galaxy_manager datastore") ("db.galaxy_manager.username", boost::program_options::value<std::string>(&galaxy_manager_db.username), "Username for authentication with the galaxy_manager datastore") ("db.galaxy_manager.password", boost::program_options::value<std::string>(&galaxy_manager_db.password), "Password for authentication with the galaxy_manager datastore") ("db.galaxy.host", boost::program_options::value<std::string>(&galaxy_db.host), "Host address for the galaxy datastore") ("db.galaxy.schema", boost::program_options::value<std::string>(&galaxy_db.schema), "Schema name for the galaxy datastore") ("db.galaxy.username", boost::program_options::value<std::string>(&galaxy_db.username), "Username for authentication with the galaxy datastore") ("db.galaxy.password", boost::program_options::value<std::string>(&galaxy_db.password), "Password for authentication with the galaxy datastore") ("service.login.udp_port", boost::program_options::value<uint16_t>(&login_config.listen_port), "The port the login service will listen for incoming client connections on") ("service.login.address", boost::program_options::value<string>(&login_config.listen_address), "The public address the login service will listen for incoming client connections on") ("service.login.status_check_duration_secs", boost::program_options::value<int>(&login_config.galaxy_status_check_duration_secs), "The amount of time between checks for updated galaxy status") ("service.login.login_error_timeout_secs", boost::program_options::value<int>(&login_config.login_error_timeout_secs)->default_value(5), "The number of seconds to wait before disconnecting a client after failed login attempt") ("service.login.auto_registration", boost::program_options::value<bool>(&login_config.login_auto_registration)->default_value(false), "Auto Registration flag") ("service.connection.ping_port", boost::program_options::value<uint16_t>(&connection_config.ping_port), "The port the connection service will listen for incoming client ping requests on") ("service.connection.udp_port", boost::program_options::value<uint16_t>(&connection_config.listen_port), "The port the connection service will listen for incoming client connections on") ("service.connection.address", boost::program_options::value<string>(&connection_config.listen_address), "The public address the connection service will listen for incoming client connections on") ; return desc; } SwganhApp::SwganhApp(int argc, char* argv[]) : io_service_() , io_work_(new boost::asio::io_service::work(io_service_)) { kernel_ = make_shared<SwganhKernel>(io_service_); running_ = false; initialized_ = false; Initialize(argc, argv); Start(); } SwganhApp::~SwganhApp() { Stop(); // Shutdown Event Dispatcher kernel_->GetEventDispatcher()->Shutdown(); kernel_.reset(); io_work_.reset(); // join the threadpool threads until each one has exited. for_each(io_threads_.begin(), io_threads_.end(), std::mem_fn(&boost::thread::join)); } void SwganhApp::Initialize(int argc, char* argv[]) { // Init Logging SetupLogging_(); // Load the configuration LoadAppConfig_(argc, argv); auto app_config = kernel_->GetAppConfig(); // Initialize kernel resources kernel_->GetDatabaseManager()->registerStorageType( "galaxy_manager", app_config.galaxy_manager_db.schema, app_config.galaxy_manager_db.host, app_config.galaxy_manager_db.username, app_config.galaxy_manager_db.password); kernel_->GetDatabaseManager()->registerStorageType( "galaxy", app_config.galaxy_db.schema, app_config.galaxy_db.host, app_config.galaxy_db.username, app_config.galaxy_db.password); CleanupServices_(); // append command dir std::string py_path = "import sys; sys.path.append('.'); sys.path.append('" + app_config.script_directory + "');"; { swganh::scripting::ScopedGilLock lock; PyRun_SimpleString(py_path.c_str()); } // Load the plugin configuration. LoadPlugins_(app_config.plugins); // Load core services LoadCoreServices_(); initialized_ = true; } void SwganhApp::Start() { if (!initialized_) { throw std::runtime_error("Called application Start before Initialize"); } running_ = true; // Start up a threadpool for running io_service based tasks/active objects // The increment starts at 2 because the main thread of execution already counts // as thread in use as does the console thread. for (uint32_t i = 1; i < boost::thread::hardware_concurrency(); ++i) { boost::thread t([this] () { io_service_.run(); }); #ifdef _WIN32 SetPriorityClass(t.native_handle(), REALTIME_PRIORITY_CLASS); #endif io_threads_.push_back(move(t)); } kernel_->GetServiceManager()->Start(); } void SwganhApp::Stop() { running_ = false; } bool SwganhApp::IsRunning() { return running_; } SwganhKernel* SwganhApp::GetAppKernel() const { return kernel_.get(); } void SwganhApp::StartInteractiveConsole() { swganh::scripting::ScopedGilLock lock; swganh::Logger::getInstance().DisableConsoleLogging(); #ifdef WIN32 std::system("cls"); #else if (std::system("clear") != 0) { LOG(::error) << "Error clearing screen, ignoring console mode"; return; } #endif std::cout << "swgpy console " << VERSION_MAJOR << "." << VERSION_MINOR << "." << VERSION_PATCH << std::endl; boost::python::object main = boost::python::object (boost::python::handle<>(boost::python::borrowed( PyImport_AddModule("__main__") ))); auto global_dict = main.attr("__dict__"); global_dict["kernel"] = boost::python::ptr(GetAppKernel()); PyRun_InteractiveLoop(stdin, "<stdin>"); swganh::Logger::getInstance().EnableConsoleLogging(); } void SwganhApp::LoadAppConfig_(int argc, char* argv[]) { auto config_description = kernel_->GetAppConfig().BuildConfigDescription(); variables_map vm; store(parse_command_line(argc, argv, config_description), vm); ifstream config_file("config/swganh.cfg"); if (!config_file.is_open()) { throw runtime_error("Unable to open the configuration file at: config/swganh.cfg"); } try { store(parse_config_file(config_file, config_description, true), vm); } catch(...) { throw runtime_error("Unable to parse the configuration file at: config/swganh.cfg"); } notify(vm); config_file.close(); if (vm.count("help")) { std::cout << config_description << "\n\n"; exit(0); } } void SwganhApp::LoadPlugins_(vector<string> plugins) { LOG(info) << "Loading plugins..."; if (!plugins.empty()) { auto plugin_manager = kernel_->GetPluginManager(); auto plugin_directory = kernel_->GetAppConfig().plugin_directory; for_each(plugins.begin(), plugins.end(), [plugin_manager, plugin_directory] (const string& plugin) { LOG(info) << "Loading plugin " << plugin; plugin_manager->LoadPlugin(plugin, plugin_directory); }); } LOG(info) << "Finished Loading plugins..."; } void SwganhApp::CleanupServices_() { auto service_directory = kernel_->GetServiceDirectory(); auto services = service_directory->getServiceSnapshot(service_directory->galaxy()); if (services.empty()) { return; } LOG(warning) << "Services were not shutdown properly"; for_each(services.begin(), services.end(), [this, &service_directory] (swganh::service::ServiceDescription& service) { service_directory->removeService(service); }); } void SwganhApp::LoadCoreServices_() { auto plugin_manager = kernel_->GetPluginManager(); auto registration_map = plugin_manager->registration_map(); regex rx("(?:.*\\:\\:)(.*Service)"); smatch m; for_each(registration_map.begin(), registration_map.end(), [this, &rx, &m] (RegistrationMap::value_type& entry) { std::string name = entry.first; if (entry.first.length() > 7 && regex_match(name, m, rx)) { auto service_name = m[1].str(); LOG(info) << "Loading Service " << name << "..."; auto service = kernel_->GetPluginManager()->CreateObject<swganh::service::ServiceInterface>(name); kernel_->GetServiceManager()->AddService(service_name, service); LOG(info) << "Loaded Service " << name; } }); auto app_config = kernel_->GetAppConfig(); if(strcmp("simulation", app_config.server_mode.c_str()) == 0 || strcmp("all", app_config.server_mode.c_str()) == 0) { auto simulation_service = kernel_->GetServiceManager()->GetService<SimulationServiceInterface>("SimulationService"); simulation_service->StartScene("corellia"); } } void SwganhApp::SetupLogging_() { swganh::Logger::getInstance().init("swganh"); }<commit_msg>Update src/swganh/app/swganh_app.cc<commit_after>// This file is part of SWGANH which is released under the MIT license. // See file LICENSE or go to http://swganh.com/LICENSE #ifndef WIN32 #include <Python.h> #endif #include "swganh/app/swganh_app.h" #include <algorithm> #include <exception> #include <fstream> #include <iostream> #ifdef WIN32 #include <regex> #else #include <boost/regex.hpp> #endif #include <boost/date_time/posix_time/posix_time.hpp> #include <boost/program_options.hpp> #include "swganh/logger.h" #include "swganh/database/database_manager_interface.h" #include "swganh/event_dispatcher.h" #include "swganh/plugin/plugin_manager.h" #include "swganh/service/datastore.h" #include "swganh/service/service_manager.h" #include "swganh/app/swganh_kernel.h" #include "swganh/combat/combat_service_interface.h" #include "swganh/chat/chat_service_interface.h" #include "swganh/character/character_service_interface.h" #include "swganh/login/login_service_interface.h" #include "swganh/connection/connection_service_interface.h" #include "swganh/simulation/simulation_service_interface.h" #include "swganh/scripting/utilities.h" #include "version.h" using namespace boost::asio; using namespace boost::program_options; using namespace std; using namespace swganh; using namespace swganh::app; using namespace swganh::chat; using namespace swganh::login; using namespace swganh::character; using namespace swganh::connection; using namespace swganh::simulation; using namespace swganh::galaxy; using swganh::plugin::RegistrationMap; #ifdef WIN32 using std::regex; using std::smatch; using std::regex_match; #else using boost::regex; using boost::smatch; using boost::regex_match; #endif options_description AppConfig::BuildConfigDescription() { options_description desc; desc.add_options() ("help,h", "Display help message and config options") ("server_mode", boost::program_options::value<std::string>(&server_mode)->default_value("all"), "Specifies the service configuration mode to run the server in.") ("plugin,p", boost::program_options::value<std::vector<std::string>>(&plugins), "Only used when single_server_mode is disabled, loads a module of the specified name") ("plugin_directory", value<string>(&plugin_directory)->default_value("plugins/"), "Directory containing the application plugins") ("script_directory", value<string>(&script_directory)->default_value("scripts"), "Directory containing the application scripts") ("tre_config", boost::program_options::value<std::string>(&tre_config), "File containing the tre configuration (live.cfg)") ("galaxy_name", boost::program_options::value<std::string>(&galaxy_name), "Name of the galaxy (cluster) to this process should run") ("resource_cache_size", boost::program_options::value<uint32_t>(&resource_cache_size), "Available cache size for the resource manager (in Megabytes)") ("db.galaxy_manager.host", boost::program_options::value<std::string>(&galaxy_manager_db.host), "Host address for the galaxy_manager datastore") ("db.galaxy_manager.schema", boost::program_options::value<std::string>(&galaxy_manager_db.schema), "Schema name for the galaxy_manager datastore") ("db.galaxy_manager.username", boost::program_options::value<std::string>(&galaxy_manager_db.username), "Username for authentication with the galaxy_manager datastore") ("db.galaxy_manager.password", boost::program_options::value<std::string>(&galaxy_manager_db.password), "Password for authentication with the galaxy_manager datastore") ("db.galaxy.host", boost::program_options::value<std::string>(&galaxy_db.host), "Host address for the galaxy datastore") ("db.galaxy.schema", boost::program_options::value<std::string>(&galaxy_db.schema), "Schema name for the galaxy datastore") ("db.galaxy.username", boost::program_options::value<std::string>(&galaxy_db.username), "Username for authentication with the galaxy datastore") ("db.galaxy.password", boost::program_options::value<std::string>(&galaxy_db.password), "Password for authentication with the galaxy datastore") ("service.login.udp_port", boost::program_options::value<uint16_t>(&login_config.listen_port), "The port the login service will listen for incoming client connections on") ("service.login.address", boost::program_options::value<string>(&login_config.listen_address), "The public address the login service will listen for incoming client connections on") ("service.login.status_check_duration_secs", boost::program_options::value<int>(&login_config.galaxy_status_check_duration_secs), "The amount of time between checks for updated galaxy status") ("service.login.login_error_timeout_secs", boost::program_options::value<int>(&login_config.login_error_timeout_secs)->default_value(5), "The number of seconds to wait before disconnecting a client after failed login attempt") ("service.login.auto_registration", boost::program_options::value<bool>(&login_config.login_auto_registration)->default_value(false), "Auto Registration flag") ("service.connection.ping_port", boost::program_options::value<uint16_t>(&connection_config.ping_port), "The port the connection service will listen for incoming client ping requests on") ("service.connection.udp_port", boost::program_options::value<uint16_t>(&connection_config.listen_port), "The port the connection service will listen for incoming client connections on") ("service.connection.address", boost::program_options::value<string>(&connection_config.listen_address), "The public address the connection service will listen for incoming client connections on") ; return desc; } SwganhApp::SwganhApp(int argc, char* argv[]) : io_service_() , io_work_(new boost::asio::io_service::work(io_service_)) { kernel_ = make_shared<SwganhKernel>(io_service_); running_ = false; initialized_ = false; Initialize(argc, argv); Start(); } SwganhApp::~SwganhApp() { Stop(); // Shutdown Event Dispatcher kernel_->GetEventDispatcher()->Shutdown(); kernel_.reset(); io_work_.reset(); // join the threadpool threads until each one has exited. for_each(io_threads_.begin(), io_threads_.end(), std::mem_fn(&boost::thread::join)); } void SwganhApp::Initialize(int argc, char* argv[]) { // Init Logging SetupLogging_(); // Load the configuration LoadAppConfig_(argc, argv); auto app_config = kernel_->GetAppConfig(); try { // Initialize kernel resources kernel_->GetDatabaseManager()->registerStorageType( "galaxy_manager", app_config.galaxy_manager_db.schema, app_config.galaxy_manager_db.host, app_config.galaxy_manager_db.username, app_config.galaxy_manager_db.password); kernel_->GetDatabaseManager()->registerStorageType( "galaxy", app_config.galaxy_db.schema, app_config.galaxy_db.host, app_config.galaxy_db.username, app_config.galaxy_db.password); } catch(...) { LOG(fatal) << "Database connection errors occurred. Did you forget to populate the db?"; } CleanupServices_(); // append command dir std::string py_path = "import sys; sys.path.append('.'); sys.path.append('" + app_config.script_directory + "');"; { swganh::scripting::ScopedGilLock lock; PyRun_SimpleString(py_path.c_str()); } // Load the plugin configuration. LoadPlugins_(app_config.plugins); // Load core services LoadCoreServices_(); initialized_ = true; } void SwganhApp::Start() { if (!initialized_) { throw std::runtime_error("Called application Start before Initialize"); } running_ = true; // Start up a threadpool for running io_service based tasks/active objects // The increment starts at 2 because the main thread of execution already counts // as thread in use as does the console thread. for (uint32_t i = 1; i < boost::thread::hardware_concurrency(); ++i) { boost::thread t([this] () { io_service_.run(); }); #ifdef _WIN32 SetPriorityClass(t.native_handle(), REALTIME_PRIORITY_CLASS); #endif io_threads_.push_back(move(t)); } kernel_->GetServiceManager()->Start(); } void SwganhApp::Stop() { running_ = false; } bool SwganhApp::IsRunning() { return running_; } SwganhKernel* SwganhApp::GetAppKernel() const { return kernel_.get(); } void SwganhApp::StartInteractiveConsole() { swganh::scripting::ScopedGilLock lock; swganh::Logger::getInstance().DisableConsoleLogging(); #ifdef WIN32 std::system("cls"); #else if (std::system("clear") != 0) { LOG(::error) << "Error clearing screen, ignoring console mode"; return; } #endif std::cout << "swgpy console " << VERSION_MAJOR << "." << VERSION_MINOR << "." << VERSION_PATCH << std::endl; boost::python::object main = boost::python::object (boost::python::handle<>(boost::python::borrowed( PyImport_AddModule("__main__") ))); auto global_dict = main.attr("__dict__"); global_dict["kernel"] = boost::python::ptr(GetAppKernel()); PyRun_InteractiveLoop(stdin, "<stdin>"); swganh::Logger::getInstance().EnableConsoleLogging(); } void SwganhApp::LoadAppConfig_(int argc, char* argv[]) { auto config_description = kernel_->GetAppConfig().BuildConfigDescription(); variables_map vm; store(parse_command_line(argc, argv, config_description), vm); ifstream config_file("config/swganh.cfg"); if (!config_file.is_open()) { throw runtime_error("Unable to open the configuration file at: config/swganh.cfg"); } try { store(parse_config_file(config_file, config_description, true), vm); } catch(...) { throw runtime_error("Unable to parse the configuration file at: config/swganh.cfg"); } notify(vm); config_file.close(); if (vm.count("help")) { std::cout << config_description << "\n\n"; exit(0); } } void SwganhApp::LoadPlugins_(vector<string> plugins) { LOG(info) << "Loading plugins..."; if (!plugins.empty()) { auto plugin_manager = kernel_->GetPluginManager(); auto plugin_directory = kernel_->GetAppConfig().plugin_directory; for_each(plugins.begin(), plugins.end(), [plugin_manager, plugin_directory] (const string& plugin) { LOG(info) << "Loading plugin " << plugin; plugin_manager->LoadPlugin(plugin, plugin_directory); }); } LOG(info) << "Finished Loading plugins..."; } void SwganhApp::CleanupServices_() { auto service_directory = kernel_->GetServiceDirectory(); auto services = service_directory->getServiceSnapshot(service_directory->galaxy()); if (services.empty()) { return; } LOG(warning) << "Services were not shutdown properly"; for_each(services.begin(), services.end(), [this, &service_directory] (swganh::service::ServiceDescription& service) { service_directory->removeService(service); }); } void SwganhApp::LoadCoreServices_() { auto plugin_manager = kernel_->GetPluginManager(); auto registration_map = plugin_manager->registration_map(); regex rx("(?:.*\\:\\:)(.*Service)"); smatch m; for_each(registration_map.begin(), registration_map.end(), [this, &rx, &m] (RegistrationMap::value_type& entry) { std::string name = entry.first; if (entry.first.length() > 7 && regex_match(name, m, rx)) { auto service_name = m[1].str(); LOG(info) << "Loading Service " << name << "..."; auto service = kernel_->GetPluginManager()->CreateObject<swganh::service::ServiceInterface>(name); kernel_->GetServiceManager()->AddService(service_name, service); LOG(info) << "Loaded Service " << name; } }); auto app_config = kernel_->GetAppConfig(); if(strcmp("simulation", app_config.server_mode.c_str()) == 0 || strcmp("all", app_config.server_mode.c_str()) == 0) { auto simulation_service = kernel_->GetServiceManager()->GetService<SimulationServiceInterface>("SimulationService"); simulation_service->StartScene("corellia"); } } void SwganhApp::SetupLogging_() { swganh::Logger::getInstance().init("swganh"); }<|endoftext|>
<commit_before>#include <stdio.h> #include <stdlib.h> #include <string.h> #ifdef USING_QT_UI #include <QtGui/QImage> #else #include "libpng17/png.h" #endif #include "png_load.h" #include "base/logging.h" // *image_data_ptr should be deleted with free() // return value of 1 == success. int pngLoad(const char *file, int *pwidth, int *pheight, unsigned char **image_data_ptr, bool flip) { #ifdef USING_QT_UI QImage image(file, "PNG"); if (image.isNull()) { ELOG("pngLoad: Error loading image %s", file); return 0; } if (flip) image = image.mirrored(); *pwidth = image.width(); *pheight = image.height(); *image_data_ptr = (unsigned char *)malloc(image.byteCount()); #if QT_VERSION < QT_VERSION_CHECK(5, 0, 0) image.convertToFormat(QImage::Format_ARGB32); uint32_t *src = (uint32_t*) image.bits(); uint32_t *dest = (uint32_t*) *image_data_ptr; // Qt4 does not support RGBA for (size_t sz = 0; sz < image.byteCount(); sz+=4, ++src, ++dest) { const uint32_t v = *src; *dest = (v & 0xFF00FF00) | ((v & 0xFF) << 16) | (( v >> 16 ) & 0xFF); // ARGB -> RGBA } #else image.convertToFormat(QImage::Format_RGBA8888); memcpy(image.bits(), *image_data_ptr, image.byteCount()); #endif #else if (flip) ELOG("pngLoad: flip flag not supported, image will be loaded upside down"); png_image png; memset(&png, 0, sizeof(png)); png.version = PNG_IMAGE_VERSION; png_image_begin_read_from_file(&png, file); if (PNG_IMAGE_FAILED(png)) { ELOG("pngLoad: %s", png.message); return 0; } *pwidth = png.width; *pheight = png.height; png.format = PNG_FORMAT_RGBA; int stride = PNG_IMAGE_ROW_STRIDE(png); *image_data_ptr = (unsigned char *)malloc(PNG_IMAGE_SIZE(png)); png_image_finish_read(&png, NULL, *image_data_ptr, stride, NULL); #endif return 1; } int pngLoadPtr(const unsigned char *input_ptr, size_t input_len, int *pwidth, int *pheight, unsigned char **image_data_ptr, bool flip) { #ifdef USING_QT_UI QImage image; if (!image.loadFromData(input_ptr, input_len, "PNG")) { ELOG("pngLoad: Error loading image"); return 0; } if (flip) image = image.mirrored(); *pwidth = image.width(); *pheight = image.height(); *image_data_ptr = (unsigned char *)malloc(image.byteCount()); #if QT_VERSION < QT_VERSION_CHECK(5, 0, 0) uint32_t *src = (uint32_t*) image.bits(); uint32_t *dest = (uint32_t*) *image_data_ptr; // Qt4 does not support RGBA for (size_t sz = 0; sz < image.byteCount(); sz+=4, ++src, ++dest) { const uint32_t v = *src; *dest = (v & 0xFF00FF00) | ((v & 0xFF) << 16) | (( v >> 16 ) & 0xFF); // convert it! } #else image.convertToFormat(QImage::Format_RGBA8888); memcpy(image.bits(), *image_data_ptr, image.byteCount()); #endif #else if (flip) ELOG("pngLoad: flip flag not supported, image will be loaded upside down"); png_image png; memset(&png, 0, sizeof(png)); png.version = PNG_IMAGE_VERSION; png_image_begin_read_from_memory(&png, input_ptr, input_len); if (PNG_IMAGE_FAILED(png)) { ELOG("pngLoad: %s", png.message); return 0; } *pwidth = png.width; *pheight = png.height; png.format = PNG_FORMAT_RGBA; int stride = PNG_IMAGE_ROW_STRIDE(png); *image_data_ptr = (unsigned char *)malloc(PNG_IMAGE_SIZE(png)); png_image_finish_read(&png, NULL, *image_data_ptr, stride, NULL); #endif return 1; } <commit_msg>Qt: RGBA8888 only in Qt5.2+<commit_after>#include <stdio.h> #include <stdlib.h> #include <string.h> #ifdef USING_QT_UI #include <QtGui/QImage> #else #include "libpng17/png.h" #endif #include "png_load.h" #include "base/logging.h" // *image_data_ptr should be deleted with free() // return value of 1 == success. int pngLoad(const char *file, int *pwidth, int *pheight, unsigned char **image_data_ptr, bool flip) { #ifdef USING_QT_UI QImage image(file, "PNG"); if (image.isNull()) { ELOG("pngLoad: Error loading image %s", file); return 0; } if (flip) image = image.mirrored(); *pwidth = image.width(); *pheight = image.height(); *image_data_ptr = (unsigned char *)malloc(image.byteCount()); #if QT_VERSION < QT_VERSION_CHECK(5, 2, 0) image.convertToFormat(QImage::Format_ARGB32); uint32_t *src = (uint32_t*) image.bits(); uint32_t *dest = (uint32_t*) *image_data_ptr; // Qt4 does not support RGBA for (size_t sz = 0; sz < image.byteCount(); sz+=4, ++src, ++dest) { const uint32_t v = *src; *dest = (v & 0xFF00FF00) | ((v & 0xFF) << 16) | (( v >> 16 ) & 0xFF); // ARGB -> RGBA } #else image.convertToFormat(QImage::Format_RGBA8888); memcpy(image.bits(), *image_data_ptr, image.byteCount()); #endif #else if (flip) ELOG("pngLoad: flip flag not supported, image will be loaded upside down"); png_image png; memset(&png, 0, sizeof(png)); png.version = PNG_IMAGE_VERSION; png_image_begin_read_from_file(&png, file); if (PNG_IMAGE_FAILED(png)) { ELOG("pngLoad: %s", png.message); return 0; } *pwidth = png.width; *pheight = png.height; png.format = PNG_FORMAT_RGBA; int stride = PNG_IMAGE_ROW_STRIDE(png); *image_data_ptr = (unsigned char *)malloc(PNG_IMAGE_SIZE(png)); png_image_finish_read(&png, NULL, *image_data_ptr, stride, NULL); #endif return 1; } int pngLoadPtr(const unsigned char *input_ptr, size_t input_len, int *pwidth, int *pheight, unsigned char **image_data_ptr, bool flip) { #ifdef USING_QT_UI QImage image; if (!image.loadFromData(input_ptr, input_len, "PNG")) { ELOG("pngLoad: Error loading image"); return 0; } if (flip) image = image.mirrored(); *pwidth = image.width(); *pheight = image.height(); *image_data_ptr = (unsigned char *)malloc(image.byteCount()); #if QT_VERSION < QT_VERSION_CHECK(5, 0, 0) uint32_t *src = (uint32_t*) image.bits(); uint32_t *dest = (uint32_t*) *image_data_ptr; // Qt4 does not support RGBA for (size_t sz = 0; sz < image.byteCount(); sz+=4, ++src, ++dest) { const uint32_t v = *src; *dest = (v & 0xFF00FF00) | ((v & 0xFF) << 16) | (( v >> 16 ) & 0xFF); // convert it! } #else image.convertToFormat(QImage::Format_RGBA8888); memcpy(image.bits(), *image_data_ptr, image.byteCount()); #endif #else if (flip) ELOG("pngLoad: flip flag not supported, image will be loaded upside down"); png_image png; memset(&png, 0, sizeof(png)); png.version = PNG_IMAGE_VERSION; png_image_begin_read_from_memory(&png, input_ptr, input_len); if (PNG_IMAGE_FAILED(png)) { ELOG("pngLoad: %s", png.message); return 0; } *pwidth = png.width; *pheight = png.height; png.format = PNG_FORMAT_RGBA; int stride = PNG_IMAGE_ROW_STRIDE(png); *image_data_ptr = (unsigned char *)malloc(PNG_IMAGE_SIZE(png)); png_image_finish_read(&png, NULL, *image_data_ptr, stride, NULL); #endif return 1; } <|endoftext|>
<commit_before>#include "destructureTupleAssignments.h" #include "stmt.h" #include "expr.h" #include "type.h" #include "stringutil.h" void DestructureTupleAssignments::postProcessStmt(Stmt* stmt) { ExprStmt* assign_stmt = dynamic_cast<ExprStmt*>(stmt); if (!assign_stmt) { return; } AssignOp* assign_expr = dynamic_cast<AssignOp*>(assign_stmt->expr); if (!assign_expr) { return; } TupleType* left_type = dynamic_cast<TupleType*>(assign_expr->left->typeInfo()->getType()); TupleType* right_type = dynamic_cast<TupleType*>(assign_expr->right->typeInfo()->getType()); if (left_type && right_type) { return; } Tuple* left_tuple = dynamic_cast<Tuple*>(assign_expr->left); Tuple* right_tuple = dynamic_cast<Tuple*>(assign_expr->right); if (!left_type && !left_tuple && !right_type && !right_tuple) { return; } if (!left_type && !left_tuple) { INT_FATAL(stmt, "Tuple to non-tuple assignment should be caught earlier"); } if (!right_type && !right_tuple) { INT_FATAL(stmt, "Non-tuple to tuple assignment should be caught earlier"); } int left_n = (left_type) ? left_type->components.n : left_tuple->exprs->length(); int right_n = (right_type) ? right_type->components.n : right_tuple->exprs->length(); if (left_n != right_n) { INT_FATAL(stmt, "Non-matching tuple assign should be caught earlier"); } if (assign_expr->type != GETS_NORM) { INT_FATAL(stmt, "Non-standard tuple assign should be caught earlier"); } for (int i = 1; i <= left_n; i++) { TupleSelect* new_left = new TupleSelect(assign_expr->left->copy(), new IntLiteral(intstring(i), i)); TupleSelect* new_right = new TupleSelect(assign_expr->right->copy(), new IntLiteral(intstring(i), i)); AssignOp* new_assign_expr = new AssignOp(assign_expr->type, new_left, new_right); ExprStmt* new_assign_stmt = new ExprStmt(new_assign_expr); stmt->insertBefore(new_assign_stmt); } stmt->extract(); } <commit_msg>A small modification of this pass led to failure of test_index_expr1.chpl. Corrected that.<commit_after>#include "destructureTupleAssignments.h" #include "stmt.h" #include "expr.h" #include "type.h" #include "stringutil.h" void DestructureTupleAssignments::postProcessStmt(Stmt* stmt) { ExprStmt* assign_stmt = dynamic_cast<ExprStmt*>(stmt); if (!assign_stmt) { return; } AssignOp* assign_expr = dynamic_cast<AssignOp*>(assign_stmt->expr); if (!assign_expr) { return; } TupleType* left_type = dynamic_cast<TupleType*>(assign_expr->left->typeInfo()->getType()); TupleType* right_type = dynamic_cast<TupleType*>(assign_expr->right->typeInfo()->getType()); //RED -- temporary workaround the situation when a index is assigned to a tuple //the index->idxType may be a tuple and thus this test will pass //the downside is that index to tuple assignment still has to be destructured so this //leads to incorrect code generation if (left_type && right_type && (assign_expr->left->typeInfo() == assign_expr->right->typeInfo())) { return; } Tuple* left_tuple = dynamic_cast<Tuple*>(assign_expr->left); Tuple* right_tuple = dynamic_cast<Tuple*>(assign_expr->right); if (!left_type && !left_tuple && !right_type && !right_tuple) { return; } if (!left_type && !left_tuple) { INT_FATAL(stmt, "Tuple to non-tuple assignment should be caught earlier"); } if (!right_type && !right_tuple) { INT_FATAL(stmt, "Non-tuple to tuple assignment should be caught earlier"); } int left_n = (left_type) ? left_type->components.n : left_tuple->exprs->length(); int right_n = (right_type) ? right_type->components.n : right_tuple->exprs->length(); if (left_n != right_n) { INT_FATAL(stmt, "Non-matching tuple assign should be caught earlier"); } if (assign_expr->type != GETS_NORM) { INT_FATAL(stmt, "Non-standard tuple assign should be caught earlier"); } for (int i = 1; i <= left_n; i++) { TupleSelect* new_left = new TupleSelect(assign_expr->left->copy(), new IntLiteral(intstring(i), i)); TupleSelect* new_right = new TupleSelect(assign_expr->right->copy(), new IntLiteral(intstring(i), i)); AssignOp* new_assign_expr = new AssignOp(assign_expr->type, new_left, new_right); ExprStmt* new_assign_stmt = new ExprStmt(new_assign_expr); stmt->insertBefore(new_assign_stmt); } stmt->extract(); } <|endoftext|>
<commit_before>#include "Base.h" #include "AudioBuffer.h" #include "FileSystem.h" #ifdef __ANDROID__ extern AAssetManager* __assetManager; #endif namespace gameplay { // Audio buffer cache static std::vector<AudioBuffer*> __buffers; #ifndef __ANDROID__ AudioBuffer::AudioBuffer(const char* path, ALuint buffer) : _filePath(path), _alBuffer(buffer) { } #else AudioBuffer::AudioBuffer(const char* path) : _filePath(path) { } #endif AudioBuffer::~AudioBuffer() { #ifndef __ANDROID__ if (_alBuffer) { alDeleteBuffers(1, &_alBuffer); _alBuffer = 0; } #endif } AudioBuffer* AudioBuffer::create(const char* path) { assert(path); // Search the cache for a stream from this file. unsigned int bufferCount = (unsigned int)__buffers.size(); AudioBuffer* buffer = NULL; for (unsigned int i = 0; i < bufferCount; i++) { buffer = __buffers[i]; if (buffer->_filePath.compare(path) == 0) { buffer->addRef(); return buffer; } } #ifndef __ANDROID__ ALuint alBuffer; ALCenum al_error; // Load audio data into a buffer. alGenBuffers(1, &alBuffer); al_error = alGetError(); if (al_error != AL_NO_ERROR) { LOG_ERROR_VARG("AudioBuffer alGenBuffers AL error: %d", al_error); alDeleteBuffers(1, &alBuffer); return NULL; } // Load sound file. FILE* file = FileSystem::openFile(path, "rb"); if (!file) { LOG_ERROR_VARG("Invalid audio buffer file: %s", path); goto cleanup; } // Read the file header char header[12]; if (fread(header, 1, 12, file) != 12) { LOG_ERROR_VARG("Invalid audio buffer file: %s", path); goto cleanup; } // Check the file format if (memcmp(header, "RIFF", 4) == 0) { if (!AudioBuffer::loadWav(file, alBuffer)) { LOG_ERROR_VARG("Invalid wave file: %s", path); goto cleanup; } } else if (memcmp(header, "OggS", 4) == 0) { if (!AudioBuffer::loadOgg(file, alBuffer)) { LOG_ERROR_VARG("Invalid ogg file: %s", path); goto cleanup; } } else { LOG_ERROR_VARG("Unsupported audio file: %s", path); } fclose(file); buffer = new AudioBuffer(path, alBuffer); // Add the buffer to the cache. __buffers.push_back(buffer); return buffer; cleanup: if (file) fclose(file); if (alBuffer) alDeleteBuffers(1, &alBuffer); return NULL; #else // Get the file header in order to determine the type. AAsset* asset = AAssetManager_open(__assetManager, path, AASSET_MODE_RANDOM); char header[12]; if (AAsset_read(asset, header, 12) != 12) { LOG_ERROR_VARG("Invalid audio buffer file: %s", path); return NULL; } // Get the file descriptor for the audio file. off_t start, length; int fd = AAsset_openFileDescriptor(asset, &start, &length); if (fd < 0) { LOG_ERROR_VARG("Failed to open file descriptor for asset: %s", path); return NULL; } AAsset_close(asset); SLDataLocator_AndroidFD data = {SL_DATALOCATOR_ANDROIDFD, fd, start, length}; // Set the appropriate mime type information. SLDataFormat_MIME mime; mime.formatType = SL_DATAFORMAT_MIME; std::string pathStr = path; if (memcmp(header, "RIFF", 4) == 0) { mime.mimeType = (SLchar*)"audio/x-wav"; mime.containerType = SL_CONTAINERTYPE_WAV; } else if (memcmp(header, "OggS", 4) == 0) { mime.mimeType = (SLchar*)"application/ogg"; mime.containerType = SL_CONTAINERTYPE_OGG; } else { LOG_ERROR_VARG("Unsupported audio file: %s", path); } buffer = new AudioBuffer(path); buffer->_data = data; buffer->_mime = mime; // Add the buffer to the cache. __buffers.push_back(buffer); return buffer; #endif } #ifndef __ANDROID__ bool AudioBuffer::loadWav(FILE* file, ALuint buffer) { unsigned char stream[12]; // Verify the wave fmt magic value meaning format. if (fread(stream, 1, 8, file) != 8 || memcmp(stream, "fmt ", 4) != 0 ) return false; // Check for a valid pcm format. if (fread(stream, 1, 2, file) != 2 || stream[1] != 0 || stream[0] != 1) { LOG_ERROR("Unsupported audio file, not PCM format."); return false; } // Get the channel count (16-bit little-endian) int channels; if (fread(stream, 1, 2, file) != 2) return false; channels = stream[1]<<8; channels |= stream[0]; // Get the sample frequency (32-bit little-endian) ALuint frequency; if (fread(stream, 1, 4, file) != 4) return false; frequency = stream[3]<<24; frequency |= stream[2]<<16; frequency |= stream[1]<<8; frequency |= stream[0]; // The next 6 bytes hold the block size and bytes-per-second. // We don't need that info, so just read and ignore it. // We could use this later if we need to know the duration. if (fread(stream, 1, 6, file) != 6) return false; // Get the bit depth (16-bit little-endian) int bits; if (fread(stream, 1, 2, file) != 2) return false; bits = stream[1]<<8; bits |= stream[0]; // Now convert the given channel count and bit depth into an OpenAL format. ALuint format = 0; if (bits == 8) { if (channels == 1) format = AL_FORMAT_MONO8; else if (channels == 2) format = AL_FORMAT_STEREO8; } else if (bits == 16) { if (channels == 1) format = AL_FORMAT_MONO16; else if (channels == 2) format = AL_FORMAT_STEREO16; } else { LOG_ERROR_VARG("Incompatible format: (%d, %d)", channels, bits); return false; } // Read the data chunk, which will hold the decoded sample data if (fread(stream, 1, 4, file) != 4 || memcmp(stream, "data", 4) != 0) { LOG_ERROR("WAV file has no data."); return false; } // Read how much data is remaining and buffer it up. unsigned int dataSize; fread(&dataSize, sizeof(int), 1, file); char* data = new char[dataSize]; if (fread(data, sizeof(char), dataSize, file) != dataSize) { LOG_ERROR("WAV file missing data."); SAFE_DELETE_ARRAY(data); return false; } alBufferData(buffer, format, data, dataSize, frequency); SAFE_DELETE_ARRAY(data); return true; } bool AudioBuffer::loadOgg(FILE* file, ALuint buffer) { OggVorbis_File ogg_file; vorbis_info* info; ALenum format; int result; int section; unsigned int size = 0; rewind(file); if ((result = ov_open(file, &ogg_file, NULL, 0)) < 0) { fclose(file); LOG_ERROR("Could not open Ogg stream."); return false; } info = ov_info(&ogg_file, -1); if (info->channels == 1) format = AL_FORMAT_MONO16; else format = AL_FORMAT_STEREO16; // size = #samples * #channels * 2 (for 16 bit) unsigned int data_size = ov_pcm_total(&ogg_file, -1) * info->channels * 2; char* data = new char[data_size]; while (size < data_size) { result = ov_read(&ogg_file, data + size, data_size - size, 0, 2, 1, &section); if (result > 0) { size += result; } else if (result < 0) { SAFE_DELETE_ARRAY(data); LOG_ERROR("OGG file missing data."); return false; } else { break; } } if (size == 0) { SAFE_DELETE_ARRAY(data); LOG_ERROR("Unable to read OGG data."); return false; } alBufferData(buffer, format, data, data_size, info->rate); SAFE_DELETE_ARRAY(data); ov_clear(&ogg_file); // ov_clear actually closes the file pointer as well file = 0; return true; } #endif } <commit_msg>Fixing a bug with some of the .wav files not loading. All wave files are not guaranteed to have 16 bytes in the fmt section. There can be optional information in there. See http://www-mmsp.ece.mcgill.ca/documents/audioformats/wave/wave.html for example. Modified the code so that it accounts for those optional sections.<commit_after>#include "Base.h" #include "AudioBuffer.h" #include "FileSystem.h" #ifdef __ANDROID__ extern AAssetManager* __assetManager; #endif namespace gameplay { // Audio buffer cache static std::vector<AudioBuffer*> __buffers; #ifndef __ANDROID__ AudioBuffer::AudioBuffer(const char* path, ALuint buffer) : _filePath(path), _alBuffer(buffer) { } #else AudioBuffer::AudioBuffer(const char* path) : _filePath(path) { } #endif AudioBuffer::~AudioBuffer() { #ifndef __ANDROID__ if (_alBuffer) { alDeleteBuffers(1, &_alBuffer); _alBuffer = 0; } #endif } AudioBuffer* AudioBuffer::create(const char* path) { assert(path); // Search the cache for a stream from this file. unsigned int bufferCount = (unsigned int)__buffers.size(); AudioBuffer* buffer = NULL; for (unsigned int i = 0; i < bufferCount; i++) { buffer = __buffers[i]; if (buffer->_filePath.compare(path) == 0) { buffer->addRef(); return buffer; } } #ifndef __ANDROID__ ALuint alBuffer; ALCenum al_error; // Load audio data into a buffer. alGenBuffers(1, &alBuffer); al_error = alGetError(); if (al_error != AL_NO_ERROR) { LOG_ERROR_VARG("AudioBuffer alGenBuffers AL error: %d", al_error); alDeleteBuffers(1, &alBuffer); return NULL; } // Load sound file. FILE* file = FileSystem::openFile(path, "rb"); if (!file) { LOG_ERROR_VARG("Invalid audio buffer file: %s", path); goto cleanup; } // Read the file header char header[12]; if (fread(header, 1, 12, file) != 12) { LOG_ERROR_VARG("Invalid audio buffer file: %s", path); goto cleanup; } // Check the file format if (memcmp(header, "RIFF", 4) == 0) { if (!AudioBuffer::loadWav(file, alBuffer)) { LOG_ERROR_VARG("Invalid wave file: %s", path); goto cleanup; } } else if (memcmp(header, "OggS", 4) == 0) { if (!AudioBuffer::loadOgg(file, alBuffer)) { LOG_ERROR_VARG("Invalid ogg file: %s", path); goto cleanup; } } else { LOG_ERROR_VARG("Unsupported audio file: %s", path); } fclose(file); buffer = new AudioBuffer(path, alBuffer); // Add the buffer to the cache. __buffers.push_back(buffer); return buffer; cleanup: if (file) fclose(file); if (alBuffer) alDeleteBuffers(1, &alBuffer); return NULL; #else // Get the file header in order to determine the type. AAsset* asset = AAssetManager_open(__assetManager, path, AASSET_MODE_RANDOM); char header[12]; if (AAsset_read(asset, header, 12) != 12) { LOG_ERROR_VARG("Invalid audio buffer file: %s", path); return NULL; } // Get the file descriptor for the audio file. off_t start, length; int fd = AAsset_openFileDescriptor(asset, &start, &length); if (fd < 0) { LOG_ERROR_VARG("Failed to open file descriptor for asset: %s", path); return NULL; } AAsset_close(asset); SLDataLocator_AndroidFD data = {SL_DATALOCATOR_ANDROIDFD, fd, start, length}; // Set the appropriate mime type information. SLDataFormat_MIME mime; mime.formatType = SL_DATAFORMAT_MIME; std::string pathStr = path; if (memcmp(header, "RIFF", 4) == 0) { mime.mimeType = (SLchar*)"audio/x-wav"; mime.containerType = SL_CONTAINERTYPE_WAV; } else if (memcmp(header, "OggS", 4) == 0) { mime.mimeType = (SLchar*)"application/ogg"; mime.containerType = SL_CONTAINERTYPE_OGG; } else { LOG_ERROR_VARG("Unsupported audio file: %s", path); } buffer = new AudioBuffer(path); buffer->_data = data; buffer->_mime = mime; // Add the buffer to the cache. __buffers.push_back(buffer); return buffer; #endif } #ifndef __ANDROID__ bool AudioBuffer::loadWav(FILE* file, ALuint buffer) { unsigned char stream[12]; // Verify the wave fmt magic value meaning format. if (fread(stream, 1, 8, file) != 8 || memcmp(stream, "fmt ", 4) != 0 ) return false; unsigned int section_size; section_size = stream[7]<<24; section_size |= stream[6]<<16; section_size |= stream[5]<<8; section_size |= stream[4]; // Check for a valid pcm format. if (fread(stream, 1, 2, file) != 2 || stream[1] != 0 || stream[0] != 1) { LOG_ERROR("Unsupported audio file, not PCM format."); return false; } // Get the channel count (16-bit little-endian) int channels; if (fread(stream, 1, 2, file) != 2) return false; channels = stream[1]<<8; channels |= stream[0]; // Get the sample frequency (32-bit little-endian) ALuint frequency; if (fread(stream, 1, 4, file) != 4) return false; frequency = stream[3]<<24; frequency |= stream[2]<<16; frequency |= stream[1]<<8; frequency |= stream[0]; // The next 6 bytes hold the block size and bytes-per-second. // We don't need that info, so just read and ignore it. // We could use this later if we need to know the duration. if (fread(stream, 1, 6, file) != 6) return false; // Get the bit depth (16-bit little-endian) int bits; if (fread(stream, 1, 2, file) != 2) return false; bits = stream[1]<<8; bits |= stream[0]; // Now convert the given channel count and bit depth into an OpenAL format. ALuint format = 0; if (bits == 8) { if (channels == 1) format = AL_FORMAT_MONO8; else if (channels == 2) format = AL_FORMAT_STEREO8; } else if (bits == 16) { if (channels == 1) format = AL_FORMAT_MONO16; else if (channels == 2) format = AL_FORMAT_STEREO16; } else { LOG_ERROR_VARG("Incompatible format: (%d, %d)", channels, bits); return false; } // Check against the size of the format header as there may be more data that we need to read if (section_size > 16) { unsigned int length = section_size - 16; // extension size is 2 bytes if (fread(stream, 1, length, file) != length) return false; } if (fread(stream, 1, 4, file) != 4) return false; // read the next chunk, could be fact section or the data section if (memcmp(stream, "fact", 4) == 0) { if (fread(stream, 1, 4, file) != 4) return false; section_size = stream[3]<<24; section_size |= stream[2]<<16; section_size |= stream[1]<<8; section_size |= stream[0]; // read in the rest of the fact section if (fread(stream, 1, section_size, file) != section_size) return false; if (fread(stream, 1, 4, file) != 4) return false; } // should now be the data section which holds the decoded sample data if (memcmp(stream, "data", 4) != 0) { LOG_ERROR("WAV file has no data."); return false; } // Read how much data is remaining and buffer it up. unsigned int dataSize; fread(&dataSize, sizeof(int), 1, file); char* data = new char[dataSize]; if (fread(data, sizeof(char), dataSize, file) != dataSize) { LOG_ERROR("WAV file missing data."); SAFE_DELETE_ARRAY(data); return false; } alBufferData(buffer, format, data, dataSize, frequency); SAFE_DELETE_ARRAY(data); return true; } bool AudioBuffer::loadOgg(FILE* file, ALuint buffer) { OggVorbis_File ogg_file; vorbis_info* info; ALenum format; int result; int section; unsigned int size = 0; rewind(file); if ((result = ov_open(file, &ogg_file, NULL, 0)) < 0) { fclose(file); LOG_ERROR("Could not open Ogg stream."); return false; } info = ov_info(&ogg_file, -1); if (info->channels == 1) format = AL_FORMAT_MONO16; else format = AL_FORMAT_STEREO16; // size = #samples * #channels * 2 (for 16 bit) unsigned int data_size = ov_pcm_total(&ogg_file, -1) * info->channels * 2; char* data = new char[data_size]; while (size < data_size) { result = ov_read(&ogg_file, data + size, data_size - size, 0, 2, 1, &section); if (result > 0) { size += result; } else if (result < 0) { SAFE_DELETE_ARRAY(data); LOG_ERROR("OGG file missing data."); return false; } else { break; } } if (size == 0) { SAFE_DELETE_ARRAY(data); LOG_ERROR("Unable to read OGG data."); return false; } alBufferData(buffer, format, data, data_size, info->rate); SAFE_DELETE_ARRAY(data); ov_clear(&ogg_file); // ov_clear actually closes the file pointer as well file = 0; return true; } #endif } <|endoftext|>
<commit_before>#ifndef __FACTOR_MASTER_H__ #define __FACTOR_MASTER_H__ #ifndef _THREAD_SAFE #define _THREAD_SAFE #endif #ifndef _REENTRANT #define _REENTRANT #endif #include <errno.h> /* C headers */ #include <fcntl.h> #include <limits.h> #include <math.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <time.h> #include <wchar.h> #include <stdint.h> /* C++ headers */ #include <algorithm> #include <list> #include <map> #include <set> #include <vector> #include <iostream> #include <iomanip> #include <limits> #define FACTOR_STRINGIZE_I(x) #x #define FACTOR_STRINGIZE(x) FACTOR_STRINGIZE_I(x) /* Record compiler version */ #if defined(__clang__) #define FACTOR_COMPILER_VERSION "Clang (GCC " __VERSION__ ")" #elif defined(__INTEL_COMPILER) #define FACTOR_COMPILER_VERSION \ "Intel C Compiler " FACTOR_STRINGIZE(__INTEL_COMPILER) #elif defined(__GNUC__) #define FACTOR_COMPILER_VERSION "GCC " __VERSION__ #elif defined(_MSC_FULL_VER) #define FACTOR_COMPILER_VERSION \ "Microsoft Visual C++ " FACTOR_STRINGIZE(_MSC_FULL_VER) #else #define FACTOR_COMPILER_VERSION "unknown" #endif /* Detect target CPU type */ #if defined(__arm__) #define FACTOR_ARM #elif defined(__amd64__) || defined(__x86_64__) || defined(_M_AMD64) #define FACTOR_AMD64 #define FACTOR_64 #elif defined(i386) || defined(__i386) || defined(__i386__) || defined(_M_IX86) #define FACTOR_X86 #elif(defined(__POWERPC__) || defined(__ppc__) || defined(_ARCH_PPC)) && \ (defined(__PPC64__) || defined(__64BIT__)) #define FACTOR_PPC64 #define FACTOR_PPC #define FACTOR_64 #elif defined(__POWERPC__) || defined(__ppc__) || defined(_ARCH_PPC) #define FACTOR_PPC32 #define FACTOR_PPC #else #error "Unsupported architecture" #endif #if defined(_MSC_VER) #define WINDOWS #define WINNT #elif defined(WIN32) #define WINDOWS #endif /* Forward-declare this since it comes up in function prototypes */ namespace factor { struct factor_vm; } /* Factor headers */ #include "assert.hpp" #include "layouts.hpp" #include "platform.hpp" #include "primitives.hpp" #include "segments.hpp" #include "gc_info.hpp" #include "contexts.hpp" #include "run.hpp" #include "objects.hpp" #include "sampling_profiler.hpp" #include "errors.hpp" #include "bignumint.hpp" #include "bignum.hpp" #include "booleans.hpp" #include "instruction_operands.hpp" #include "code_blocks.hpp" #include "bump_allocator.hpp" #include "bitwise_hacks.hpp" #include "mark_bits.hpp" #include "free_list.hpp" #include "fixup.hpp" #include "tuples.hpp" #include "free_list_allocator.hpp" #include "write_barrier.hpp" #include "object_start_map.hpp" #include "nursery_space.hpp" #include "aging_space.hpp" #include "tenured_space.hpp" #include "data_heap.hpp" #include "code_heap.hpp" #include "gc.hpp" #include "strings.hpp" #include "float_bits.hpp" #include "io.hpp" #include "image.hpp" #include "callbacks.hpp" #include "dispatch.hpp" #include "entry_points.hpp" #include "safepoints.hpp" #include "vm.hpp" #include "allot.hpp" #include "tagged.hpp" #include "data_roots.hpp" #include "code_roots.hpp" #include "generic_arrays.hpp" #include "callstack.hpp" #include "slot_visitor.hpp" #include "collector.hpp" #include "copying_collector.hpp" #include "nursery_collector.hpp" #include "aging_collector.hpp" #include "to_tenured_collector.hpp" #include "code_block_visitor.hpp" #include "full_collector.hpp" #include "arrays.hpp" #include "math.hpp" #include "byte_arrays.hpp" #include "jit.hpp" #include "quotations.hpp" #include "inline_cache.hpp" #include "mvm.hpp" #include "factor.hpp" #include "utilities.hpp" #endif /* __FACTOR_MASTER_H__ */ <commit_msg>vm: Fix compilation on Windows. Fixes #1086.<commit_after>#ifndef __FACTOR_MASTER_H__ #define __FACTOR_MASTER_H__ #ifndef _THREAD_SAFE #define _THREAD_SAFE #endif #ifndef _REENTRANT #define _REENTRANT #endif #include <errno.h> /* C headers */ #include <fcntl.h> #include <limits.h> #include <math.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <time.h> #include <wchar.h> #include <stdint.h> /* C++ headers */ #include <algorithm> #include <list> #include <map> #include <set> #include <vector> #include <iostream> #include <iomanip> #include <limits> #include <string> #define FACTOR_STRINGIZE_I(x) #x #define FACTOR_STRINGIZE(x) FACTOR_STRINGIZE_I(x) /* Record compiler version */ #if defined(__clang__) #define FACTOR_COMPILER_VERSION "Clang (GCC " __VERSION__ ")" #elif defined(__INTEL_COMPILER) #define FACTOR_COMPILER_VERSION \ "Intel C Compiler " FACTOR_STRINGIZE(__INTEL_COMPILER) #elif defined(__GNUC__) #define FACTOR_COMPILER_VERSION "GCC " __VERSION__ #elif defined(_MSC_FULL_VER) #define FACTOR_COMPILER_VERSION \ "Microsoft Visual C++ " FACTOR_STRINGIZE(_MSC_FULL_VER) #else #define FACTOR_COMPILER_VERSION "unknown" #endif /* Detect target CPU type */ #if defined(__arm__) #define FACTOR_ARM #elif defined(__amd64__) || defined(__x86_64__) || defined(_M_AMD64) #define FACTOR_AMD64 #define FACTOR_64 #elif defined(i386) || defined(__i386) || defined(__i386__) || defined(_M_IX86) #define FACTOR_X86 #elif(defined(__POWERPC__) || defined(__ppc__) || defined(_ARCH_PPC)) && \ (defined(__PPC64__) || defined(__64BIT__)) #define FACTOR_PPC64 #define FACTOR_PPC #define FACTOR_64 #elif defined(__POWERPC__) || defined(__ppc__) || defined(_ARCH_PPC) #define FACTOR_PPC32 #define FACTOR_PPC #else #error "Unsupported architecture" #endif #if defined(_MSC_VER) #define WINDOWS #define WINNT #elif defined(WIN32) #define WINDOWS #endif /* Forward-declare this since it comes up in function prototypes */ namespace factor { struct factor_vm; } /* Factor headers */ #include "assert.hpp" #include "layouts.hpp" #include "platform.hpp" #include "primitives.hpp" #include "segments.hpp" #include "gc_info.hpp" #include "contexts.hpp" #include "run.hpp" #include "objects.hpp" #include "sampling_profiler.hpp" #include "errors.hpp" #include "bignumint.hpp" #include "bignum.hpp" #include "booleans.hpp" #include "instruction_operands.hpp" #include "code_blocks.hpp" #include "bump_allocator.hpp" #include "bitwise_hacks.hpp" #include "mark_bits.hpp" #include "free_list.hpp" #include "fixup.hpp" #include "tuples.hpp" #include "free_list_allocator.hpp" #include "write_barrier.hpp" #include "object_start_map.hpp" #include "nursery_space.hpp" #include "aging_space.hpp" #include "tenured_space.hpp" #include "data_heap.hpp" #include "code_heap.hpp" #include "gc.hpp" #include "strings.hpp" #include "float_bits.hpp" #include "io.hpp" #include "image.hpp" #include "callbacks.hpp" #include "dispatch.hpp" #include "entry_points.hpp" #include "safepoints.hpp" #include "vm.hpp" #include "allot.hpp" #include "tagged.hpp" #include "data_roots.hpp" #include "code_roots.hpp" #include "generic_arrays.hpp" #include "callstack.hpp" #include "slot_visitor.hpp" #include "collector.hpp" #include "copying_collector.hpp" #include "nursery_collector.hpp" #include "aging_collector.hpp" #include "to_tenured_collector.hpp" #include "code_block_visitor.hpp" #include "full_collector.hpp" #include "arrays.hpp" #include "math.hpp" #include "byte_arrays.hpp" #include "jit.hpp" #include "quotations.hpp" #include "inline_cache.hpp" #include "mvm.hpp" #include "factor.hpp" #include "utilities.hpp" #endif /* __FACTOR_MASTER_H__ */ <|endoftext|>
<commit_before>// Copyright (c) 2020 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include <netaddress.h> #include <test/fuzz/FuzzedDataProvider.h> #include <test/fuzz/fuzz.h> #include <cassert> #include <cstdint> #include <netinet/in.h> #include <vector> namespace { CNetAddr ConsumeNetAddr(FuzzedDataProvider& fuzzed_data_provider) noexcept { const Network network = fuzzed_data_provider.PickValueInArray({Network::NET_IPV4, Network::NET_IPV6, Network::NET_INTERNAL, Network::NET_ONION}); if (network == Network::NET_IPV4) { const in_addr v4_addr = { .s_addr = fuzzed_data_provider.ConsumeIntegral<uint32_t>()}; return CNetAddr{v4_addr}; } else if (network == Network::NET_IPV6) { if (fuzzed_data_provider.remaining_bytes() < 16) { return CNetAddr{}; } in6_addr v6_addr = {}; memcpy(v6_addr.s6_addr, fuzzed_data_provider.ConsumeBytes<uint8_t>(16).data(), 16); return CNetAddr{v6_addr, fuzzed_data_provider.ConsumeIntegral<uint32_t>()}; } else if (network == Network::NET_INTERNAL) { CNetAddr net_addr; net_addr.SetInternal(fuzzed_data_provider.ConsumeBytesAsString(32)); return net_addr; } else if (network == Network::NET_ONION) { CNetAddr net_addr; net_addr.SetSpecial(fuzzed_data_provider.ConsumeBytesAsString(32)); return net_addr; } else { assert(false); } } }; // namespace void test_one_input(const std::vector<uint8_t>& buffer) { FuzzedDataProvider fuzzed_data_provider(buffer.data(), buffer.size()); const CNetAddr net_addr = ConsumeNetAddr(fuzzed_data_provider); for (int i = 0; i < 15; ++i) { (void)net_addr.GetByte(i); } (void)net_addr.GetHash(); (void)net_addr.GetNetClass(); if (net_addr.GetNetwork() == Network::NET_IPV4) { assert(net_addr.IsIPv4()); } if (net_addr.GetNetwork() == Network::NET_IPV6) { assert(net_addr.IsIPv6()); } if (net_addr.GetNetwork() == Network::NET_ONION) { assert(net_addr.IsTor()); } if (net_addr.GetNetwork() == Network::NET_INTERNAL) { assert(net_addr.IsInternal()); } if (net_addr.GetNetwork() == Network::NET_UNROUTABLE) { assert(!net_addr.IsRoutable()); } (void)net_addr.IsBindAny(); if (net_addr.IsInternal()) { assert(net_addr.GetNetwork() == Network::NET_INTERNAL); } if (net_addr.IsIPv4()) { assert(net_addr.GetNetwork() == Network::NET_IPV4 || net_addr.GetNetwork() == Network::NET_UNROUTABLE); } if (net_addr.IsIPv6()) { assert(net_addr.GetNetwork() == Network::NET_IPV6 || net_addr.GetNetwork() == Network::NET_UNROUTABLE); } (void)net_addr.IsLocal(); if (net_addr.IsRFC1918() || net_addr.IsRFC2544() || net_addr.IsRFC6598() || net_addr.IsRFC5737() || net_addr.IsRFC3927()) { assert(net_addr.IsIPv4()); } (void)net_addr.IsRFC2544(); if (net_addr.IsRFC3849() || net_addr.IsRFC3964() || net_addr.IsRFC4380() || net_addr.IsRFC4843() || net_addr.IsRFC7343() || net_addr.IsRFC4862() || net_addr.IsRFC6052() || net_addr.IsRFC6145()) { assert(net_addr.IsIPv6()); } (void)net_addr.IsRFC3927(); (void)net_addr.IsRFC3964(); if (net_addr.IsRFC4193()) { assert(net_addr.GetNetwork() == Network::NET_ONION || net_addr.GetNetwork() == Network::NET_INTERNAL || net_addr.GetNetwork() == Network::NET_UNROUTABLE); } (void)net_addr.IsRFC4380(); (void)net_addr.IsRFC4843(); (void)net_addr.IsRFC4862(); (void)net_addr.IsRFC5737(); (void)net_addr.IsRFC6052(); (void)net_addr.IsRFC6145(); (void)net_addr.IsRFC6598(); (void)net_addr.IsRFC7343(); if (!net_addr.IsRoutable()) { assert(net_addr.GetNetwork() == Network::NET_UNROUTABLE || net_addr.GetNetwork() == Network::NET_INTERNAL); } if (net_addr.IsTor()) { assert(net_addr.GetNetwork() == Network::NET_ONION); } (void)net_addr.IsValid(); (void)net_addr.ToString(); (void)net_addr.ToStringIP(); const CSubNet sub_net{net_addr, fuzzed_data_provider.ConsumeIntegral<int32_t>()}; (void)sub_net.IsValid(); (void)sub_net.ToString(); const CService service{net_addr, fuzzed_data_provider.ConsumeIntegral<uint16_t>()}; (void)service.GetKey(); (void)service.GetPort(); (void)service.ToString(); (void)service.ToStringIPPort(); (void)service.ToStringPort(); const CNetAddr other_net_addr = ConsumeNetAddr(fuzzed_data_provider); (void)net_addr.GetReachabilityFrom(&other_net_addr); (void)sub_net.Match(other_net_addr); const CService other_service{net_addr, fuzzed_data_provider.ConsumeIntegral<uint16_t>()}; assert((service == other_service) != (service != other_service)); } <commit_msg>tests: Add fuzzing of CSubNet, CNetAddr and CService related functions<commit_after>// Copyright (c) 2020 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include <netaddress.h> #include <test/fuzz/FuzzedDataProvider.h> #include <test/fuzz/fuzz.h> #include <cassert> #include <cstdint> #include <netinet/in.h> #include <vector> namespace { CNetAddr ConsumeNetAddr(FuzzedDataProvider& fuzzed_data_provider) noexcept { const Network network = fuzzed_data_provider.PickValueInArray({Network::NET_IPV4, Network::NET_IPV6, Network::NET_INTERNAL, Network::NET_ONION}); if (network == Network::NET_IPV4) { const in_addr v4_addr = { .s_addr = fuzzed_data_provider.ConsumeIntegral<uint32_t>()}; return CNetAddr{v4_addr}; } else if (network == Network::NET_IPV6) { if (fuzzed_data_provider.remaining_bytes() < 16) { return CNetAddr{}; } in6_addr v6_addr = {}; memcpy(v6_addr.s6_addr, fuzzed_data_provider.ConsumeBytes<uint8_t>(16).data(), 16); return CNetAddr{v6_addr, fuzzed_data_provider.ConsumeIntegral<uint32_t>()}; } else if (network == Network::NET_INTERNAL) { CNetAddr net_addr; net_addr.SetInternal(fuzzed_data_provider.ConsumeBytesAsString(32)); return net_addr; } else if (network == Network::NET_ONION) { CNetAddr net_addr; net_addr.SetSpecial(fuzzed_data_provider.ConsumeBytesAsString(32)); return net_addr; } else { assert(false); } } }; // namespace void test_one_input(const std::vector<uint8_t>& buffer) { FuzzedDataProvider fuzzed_data_provider(buffer.data(), buffer.size()); const CNetAddr net_addr = ConsumeNetAddr(fuzzed_data_provider); for (int i = 0; i < 15; ++i) { (void)net_addr.GetByte(i); } (void)net_addr.GetHash(); (void)net_addr.GetNetClass(); if (net_addr.GetNetwork() == Network::NET_IPV4) { assert(net_addr.IsIPv4()); } if (net_addr.GetNetwork() == Network::NET_IPV6) { assert(net_addr.IsIPv6()); } if (net_addr.GetNetwork() == Network::NET_ONION) { assert(net_addr.IsTor()); } if (net_addr.GetNetwork() == Network::NET_INTERNAL) { assert(net_addr.IsInternal()); } if (net_addr.GetNetwork() == Network::NET_UNROUTABLE) { assert(!net_addr.IsRoutable()); } (void)net_addr.IsBindAny(); if (net_addr.IsInternal()) { assert(net_addr.GetNetwork() == Network::NET_INTERNAL); } if (net_addr.IsIPv4()) { assert(net_addr.GetNetwork() == Network::NET_IPV4 || net_addr.GetNetwork() == Network::NET_UNROUTABLE); } if (net_addr.IsIPv6()) { assert(net_addr.GetNetwork() == Network::NET_IPV6 || net_addr.GetNetwork() == Network::NET_UNROUTABLE); } (void)net_addr.IsLocal(); if (net_addr.IsRFC1918() || net_addr.IsRFC2544() || net_addr.IsRFC6598() || net_addr.IsRFC5737() || net_addr.IsRFC3927()) { assert(net_addr.IsIPv4()); } (void)net_addr.IsRFC2544(); if (net_addr.IsRFC3849() || net_addr.IsRFC3964() || net_addr.IsRFC4380() || net_addr.IsRFC4843() || net_addr.IsRFC7343() || net_addr.IsRFC4862() || net_addr.IsRFC6052() || net_addr.IsRFC6145()) { assert(net_addr.IsIPv6()); } (void)net_addr.IsRFC3927(); (void)net_addr.IsRFC3964(); if (net_addr.IsRFC4193()) { assert(net_addr.GetNetwork() == Network::NET_ONION || net_addr.GetNetwork() == Network::NET_INTERNAL || net_addr.GetNetwork() == Network::NET_UNROUTABLE); } (void)net_addr.IsRFC4380(); (void)net_addr.IsRFC4843(); (void)net_addr.IsRFC4862(); (void)net_addr.IsRFC5737(); (void)net_addr.IsRFC6052(); (void)net_addr.IsRFC6145(); (void)net_addr.IsRFC6598(); (void)net_addr.IsRFC7343(); if (!net_addr.IsRoutable()) { assert(net_addr.GetNetwork() == Network::NET_UNROUTABLE || net_addr.GetNetwork() == Network::NET_INTERNAL); } if (net_addr.IsTor()) { assert(net_addr.GetNetwork() == Network::NET_ONION); } (void)net_addr.IsValid(); (void)net_addr.ToString(); (void)net_addr.ToStringIP(); const CSubNet sub_net{net_addr, fuzzed_data_provider.ConsumeIntegral<int32_t>()}; (void)sub_net.IsValid(); (void)sub_net.ToString(); const CService service{net_addr, fuzzed_data_provider.ConsumeIntegral<uint16_t>()}; (void)service.GetKey(); (void)service.GetPort(); (void)service.ToString(); (void)service.ToStringIPPort(); (void)service.ToStringPort(); const CNetAddr other_net_addr = ConsumeNetAddr(fuzzed_data_provider); (void)net_addr.GetReachabilityFrom(&other_net_addr); (void)sub_net.Match(other_net_addr); const CService other_service{net_addr, fuzzed_data_provider.ConsumeIntegral<uint16_t>()}; assert((service == other_service) != (service != other_service)); (void)(service < other_service); const CSubNet sub_net_copy_1{net_addr, other_net_addr}; const CSubNet sub_net_copy_2{net_addr}; CNetAddr mutable_net_addr; mutable_net_addr.SetIP(net_addr); assert(net_addr == mutable_net_addr); } <|endoftext|>
<commit_before>/** ****************************************************************************** * Xenia : Xbox 360 Emulator Research Project * ****************************************************************************** * Copyright 2013 Ben Vanik. All rights reserved. * * Released under the BSD license - see LICENSE in the root for more details. * ****************************************************************************** */ #include <xenia/kernel/xboxkrnl_debug.h> #include <xenia/kernel/kernel_state.h> #include <xenia/kernel/xboxkrnl_private.h> #include <xenia/kernel/objects/xthread.h> #include <xenia/kernel/util/shim_utils.h> using namespace xe; using namespace xe::kernel; using namespace xe::kernel::xboxkrnl; namespace xe { namespace kernel { // TODO: clean me up! SHIM_CALL DbgPrint_shim( PPCContext* ppc_state, KernelState* state) { uint32_t format_ptr = SHIM_GET_ARG_32(0); if (format_ptr == 0) { SHIM_SET_RETURN(-1); return; } const char *format = (const char *)SHIM_MEM_ADDR(format_ptr); int arg_index = 0; char buffer[512]; // TODO: ensure it never writes past the end of the buffer... char *b = buffer; for (; *format != '\0'; ++format) { const char *start = format; if (*format != '%') { *b++ = *format; continue; } ++format; if (*format == '\0') { break; } if (*format == '%') { *b++ = *format; continue; } const char *end; end = format; // skip flags while (*end == '-' || *end == '+' || *end == ' ' || *end == '#' || *end == '0') { ++end; } if (*end == '\0') { break; } int arg_extras = 0; // skip width if (*end == '*') { ++end; arg_extras++; } else { while (*end >= '0' && *end <= '9') { ++end; } } if (*end == '\0') { break; } // skip precision if (*end == '.') { ++end; if (*end == '*') { ++end; ++arg_extras; } else { while (*end >= '0' && *end <= '9') { ++end; } } } if (*end == '\0') { break; } // get length int arg_size = 4; if (*end == 'h') { ++end; arg_size = 4; if (*end == 'h') { ++end; } } else if (*end == 'l') { ++end; arg_size = 4; if (*end == 'l') { ++end; arg_size = 8; } } else if (*end == 'j') { arg_size = 8; ++end; } else if (*end == 'z') { arg_size = 4; ++end; } else if (*end == 't') { arg_size = 8; ++end; } else if (*end == 'L') { arg_size = 8; ++end; } if (*end == '\0') { break; } if (*end == 'd' || *end == 'i' || *end == 'u' || *end == 'o' || *end == 'x' || *end == 'X' || *end == 'f' || *end == 'F' || *end == 'e' || *end == 'E' || *end == 'g' || *end == 'G' || *end == 'a' || *end == 'A' || *end == 'c') { char local[512]; local[0] = '\0'; strncat(local, start, end + 1 - start); XEASSERT(arg_size == 8 || arg_size == 4); if (arg_size == 8) { if (arg_extras == 0) { uint64_t value = arg_index < 7 ? SHIM_GET_ARG_64(1 + arg_index) : SHIM_MEM_32(SHIM_GPR_32(1) + 16 + ((1 + arg_index) * 8)); int result = sprintf(b, local, value); b += result; arg_index++; } else { XEASSERT(false); } } else if (arg_size == 4) { if (arg_extras == 0) { uint64_t value = arg_index < 7 ? SHIM_GET_ARG_64(1 + arg_index) : SHIM_MEM_32(SHIM_GPR_32(1) + 16 + ((1 + arg_index) * 8)); int result = sprintf(b, local, (uint32_t)value); b += result; arg_index++; } else { XEASSERT(false); } } } else if (*end == 's' || *end == 'p' || *end == 'n') { char local[512]; local[0] = '\0'; strncat(local, start, end + 1 - start); XEASSERT(arg_size == 4); if (arg_extras == 0) { uint32_t value = arg_index < 7 ? SHIM_GET_ARG_32(1 + arg_index) : (uint32_t)SHIM_MEM_64(SHIM_GPR_32(1) + 16 + ((1 + arg_index) * 8)); const char *pointer = (const char *)SHIM_MEM_ADDR(value); int result = sprintf(b, local, pointer); b += result; arg_index++; } else { XEASSERT(false); } } else { XEASSERT(false); break; } format = end; } *b++ = '\0'; XELOGD("(DbgPrint) %s", buffer); } void xeDbgBreakPoint() { DebugBreak(); } SHIM_CALL DbgBreakPoint_shim( PPCContext* ppc_state, KernelState* state) { XELOGD("DbgBreakPoint()"); } SHIM_CALL RtlRaiseException_shim( PPCContext* ppc_state, KernelState* state) { uint32_t record_ptr = SHIM_GET_ARG_32(0); uint32_t code = SHIM_MEM_32(record_ptr + 0); XELOGD( "RtlRaiseException(%.8X(%.8X))", record_ptr, code); XEASSERTALWAYS(); } } // namespace kernel } // namespace xe void xe::kernel::xboxkrnl::RegisterDebugExports( ExportResolver* export_resolver, KernelState* state) { SHIM_SET_MAPPING("xboxkrnl.exe", DbgPrint, state); SHIM_SET_MAPPING("xboxkrnl.exe", DbgBreakPoint, state); SHIM_SET_MAPPING("xboxkrnl.exe", RtlRaiseException, state); } <commit_msg>RtlRaiseException handling thread naming. But needs issue #54.<commit_after>/** ****************************************************************************** * Xenia : Xbox 360 Emulator Research Project * ****************************************************************************** * Copyright 2013 Ben Vanik. All rights reserved. * * Released under the BSD license - see LICENSE in the root for more details. * ****************************************************************************** */ #include <xenia/kernel/xboxkrnl_debug.h> #include <xenia/kernel/kernel_state.h> #include <xenia/kernel/xboxkrnl_private.h> #include <xenia/kernel/objects/xthread.h> #include <xenia/kernel/util/shim_utils.h> using namespace xe; using namespace xe::kernel; using namespace xe::kernel::xboxkrnl; namespace xe { namespace kernel { // TODO: clean me up! SHIM_CALL DbgPrint_shim( PPCContext* ppc_state, KernelState* state) { uint32_t format_ptr = SHIM_GET_ARG_32(0); if (format_ptr == 0) { SHIM_SET_RETURN(-1); return; } const char *format = (const char *)SHIM_MEM_ADDR(format_ptr); int arg_index = 0; char buffer[512]; // TODO: ensure it never writes past the end of the buffer... char *b = buffer; for (; *format != '\0'; ++format) { const char *start = format; if (*format != '%') { *b++ = *format; continue; } ++format; if (*format == '\0') { break; } if (*format == '%') { *b++ = *format; continue; } const char *end; end = format; // skip flags while (*end == '-' || *end == '+' || *end == ' ' || *end == '#' || *end == '0') { ++end; } if (*end == '\0') { break; } int arg_extras = 0; // skip width if (*end == '*') { ++end; arg_extras++; } else { while (*end >= '0' && *end <= '9') { ++end; } } if (*end == '\0') { break; } // skip precision if (*end == '.') { ++end; if (*end == '*') { ++end; ++arg_extras; } else { while (*end >= '0' && *end <= '9') { ++end; } } } if (*end == '\0') { break; } // get length int arg_size = 4; if (*end == 'h') { ++end; arg_size = 4; if (*end == 'h') { ++end; } } else if (*end == 'l') { ++end; arg_size = 4; if (*end == 'l') { ++end; arg_size = 8; } } else if (*end == 'j') { arg_size = 8; ++end; } else if (*end == 'z') { arg_size = 4; ++end; } else if (*end == 't') { arg_size = 8; ++end; } else if (*end == 'L') { arg_size = 8; ++end; } if (*end == '\0') { break; } if (*end == 'd' || *end == 'i' || *end == 'u' || *end == 'o' || *end == 'x' || *end == 'X' || *end == 'f' || *end == 'F' || *end == 'e' || *end == 'E' || *end == 'g' || *end == 'G' || *end == 'a' || *end == 'A' || *end == 'c') { char local[512]; local[0] = '\0'; strncat(local, start, end + 1 - start); XEASSERT(arg_size == 8 || arg_size == 4); if (arg_size == 8) { if (arg_extras == 0) { uint64_t value = arg_index < 7 ? SHIM_GET_ARG_64(1 + arg_index) : SHIM_MEM_32(SHIM_GPR_32(1) + 16 + ((1 + arg_index) * 8)); int result = sprintf(b, local, value); b += result; arg_index++; } else { XEASSERT(false); } } else if (arg_size == 4) { if (arg_extras == 0) { uint64_t value = arg_index < 7 ? SHIM_GET_ARG_64(1 + arg_index) : SHIM_MEM_32(SHIM_GPR_32(1) + 16 + ((1 + arg_index) * 8)); int result = sprintf(b, local, (uint32_t)value); b += result; arg_index++; } else { XEASSERT(false); } } } else if (*end == 's' || *end == 'p' || *end == 'n') { char local[512]; local[0] = '\0'; strncat(local, start, end + 1 - start); XEASSERT(arg_size == 4); if (arg_extras == 0) { uint32_t value = arg_index < 7 ? SHIM_GET_ARG_32(1 + arg_index) : (uint32_t)SHIM_MEM_64(SHIM_GPR_32(1) + 16 + ((1 + arg_index) * 8)); const char *pointer = (const char *)SHIM_MEM_ADDR(value); int result = sprintf(b, local, pointer); b += result; arg_index++; } else { XEASSERT(false); } } else { XEASSERT(false); break; } format = end; } *b++ = '\0'; XELOGD("(DbgPrint) %s", buffer); } void xeDbgBreakPoint() { DebugBreak(); } SHIM_CALL DbgBreakPoint_shim( PPCContext* ppc_state, KernelState* state) { XELOGD("DbgBreakPoint()"); } SHIM_CALL RtlRaiseException_shim( PPCContext* ppc_state, KernelState* state) { uint32_t record_ptr = SHIM_GET_ARG_32(0); uint32_t code = SHIM_MEM_32(record_ptr + 0); uint32_t flags = SHIM_MEM_32(record_ptr + 4); // ... uint32_t param_count = SHIM_MEM_32(record_ptr + 16); XELOGD( "RtlRaiseException(%.8X(%.8X))", record_ptr, code); if (code == 0x406D1388) { // SetThreadName. FFS. uint32_t thread_info_ptr = record_ptr + 20; uint32_t type = SHIM_MEM_32(thread_info_ptr + 0); XEASSERT(type == 0x1000); uint32_t name_ptr = SHIM_MEM_32(thread_info_ptr + 4); uint32_t thread_id = SHIM_MEM_32(thread_info_ptr + 8); const char* name = (const char*)SHIM_MEM_ADDR(name_ptr); XThread* thread = NULL; if (thread_id == -1) { // Current thread. thread = XThread::GetCurrentThread(); thread->Retain(); } else { // Lookup thread by ID. thread = state->GetThreadByID(thread_id); } if (thread) { thread->set_name(name); thread->Release(); } } // TODO(benvanik): unwinding. // This is going to suck. XEASSERTALWAYS(); } } // namespace kernel } // namespace xe void xe::kernel::xboxkrnl::RegisterDebugExports( ExportResolver* export_resolver, KernelState* state) { SHIM_SET_MAPPING("xboxkrnl.exe", DbgPrint, state); SHIM_SET_MAPPING("xboxkrnl.exe", DbgBreakPoint, state); SHIM_SET_MAPPING("xboxkrnl.exe", RtlRaiseException, state); } <|endoftext|>
<commit_before>/* Copyright (c) 2009 Sony Pictures Imageworks, et al. 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 Sony Pictures Imageworks 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. */ ///////////////////////////////////////////////////////////////////////// /// \file /// /// Shader interpreter implementation of control flow statements /// such as 'if', 'for', etc. /// ///////////////////////////////////////////////////////////////////////// #include <iostream> #include "oslexec_pvt.h" #include "oslops.h" #include "OpenImageIO/varyingref.h" #include "OpenImageIO/sysutil.h" #ifdef OSL_NAMESPACE namespace OSL_NAMESPACE { #endif namespace OSL { namespace pvt { DECLOP (OP_if) { ASSERT (nargs == 1); Symbol &Condition (exec->sym (args[0])); ASSERT (Condition.typespec().is_int()); VaryingRef<int> condition ((int *)Condition.data(), Condition.step()); Opcode &op (exec->op()); // Determine if it's a "uniform if" bool uniform = Condition.is_uniform (); if (! uniform) { // Second chance -- what if the condition is varying, but the // results are the same at all points? uniform = true; for (int i = beginpoint+1; i < endpoint; ++i) if (runflags[i] && condition[i] != condition[beginpoint]) { uniform = false; break; } } // FIXME -- if there's potentially a 'break' or 'continue' inside // this conditional, we need to treat it as varying. if (uniform) { // Uniform condition -- don't need new runflags if (condition[beginpoint]) { // Condition is true -- execute the true clause. // But if there is no else clause, do nothing (!) and the // normal execution will just take care of itself if (op.jump(1) != op.jump(0)) { exec->run (exec->ip()+1, op.jump(0)); // Run the true clause exec->ip (op.jump(1) - 1); // Skip the false clause } } else { // Condition is false -- just a jump to 'else' and keep going exec->ip (op.jump(0) - 1); } return; } // From here on, varying condition or potential break/continue at play // Generate new true and false runflags based on the condition Runflag *true_runflags = ALLOCA (Runflag, exec->npoints()); memcpy (true_runflags, runflags, exec->npoints() * sizeof(Runflag)); Runflag *false_runflags = ALLOCA (Runflag, exec->npoints()); memcpy (true_runflags, runflags, exec->npoints() * sizeof(Runflag)); for (int i = beginpoint; i < endpoint; ++i) { if (runflags[i]) { if (condition[i]) false_runflags[i] = RunflagOff; else true_runflags[i] = RunflagOff; } } // True clause exec->push_runflags (true_runflags, beginpoint, endpoint); exec->run (exec->ip() + 1, op.jump(0)); exec->pop_runflags (); // False clause if (op.jump(0) < op.jump(1)) { exec->push_runflags (false_runflags, beginpoint, endpoint); exec->run (op.jump(0), op.jump(1)); exec->pop_runflags (); } // Jump to after the if (remember that the interpreter loop will // increment the ip one more time, so back up one. exec->ip (op.jump(1) - 1); // FIXME -- we may need to call new_runflag_range here if, during // execution, we may have hit a 'break' or 'continue'. } DECLOP (OP_for) { ASSERT (nargs == 1); Symbol &Condition (exec->sym (args[0])); ASSERT (Condition.typespec().is_int()); Opcode &op (exec->op()); // Jump addresses int startinit = exec->ip() + 1; int startcondition = op.jump (0); int startbody = op.jump (1); int startiterate = op.jump (2); int done = op.jump (3); // Execute the initialization if (startinit < startcondition) exec->run (startinit, startcondition); Runflag *true_runflags = NULL; // Allocate as needed while (1) { // Execute the condition exec->run (startcondition, startbody); // Determine if it's a "uniform if" bool uniform = Condition.is_uniform (); VaryingRef<int> condition ((int *)Condition.data(), Condition.step()); // FIXME -- if there's potentially a 'break' or 'continue' inside // this loop, we need to treat it as varying. if (uniform) { // Uniform condition -- don't need new runflags if (condition[beginpoint]) exec->run (startbody, startiterate); // Run the body else break; // break out of the loop } else { // From here on, varying condition or potential // break/continue at play // Generate new runflags based on the condition if (! true_runflags) { true_runflags = ALLOCA (Runflag, exec->npoints()); memcpy (true_runflags, runflags, exec->npoints() * sizeof(Runflag)); exec->push_runflags (true_runflags, beginpoint, endpoint); } int turnedoff = 0; // Number of points that turned off bool all_off = true; // Are all points turned off? for (int i = beginpoint; i < endpoint; ++i) { if (true_runflags[i]) { if (condition[i]) all_off = false; // this point is still on else { // this point has turned off on this iteration true_runflags[i] = RunflagOff; ++turnedoff; } } } if (all_off) break; // No points left on // At least one point is still on if (turnedoff) { // If we turned off any "new" points on this iteration, // reset the runflags exec->pop_runflags (); exec->push_runflags (true_runflags, beginpoint, endpoint); } // Execute the body exec->run (startbody, startiterate); // FIXME -- we may need to call new_runflag_range here if, during // execution, we may have hit a 'break' or 'continue'. } if (startiterate < done) exec->run (startiterate, done); } if (true_runflags) { // Restore old runflags if we ever made new ones exec->pop_runflags (); } // Skip to after the loop exec->ip (done-1); } DECLOP (OP_dowhile) { ASSERT (nargs == 1); Symbol &Condition (exec->sym (args[0])); ASSERT (Condition.typespec().is_int()); Opcode &op (exec->op()); // Jump addresses int startinit = exec->ip() + 1; int startcondition = op.jump (0); int startbody = op.jump (1); int startiterate = op.jump (2); int done = op.jump (3); // Execute the initialization if (startinit < startcondition) exec->run (startinit, startcondition); Runflag *true_runflags = NULL; // Allocate as needed while (1) { // Execute the body exec->run (startbody, startiterate); // Execute the condition exec->run (startcondition, startbody); // Determine if it's a "uniform if" bool uniform = Condition.is_uniform (); VaryingRef<int> condition ((int *)Condition.data(), Condition.step()); // FIXME -- if there's potentially a 'break' or 'continue' inside // this loop, we need to treat it as varying. if (uniform) { // Uniform condition -- don't need new runflags if (condition[beginpoint]) continue; // All true, back to the beginning else break; // All false, break out of the loop } else { // From here on, varying condition or potential // break/continue at play // Generate new runflags based on the condition if (! true_runflags) { true_runflags = ALLOCA (Runflag, exec->npoints()); memcpy (true_runflags, runflags, exec->npoints() * sizeof(Runflag)); exec->push_runflags (true_runflags, beginpoint, endpoint); } int turnedoff = 0; // Number of points that turned off bool all_off = true; // Are all points turned off? for (int i = beginpoint; i < endpoint; ++i) { if (true_runflags[i]) { if (condition[i]) all_off = false; // this point is still on else { // this point has turned off on this iteration true_runflags[i] = RunflagOff; ++turnedoff; } } } if (all_off) break; // No points left on // At least one point is still on if (turnedoff) { // If we turned off any "new" points on this iteration, // reset the runflags exec->pop_runflags (); exec->push_runflags (true_runflags, beginpoint, endpoint); } // FIXME -- we may need to call new_runflag_range here if, during // execution, we may have hit a 'break' or 'continue'. } } if (true_runflags) { // Restore old runflags if we ever made new ones exec->pop_runflags (); } // Skip to after the loop exec->ip (done-1); } }; // namespace pvt }; // namespace OSL #ifdef OSL_NAMESPACE }; // end namespace OSL_NAMESPACE #endif <commit_msg>Bug fix -- wasn't initializing the 'false' case runflags for varying 'if'.<commit_after>/* Copyright (c) 2009 Sony Pictures Imageworks, et al. 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 Sony Pictures Imageworks 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. */ ///////////////////////////////////////////////////////////////////////// /// \file /// /// Shader interpreter implementation of control flow statements /// such as 'if', 'for', etc. /// ///////////////////////////////////////////////////////////////////////// #include <iostream> #include "oslexec_pvt.h" #include "oslops.h" #include "OpenImageIO/varyingref.h" #include "OpenImageIO/sysutil.h" #ifdef OSL_NAMESPACE namespace OSL_NAMESPACE { #endif namespace OSL { namespace pvt { DECLOP (OP_if) { ASSERT (nargs == 1); Symbol &Condition (exec->sym (args[0])); ASSERT (Condition.typespec().is_int()); VaryingRef<int> condition ((int *)Condition.data(), Condition.step()); Opcode &op (exec->op()); // Determine if it's a "uniform if" bool uniform = Condition.is_uniform (); if (! uniform) { // Second chance -- what if the condition is varying, but the // results are the same at all points? uniform = true; for (int i = beginpoint+1; i < endpoint; ++i) if (runflags[i] && condition[i] != condition[beginpoint]) { uniform = false; break; } } // FIXME -- if there's potentially a 'break' or 'continue' inside // this conditional, we need to treat it as varying. if (uniform) { // Uniform condition -- don't need new runflags if (condition[beginpoint]) { // Condition is true -- execute the true clause. // But if there is no else clause, do nothing (!) and the // normal execution will just take care of itself if (op.jump(1) != op.jump(0)) { exec->run (exec->ip()+1, op.jump(0)); // Run the true clause exec->ip (op.jump(1) - 1); // Skip the false clause } } else { // Condition is false -- just a jump to 'else' and keep going exec->ip (op.jump(0) - 1); } return; } // From here on, varying condition or potential break/continue at play // Generate new true and false runflags based on the condition Runflag *true_runflags = ALLOCA (Runflag, exec->npoints()); memcpy (true_runflags, runflags, exec->npoints() * sizeof(Runflag)); Runflag *false_runflags = ALLOCA (Runflag, exec->npoints()); memcpy (false_runflags, runflags, exec->npoints() * sizeof(Runflag)); for (int i = beginpoint; i < endpoint; ++i) { if (runflags[i]) { if (condition[i]) false_runflags[i] = RunflagOff; else true_runflags[i] = RunflagOff; } } // True clause exec->push_runflags (true_runflags, beginpoint, endpoint); exec->run (exec->ip() + 1, op.jump(0)); exec->pop_runflags (); // False clause if (op.jump(0) < op.jump(1)) { exec->push_runflags (false_runflags, beginpoint, endpoint); exec->run (op.jump(0), op.jump(1)); exec->pop_runflags (); } // Jump to after the if (remember that the interpreter loop will // increment the ip one more time, so back up one. exec->ip (op.jump(1) - 1); // FIXME -- we may need to call new_runflag_range here if, during // execution, we may have hit a 'break' or 'continue'. } DECLOP (OP_for) { ASSERT (nargs == 1); Symbol &Condition (exec->sym (args[0])); ASSERT (Condition.typespec().is_int()); Opcode &op (exec->op()); // Jump addresses int startinit = exec->ip() + 1; int startcondition = op.jump (0); int startbody = op.jump (1); int startiterate = op.jump (2); int done = op.jump (3); // Execute the initialization if (startinit < startcondition) exec->run (startinit, startcondition); Runflag *true_runflags = NULL; // Allocate as needed while (1) { // Execute the condition exec->run (startcondition, startbody); // Determine if it's a "uniform if" bool uniform = Condition.is_uniform (); VaryingRef<int> condition ((int *)Condition.data(), Condition.step()); // FIXME -- if there's potentially a 'break' or 'continue' inside // this loop, we need to treat it as varying. if (uniform) { // Uniform condition -- don't need new runflags if (condition[beginpoint]) exec->run (startbody, startiterate); // Run the body else break; // break out of the loop } else { // From here on, varying condition or potential // break/continue at play // Generate new runflags based on the condition if (! true_runflags) { true_runflags = ALLOCA (Runflag, exec->npoints()); memcpy (true_runflags, runflags, exec->npoints() * sizeof(Runflag)); exec->push_runflags (true_runflags, beginpoint, endpoint); } int turnedoff = 0; // Number of points that turned off bool all_off = true; // Are all points turned off? for (int i = beginpoint; i < endpoint; ++i) { if (true_runflags[i]) { if (condition[i]) all_off = false; // this point is still on else { // this point has turned off on this iteration true_runflags[i] = RunflagOff; ++turnedoff; } } } if (all_off) break; // No points left on // At least one point is still on if (turnedoff) { // If we turned off any "new" points on this iteration, // reset the runflags exec->pop_runflags (); exec->push_runflags (true_runflags, beginpoint, endpoint); } // Execute the body exec->run (startbody, startiterate); // FIXME -- we may need to call new_runflag_range here if, during // execution, we may have hit a 'break' or 'continue'. } if (startiterate < done) exec->run (startiterate, done); } if (true_runflags) { // Restore old runflags if we ever made new ones exec->pop_runflags (); } // Skip to after the loop exec->ip (done-1); } DECLOP (OP_dowhile) { ASSERT (nargs == 1); Symbol &Condition (exec->sym (args[0])); ASSERT (Condition.typespec().is_int()); Opcode &op (exec->op()); // Jump addresses int startinit = exec->ip() + 1; int startcondition = op.jump (0); int startbody = op.jump (1); int startiterate = op.jump (2); int done = op.jump (3); // Execute the initialization if (startinit < startcondition) exec->run (startinit, startcondition); Runflag *true_runflags = NULL; // Allocate as needed while (1) { // Execute the body exec->run (startbody, startiterate); // Execute the condition exec->run (startcondition, startbody); // Determine if it's a "uniform if" bool uniform = Condition.is_uniform (); VaryingRef<int> condition ((int *)Condition.data(), Condition.step()); // FIXME -- if there's potentially a 'break' or 'continue' inside // this loop, we need to treat it as varying. if (uniform) { // Uniform condition -- don't need new runflags if (condition[beginpoint]) continue; // All true, back to the beginning else break; // All false, break out of the loop } else { // From here on, varying condition or potential // break/continue at play // Generate new runflags based on the condition if (! true_runflags) { true_runflags = ALLOCA (Runflag, exec->npoints()); memcpy (true_runflags, runflags, exec->npoints() * sizeof(Runflag)); exec->push_runflags (true_runflags, beginpoint, endpoint); } int turnedoff = 0; // Number of points that turned off bool all_off = true; // Are all points turned off? for (int i = beginpoint; i < endpoint; ++i) { if (true_runflags[i]) { if (condition[i]) all_off = false; // this point is still on else { // this point has turned off on this iteration true_runflags[i] = RunflagOff; ++turnedoff; } } } if (all_off) break; // No points left on // At least one point is still on if (turnedoff) { // If we turned off any "new" points on this iteration, // reset the runflags exec->pop_runflags (); exec->push_runflags (true_runflags, beginpoint, endpoint); } // FIXME -- we may need to call new_runflag_range here if, during // execution, we may have hit a 'break' or 'continue'. } } if (true_runflags) { // Restore old runflags if we ever made new ones exec->pop_runflags (); } // Skip to after the loop exec->ip (done-1); } }; // namespace pvt }; // namespace OSL #ifdef OSL_NAMESPACE }; // end namespace OSL_NAMESPACE #endif <|endoftext|>
<commit_before>/*========================================================================= Library: CTK Copyright (c) Kitware Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0.txt Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. =========================================================================*/ // Qt includes #include <QApplication> #include <QDebug> #include <QIcon> #include <QMouseEvent> #include <QPainter> #include <QRect> #include <QStyleOption> // CTK includes #include "ctkSearchBox.h" // -------------------------------------------------- class ctkSearchBoxPrivate { Q_DECLARE_PUBLIC(ctkSearchBox); protected: ctkSearchBox* const q_ptr; public: ctkSearchBoxPrivate(ctkSearchBox& object); void init(); /// Position and size for the clear icon in the QLineEdit QRect clearRect()const; /// Position and size for the search icon in the QLineEdit QRect searchRect()const; QIcon clearIcon; QIcon searchIcon; QIcon::Mode clearIconMode; }; // -------------------------------------------------- ctkSearchBoxPrivate::ctkSearchBoxPrivate(ctkSearchBox &object) : q_ptr(&object) { this->clearIcon = QIcon(":Icons/clear.svg"); this->searchIcon = QIcon(":Icons/search.svg"); this->clearIconMode = QIcon::Disabled; } // -------------------------------------------------- void ctkSearchBoxPrivate::init() { Q_Q(ctkSearchBox); // Set a text by default on the QLineEdit q->setPlaceholderText(q->tr("Search...")); QObject::connect(q, SIGNAL(textChanged(const QString&)), q, SLOT(updateClearButtonState())); } // -------------------------------------------------- QRect ctkSearchBoxPrivate::clearRect()const { Q_Q(const ctkSearchBox); QRect cRect = this->searchRect(); cRect.moveLeft(q->width() - cRect.width() - cRect.left()); return cRect; } // -------------------------------------------------- QRect ctkSearchBoxPrivate::searchRect()const { Q_Q(const ctkSearchBox); QRect sRect; // If the QLineEdit has a frame, the icon must be shifted from // the frame line width if (q->hasFrame()) { QStyleOptionFrameV2 opt; q->initStyleOption(&opt); sRect.moveTopLeft(QPoint(opt.lineWidth, opt.lineWidth)); } // Hardcoded: shift by 1 pixel because some styles have a focus frame inside // the line edit frame. sRect.translate(QPoint(1,1)); // Square size sRect.setSize(QSize(q->height(),q->height()) - 2*QSize(sRect.left(), sRect.top())); return sRect; } // -------------------------------------------------- ctkSearchBox::ctkSearchBox(QWidget* _parent) : QLineEdit(_parent) , d_ptr(new ctkSearchBoxPrivate(*this)) { Q_D(ctkSearchBox); d->init(); } // -------------------------------------------------- ctkSearchBox::~ctkSearchBox() { } // -------------------------------------------------- void ctkSearchBox::paintEvent(QPaintEvent * event) { Q_D(ctkSearchBox); QPainter p(this); // Draw the line edit with text. // Text has already been shifted to the right (in resizeEvent()) to leave // space for the search icon. this->Superclass::paintEvent(event); // Draw clearIcon QRect cRect = d->clearRect(); QPixmap closePixmap = d->clearIcon.pixmap(cRect.size(),d->clearIconMode); this->style()->drawItemPixmap(&p, cRect, Qt::AlignCenter, closePixmap); // Draw searchIcon QRect sRect = d->searchRect(); QPixmap searchPixmap = d->searchIcon.pixmap(sRect.size()); this->style()->drawItemPixmap(&p, sRect, Qt::AlignCenter, searchPixmap); } // -------------------------------------------------- void ctkSearchBox::mousePressEvent(QMouseEvent *e) { Q_D(ctkSearchBox); if(d->clearRect().contains(e->pos())) { this->clear(); return; } if(d->searchRect().contains(e->pos())) { this->selectAll(); return; } this->Superclass::mousePressEvent(e); } // -------------------------------------------------- void ctkSearchBox::mouseMoveEvent(QMouseEvent *e) { Q_D(ctkSearchBox); if(d->clearRect().contains(e->pos()) || d->searchRect().contains(e->pos())) { this->setCursor(Qt::ArrowCursor); } else { this->setCursor(this->isReadOnly() ? Qt::ArrowCursor : Qt::IBeamCursor); } this->Superclass::mouseMoveEvent(e); } // -------------------------------------------------- void ctkSearchBox::resizeEvent(QResizeEvent * event) { Q_D(ctkSearchBox); static int iconSpacing = 4; // hardcoded, same way as pushbutton icon spacing QRect cRect = d->clearRect(); QRect sRect = d->searchRect(); // Set 2 margins each sides of the QLineEdit, according to the icons this->setTextMargins( sRect.right() + iconSpacing, 0, event->size().width() - cRect.left() - iconSpacing,0); } // -------------------------------------------------- void ctkSearchBox::updateClearButtonState() { Q_D(ctkSearchBox); d->clearIconMode = this->text().isEmpty() ? QIcon::Disabled : QIcon::Normal; } <commit_msg>Modification to fix a probleme under Windows<commit_after>/*========================================================================= Library: CTK Copyright (c) Kitware Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0.txt Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. =========================================================================*/ // Qt includes #include <QApplication> #include <QDebug> #include <QIcon> #include <QMouseEvent> #include <QPainter> #include <QRect> #include <QStyleOption> // CTK includes #include "ctkSearchBox.h" // -------------------------------------------------- class ctkSearchBoxPrivate { Q_DECLARE_PUBLIC(ctkSearchBox); protected: ctkSearchBox* const q_ptr; public: ctkSearchBoxPrivate(ctkSearchBox& object); void init(); /// Position and size for the clear icon in the QLineEdit QRect clearRect()const; /// Position and size for the search icon in the QLineEdit QRect searchRect()const; QIcon clearIcon; QIcon searchIcon; QIcon::Mode clearIconMode; }; // -------------------------------------------------- ctkSearchBoxPrivate::ctkSearchBoxPrivate(ctkSearchBox &object) : q_ptr(&object) { this->clearIcon = QIcon(":Icons/clear.svg"); this->searchIcon = QIcon(":Icons/search.svg"); this->clearIconMode = QIcon::Disabled; } // -------------------------------------------------- void ctkSearchBoxPrivate::init() { Q_Q(ctkSearchBox); // Set a text by default on the QLineEdit q->setPlaceholderText(q->tr("Search...")); QObject::connect(q, SIGNAL(textChanged(const QString&)), q, SLOT(updateClearButtonState())); } // -------------------------------------------------- QRect ctkSearchBoxPrivate::clearRect()const { Q_Q(const ctkSearchBox); QRect cRect = this->searchRect(); cRect.moveLeft(q->width() - cRect.width() - cRect.left()); return cRect; } // -------------------------------------------------- QRect ctkSearchBoxPrivate::searchRect()const { Q_Q(const ctkSearchBox); QRect sRect; // If the QLineEdit has a frame, the icon must be shifted from // the frame line width if (q->hasFrame()) { QStyleOptionFrameV2 opt; q->initStyleOption(&opt); sRect.moveTopLeft(QPoint(opt.lineWidth, opt.lineWidth)); } // Hardcoded: shift by 1 pixel because some styles have a focus frame inside // the line edit frame. sRect.translate(QPoint(1,1)); // Square size sRect.setSize(QSize(q->height(),q->height()) - 2*QSize(sRect.left(), sRect.top())); return sRect; } // -------------------------------------------------- ctkSearchBox::ctkSearchBox(QWidget* _parent) : QLineEdit(_parent) , d_ptr(new ctkSearchBoxPrivate(*this)) { Q_D(ctkSearchBox); d->init(); } // -------------------------------------------------- ctkSearchBox::~ctkSearchBox() { } // -------------------------------------------------- void ctkSearchBox::paintEvent(QPaintEvent * event) { Q_D(ctkSearchBox); // Draw the line edit with text. // Text has already been shifted to the right (in resizeEvent()) to leave // space for the search icon. this->Superclass::paintEvent(event); QPainter p(this); // Draw clearIcon QRect cRect = d->clearRect(); QPixmap closePixmap = d->clearIcon.pixmap(cRect.size(),d->clearIconMode); this->style()->drawItemPixmap(&p, cRect, Qt::AlignCenter, closePixmap); // Draw searchIcon QRect sRect = d->searchRect(); QPixmap searchPixmap = d->searchIcon.pixmap(sRect.size()); this->style()->drawItemPixmap(&p, sRect, Qt::AlignCenter, searchPixmap); } // -------------------------------------------------- void ctkSearchBox::mousePressEvent(QMouseEvent *e) { Q_D(ctkSearchBox); if(d->clearRect().contains(e->pos())) { this->clear(); return; } if(d->searchRect().contains(e->pos())) { this->selectAll(); return; } this->Superclass::mousePressEvent(e); } // -------------------------------------------------- void ctkSearchBox::mouseMoveEvent(QMouseEvent *e) { Q_D(ctkSearchBox); if(d->clearRect().contains(e->pos()) || d->searchRect().contains(e->pos())) { this->setCursor(Qt::ArrowCursor); } else { this->setCursor(this->isReadOnly() ? Qt::ArrowCursor : Qt::IBeamCursor); } this->Superclass::mouseMoveEvent(e); } // -------------------------------------------------- void ctkSearchBox::resizeEvent(QResizeEvent * event) { Q_D(ctkSearchBox); static int iconSpacing = 4; // hardcoded, same way as pushbutton icon spacing QRect cRect = d->clearRect(); QRect sRect = d->searchRect(); // Set 2 margins each sides of the QLineEdit, according to the icons this->setTextMargins( sRect.right() + iconSpacing, 0, event->size().width() - cRect.left() - iconSpacing,0); } // -------------------------------------------------- void ctkSearchBox::updateClearButtonState() { Q_D(ctkSearchBox); d->clearIconMode = this->text().isEmpty() ? QIcon::Disabled : QIcon::Normal; } <|endoftext|>
<commit_before>/* Copyright (c) 2013 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Leonardo de Moura */ #include "util/flet.h" #include "util/scoped_map.h" #include "util/interrupt.h" #include "kernel/environment.h" #include "kernel/normalizer.h" #include "kernel/builtin.h" #include "kernel/kernel_exception.h" #include "kernel/type_checker_justification.h" #include "kernel/instantiate.h" #include "kernel/free_vars.h" #include "kernel/metavar.h" #include "library/kernel_bindings.h" #include "library/type_inferer.h" namespace lean { static name g_x_name("x"); class type_inferer::imp { typedef scoped_map<expr, expr, expr_hash_alloc, expr_eqp> cache; typedef buffer<unification_constraint> unification_constraints; environment m_env; context m_ctx; metavar_env * m_menv; unsigned m_menv_timestamp; unification_constraints * m_uc; normalizer m_normalizer; cache m_cache; expr normalize(expr const & e, context const & ctx) { return m_normalizer(e, ctx); } expr check_type(expr const & e, expr const & s, context const & ctx) { if (is_type(e)) return e; if (is_bool(e)) return Type(); expr u = normalize(e, ctx); if (is_type(u)) return u; if (is_bool(u)) return Type(); if (has_metavar(u) && m_menv) { justification jst = mk_type_expected_justification(ctx, s); m_uc->push_back(mk_convertible_constraint(ctx, u, TypeU, jst)); return u; } throw type_expected_exception(m_env, ctx, s); } expr get_range(expr t, expr const & e, context const & ctx) { unsigned num = num_args(e) - 1; while (num > 0) { --num; if (is_pi(t)) { t = abst_body(t); } else { t = m_normalizer(t, ctx); if (is_pi(t)) { t = abst_body(t); } else if (has_metavar(t) && m_menv) { // Create two fresh variables A and B, // and assign r == (Pi(x : A), B x) expr A = m_menv->mk_metavar(ctx); expr B = m_menv->mk_metavar(ctx); expr p = mk_pi(g_x_name, A, B(Var(0))); justification jst = mk_function_expected_justification(ctx, e); m_uc->push_back(mk_eq_constraint(ctx, t, p, jst)); t = abst_body(p); } else { throw function_expected_exception(m_env, ctx, e); } } } if (closed(t)) return t; else return instantiate(t, num_args(e)-1, &arg(e, 1)); } void set_menv(metavar_env * menv) { if (m_menv == menv) { // Check whether m_menv has been updated since the last time the checker has been invoked if (m_menv && m_menv->get_timestamp() > m_menv_timestamp) { m_menv_timestamp = m_menv->get_timestamp(); m_cache.clear(); } } else { m_menv = menv; m_cache.clear(); m_menv_timestamp = m_menv ? m_menv->get_timestamp() : 0; } } expr infer_type(expr const & e, context const & ctx) { // cheap cases, we do not cache results switch (e.kind()) { case expr_kind::MetaVar: if (m_menv) { if (m_menv->is_assigned(e)) return infer_type(m_menv->get_subst(e), ctx); else return m_menv->get_type(e); } else { throw unexpected_metavar_occurrence(m_env, e); } case expr_kind::Constant: { if (const_type(e)) { return const_type(e); } else { object const & obj = m_env.get_object(const_name(e)); if (obj.has_type()) return obj.get_type(); else throw has_no_type_exception(m_env, e); } break; } case expr_kind::Var: { auto p = lookup_ext(ctx, var_idx(e)); context_entry const & ce = p.first; if (ce.get_domain()) { context const & ce_ctx = p.second; return lift_free_vars(ce.get_domain(), ctx.size() - ce_ctx.size()); } // Remark: the case where ce.get_domain() is not // available is not considered cheap. break; } case expr_kind::Eq: return mk_bool_type(); case expr_kind::Value: return to_value(e).get_type(); case expr_kind::Type: return mk_type(ty_level(e) + 1); case expr_kind::App: case expr_kind::Lambda: case expr_kind::Pi: case expr_kind::Let: break; // expensive cases } check_interrupted(); bool shared = false; if (is_shared(e)) { shared = true; auto it = m_cache.find(e); if (it != m_cache.end()) return it->second; } expr r; switch (e.kind()) { case expr_kind::Constant: case expr_kind::Eq: case expr_kind::Value: case expr_kind::Type: case expr_kind::MetaVar: lean_unreachable(); // LCOV_EXCL_LINE case expr_kind::Var: { auto p = lookup_ext(ctx, var_idx(e)); context_entry const & ce = p.first; context const & ce_ctx = p.second; lean_assert(!ce.get_domain()); r = lift_free_vars(infer_type(ce.get_body(), ce_ctx), ctx.size() - ce_ctx.size()); break; } case expr_kind::App: { expr const & f = arg(e, 0); expr f_t = infer_type(f, ctx); r = get_range(f_t, e, ctx); break; } case expr_kind::Lambda: { cache::mk_scope sc(m_cache); r = mk_pi(abst_name(e), abst_domain(e), infer_type(abst_body(e), extend(ctx, abst_name(e), abst_domain(e)))); break; } case expr_kind::Pi: { expr t1 = check_type(infer_type(abst_domain(e), ctx), abst_domain(e), ctx); expr t2; { cache::mk_scope sc(m_cache); context new_ctx = extend(ctx, abst_name(e), abst_domain(e)); t2 = check_type(infer_type(abst_body(e), new_ctx), abst_body(e), new_ctx); } if (is_type(t1) && is_type(t2)) { r = mk_type(max(ty_level(t1), ty_level(t2))); } else { lean_assert(m_uc); justification jst = mk_max_type_justification(ctx, e); r = m_menv->mk_metavar(ctx); m_uc->push_back(mk_max_constraint(ctx, t1, t2, r, jst)); } break; } case expr_kind::Let: { cache::mk_scope sc(m_cache); r = infer_type(let_body(e), extend(ctx, let_name(e), let_type(e), let_value(e))); break; }} if (shared) { m_cache.insert(e, r); } return r; } void set_ctx(context const & ctx) { if (!is_eqp(m_ctx, ctx)) { clear(); m_ctx = ctx; } } public: imp(environment const & env): m_env(env), m_normalizer(env) { m_menv = nullptr; m_menv_timestamp = 0; m_uc = nullptr; } expr operator()(expr const & e, context const & ctx, metavar_env * menv, buffer<unification_constraint> & uc) { set_ctx(ctx); set_menv(menv); flet<unification_constraints*> set(m_uc, &uc); return infer_type(e, ctx); } void clear() { m_cache.clear(); m_normalizer.clear(); m_ctx = context(); m_menv = nullptr; m_menv_timestamp = 0; } bool is_proposition(expr const & e, context const & ctx) { buffer<unification_constraint> uc; expr t = operator()(e, ctx, nullptr, uc); if (is_bool(t)) return true; else return is_bool(normalize(e, ctx)); } }; type_inferer::type_inferer(environment const & env):m_ptr(new imp(env)) {} type_inferer::~type_inferer() {} expr type_inferer::operator()(expr const & e, context const & ctx, metavar_env * menv, buffer<unification_constraint> & uc) { return m_ptr->operator()(e, ctx, menv, uc); } expr type_inferer::operator()(expr const & e, context const & ctx) { buffer<unification_constraint> uc; return operator()(e, ctx, nullptr, uc); } bool type_inferer::is_proposition(expr const & e, context const & ctx) { return m_ptr->is_proposition(e, ctx); } void type_inferer::clear() { m_ptr->clear(); } constexpr char const * type_inferer_mt = "type_inferer"; type_inferer & to_type_inferer(lua_State * L, int i) { return *static_cast<type_inferer*>(luaL_checkudata(L, i, type_inferer_mt)); } DECL_PRED(type_inferer) DECL_GC(type_inferer) static int type_inferer_call(lua_State * L) { int nargs = lua_gettop(L); type_inferer & inferer = to_type_inferer(L, 1); if (nargs == 2) return push_expr(L, inferer(to_nonnull_expr(L, 2))); else return push_expr(L, inferer(to_nonnull_expr(L, 2), to_context(L, 3))); } static int type_inferer_clear(lua_State * L) { to_type_inferer(L, 1).clear(); return 0; } static int mk_type_inferer(lua_State * L) { void * mem = lua_newuserdata(L, sizeof(type_inferer)); new (mem) type_inferer(to_environment(L, 1)); luaL_getmetatable(L, type_inferer_mt); lua_setmetatable(L, -2); return 1; } static const struct luaL_Reg type_inferer_m[] = { {"__gc", type_inferer_gc}, // never throws {"__call", safe_function<type_inferer_call>}, {"clear", safe_function<type_inferer_clear>}, {0, 0} }; void open_type_inferer(lua_State * L) { luaL_newmetatable(L, type_inferer_mt); lua_pushvalue(L, -1); lua_setfield(L, -2, "__index"); setfuncs(L, type_inferer_m, 0); SET_GLOBAL_FUN(mk_type_inferer, "type_inferer"); SET_GLOBAL_FUN(type_inferer_pred, "is_type_inferer"); } } <commit_msg>fix(library/type_inferer): typo<commit_after>/* Copyright (c) 2013 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Leonardo de Moura */ #include "util/flet.h" #include "util/scoped_map.h" #include "util/interrupt.h" #include "kernel/environment.h" #include "kernel/normalizer.h" #include "kernel/builtin.h" #include "kernel/kernel_exception.h" #include "kernel/type_checker_justification.h" #include "kernel/instantiate.h" #include "kernel/free_vars.h" #include "kernel/metavar.h" #include "library/kernel_bindings.h" #include "library/type_inferer.h" namespace lean { static name g_x_name("x"); class type_inferer::imp { typedef scoped_map<expr, expr, expr_hash_alloc, expr_eqp> cache; typedef buffer<unification_constraint> unification_constraints; environment m_env; context m_ctx; metavar_env * m_menv; unsigned m_menv_timestamp; unification_constraints * m_uc; normalizer m_normalizer; cache m_cache; expr normalize(expr const & e, context const & ctx) { return m_normalizer(e, ctx); } expr check_type(expr const & e, expr const & s, context const & ctx) { if (is_type(e)) return e; if (is_bool(e)) return Type(); expr u = normalize(e, ctx); if (is_type(u)) return u; if (is_bool(u)) return Type(); if (has_metavar(u) && m_menv) { justification jst = mk_type_expected_justification(ctx, s); m_uc->push_back(mk_convertible_constraint(ctx, u, TypeU, jst)); return u; } throw type_expected_exception(m_env, ctx, s); } expr get_range(expr t, expr const & e, context const & ctx) { unsigned num = num_args(e) - 1; while (num > 0) { --num; if (is_pi(t)) { t = abst_body(t); } else { t = m_normalizer(t, ctx); if (is_pi(t)) { t = abst_body(t); } else if (has_metavar(t) && m_menv) { // Create two fresh variables A and B, // and assign r == (Pi(x : A), B x) expr A = m_menv->mk_metavar(ctx); expr B = m_menv->mk_metavar(ctx); expr p = mk_pi(g_x_name, A, B(Var(0))); justification jst = mk_function_expected_justification(ctx, e); m_uc->push_back(mk_eq_constraint(ctx, t, p, jst)); t = abst_body(p); } else { throw function_expected_exception(m_env, ctx, e); } } } if (closed(t)) return t; else return instantiate(t, num_args(e)-1, &arg(e, 1)); } void set_menv(metavar_env * menv) { if (m_menv == menv) { // Check whether m_menv has been updated since the last time the checker has been invoked if (m_menv && m_menv->get_timestamp() > m_menv_timestamp) { m_menv_timestamp = m_menv->get_timestamp(); m_cache.clear(); } } else { m_menv = menv; m_cache.clear(); m_menv_timestamp = m_menv ? m_menv->get_timestamp() : 0; } } expr infer_type(expr const & e, context const & ctx) { // cheap cases, we do not cache results switch (e.kind()) { case expr_kind::MetaVar: if (m_menv) { if (m_menv->is_assigned(e)) return infer_type(m_menv->get_subst(e), ctx); else return m_menv->get_type(e); } else { throw unexpected_metavar_occurrence(m_env, e); } case expr_kind::Constant: { if (const_type(e)) { return const_type(e); } else { object const & obj = m_env.get_object(const_name(e)); if (obj.has_type()) return obj.get_type(); else throw has_no_type_exception(m_env, e); } break; } case expr_kind::Var: { auto p = lookup_ext(ctx, var_idx(e)); context_entry const & ce = p.first; if (ce.get_domain()) { context const & ce_ctx = p.second; return lift_free_vars(ce.get_domain(), ctx.size() - ce_ctx.size()); } // Remark: the case where ce.get_domain() is not // available is not considered cheap. break; } case expr_kind::Eq: return mk_bool_type(); case expr_kind::Value: return to_value(e).get_type(); case expr_kind::Type: return mk_type(ty_level(e) + 1); case expr_kind::App: case expr_kind::Lambda: case expr_kind::Pi: case expr_kind::Let: break; // expensive cases } check_interrupted(); bool shared = false; if (is_shared(e)) { shared = true; auto it = m_cache.find(e); if (it != m_cache.end()) return it->second; } expr r; switch (e.kind()) { case expr_kind::Constant: case expr_kind::Eq: case expr_kind::Value: case expr_kind::Type: case expr_kind::MetaVar: lean_unreachable(); // LCOV_EXCL_LINE case expr_kind::Var: { auto p = lookup_ext(ctx, var_idx(e)); context_entry const & ce = p.first; context const & ce_ctx = p.second; lean_assert(!ce.get_domain()); r = lift_free_vars(infer_type(ce.get_body(), ce_ctx), ctx.size() - ce_ctx.size()); break; } case expr_kind::App: { expr const & f = arg(e, 0); expr f_t = infer_type(f, ctx); r = get_range(f_t, e, ctx); break; } case expr_kind::Lambda: { cache::mk_scope sc(m_cache); r = mk_pi(abst_name(e), abst_domain(e), infer_type(abst_body(e), extend(ctx, abst_name(e), abst_domain(e)))); break; } case expr_kind::Pi: { expr t1 = check_type(infer_type(abst_domain(e), ctx), abst_domain(e), ctx); expr t2; { cache::mk_scope sc(m_cache); context new_ctx = extend(ctx, abst_name(e), abst_domain(e)); t2 = check_type(infer_type(abst_body(e), new_ctx), abst_body(e), new_ctx); } if (is_type(t1) && is_type(t2)) { r = mk_type(max(ty_level(t1), ty_level(t2))); } else { lean_assert(m_uc); justification jst = mk_max_type_justification(ctx, e); r = m_menv->mk_metavar(ctx); m_uc->push_back(mk_max_constraint(ctx, t1, t2, r, jst)); } break; } case expr_kind::Let: { cache::mk_scope sc(m_cache); r = infer_type(let_body(e), extend(ctx, let_name(e), let_type(e), let_value(e))); break; }} if (shared) { m_cache.insert(e, r); } return r; } void set_ctx(context const & ctx) { if (!is_eqp(m_ctx, ctx)) { clear(); m_ctx = ctx; } } public: imp(environment const & env): m_env(env), m_normalizer(env) { m_menv = nullptr; m_menv_timestamp = 0; m_uc = nullptr; } expr operator()(expr const & e, context const & ctx, metavar_env * menv, buffer<unification_constraint> & uc) { set_ctx(ctx); set_menv(menv); flet<unification_constraints*> set(m_uc, &uc); return infer_type(e, ctx); } void clear() { m_cache.clear(); m_normalizer.clear(); m_ctx = context(); m_menv = nullptr; m_menv_timestamp = 0; } bool is_proposition(expr const & e, context const & ctx) { buffer<unification_constraint> uc; expr t = operator()(e, ctx, nullptr, uc); if (is_bool(t)) return true; else return is_bool(normalize(t, ctx)); } }; type_inferer::type_inferer(environment const & env):m_ptr(new imp(env)) {} type_inferer::~type_inferer() {} expr type_inferer::operator()(expr const & e, context const & ctx, metavar_env * menv, buffer<unification_constraint> & uc) { return m_ptr->operator()(e, ctx, menv, uc); } expr type_inferer::operator()(expr const & e, context const & ctx) { buffer<unification_constraint> uc; return operator()(e, ctx, nullptr, uc); } bool type_inferer::is_proposition(expr const & e, context const & ctx) { return m_ptr->is_proposition(e, ctx); } void type_inferer::clear() { m_ptr->clear(); } constexpr char const * type_inferer_mt = "type_inferer"; type_inferer & to_type_inferer(lua_State * L, int i) { return *static_cast<type_inferer*>(luaL_checkudata(L, i, type_inferer_mt)); } DECL_PRED(type_inferer) DECL_GC(type_inferer) static int type_inferer_call(lua_State * L) { int nargs = lua_gettop(L); type_inferer & inferer = to_type_inferer(L, 1); if (nargs == 2) return push_expr(L, inferer(to_nonnull_expr(L, 2))); else return push_expr(L, inferer(to_nonnull_expr(L, 2), to_context(L, 3))); } static int type_inferer_clear(lua_State * L) { to_type_inferer(L, 1).clear(); return 0; } static int mk_type_inferer(lua_State * L) { void * mem = lua_newuserdata(L, sizeof(type_inferer)); new (mem) type_inferer(to_environment(L, 1)); luaL_getmetatable(L, type_inferer_mt); lua_setmetatable(L, -2); return 1; } static const struct luaL_Reg type_inferer_m[] = { {"__gc", type_inferer_gc}, // never throws {"__call", safe_function<type_inferer_call>}, {"clear", safe_function<type_inferer_clear>}, {0, 0} }; void open_type_inferer(lua_State * L) { luaL_newmetatable(L, type_inferer_mt); lua_pushvalue(L, -1); lua_setfield(L, -2, "__index"); setfuncs(L, type_inferer_m, 0); SET_GLOBAL_FUN(mk_type_inferer, "type_inferer"); SET_GLOBAL_FUN(type_inferer_pred, "is_type_inferer"); } } <|endoftext|>
<commit_before>// // Copyright (c) 2008-2013 the Urho3D project. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // #include "Precompiled.h" #include "ArrayPtr.h" #include "Context.h" #include "Deserializer.h" #include "Log.h" #include "Profiler.h" #include "ResourceCache.h" #include "Serializer.h" #include "XMLFile.h" #include <pugixml.hpp> #include "DebugNew.h" namespace Urho3D { /// XML writer for pugixml. class XMLWriter : public pugi::xml_writer { public: /// Construct. XMLWriter(Serializer& dest) : dest_(dest), success_(true) { } /// Write bytes to output. void write(const void* data, size_t size) { if (dest_.Write(data, size) != size) success_ = false; } /// Destination serializer. Serializer& dest_; /// Success flag. bool success_; }; XMLFile::XMLFile(Context* context) : Resource(context), document_(new pugi::xml_document()) { } XMLFile::~XMLFile() { delete document_; document_ = 0; } void XMLFile::RegisterObject(Context* context) { context->RegisterFactory<XMLFile>(); } bool XMLFile::Load(Deserializer& source) { PROFILE(LoadXMLFile); unsigned dataSize = source.GetSize(); if (!dataSize && !source.GetName().Empty()) { LOGERROR("Zero sized XML data in " + source.GetName()); return false; } SharedArrayPtr<char> buffer(new char[dataSize]); if (source.Read(buffer.Get(), dataSize) != dataSize) return false; if (!document_->load_buffer(buffer.Get(), dataSize)) { LOGERROR("Could not parse XML data from " + source.GetName()); return false; } XMLElement rootElem = GetRoot(); String inherit = rootElem ? rootElem.GetAttribute("inherit") : String::EMPTY; if (!inherit.Empty()) { // The existence of this attribute indicates this is an RFC 5261 patch file ResourceCache* cache = GetSubsystem<ResourceCache>(); XMLFile* inheritedXMLFile = cache->GetResource<XMLFile>(inherit); if (!inheritedXMLFile) { LOGERRORF("Could not find inherit RenderPath XML file: %s", inherit.CString()); return false; } // Patch this XMLFile and leave the original inherited XMLFile as it is pugi::xml_document* patchDocument = document_; document_ = new pugi::xml_document(); document_->reset(*inheritedXMLFile->document_); // Unfortunately there is no way to adjust the data size correctly Patch(rootElem); delete patchDocument; } // Note: this probably does not reflect internal data structure size accurately SetMemoryUse(dataSize); return true; } bool XMLFile::Save(Serializer& dest) const { XMLWriter writer(dest); document_->save(writer); return writer.success_; } XMLElement XMLFile::CreateRoot(const String& name) { document_->reset(); pugi::xml_node root = document_->append_child(name.CString()); return XMLElement(this, root.internal_object()); } XMLElement XMLFile::GetRoot(const String& name) { pugi::xml_node root = document_->first_child(); if (root.empty()) return XMLElement(); if (!name.Empty() && name != root.name()) return XMLElement(); else return XMLElement(this, root.internal_object()); } void XMLFile::Patch(XMLFile* patchFile) { Patch(patchFile->GetRoot()); } void XMLFile::Patch(XMLElement patchElement) { pugi::xml_node root = pugi::xml_node(patchElement.GetNode()); for (pugi::xml_node::iterator patch = root.begin(); patch != root.end(); patch++) { pugi::xml_attribute sel = patch->attribute("sel"); if (sel.empty()) { LOGERROR("XML Patch failed due to node not having a sel attribute."); continue; } // Only select a single node at a time, they can use xpath to select specific ones in multiple otherwise the node set becomes invalid due to changes pugi::xpath_node original = document_->select_single_node(sel.value()); if (!original) { LOGERRORF("XML Patch failed with bad select: %s.", sel.value()); continue; } if (strcmp(patch->name(),"add") == 0) PatchAdd(*patch, original); else if (strcmp(patch->name(), "replace") == 0) PatchReplace(*patch, original); else if (strcmp(patch->name(), "remove") == 0) PatchRemove(original); else LOGERROR("XMLFiles used for patching should only use 'add', 'replace' or 'remove' elements."); } } void XMLFile::PatchAdd(const pugi::xml_node& patch, pugi::xpath_node& original) { // If not a node, log an error if (original.attribute()) { LOGERRORF("XML Patch failed calling Add due to not selecting a node, %s attribute was selected.", original.attribute().name()); return; } // If no type add node, if contains '@' treat as attribute pugi::xml_attribute type = patch.attribute("type"); if (!type || strlen(type.value()) <= 0) AddNode(patch, original); else if (type.value()[0] == '@') AddAttribute(patch, original); } void XMLFile::PatchReplace(const pugi::xml_node& patch, pugi::xpath_node& original) { // If no attribute but node then its a node, otherwise its an attribute or null if (!original.attribute() && original.node()) { pugi::xml_node parent = original.node().parent(); parent.insert_copy_before(patch.first_child(), original.node()); parent.remove_child(original.node()); } else if (original.attribute()) { original.attribute().set_value(patch.child_value()); } } void XMLFile::PatchRemove(const pugi::xpath_node& original) { // If no attribute but node then its a node, otherwise its an attribute or null if (!original.attribute() && original.node()) { pugi::xml_node parent = original.parent(); parent.remove_child(original.node()); } else if (original.attribute()) { pugi::xml_node parent = original.parent(); parent.remove_attribute(original.attribute()); } } void XMLFile::AddNode(const pugi::xml_node& patch, pugi::xpath_node& original) { // If pos is null, append or prepend add as a child, otherwise add before or after, the default is to append as a child pugi::xml_attribute pos = patch.attribute("pos"); if (!pos || strlen(pos.value()) <= 0 || pos.value() == "append") { pugi::xml_node::iterator start = patch.begin(); pugi::xml_node::iterator end = patch.end(); // There can not be two consecutive text nodes, so check to see if they need to be combined // If they have been we can skip the first node of the nodes to add if (CombineText(patch.first_child(), original.node().last_child(), false)) start++; for (; start != end; start++) original.node().append_copy(*start); } else if (strcmp(pos.value(), "prepend") == 0) { pugi::xml_node::iterator start = patch.begin(); pugi::xml_node::iterator end = patch.end(); // There can not be two consecutive text nodes, so check to see if they need to be combined // If they have been we can skip the last node of the nodes to add if (CombineText(patch.last_child(), original.node().first_child(), true)) end--; pugi::xml_node pos = original.node().first_child(); for (; start != end; start++) original.node().insert_copy_before(*start, pos); } else if (strcmp(pos.value(), "before") == 0) { pugi::xml_node::iterator start = patch.begin(); pugi::xml_node::iterator end = patch.end(); // There can not be two consecutive text nodes, so check to see if they need to be combined // If they have been we can skip the first node of the nodes to add if (CombineText(patch.first_child(), original.node().previous_sibling(), false)) start++; // There can not be two consecutive text nodes, so check to see if they need to be combined // If they have been we can skip the last node of the nodes to add if (CombineText(patch.last_child(), original.node(), true)) end--; for (; start != end; start++) original.parent().insert_copy_before(*start, original.node()); } else if (strcmp(pos.value(), "after") == 0) { pugi::xml_node::iterator start = patch.begin(); pugi::xml_node::iterator end = patch.end(); // There can not be two consecutive text nodes, so check to see if they need to be combined // If they have been we can skip the first node of the nodes to add if (CombineText(patch.first_child(), original.node(), false)) start++; // There can not be two consecutive text nodes, so check to see if they need to be combined // If they have been we can skip the last node of the nodes to add if (CombineText(patch.last_child(), original.node().next_sibling(), true)) end--; pugi::xml_node pos = original.node(); for (; start != end; start++) pos = original.parent().insert_copy_after(*start, pos); } } void XMLFile::AddAttribute(const pugi::xml_node& patch, pugi::xpath_node& original) { pugi::xml_attribute attribute = patch.attribute("type"); if (!patch.first_child() && patch.first_child().type() != pugi::node_pcdata) { LOGERRORF("XML Patch failed calling Add due to attempting to add non text to an attribute for %s.", attribute.value()); return; } String name(attribute.value()); name = name.Substring(1); pugi::xml_attribute newAttribute = original.node().append_attribute(name.CString()); newAttribute.set_value(patch.child_value()); } bool XMLFile::CombineText(const pugi::xml_node& patch, pugi::xml_node original, bool prepend) { if (!patch || !original) return false; if ((patch.type() == pugi::node_pcdata && original.type() == pugi::node_pcdata) || (patch.type() == pugi::node_cdata && original.type() == pugi::node_cdata)) { if (prepend) original.set_value(ToString("%s%s", patch.value(), original.value()).CString()); else original.set_value(ToString("%s%s", original.value(), patch.value()).CString()); return true; } return false; } } <commit_msg>Code cleanup. [ci skip]<commit_after>// // Copyright (c) 2008-2013 the Urho3D project. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // #include "Precompiled.h" #include "ArrayPtr.h" #include "Context.h" #include "Deserializer.h" #include "Log.h" #include "Profiler.h" #include "ResourceCache.h" #include "Serializer.h" #include "XMLFile.h" #include <pugixml.hpp> #include "DebugNew.h" namespace Urho3D { /// XML writer for pugixml. class XMLWriter : public pugi::xml_writer { public: /// Construct. XMLWriter(Serializer& dest) : dest_(dest), success_(true) { } /// Write bytes to output. void write(const void* data, size_t size) { if (dest_.Write(data, size) != size) success_ = false; } /// Destination serializer. Serializer& dest_; /// Success flag. bool success_; }; XMLFile::XMLFile(Context* context) : Resource(context), document_(new pugi::xml_document()) { } XMLFile::~XMLFile() { delete document_; document_ = 0; } void XMLFile::RegisterObject(Context* context) { context->RegisterFactory<XMLFile>(); } bool XMLFile::Load(Deserializer& source) { PROFILE(LoadXMLFile); unsigned dataSize = source.GetSize(); if (!dataSize && !source.GetName().Empty()) { LOGERROR("Zero sized XML data in " + source.GetName()); return false; } SharedArrayPtr<char> buffer(new char[dataSize]); if (source.Read(buffer.Get(), dataSize) != dataSize) return false; if (!document_->load_buffer(buffer.Get(), dataSize)) { LOGERROR("Could not parse XML data from " + source.GetName()); return false; } XMLElement rootElem = GetRoot(); String inherit = rootElem.GetAttribute("inherit"); if (!inherit.Empty()) { // The existence of this attribute indicates this is an RFC 5261 patch file ResourceCache* cache = GetSubsystem<ResourceCache>(); XMLFile* inheritedXMLFile = cache->GetResource<XMLFile>(inherit); if (!inheritedXMLFile) { LOGERRORF("Could not find inherit RenderPath XML file: %s", inherit.CString()); return false; } // Patch this XMLFile and leave the original inherited XMLFile as it is pugi::xml_document* patchDocument = document_; document_ = new pugi::xml_document(); document_->reset(*inheritedXMLFile->document_); // Unfortunately there is no way to adjust the data size correctly Patch(rootElem); delete patchDocument; } // Note: this probably does not reflect internal data structure size accurately SetMemoryUse(dataSize); return true; } bool XMLFile::Save(Serializer& dest) const { XMLWriter writer(dest); document_->save(writer); return writer.success_; } XMLElement XMLFile::CreateRoot(const String& name) { document_->reset(); pugi::xml_node root = document_->append_child(name.CString()); return XMLElement(this, root.internal_object()); } XMLElement XMLFile::GetRoot(const String& name) { pugi::xml_node root = document_->first_child(); if (root.empty()) return XMLElement(); if (!name.Empty() && name != root.name()) return XMLElement(); else return XMLElement(this, root.internal_object()); } void XMLFile::Patch(XMLFile* patchFile) { Patch(patchFile->GetRoot()); } void XMLFile::Patch(XMLElement patchElement) { pugi::xml_node root = pugi::xml_node(patchElement.GetNode()); for (pugi::xml_node::iterator patch = root.begin(); patch != root.end(); patch++) { pugi::xml_attribute sel = patch->attribute("sel"); if (sel.empty()) { LOGERROR("XML Patch failed due to node not having a sel attribute."); continue; } // Only select a single node at a time, they can use xpath to select specific ones in multiple otherwise the node set becomes invalid due to changes pugi::xpath_node original = document_->select_single_node(sel.value()); if (!original) { LOGERRORF("XML Patch failed with bad select: %s.", sel.value()); continue; } if (strcmp(patch->name(),"add") == 0) PatchAdd(*patch, original); else if (strcmp(patch->name(), "replace") == 0) PatchReplace(*patch, original); else if (strcmp(patch->name(), "remove") == 0) PatchRemove(original); else LOGERROR("XMLFiles used for patching should only use 'add', 'replace' or 'remove' elements."); } } void XMLFile::PatchAdd(const pugi::xml_node& patch, pugi::xpath_node& original) { // If not a node, log an error if (original.attribute()) { LOGERRORF("XML Patch failed calling Add due to not selecting a node, %s attribute was selected.", original.attribute().name()); return; } // If no type add node, if contains '@' treat as attribute pugi::xml_attribute type = patch.attribute("type"); if (!type || strlen(type.value()) <= 0) AddNode(patch, original); else if (type.value()[0] == '@') AddAttribute(patch, original); } void XMLFile::PatchReplace(const pugi::xml_node& patch, pugi::xpath_node& original) { // If no attribute but node then its a node, otherwise its an attribute or null if (!original.attribute() && original.node()) { pugi::xml_node parent = original.node().parent(); parent.insert_copy_before(patch.first_child(), original.node()); parent.remove_child(original.node()); } else if (original.attribute()) { original.attribute().set_value(patch.child_value()); } } void XMLFile::PatchRemove(const pugi::xpath_node& original) { // If no attribute but node then its a node, otherwise its an attribute or null if (!original.attribute() && original.node()) { pugi::xml_node parent = original.parent(); parent.remove_child(original.node()); } else if (original.attribute()) { pugi::xml_node parent = original.parent(); parent.remove_attribute(original.attribute()); } } void XMLFile::AddNode(const pugi::xml_node& patch, pugi::xpath_node& original) { // If pos is null, append or prepend add as a child, otherwise add before or after, the default is to append as a child pugi::xml_attribute pos = patch.attribute("pos"); if (!pos || strlen(pos.value()) <= 0 || pos.value() == "append") { pugi::xml_node::iterator start = patch.begin(); pugi::xml_node::iterator end = patch.end(); // There can not be two consecutive text nodes, so check to see if they need to be combined // If they have been we can skip the first node of the nodes to add if (CombineText(patch.first_child(), original.node().last_child(), false)) start++; for (; start != end; start++) original.node().append_copy(*start); } else if (strcmp(pos.value(), "prepend") == 0) { pugi::xml_node::iterator start = patch.begin(); pugi::xml_node::iterator end = patch.end(); // There can not be two consecutive text nodes, so check to see if they need to be combined // If they have been we can skip the last node of the nodes to add if (CombineText(patch.last_child(), original.node().first_child(), true)) end--; pugi::xml_node pos = original.node().first_child(); for (; start != end; start++) original.node().insert_copy_before(*start, pos); } else if (strcmp(pos.value(), "before") == 0) { pugi::xml_node::iterator start = patch.begin(); pugi::xml_node::iterator end = patch.end(); // There can not be two consecutive text nodes, so check to see if they need to be combined // If they have been we can skip the first node of the nodes to add if (CombineText(patch.first_child(), original.node().previous_sibling(), false)) start++; // There can not be two consecutive text nodes, so check to see if they need to be combined // If they have been we can skip the last node of the nodes to add if (CombineText(patch.last_child(), original.node(), true)) end--; for (; start != end; start++) original.parent().insert_copy_before(*start, original.node()); } else if (strcmp(pos.value(), "after") == 0) { pugi::xml_node::iterator start = patch.begin(); pugi::xml_node::iterator end = patch.end(); // There can not be two consecutive text nodes, so check to see if they need to be combined // If they have been we can skip the first node of the nodes to add if (CombineText(patch.first_child(), original.node(), false)) start++; // There can not be two consecutive text nodes, so check to see if they need to be combined // If they have been we can skip the last node of the nodes to add if (CombineText(patch.last_child(), original.node().next_sibling(), true)) end--; pugi::xml_node pos = original.node(); for (; start != end; start++) pos = original.parent().insert_copy_after(*start, pos); } } void XMLFile::AddAttribute(const pugi::xml_node& patch, pugi::xpath_node& original) { pugi::xml_attribute attribute = patch.attribute("type"); if (!patch.first_child() && patch.first_child().type() != pugi::node_pcdata) { LOGERRORF("XML Patch failed calling Add due to attempting to add non text to an attribute for %s.", attribute.value()); return; } String name(attribute.value()); name = name.Substring(1); pugi::xml_attribute newAttribute = original.node().append_attribute(name.CString()); newAttribute.set_value(patch.child_value()); } bool XMLFile::CombineText(const pugi::xml_node& patch, pugi::xml_node original, bool prepend) { if (!patch || !original) return false; if ((patch.type() == pugi::node_pcdata && original.type() == pugi::node_pcdata) || (patch.type() == pugi::node_cdata && original.type() == pugi::node_cdata)) { if (prepend) original.set_value(ToString("%s%s", patch.value(), original.value()).CString()); else original.set_value(ToString("%s%s", original.value(), patch.value()).CString()); return true; } return false; } } <|endoftext|>
<commit_before>#ifndef VPP_WINDOW_HPP__ # define VPP_WINDOW_HPP__ # include <vpp/imageNd.hh> namespace vpp { template <typename I> class window_iterator { public: typedef typename I::value_type V; inline window_iterator(V* p, const std::vector<int>& offsets, int i) : offsets_(offsets), p_(p), cur_((V*)(((char*)p) + offsets_[i])), i_(i) { } inline window_iterator<I>& operator++() { i_++; cur_ = (V*)((char*)(p_) + offsets_[i_]); } inline V& operator*() { return *cur_; } inline const V& operator*() const { return *cur_; } inline int i() const { return i_; } private: const std::vector<int>& offsets_; V* p_; V* cur_; int i_; }; template <typename I> bool operator==(const window_iterator<I>& a, const window_iterator<I>& b) { return a.i() == b.i(); } template <typename I> bool operator!=(const window_iterator<I>& a, const window_iterator<I>& b) { return !(a == b); } template <typename I> class window_range { public: typedef typename I::coord_type coord_type; typedef typename I::value_type value_type; typedef typename I::iterator I_iterator; typedef window_iterator<I> iterator; inline window_range(value_type* p, const std::vector<int>& offsets) : p_(p), offsets_(offsets) { } inline iterator begin() { return window_iterator<I>(p_, offsets_, 0); } inline iterator end() { return window_iterator<I>(p_, offsets_, offsets_.size() - 1); } private: value_type* p_; const std::vector<int>& offsets_; }; template <typename I> class window { public: typedef typename I::coord_type coord_type; typedef typename I::value_type value_type; typedef typename I::iterator I_iterator; window(const I& img, const std::vector<coord_type>& cds) { for (auto p : cds) offsets_.push_back(img.offset_of(p)); offsets_.push_back(0); } inline window_range<I> operator()(value_type& p) const { return window_range<I>(&p, offsets_); } private: std::vector<int> offsets_; }; template <typename I> window<I> make_window(const I& img, const std::vector<typename I::coord_type>& cds) { return window<I>(img, cds); } }; #endif <commit_msg>New syntax for window iterations.<commit_after>#ifndef VPP_WINDOW_HPP__ # define VPP_WINDOW_HPP__ # include <vpp/imageNd.hh> namespace vpp { template <typename V> struct window_runner { inline window_runner(const std::vector<int>& offsets, V& pix) : offsets_(offsets), pix_((char*)&pix) { } template <typename F> inline void operator<(F f) { for (auto off : offsets_) f(*(V*)(pix_ + off)); } const std::vector<int>& offsets_; char* pix_; }; template <typename I> class window { public: typedef typename I::coord_type coord_type; typedef typename I::value_type value_type; typedef typename I::iterator I_iterator; window(const I& img, const std::vector<coord_type>& cds) { for (auto p : cds) offsets_.push_back(img.offset_of(p)); } inline window_runner<value_type> operator()(value_type& p) const { return window_runner<value_type>(offsets_, p); } private: std::vector<int> offsets_; }; template <typename I> window<I> make_window(const I& img, const std::vector<typename I::coord_type>& cds) { return window<I>(img, cds); } }; #endif <|endoftext|>
<commit_before>#ifndef Matrix_hpp #define Matrix_hpp //https://msdn.microsoft.com/ru-ru/library/f1b2td24.aspx #include <iostream> #include <fstream> #include "MatrixException.hpp" template <class MatrixT> class Matrix; template <class MatrixT> std::istream& operator>> (std::istream& stream, Matrix<MatrixT>& matrix) throw (StreamException); template <class MatrixT> std::ostream& operator<< (std::ostream& stream, const Matrix<MatrixT>& matrix); template <class MatrixT = int> class Matrix { public: Matrix() : lines(0), columns(0), elements(nullptr) {} Matrix(unsigned int _lines, unsigned int _columns); Matrix(const Matrix<MatrixT>& source_matrix); Matrix& operator= (const Matrix& source_matrix); void InitFromRandom(); void InitFromFile(const char *filename) throw (FileException); MatrixT* operator[](unsigned int index) const throw (IndexException); Matrix<MatrixT> operator+(const Matrix<MatrixT>& right_matrix) const throw (AddException); Matrix<MatrixT> operator*(const Matrix<MatrixT>& right_matrix) const throw (MultiplyException); bool operator==(const Matrix<MatrixT>& right_matrix) const; bool operator!=(const Matrix<MatrixT>& right_matrix) const; unsigned int GetNumberOfLines() const; unsigned int GetNumberOfColumns() const; ~Matrix(); //template <class MatrixT> friend std::istream& operator>> <>(std::istream& stream, Matrix<MatrixT>& matrix) throw (StreamException); //template <class MatrixT> friend std::ostream& operator<< <>(std::ostream& stream, const Matrix<MatrixT>& matrix); private: MatrixT **elements; unsigned int lines, columns; }; template <class MatrixT> std::istream& operator>> (std::istream& stream, Matrix<MatrixT>& matrix) throw (StreamException){ for (unsigned int i = 0; i < matrix.lines; i++) { for (unsigned int j = 0; j < matrix.columns; j++) { if (!(stream >> matrix[i][j])) { throw StreamException(); } } } return stream; } template <class MatrixT> std::ostream& operator<< (std::ostream& stream, const Matrix<MatrixT>& matrix) { for (unsigned int i = 0; i < matrix.lines; i++) { for (unsigned int j = 0; j < matrix.columns; j++) { stream << matrix[i][j] << " "; } stream << '\n'; } return stream; } template <typename MatrixT> Matrix<MatrixT>::Matrix(unsigned int _lines, unsigned int _columns) : lines(_lines), columns(_columns), elements(new MatrixT*[_lines]) { for (unsigned int i = 0; i < lines; i++) { elements[i] = new MatrixT[columns]; for (unsigned int j = 0; j < columns; j++) { elements[i][j] = 0; } } } template <typename MatrixT> Matrix<MatrixT>::Matrix(const Matrix<MatrixT>& source_matrix) : lines(source_matrix.lines), columns(source_matrix.columns) { elements = new MatrixT*[lines]; for (unsigned int i = 0; i < lines; i++) { elements[i] = new MatrixT[columns]; for (unsigned int j = 0; j < columns; j++) { elements[i][j] = source_matrix[i][j]; } } } template <typename MatrixT> Matrix<MatrixT>& Matrix<MatrixT>::operator= (const Matrix<MatrixT>& source_matrix) { if (lines != source_matrix.lines || columns != source_matrix.columns) { this -> ~Matrix(); lines = source_matrix.lines; columns = source_matrix.columns; elements = new int*[lines]; for (int i = 0; i < lines; i++) { elements[i] = new int[columns]; for (int j = 0; j < columns; j++) { elements[i][j] = source_matrix[i][j]; } } } else { for (int i = 0; i < lines; i++) { for (int j = 0; j < columns; j++) { elements[i][j] = source_matrix[i][j]; } } } return *this; } template <typename MatrixT> void Matrix<MatrixT>::InitFromRandom() { for (int i = 0; i < lines; i++) { for (int j = 0; j < columns; j++) { elements[i][j] = rand() % 90 + 10; } } } template <typename MatrixT> void Matrix<MatrixT>::InitFromFile(const char *filename) throw (FileException){ std::fstream file(filename); if (!file) throw FileException(); file >> *this; } template <typename MatrixT> MatrixT* Matrix<MatrixT>::operator[](unsigned int index) const throw (IndexException){ if (index >= lines) throw IndexException(); return elements[index]; } template <typename MatrixT> Matrix<MatrixT> Matrix<MatrixT>::operator+(const Matrix<MatrixT>& right_matrix) const throw (AddException){ if (columns != right_matrix.GetNumberOfColumns() || lines != right_matrix.GetNumberOfLines()) throw AddException(); Matrix<MatrixT> result(lines, columns); for (int i = 0; i < lines; i++) { for (int j = 0; j < columns; j++) { result[i][j] = elements[i][j] + right_matrix[i][j]; } } return result; } template <typename MatrixT> Matrix<MatrixT> Matrix<MatrixT>::operator*(const Matrix& right_matrix) const throw (MultiplyException) { if (columns != right_matrix.lines) throw MultiplyException(); Matrix<MatrixT> result(lines, right_matrix.columns); for (int i = 0; i < lines; i++) { for (int j = 0; j < right_matrix.columns; j++) { result[i][j] = 0; for (int k = 0; k < right_matrix.lines; k++) result[i][j] += elements[i][k] * right_matrix[k][j]; } } return result; } template<typename MatrixT> bool Matrix<MatrixT>::operator==(const Matrix<MatrixT>& right_matrix) const { if (lines != right_matrix.lines || columns != right_matrix.columns) { return false; } else { for (unsigned i = 0; i < lines; i++) { for (unsigned j = 0; j < columns; j++) { if (operator[](i)[j] != right_matrix[i][j]) { return false; } } } return true; } } template<typename MatrixT> bool Matrix<MatrixT>::operator!=(const Matrix<MatrixT>& right_matrix) const { return !(operator==(right_matrix)); } template <typename MatrixT> unsigned int Matrix<MatrixT>::GetNumberOfLines() const { return lines; } template <typename MatrixT> unsigned int Matrix<MatrixT>::GetNumberOfColumns() const { return columns; } template <typename MatrixT> Matrix<MatrixT>::~Matrix() { for (unsigned int i = 0; i < lines; i++) delete[] elements[i]; delete[] elements; } #endif <commit_msg>Update Matrix.hpp<commit_after>#ifndef Matrix_hpp #define Matrix_hpp //https://msdn.microsoft.com/ru-ru/library/f1b2td24.aspx #include <iostream> #include <fstream> #include "MatrixException.hpp" template <class MatrixT> class Matrix; template <class MatrixT> std::istream& operator>> (std::istream& stream, Matrix<MatrixT>& matrix) throw (StreamException); template <class MatrixT> std::ostream& operator<< (std::ostream& stream, const Matrix<MatrixT>& matrix); template <class MatrixT = int> class Matrix { public: Matrix() : lines(0), columns(0), elements(nullptr) {} Matrix(size_t _lines, unsigned int _columns); Matrix(const Matrix<MatrixT>& source_matrix); Matrix& operator= (const Matrix& source_matrix); void InitFromRandom(); void InitFromFile(const char *filename) throw (FileException); MatrixT* operator[](unsigned int index) const throw (IndexException); Matrix<MatrixT> operator+(const Matrix<MatrixT>& right_matrix) const throw (AddException); Matrix<MatrixT> operator*(const Matrix<MatrixT>& right_matrix) const throw (MultiplyException); bool operator==(const Matrix<MatrixT>& right_matrix) const; bool operator!=(const Matrix<MatrixT>& right_matrix) const; unsigned int GetNumberOfLines() const; unsigned int GetNumberOfColumns() const; ~Matrix(); //template <class MatrixT> friend std::istream& operator>> <>(std::istream& stream, Matrix<MatrixT>& matrix) throw (StreamException); //template <class MatrixT> friend std::ostream& operator<< <>(std::ostream& stream, const Matrix<MatrixT>& matrix); private: MatrixT **elements; unsigned int lines, columns; }; template <class MatrixT> std::istream& operator>> (std::istream& stream, Matrix<MatrixT>& matrix) throw (StreamException){ for (unsigned int i = 0; i < matrix.lines; i++) { for (unsigned int j = 0; j < matrix.columns; j++) { if (!(stream >> matrix[i][j])) { throw StreamException(); } } } return stream; } template <class MatrixT> std::ostream& operator<< (std::ostream& stream, const Matrix<MatrixT>& matrix) { for (unsigned int i = 0; i < matrix.lines; i++) { for (unsigned int j = 0; j < matrix.columns; j++) { stream << matrix[i][j] << " "; } stream << '\n'; } return stream; } template <typename MatrixT> Matrix<MatrixT>::Matrix(unsigned int _lines, unsigned int _columns) : lines(_lines), columns(_columns), elements(new MatrixT*[_lines]) { for (unsigned int i = 0; i < lines; i++) { elements[i] = new MatrixT[columns]; for (unsigned int j = 0; j < columns; j++) { elements[i][j] = 0; } } } template <typename MatrixT> Matrix<MatrixT>::Matrix(const Matrix<MatrixT>& source_matrix) : lines(source_matrix.lines), columns(source_matrix.columns) { elements = new MatrixT*[lines]; for (unsigned int i = 0; i < lines; i++) { elements[i] = new MatrixT[columns]; for (unsigned int j = 0; j < columns; j++) { elements[i][j] = source_matrix[i][j]; } } } template <typename MatrixT> Matrix<MatrixT>& Matrix<MatrixT>::operator= (const Matrix<MatrixT>& source_matrix) { if (lines != source_matrix.lines || columns != source_matrix.columns) { this -> ~Matrix(); lines = source_matrix.lines; columns = source_matrix.columns; elements = new int*[lines]; for (int i = 0; i < lines; i++) { elements[i] = new int[columns]; for (int j = 0; j < columns; j++) { elements[i][j] = source_matrix[i][j]; } } } else { for (int i = 0; i < lines; i++) { for (int j = 0; j < columns; j++) { elements[i][j] = source_matrix[i][j]; } } } return *this; } template <typename MatrixT> void Matrix<MatrixT>::InitFromRandom() { for (int i = 0; i < lines; i++) { for (int j = 0; j < columns; j++) { elements[i][j] = rand() % 90 + 10; } } } template <typename MatrixT> void Matrix<MatrixT>::InitFromFile(const char *filename) throw (FileException){ std::fstream file(filename); if (!file) throw FileException(); file >> *this; } template <typename MatrixT> MatrixT* Matrix<MatrixT>::operator[](unsigned int index) const throw (IndexException){ if (index >= lines) throw IndexException(); return elements[index]; } template <typename MatrixT> Matrix<MatrixT> Matrix<MatrixT>::operator+(const Matrix<MatrixT>& right_matrix) const throw (AddException){ if (columns != right_matrix.GetNumberOfColumns() || lines != right_matrix.GetNumberOfLines()) throw AddException(); Matrix<MatrixT> result(lines, columns); for (int i = 0; i < lines; i++) { for (int j = 0; j < columns; j++) { result[i][j] = elements[i][j] + right_matrix[i][j]; } } return result; } template <typename MatrixT> Matrix<MatrixT> Matrix<MatrixT>::operator*(const Matrix& right_matrix) const throw (MultiplyException) { if (columns != right_matrix.lines) throw MultiplyException(); Matrix<MatrixT> result(lines, right_matrix.columns); for (int i = 0; i < lines; i++) { for (int j = 0; j < right_matrix.columns; j++) { result[i][j] = 0; for (int k = 0; k < right_matrix.lines; k++) result[i][j] += elements[i][k] * right_matrix[k][j]; } } return result; } template<typename MatrixT> bool Matrix<MatrixT>::operator==(const Matrix<MatrixT>& right_matrix) const { if (lines != right_matrix.lines || columns != right_matrix.columns) { return false; } else { for (unsigned i = 0; i < lines; i++) { for (unsigned j = 0; j < columns; j++) { if (operator[](i)[j] != right_matrix[i][j]) { return false; } } } return true; } } template<typename MatrixT> bool Matrix<MatrixT>::operator!=(const Matrix<MatrixT>& right_matrix) const { return !(operator==(right_matrix)); } template <typename MatrixT> unsigned int Matrix<MatrixT>::GetNumberOfLines() const { return lines; } template <typename MatrixT> unsigned int Matrix<MatrixT>::GetNumberOfColumns() const { return columns; } template <typename MatrixT> Matrix<MatrixT>::~Matrix() { for (unsigned int i = 0; i < lines; i++) delete[] elements[i]; delete[] elements; } #endif <|endoftext|>
<commit_before>#include "serialise.hh" #include "util.hh" #include "remote-store.hh" #include "worker-protocol.hh" #include "archive.hh" #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <iostream> #include <unistd.h> namespace nix { RemoteStore::RemoteStore() { toChild.create(); fromChild.create(); /* Start the worker. */ string worker = "nix-worker"; child = fork(); switch (child) { case -1: throw SysError("unable to fork"); case 0: try { /* child */ fromChild.readSide.close(); if (dup2(fromChild.writeSide, STDOUT_FILENO) == -1) throw SysError("dupping write side"); toChild.writeSide.close(); if (dup2(toChild.readSide, STDIN_FILENO) == -1) throw SysError("dupping read side"); int fdDebug = open("/tmp/worker-log", O_WRONLY | O_CREAT | O_TRUNC, 0644); assert(fdDebug != -1); if (dup2(fdDebug, STDERR_FILENO) == -1) throw SysError("dupping stderr"); close(fdDebug); execlp(worker.c_str(), worker.c_str(), "-vvv", "--slave", NULL); throw SysError(format("executing `%1%'") % worker); } catch (std::exception & e) { std::cerr << format("child error: %1%\n") % e.what(); } quickExit(1); } fromChild.writeSide.close(); toChild.readSide.close(); from.fd = fromChild.readSide; to.fd = toChild.writeSide; /* Send the magic greeting, check for the reply. */ writeInt(WORKER_MAGIC_1, to); unsigned int magic = readInt(from); if (magic != WORKER_MAGIC_2) throw Error("protocol mismatch"); } RemoteStore::~RemoteStore() { try { fromChild.readSide.close(); toChild.writeSide.close(); child.wait(true); } catch (Error & e) { printMsg(lvlError, format("error (ignored): %1%") % e.msg()); } } bool RemoteStore::isValidPath(const Path & path) { writeInt(wopIsValidPath, to); writeString(path, to); unsigned int reply = readInt(from); return reply != 0; } Substitutes RemoteStore::querySubstitutes(const Path & path) { throw Error("not implemented 2"); } bool RemoteStore::hasSubstitutes(const Path & path) { writeInt(wopHasSubstitutes, to); writeString(path, to); unsigned int reply = readInt(from); return reply != 0; } Hash RemoteStore::queryPathHash(const Path & path) { writeInt(wopQueryPathHash, to); writeString(path, to); string hash = readString(from); return parseHash(htSHA256, hash); } void RemoteStore::queryReferences(const Path & path, PathSet & references) { writeInt(wopQueryReferences, to); writeString(path, to); PathSet references2 = readStringSet(from); references.insert(references2.begin(), references2.end()); } void RemoteStore::queryReferrers(const Path & path, PathSet & referrers) { writeInt(wopQueryReferrers, to); writeString(path, to); PathSet referrers2 = readStringSet(from); referrers.insert(referrers2.begin(), referrers2.end()); } Path RemoteStore::addToStore(const Path & _srcPath, bool fixed, bool recursive, string hashAlgo) { Path srcPath(absPath(_srcPath)); writeInt(wopAddToStore, to); writeString(baseNameOf(srcPath), to); writeInt(fixed ? 1 : 0, to); writeInt(recursive ? 1 : 0, to); writeString(hashAlgo, to); dumpPath(srcPath, to); Path path = readString(from); return path; } Path RemoteStore::addTextToStore(const string & suffix, const string & s, const PathSet & references) { writeInt(wopAddTextToStore, to); writeString(suffix, to); writeString(s, to); writeStringSet(references, to); Path path = readString(from); return path; } void RemoteStore::buildDerivations(const PathSet & drvPaths) { writeInt(wopBuildDerivations, to); writeStringSet(drvPaths, to); processStderr(); readInt(from); } void RemoteStore::ensurePath(const Path & path) { writeInt(wopEnsurePath, to); writeString(path, to); readInt(from); } void RemoteStore::addTempRoot(const Path & path) { writeInt(wopAddTempRoot, to); writeString(path, to); readInt(from); } void RemoteStore::syncWithGC() { writeInt(wopSyncWithGC, to); readInt(from); } void RemoteStore::processStderr() { unsigned int msg; while ((msg = readInt(from)) == STDERR_NEXT) { string s = readString(from); writeToStderr((unsigned char *) s.c_str(), s.size()); } if (msg == STDERR_ERROR) throw Error(readString(from)); else if (msg != STDERR_LAST) throw Error("protocol error processing standard error"); } } <commit_msg>* Better error message if the worker doesn't start.<commit_after>#include "serialise.hh" #include "util.hh" #include "remote-store.hh" #include "worker-protocol.hh" #include "archive.hh" #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <iostream> #include <unistd.h> namespace nix { RemoteStore::RemoteStore() { toChild.create(); fromChild.create(); /* Start the worker. */ string worker = "nix-worker"; child = fork(); switch (child) { case -1: throw SysError("unable to fork"); case 0: try { /* child */ fromChild.readSide.close(); if (dup2(fromChild.writeSide, STDOUT_FILENO) == -1) throw SysError("dupping write side"); toChild.writeSide.close(); if (dup2(toChild.readSide, STDIN_FILENO) == -1) throw SysError("dupping read side"); int fdDebug = open("/tmp/worker-log", O_WRONLY | O_CREAT | O_TRUNC, 0644); assert(fdDebug != -1); if (dup2(fdDebug, STDERR_FILENO) == -1) throw SysError("dupping stderr"); close(fdDebug); execlp(worker.c_str(), worker.c_str(), "-vvv", "--slave", NULL); throw SysError(format("executing `%1%'") % worker); } catch (std::exception & e) { std::cerr << format("child error: %1%\n") % e.what(); } quickExit(1); } fromChild.writeSide.close(); toChild.readSide.close(); from.fd = fromChild.readSide; to.fd = toChild.writeSide; /* Send the magic greeting, check for the reply. */ try { writeInt(WORKER_MAGIC_1, to); unsigned int magic = readInt(from); if (magic != WORKER_MAGIC_2) throw Error("protocol mismatch"); } catch (Error & e) { throw Error(format("cannot start worker process `%1%' (%2%)") % worker % e.msg()); } } RemoteStore::~RemoteStore() { try { fromChild.readSide.close(); toChild.writeSide.close(); child.wait(true); } catch (Error & e) { printMsg(lvlError, format("error (ignored): %1%") % e.msg()); } } bool RemoteStore::isValidPath(const Path & path) { writeInt(wopIsValidPath, to); writeString(path, to); unsigned int reply = readInt(from); return reply != 0; } Substitutes RemoteStore::querySubstitutes(const Path & path) { throw Error("not implemented 2"); } bool RemoteStore::hasSubstitutes(const Path & path) { writeInt(wopHasSubstitutes, to); writeString(path, to); unsigned int reply = readInt(from); return reply != 0; } Hash RemoteStore::queryPathHash(const Path & path) { writeInt(wopQueryPathHash, to); writeString(path, to); string hash = readString(from); return parseHash(htSHA256, hash); } void RemoteStore::queryReferences(const Path & path, PathSet & references) { writeInt(wopQueryReferences, to); writeString(path, to); PathSet references2 = readStringSet(from); references.insert(references2.begin(), references2.end()); } void RemoteStore::queryReferrers(const Path & path, PathSet & referrers) { writeInt(wopQueryReferrers, to); writeString(path, to); PathSet referrers2 = readStringSet(from); referrers.insert(referrers2.begin(), referrers2.end()); } Path RemoteStore::addToStore(const Path & _srcPath, bool fixed, bool recursive, string hashAlgo) { Path srcPath(absPath(_srcPath)); writeInt(wopAddToStore, to); writeString(baseNameOf(srcPath), to); writeInt(fixed ? 1 : 0, to); writeInt(recursive ? 1 : 0, to); writeString(hashAlgo, to); dumpPath(srcPath, to); Path path = readString(from); return path; } Path RemoteStore::addTextToStore(const string & suffix, const string & s, const PathSet & references) { writeInt(wopAddTextToStore, to); writeString(suffix, to); writeString(s, to); writeStringSet(references, to); Path path = readString(from); return path; } void RemoteStore::buildDerivations(const PathSet & drvPaths) { writeInt(wopBuildDerivations, to); writeStringSet(drvPaths, to); processStderr(); readInt(from); } void RemoteStore::ensurePath(const Path & path) { writeInt(wopEnsurePath, to); writeString(path, to); readInt(from); } void RemoteStore::addTempRoot(const Path & path) { writeInt(wopAddTempRoot, to); writeString(path, to); readInt(from); } void RemoteStore::syncWithGC() { writeInt(wopSyncWithGC, to); readInt(from); } void RemoteStore::processStderr() { unsigned int msg; while ((msg = readInt(from)) == STDERR_NEXT) { string s = readString(from); writeToStderr((unsigned char *) s.c_str(), s.size()); } if (msg == STDERR_ERROR) throw Error(readString(from)); else if (msg != STDERR_LAST) throw Error("protocol error processing standard error"); } } <|endoftext|>
<commit_before>#pragma once #include "stdafx.h" static std::map<std::string,void*> s_InitializationMap; //ʼֵ inline void InitInitializationMap() //ʼʼֵ { s_InitializationMap[typeid(int).name()] = new int(0); s_InitializationMap[typeid(float).name()] = new float(0.00f); s_InitializationMap[typeid(double).name()] = new double(0.00f); s_InitializationMap[typeid(char).name()] = new char(char(0)); s_InitializationMap[typeid(bool).name()] = new bool(false); } inline void ReleaseInitializationMap() //ͷųʼֵ { for (auto i : s_InitializationMap) { delete i.second; } } template <typename T> inline void GetInitialization(T** c) //ȡ͵ijʼֵ { auto i = find(s_InitializationMap.begin(), s_InitializationMap.end(), typeid(*(*c)).name()); if (i != s_InitializationMap.end()) { memcpy(*c, (*i).second, sizeof(T)); } else { s_InitializationMap.insert(make_pair(typeid(T).name(), new T())); memcpy(*c, s_InitializationMap[typeid(T).name()], sizeof(T)); } } struct MemoryBlock //ڴϢ { void* m_Address; size_t m_Size; MemoryBlock() { m_Address = NULL; m_Size = 0; } MemoryBlock(void* address, size_t size) { m_Address = address; m_Size = size; } }; void CleanMemoryBlock(const MemoryBlock& mb) { memset(mb.m_Address, NULL, mb.m_Size); } class MemoryManager //ڴջΨһģ { protected: size_t m_Top; void* m_Memory; std::vector<MemoryBlock> m_MemoryBlocks; std::vector<MemoryBlock> m_FreeMemoryBlocks; public: static const size_t m_MemorySize = 0xffff; MemoryManager() { m_Memory = malloc(m_MemorySize); m_Top = 0; InitInitializationMap(); } ~MemoryManager() { free(m_Memory); m_Memory = NULL; ReleaseInitializationMap(); } template<typename T> bool ReuseMemory(T** dest) { if (m_FreeMemoryBlocks.size() == 0) return false; else { for (vector<MemoryBlock>::iterator i = m_FreeMemoryBlocks.begin(); i != m_FreeMemoryBlocks.end(); i += 1) { if ((*i).m_Size >= sizeof(T)) { m_MemoryBlocks.push_back(MemoryBlock((*i).m_Address, sizeof(T))); *dest = (T*)((*i).m_Address); CleanMemoryBlock(m_MemoryBlocks[m_MemoryBlocks.size() - 1]); GetInitialization(dest); if ((*i).m_Size == sizeof(T)) { m_FreeMemoryBlocks.erase(i); } else { (*i).m_Address = *dest + sizeof(T); (*i).m_Size -= sizeof(T); } return true; } } } return false; } template<typename T> bool ReuseMemory(std::pair<T**, size_t> c) { if (m_FreeMemoryBlocks.size() == 0) return false; else { for (vector<MemoryBlock>::iterator i = m_FreeMemoryBlocks.begin(); i != m_FreeMemoryBlocks.end(); i += 1) { if ((*i).m_Size >= c.second * sizeof(T)) { m_MemoryBlocks.push_back(MemoryBlock((*i).m_Address, c.second * sizeof(T))); *c.first = (T*)((*i).m_Address); CleanMemoryBlock(m_MemoryBlocks[m_MemoryBlocks.size() - 1]); GetInitialization(dest); if ((*i).m_Size == c.second * sizeof(T)) { m_FreeMemoryBlocks.erase(i); } else { (*i).m_Address = *c.first + c.second * sizeof(T); (*i).m_Size -= c.second * sizeof(T); } return true; } } } return false; } template<typename T> void NewObject(T** dest) { if (!ReuseMemory(dest)) { m_MemoryBlocks.push_back(MemoryBlock(m_Memory + m_Top, sizeof(T))); *dest = (T*)(m_Memory + m_Top); CleanMemoryBlock(m_MemoryBlocks[m_MemoryBlocks.size() - 1]); GetInitialization(dest); m_Top += sizeof(T); } } template<typename T, typename... TS> void NewObject(T** dest, TS**... ts) { NewObject(dest); NewObject(ts...); } template<typename T> void NewObject(std::pair<T**, size_t> c) { if (!ReuseMemory(c)) { m_MemoryBlocks.push_back(MemoryBlock(m_Memory + m_Top, c.second * sizeof(T))); *c.first = (T*)(m_Memory + m_Top); CleanMemoryBlock(m_MemoryBlocks[m_MemoryBlocks.size() - 1]); GetInitialization(dest); m_Top += c.second * sizeof(T); } } template<typename T> bool ReleaseObject(T** dest) { for (vector<MemoryBlock>::iterator i = m_MemoryBlocks.begin(); i != m_MemoryBlocks.end(); i += 1) { if ((*i).m_Address == *dest) { m_FreeMemoryBlocks.push_back(*i); m_MemoryBlocks.erase(i); *dest = NULL; return true; } } return false; } template<typename T, typename... TS> bool ReleaseObject(T** dest, TS**... ts) { return (Release(dest)&Release(ts...)); } }; template<typename T> class Pointer //ʹڴָ { protected: MemoryManager& m_MemoryManager; T* m_pContent; public: Pointer(MemoryManager& m) :m_MemoryManager(m),m_pContent(NULL){} ~Pointer() { if (m_pContent) m_MemoryManager.ReleaseObject(&m_pContent); } void InitUnit() { m_MemoryManager.NewObject(&m_pContent); } void InitArray(size_t size) { m_MemoryManager.NewObject(make_pair(&m_pContent, size)); } bool operator = (const Pointer&) = delete; T& operator * () { return *m_pContent; } }; template<typename T> class UnitPointer :public Pointer<T> //ָ򵥸ָ { UnitPointer(MemoryManager& m) :Pointer(m) { InitUnit(); } ~UnitPointer() { ~Pointer(); } }; template<typename T> class ArrayPointer :public Pointer<T> //ָγɵָ { ArrayPointer(MemoryManager& m,size_t size) :Pointer(m) { InitArray(size); } ~ArrayPointer() { ~Pointer(); } };<commit_msg>the MemorytInitialization can't use<commit_after>#pragma once #include "stdafx.h" /* static std::map<std::string,void*> s_InitializationMap; //ʼֵ inline void InitInitializationMap() //ʼʼֵ { s_InitializationMap[typeid(int).name()] = new int(0); s_InitializationMap[typeid(float).name()] = new float(0.00f); s_InitializationMap[typeid(double).name()] = new double(0.00f); s_InitializationMap[typeid(char).name()] = new char(char(0)); s_InitializationMap[typeid(bool).name()] = new bool(false); } inline void ReleaseInitializationMap() //ͷųʼֵ { for (auto i : s_InitializationMap) { delete i.second; } } template <typename T> inline void GetInitialization(T** c) //ȡ͵ijʼֵ { auto i = find(s_InitializationMap.begin(), s_InitializationMap.end(), typeid(*(*c)).name()); if (i != s_InitializationMap.end()) { memcpy(*c, (*i).second, sizeof(T)); } else { s_InitializationMap.insert(std::make_pair(typeid(T).name(), new T())); memcpy(*c, s_InitializationMap[typeid(T).name()], sizeof(T)); } } */ struct MemoryBlock //ڴϢ { void* m_Address; size_t m_Size; MemoryBlock() { m_Address = NULL; m_Size = 0; } MemoryBlock(void* address, size_t size) { m_Address = address; m_Size = size; } }; void CleanMemoryBlock(const MemoryBlock& mb) { memset(mb.m_Address, NULL, mb.m_Size); } class MemoryManager //ڴջΨһģ { protected: size_t m_Top; void* m_Memory; std::vector<MemoryBlock> m_MemoryBlocks; std::vector<MemoryBlock> m_FreeMemoryBlocks; public: static const size_t m_MemorySize = 0xffff; MemoryManager() { m_Memory = malloc(m_MemorySize); m_Top = 0; // InitInitializationMap(); } ~MemoryManager() { free(m_Memory); m_Memory = NULL; // ReleaseInitializationMap(); } template<typename T> bool ReuseMemory(T** dest) { if (m_FreeMemoryBlocks.size() == 0) return false; else { for (std::vector<MemoryBlock>::iterator i = m_FreeMemoryBlocks.begin(); i != m_FreeMemoryBlocks.end(); i += 1) { if ((*i).m_Size >= sizeof(T)) { m_MemoryBlocks.push_back(MemoryBlock((*i).m_Address, sizeof(T))); *dest = (T*)((*i).m_Address); CleanMemoryBlock(m_MemoryBlocks[m_MemoryBlocks.size() - 1]); // GetInitialization(dest); if ((*i).m_Size == sizeof(T)) { m_FreeMemoryBlocks.erase(i); } else { (*i).m_Address = *dest + sizeof(T); (*i).m_Size -= sizeof(T); } return true; } } } return false; } template<typename T> bool ReuseMemory(std::pair<T**, size_t> c) { if (m_FreeMemoryBlocks.size() == 0) return false; else { for (vector<MemoryBlock>::iterator i = m_FreeMemoryBlocks.begin(); i != m_FreeMemoryBlocks.end(); i += 1) { if ((*i).m_Size >= c.second * sizeof(T)) { m_MemoryBlocks.push_back(MemoryBlock((*i).m_Address, c.second * sizeof(T))); *c.first = (T*)((*i).m_Address); CleanMemoryBlock(m_MemoryBlocks[m_MemoryBlocks.size() - 1]); // GetInitialization(dest); if ((*i).m_Size == c.second * sizeof(T)) { m_FreeMemoryBlocks.erase(i); } else { (*i).m_Address = *c.first + c.second * sizeof(T); (*i).m_Size -= c.second * sizeof(T); } return true; } } } return false; } template<typename T> void NewObject(T** dest) { if (!ReuseMemory(dest)) { m_MemoryBlocks.push_back(MemoryBlock((void*)((char*)m_Memory + m_Top), sizeof(T))); *dest = (T*)((char*)m_Memory + m_Top); CleanMemoryBlock(m_MemoryBlocks[m_MemoryBlocks.size() - 1]); // GetInitialization(dest); m_Top += sizeof(T); } } template<typename T, typename... TS> void NewObject(T** dest, TS**... ts) { NewObject(dest); NewObject(ts...); } template<typename T> void NewObject(std::pair<T**, size_t> c) { if (!ReuseMemory(c)) { m_MemoryBlocks.push_back(MemoryBlock(m_Memory + m_Top, c.second * sizeof(T))); *c.first = (T*)(m_Memory + m_Top); CleanMemoryBlock(m_MemoryBlocks[m_MemoryBlocks.size() - 1]); // GetInitialization(dest); m_Top += c.second * sizeof(T); } } template<typename T> bool ReleaseObject(T** dest) { for (std::vector<MemoryBlock>::iterator i = m_MemoryBlocks.begin(); i != m_MemoryBlocks.end(); i += 1) { if ((*i).m_Address == *dest) { m_FreeMemoryBlocks.push_back(*i); m_MemoryBlocks.erase(i); *dest = NULL; return true; } } return false; } template<typename T, typename... TS> bool ReleaseObject(T** dest, TS**... ts) { return (Release(dest)&Release(ts...)); } }; template<typename T> class Pointer //ʹڴָ { protected: MemoryManager& m_MemoryManager; T* m_pContent; public: Pointer(MemoryManager& m) :m_MemoryManager(m),m_pContent(NULL){} ~Pointer() { if (m_pContent) m_MemoryManager.ReleaseObject(&m_pContent); } void InitUnit() { m_MemoryManager.NewObject(&m_pContent); } void InitArray(size_t size) { m_MemoryManager.NewObject(make_pair(&m_pContent, size)); } bool operator = (const Pointer&) = delete; T& operator * () { return *m_pContent; } }; template<typename T> class UnitPointer :public Pointer<T> //ָ򵥸ָ { public: UnitPointer(MemoryManager& m) :Pointer(m) { Pointer<T>::InitUnit(); } }; template<typename T> class ArrayPointer :public Pointer<T> //ָγɵָ { public: ArrayPointer(MemoryManager& m,size_t size) :Pointer(m) { Pointer<T>::InitArray(size); } };<|endoftext|>
<commit_before>/** * @file paramgen.cpp * * @brief Parameter generation utility for Zerocoin. * * @author Ian Miers, Christina Garman and Matthew Green * @date June 2013 * * @copyright Copyright 2013 Ian Miers, Christina Garman and Matthew Green * @license This project is released under the MIT license. **/ // Copyright (c) 2017-2019 The PIVX developers #include <string> #include <iostream> #include <fstream> //#include <curses.h> #include <exception> #include "Zerocoin.h" #define DEFAULT_MODULUS_SIZE 3072 #define MIN_MODULUS_SIZE 1026 void PrintWarning() { cout << "Zerocoin parameter generation utility" << endl; cout << "-------------------------------------" << endl << endl; cout << "This utility generates an l-bit modulus N as the product of" << endl; cout << "two safe primes p, q. The values p and q are not stored." << endl; cout << "Call this program with no arguments to see usage options." << endl; cout << endl; cout << "SECURITY WARNING: ZEROCOIN PARAMETERS MUST BE GENERATED BY" << endl; cout << "A TRUSTED PARTY WHO DOES NOT STORE THE FACTORS. WHILE WE MAKE" << endl; cout << "A BEST EFFORT TO DESTROY THIS INFORMATION WE DO NOT TAKE" << endl; cout << "SPECIAL PRECAUTIONS TO ENSURE THAT THEY ARE DESTROYED." << endl; cout << endl; cout << "USE THIS UTILITY AT YOUR OWN RISK" << endl << endl; } void usage() { printf("Usage:\n"); printf(" -b <numbits>\n"); printf(" -o <output file>\n"); exit (8); } int main(int argc, char **argv) { static CBigNum resultModulus(0); uint32_t numBits = DEFAULT_MODULUS_SIZE; ofstream outfile; char* outfileName; bool writeToFile = false; while ((argc > 1) && (argv[1][0] == '-')) { switch (argv[1][1]) { case 'b': numBits = atoi(argv[2]); ++argv; --argc; break; case 'o': outfileName = argv[2]; writeToFile = true; break; case 'h': usage(); break; default: printf("Wrong Argument: %s\n", argv[1]); usage(); break; } ++argv; --argc; } if (numBits < MIN_MODULUS_SIZE) { cout << "Modulus is below minimum length (" << MIN_MODULUS_SIZE << ") bits" << endl; return(0); } PrintWarning(); cout << "Modulus size set to " << numBits << " bits." << endl; cout << "Generating parameters. This may take a few minutes..." << endl; // Generate two safe primes "p" and "q" CBigNum *p, *q; p = new CBigNum(0); q = new CBigNum(0); *p = CBigNum::generatePrime(numBits / 2, true); *q = CBigNum::generatePrime(numBits / 2, true); // Multiply to compute N resultModulus = (*p) * (*q); // Wipe out the factors delete p; delete q; // Convert to a hexidecimal string std::string resultHex = resultModulus.ToString(16); cout << endl << "N = " << endl << resultHex << endl; if (writeToFile) { try { outfile.open (outfileName); outfile << resultHex; outfile.close(); cout << endl << "Result has been written to file '" << outfileName << "'." << endl; } catch (const std::runtime_error& e) { cout << "Unable to write to file:" << e.what() << endl; } } } <commit_msg>[Cleanup] Remove unused Parameter generation utility for zerocoin<commit_after><|endoftext|>
<commit_before>#include "lxqtfiledialoghelper.h" #include <libfm-qt/libfmqt.h> #include <libfm-qt/filedialog.h> #include <QWindow> #include <QMimeDatabase> #include <QDebug> #include <QTimer> #include <memory> static std::unique_ptr<Fm::LibFmQt> libfmQtContext_; LXQtFileDialogHelper::LXQtFileDialogHelper() { if(!libfmQtContext_) { // initialize libfm-qt only once libfmQtContext_ = std::unique_ptr<Fm::LibFmQt>{new Fm::LibFmQt()}; } // can only be used after libfm-qt initialization dlg_ = std::unique_ptr<Fm::FileDialog>(new Fm::FileDialog()); connect(dlg_.get(), &Fm::FileDialog::accepted, this, &LXQtFileDialogHelper::accept); connect(dlg_.get(), &Fm::FileDialog::rejected, this, &LXQtFileDialogHelper::reject); connect(dlg_.get(), &Fm::FileDialog::fileSelected, this, &LXQtFileDialogHelper::fileSelected); connect(dlg_.get(), &Fm::FileDialog::filesSelected, this, &LXQtFileDialogHelper::filesSelected); connect(dlg_.get(), &Fm::FileDialog::currentChanged, this, &LXQtFileDialogHelper::currentChanged); connect(dlg_.get(), &Fm::FileDialog::directoryEntered, this, &LXQtFileDialogHelper::directoryEntered); connect(dlg_.get(), &Fm::FileDialog::filterSelected, this, &LXQtFileDialogHelper::filterSelected); } LXQtFileDialogHelper::~LXQtFileDialogHelper() { } void LXQtFileDialogHelper::exec() { dlg_->exec(); } bool LXQtFileDialogHelper::show(Qt::WindowFlags windowFlags, Qt::WindowModality windowModality, QWindow* parent) { dlg_->setAttribute(Qt::WA_NativeWindow, true); // without this, sometimes windowHandle() will return nullptr dlg_->setWindowFlags(windowFlags); dlg_->setWindowModality(windowModality); // Reference: KDE implementation // https://github.com/KDE/plasma-integration/blob/master/src/platformtheme/kdeplatformfiledialoghelper.cpp dlg_->windowHandle()->setTransientParent(parent); applyOptions(); // NOTE: the timer here is required as a workaround borrowed from KDE. Without this, the dialog UI will be blocked. // QFileDialog calls our platform plugin to show our own native file dialog instead of showing its widget. // However, it still creates a hidden dialog internally, and then make it modal. // So user input from all other windows that are not the children of the QFileDialog widget will be blocked. // This includes our own dialog. After the return of this show() method, QFileDialog creates its own window and // then make it modal, which blocks our UI. The timer schedule a delayed popup of our file dialog, so we can // show again after QFileDialog and override the modal state. Then our UI can be unblocked. QTimer::singleShot(0, dlg_.get(), &QDialog::show); dlg_->setFocus(); return true; } void LXQtFileDialogHelper::hide() { dlg_->hide(); } bool LXQtFileDialogHelper::defaultNameFilterDisables() const { return false; } void LXQtFileDialogHelper::setDirectory(const QUrl& directory) { dlg_->setDirectory(directory); } QUrl LXQtFileDialogHelper::directory() const { return dlg_->directory(); } void LXQtFileDialogHelper::selectFile(const QUrl& filename) { dlg_->selectFile(filename); } QList<QUrl> LXQtFileDialogHelper::selectedFiles() const { return dlg_->selectedFiles(); } void LXQtFileDialogHelper::setFilter() { // FIXME: what's this? // The gtk+ 3 file dialog helper in Qt5 update options in this method. applyOptions(); } void LXQtFileDialogHelper::selectNameFilter(const QString& filter) { dlg_->selectNameFilter(filter); } #if QT_VERSION >= QT_VERSION_CHECK(5, 9, 0) QString LXQtFileDialogHelper::selectedMimeTypeFilter() const { const auto mimeTypeFromFilter = QMimeDatabase().mimeTypeForName(dlg_->selectedNameFilter()); if(mimeTypeFromFilter.isValid()) { return mimeTypeFromFilter.name(); } QList<QUrl> sel = dlg_->selectedFiles(); if(sel.isEmpty()) { return QString(); } return QMimeDatabase().mimeTypeForUrl(sel.at(0)).name(); } void LXQtFileDialogHelper::selectMimeTypeFilter(const QString& filter) { dlg_->selectNameFilter(filter); } #endif QString LXQtFileDialogHelper::selectedNameFilter() const { return dlg_->selectedNameFilter(); } bool LXQtFileDialogHelper::isSupportedUrl(const QUrl& url) const { return dlg_->isSupportedUrl(url); } void LXQtFileDialogHelper::applyOptions() { auto& opt = options(); if(options()->testOption(QFileDialogOptions::ShowDirsOnly)) { if(!options()->windowTitle().isEmpty()) { dlg_->setWindowTitle(options()->windowTitle()); } } else { if(options()->windowTitle().isEmpty()) { dlg_->setWindowTitle(options()->acceptMode() == QFileDialogOptions::AcceptOpen ? tr("Open File") : tr("Save File")); } else { dlg_->setWindowTitle(options()->windowTitle()); } } dlg_->setFilter(opt->filter()); dlg_->setViewMode(opt->viewMode() == QFileDialogOptions::Detail ? Fm::FolderView::DetailedListMode : Fm::FolderView::CompactMode); dlg_->setFileMode(QFileDialog::FileMode(opt->fileMode())); dlg_->setAcceptMode(QFileDialog::AcceptMode(opt->acceptMode())); // bool useDefaultNameFilters() const; dlg_->setNameFilters(opt->nameFilters()); if(!opt->mimeTypeFilters().empty()) { dlg_->setMimeTypeFilters(opt->mimeTypeFilters()); } dlg_->setDefaultSuffix(opt->defaultSuffix()); // QStringList history() const; for(int i = 0; i < QFileDialogOptions::DialogLabelCount; ++i) { auto label = static_cast<QFileDialogOptions::DialogLabel>(i); if(opt->isLabelExplicitlySet(label)) { dlg_->setLabelText(static_cast<QFileDialog::DialogLabel>(label), opt->labelText(label)); } } auto url = opt->initialDirectory(); if(url.isValid()) { dlg_->setDirectory(url); } #if QT_VERSION >= QT_VERSION_CHECK(5, 9, 0) auto filter = opt->initiallySelectedMimeTypeFilter(); if(!filter.isEmpty()) { selectMimeTypeFilter(filter); } else { filter = opt->initiallySelectedNameFilter(); if(!filter.isEmpty()) { selectNameFilter(options()->initiallySelectedNameFilter()); } } #else filter = opt->initiallySelectedNameFilter(); if(!filter.isEmpty()) { selectNameFilter(filter); } #endif auto selectedFiles = opt->initiallySelectedFiles(); for(const auto& selectedFile: selectedFiles) { selectFile(selectedFile); } // QStringList supportedSchemes() const; } /* FileDialogPlugin::FileDialogPlugin() { } QPlatformFileDialogHelper *FileDialogPlugin::createHelper() { return new LXQtFileDialogHelper(); } */ <commit_msg>Central positioning with respect to parent<commit_after>#include "lxqtfiledialoghelper.h" #include <libfm-qt/libfmqt.h> #include <libfm-qt/filedialog.h> #include <QWindow> #include <QMimeDatabase> #include <QDebug> #include <QTimer> #include <memory> static std::unique_ptr<Fm::LibFmQt> libfmQtContext_; LXQtFileDialogHelper::LXQtFileDialogHelper() { if(!libfmQtContext_) { // initialize libfm-qt only once libfmQtContext_ = std::unique_ptr<Fm::LibFmQt>{new Fm::LibFmQt()}; } // can only be used after libfm-qt initialization dlg_ = std::unique_ptr<Fm::FileDialog>(new Fm::FileDialog()); connect(dlg_.get(), &Fm::FileDialog::accepted, this, &LXQtFileDialogHelper::accept); connect(dlg_.get(), &Fm::FileDialog::rejected, this, &LXQtFileDialogHelper::reject); connect(dlg_.get(), &Fm::FileDialog::fileSelected, this, &LXQtFileDialogHelper::fileSelected); connect(dlg_.get(), &Fm::FileDialog::filesSelected, this, &LXQtFileDialogHelper::filesSelected); connect(dlg_.get(), &Fm::FileDialog::currentChanged, this, &LXQtFileDialogHelper::currentChanged); connect(dlg_.get(), &Fm::FileDialog::directoryEntered, this, &LXQtFileDialogHelper::directoryEntered); connect(dlg_.get(), &Fm::FileDialog::filterSelected, this, &LXQtFileDialogHelper::filterSelected); } LXQtFileDialogHelper::~LXQtFileDialogHelper() { } void LXQtFileDialogHelper::exec() { dlg_->exec(); } bool LXQtFileDialogHelper::show(Qt::WindowFlags windowFlags, Qt::WindowModality windowModality, QWindow* parent) { dlg_->setAttribute(Qt::WA_NativeWindow, true); // without this, sometimes windowHandle() will return nullptr dlg_->setWindowFlags(windowFlags); dlg_->setWindowModality(windowModality); // Reference: KDE implementation // https://github.com/KDE/plasma-integration/blob/master/src/platformtheme/kdeplatformfiledialoghelper.cpp dlg_->windowHandle()->setTransientParent(parent); // central positioning with respect to the parent window if(parent && parent->isVisible()) { dlg_->move(parent->x() + parent->width()/2 - dlg_->width()/2, parent->y() + parent->height()/2 - dlg_->height()/ 2); } applyOptions(); // NOTE: the timer here is required as a workaround borrowed from KDE. Without this, the dialog UI will be blocked. // QFileDialog calls our platform plugin to show our own native file dialog instead of showing its widget. // However, it still creates a hidden dialog internally, and then make it modal. // So user input from all other windows that are not the children of the QFileDialog widget will be blocked. // This includes our own dialog. After the return of this show() method, QFileDialog creates its own window and // then make it modal, which blocks our UI. The timer schedule a delayed popup of our file dialog, so we can // show again after QFileDialog and override the modal state. Then our UI can be unblocked. QTimer::singleShot(0, dlg_.get(), &QDialog::show); dlg_->setFocus(); return true; } void LXQtFileDialogHelper::hide() { dlg_->hide(); } bool LXQtFileDialogHelper::defaultNameFilterDisables() const { return false; } void LXQtFileDialogHelper::setDirectory(const QUrl& directory) { dlg_->setDirectory(directory); } QUrl LXQtFileDialogHelper::directory() const { return dlg_->directory(); } void LXQtFileDialogHelper::selectFile(const QUrl& filename) { dlg_->selectFile(filename); } QList<QUrl> LXQtFileDialogHelper::selectedFiles() const { return dlg_->selectedFiles(); } void LXQtFileDialogHelper::setFilter() { // FIXME: what's this? // The gtk+ 3 file dialog helper in Qt5 update options in this method. applyOptions(); } void LXQtFileDialogHelper::selectNameFilter(const QString& filter) { dlg_->selectNameFilter(filter); } #if QT_VERSION >= QT_VERSION_CHECK(5, 9, 0) QString LXQtFileDialogHelper::selectedMimeTypeFilter() const { const auto mimeTypeFromFilter = QMimeDatabase().mimeTypeForName(dlg_->selectedNameFilter()); if(mimeTypeFromFilter.isValid()) { return mimeTypeFromFilter.name(); } QList<QUrl> sel = dlg_->selectedFiles(); if(sel.isEmpty()) { return QString(); } return QMimeDatabase().mimeTypeForUrl(sel.at(0)).name(); } void LXQtFileDialogHelper::selectMimeTypeFilter(const QString& filter) { dlg_->selectNameFilter(filter); } #endif QString LXQtFileDialogHelper::selectedNameFilter() const { return dlg_->selectedNameFilter(); } bool LXQtFileDialogHelper::isSupportedUrl(const QUrl& url) const { return dlg_->isSupportedUrl(url); } void LXQtFileDialogHelper::applyOptions() { auto& opt = options(); // set title if(opt->windowTitle().isEmpty()) { dlg_->setWindowTitle(opt->acceptMode() == QFileDialogOptions::AcceptOpen ? tr("Open File") : tr("Save File")); } else { dlg_->setWindowTitle(opt->windowTitle()); } dlg_->setFilter(opt->filter()); dlg_->setViewMode(opt->viewMode() == QFileDialogOptions::Detail ? Fm::FolderView::DetailedListMode : Fm::FolderView::CompactMode); dlg_->setFileMode(QFileDialog::FileMode(opt->fileMode())); dlg_->setAcceptMode(QFileDialog::AcceptMode(opt->acceptMode())); // also sets a default label for accept button // bool useDefaultNameFilters() const; dlg_->setNameFilters(opt->nameFilters()); if(!opt->mimeTypeFilters().empty()) { dlg_->setMimeTypeFilters(opt->mimeTypeFilters()); } dlg_->setDefaultSuffix(opt->defaultSuffix()); // QStringList history() const; // explicitly set labels for(int i = 0; i < QFileDialogOptions::DialogLabelCount; ++i) { auto label = static_cast<QFileDialogOptions::DialogLabel>(i); if(opt->isLabelExplicitlySet(label)) { dlg_->setLabelText(static_cast<QFileDialog::DialogLabel>(label), opt->labelText(label)); } } auto url = opt->initialDirectory(); if(url.isValid()) { dlg_->setDirectory(url); } #if QT_VERSION >= QT_VERSION_CHECK(5, 9, 0) auto filter = opt->initiallySelectedMimeTypeFilter(); if(!filter.isEmpty()) { selectMimeTypeFilter(filter); } else { filter = opt->initiallySelectedNameFilter(); if(!filter.isEmpty()) { selectNameFilter(opt->initiallySelectedNameFilter()); } } #else filter = opt->initiallySelectedNameFilter(); if(!filter.isEmpty()) { selectNameFilter(filter); } #endif auto selectedFiles = opt->initiallySelectedFiles(); for(const auto& selectedFile: selectedFiles) { selectFile(selectedFile); } // QStringList supportedSchemes() const; } /* FileDialogPlugin::FileDialogPlugin() { } QPlatformFileDialogHelper *FileDialogPlugin::createHelper() { return new LXQtFileDialogHelper(); } */ <|endoftext|>
<commit_before>/* Copyright (C) 2013 Slawomir Cygan <[email protected]> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "gtest/gtest.h" #include <DGLCommon/gl-types.h> #include <DGLCommon/gl-formats.h> #include <DGLCommon/os.h> #include <DGLWrapper/api-loader.h> namespace { // The fixture for testing class Foo. class DGLCommonUT : public ::testing::Test { protected: // You can remove any or all of the following functions if its body // is empty. DGLCommonUT() { // You can do set-up work for each test here. } virtual ~DGLCommonUT() { // You can do clean-up work that doesn't throw exceptions here. } // If the constructor and destructor are not enough for setting up // and cleaning up each test, you can define the following methods: virtual void SetUp() { // Code here will be called immediately after the constructor (right // before each test). } virtual void TearDown() { // Code here will be called immediately after each test (right // before the destructor). } // Objects declared here can be used by all tests in the test case for Foo. }; // Smoke test all inputs of codegen has been parsed to functionList TEST_F(DGLCommonUT, codegen_entryps) { //gl.h + gl2.h ASSERT_STREQ(GetEntryPointName(glEnable_Call), "glEnable"); //glext.h ASSERT_STREQ(GetEntryPointName(glDrawArraysInstancedBaseInstance_Call), "glDrawArraysInstancedBaseInstance"); ASSERT_STREQ(GetEntryPointName(glDrawArraysInstancedARB_Call), "glDrawArraysInstancedARB"); //wgl ASSERT_STREQ(GetEntryPointName(wglCreateContext_Call), "wglCreateContext"); //wgl-notrace ASSERT_STREQ(GetEntryPointName(wglSetPixelFormat_Call), "wglSetPixelFormat"); //wglext.h ASSERT_STREQ(GetEntryPointName(wglCreateContextAttribsARB_Call), "wglCreateContextAttribsARB"); //egl.h ASSERT_STREQ(GetEntryPointName(eglBindAPI_Call), "eglBindAPI"); ASSERT_STREQ(GetEntryPointName(eglCreateContext_Call), "eglCreateContext"); ASSERT_STREQ(GetEntryPointName(eglMakeCurrent_Call), "eglMakeCurrent"); ASSERT_STREQ(GetEntryPointName(eglGetProcAddress_Call), "eglGetProcAddress"); //eglext.h ASSERT_STREQ(GetEntryPointName(eglCreateImageKHR_Call), "eglCreateImageKHR"); ASSERT_STREQ(GetEntryPointName(eglQuerySurfacePointerANGLE_Call), "eglQuerySurfacePointerANGLE"); //glx.h ASSERT_STREQ(GetEntryPointName(glXChooseFBConfig_Call), "glXChooseFBConfig"); const char* null = NULL; //null ASSERT_STREQ(GetEntryPointName(NO_ENTRYPOINT), "<unknown>"); } //here direct pointers are kept (pointers to entrypoints exposed by underlying OpenGL32 implementation //use DIRECT_CALL(name) to call one of these pointers int ut_PointerLibraries[Entrypoints_NUM] = { #define FUNC_LIST_ELEM_SUPPORTED(name, type, library) library, #define FUNC_LIST_ELEM_NOT_SUPPORTED(name, type, library) FUNC_LIST_ELEM_SUPPORTED(name, type, library) #include "codegen/functionList.inl" #undef FUNC_LIST_ELEM_SUPPORTED #undef FUNC_LIST_ELEM_NOT_SUPPORTED }; TEST_F(DGLCommonUT, codegen_libraries) { //gl.h + gl2.h EXPECT_EQ(LIBRARY_GL | LIBRARY_ES2, ut_PointerLibraries[glEnable_Call]); //all ES2 entryps are should be shared with GL or GL_EXT for (int i = 0; i < NUM_ENTRYPOINTS; i++) { if (ut_PointerLibraries[i] & LIBRARY_ES2) { EXPECT_GT(ut_PointerLibraries[i] & (LIBRARY_GL | LIBRARY_GL_EXT), 0); } } //glext.h EXPECT_EQ(LIBRARY_GL_EXT, ut_PointerLibraries[glDrawArraysInstancedBaseInstance_Call]); EXPECT_EQ(LIBRARY_GL_EXT, ut_PointerLibraries[glDrawArraysInstancedARB_Call]); //wgl EXPECT_EQ(LIBRARY_WGL, ut_PointerLibraries[wglCreateContext_Call]); //wgl-notrace EXPECT_EQ(LIBRARY_WGL, ut_PointerLibraries[wglSetPixelFormat_Call]); //wglext.h EXPECT_EQ(LIBRARY_WGL_EXT, ut_PointerLibraries[wglCreateContextAttribsARB_Call]); //egl.h EXPECT_EQ(LIBRARY_EGL, ut_PointerLibraries[eglBindAPI_Call]); EXPECT_EQ(LIBRARY_EGL, ut_PointerLibraries[eglCreateContext_Call]); EXPECT_EQ(LIBRARY_EGL, ut_PointerLibraries[eglMakeCurrent_Call]); EXPECT_EQ(LIBRARY_EGL, ut_PointerLibraries[eglGetProcAddress_Call]); //eglext.h EXPECT_EQ(LIBRARY_EGL_EXT, ut_PointerLibraries[eglCreateImageKHR_Call]); //glx.h EXPECT_EQ(LIBRARY_GLX, ut_PointerLibraries[glXChooseFBConfig_Call]); } TEST_F(DGLCommonUT, codegen_entryp_names) { EXPECT_EQ(GetEntryPointEnum("bad"), NO_ENTRYPOINT); EXPECT_EQ(GetEntryPointEnum("glDrawArrays"), glDrawArrays_Call); EXPECT_EQ(GetEntryPointName(GetEntryPointEnum("glDrawArrays")), "glDrawArrays"); EXPECT_EQ(GetEntryPointEnum(GetEntryPointName(glDrawArrays_Call)), glDrawArrays_Call); } TEST_F(DGLCommonUT, formats_iformat) { DGLPixelTransfer rgba8(std::vector<GLint>(), std::vector<GLint>(), GL_RGBA8); EXPECT_EQ(rgba8.getFormat(), GL_RGBA); EXPECT_EQ(rgba8.getType(), GL_UNSIGNED_BYTE); } TEST_F(DGLCommonUT, formats_noiformat) { std::vector<GLint>rgbaSizes(4, 0); rgbaSizes[0] = rgbaSizes[1] = rgbaSizes[2] = 8; std::vector<GLint>dsSizes(2, 0); DGLPixelTransfer rgba8(rgbaSizes, dsSizes, 0); EXPECT_EQ(rgba8.getFormat(), GL_RGB); EXPECT_EQ(rgba8.getType(), GL_FLOAT); } TEST_F(DGLCommonUT, os_env) { EXPECT_EQ("", Os::getEnv("test_name")); Os::setEnv("test_name", "test_value"); EXPECT_EQ("test_value", Os::getEnv("test_name")); } } // namespace <commit_msg>Actualize UT tests (glEnable is also in ES3, default read type is UBYTE).<commit_after>/* Copyright (C) 2013 Slawomir Cygan <[email protected]> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "gtest/gtest.h" #include <DGLCommon/gl-types.h> #include <DGLCommon/gl-formats.h> #include <DGLCommon/os.h> #include <DGLWrapper/api-loader.h> namespace { // The fixture for testing class Foo. class DGLCommonUT : public ::testing::Test { protected: // You can remove any or all of the following functions if its body // is empty. DGLCommonUT() { // You can do set-up work for each test here. } virtual ~DGLCommonUT() { // You can do clean-up work that doesn't throw exceptions here. } // If the constructor and destructor are not enough for setting up // and cleaning up each test, you can define the following methods: virtual void SetUp() { // Code here will be called immediately after the constructor (right // before each test). } virtual void TearDown() { // Code here will be called immediately after each test (right // before the destructor). } // Objects declared here can be used by all tests in the test case for Foo. }; // Smoke test all inputs of codegen has been parsed to functionList TEST_F(DGLCommonUT, codegen_entryps) { //gl.h + gl2.h ASSERT_STREQ(GetEntryPointName(glEnable_Call), "glEnable"); //glext.h ASSERT_STREQ(GetEntryPointName(glDrawArraysInstancedBaseInstance_Call), "glDrawArraysInstancedBaseInstance"); ASSERT_STREQ(GetEntryPointName(glDrawArraysInstancedARB_Call), "glDrawArraysInstancedARB"); //wgl ASSERT_STREQ(GetEntryPointName(wglCreateContext_Call), "wglCreateContext"); //wgl-notrace ASSERT_STREQ(GetEntryPointName(wglSetPixelFormat_Call), "wglSetPixelFormat"); //wglext.h ASSERT_STREQ(GetEntryPointName(wglCreateContextAttribsARB_Call), "wglCreateContextAttribsARB"); //egl.h ASSERT_STREQ(GetEntryPointName(eglBindAPI_Call), "eglBindAPI"); ASSERT_STREQ(GetEntryPointName(eglCreateContext_Call), "eglCreateContext"); ASSERT_STREQ(GetEntryPointName(eglMakeCurrent_Call), "eglMakeCurrent"); ASSERT_STREQ(GetEntryPointName(eglGetProcAddress_Call), "eglGetProcAddress"); //eglext.h ASSERT_STREQ(GetEntryPointName(eglCreateImageKHR_Call), "eglCreateImageKHR"); ASSERT_STREQ(GetEntryPointName(eglQuerySurfacePointerANGLE_Call), "eglQuerySurfacePointerANGLE"); //glx.h ASSERT_STREQ(GetEntryPointName(glXChooseFBConfig_Call), "glXChooseFBConfig"); const char* null = NULL; //null ASSERT_STREQ(GetEntryPointName(NO_ENTRYPOINT), "<unknown>"); } //here direct pointers are kept (pointers to entrypoints exposed by underlying OpenGL32 implementation //use DIRECT_CALL(name) to call one of these pointers int ut_PointerLibraries[Entrypoints_NUM] = { #define FUNC_LIST_ELEM_SUPPORTED(name, type, library) library, #define FUNC_LIST_ELEM_NOT_SUPPORTED(name, type, library) FUNC_LIST_ELEM_SUPPORTED(name, type, library) #include "codegen/functionList.inl" #undef FUNC_LIST_ELEM_SUPPORTED #undef FUNC_LIST_ELEM_NOT_SUPPORTED }; TEST_F(DGLCommonUT, codegen_libraries) { //gl.h + gl2.h EXPECT_EQ(LIBRARY_GL | LIBRARY_ES2 | LIBRARY_ES3, ut_PointerLibraries[glEnable_Call]); //all ES2 entryps are should be shared with GL or GL_EXT for (int i = 0; i < NUM_ENTRYPOINTS; i++) { if (ut_PointerLibraries[i] & LIBRARY_ES2) { EXPECT_GT(ut_PointerLibraries[i] & (LIBRARY_GL | LIBRARY_GL_EXT), 0); } } //glext.h EXPECT_EQ(LIBRARY_GL_EXT, ut_PointerLibraries[glDrawArraysInstancedBaseInstance_Call]); EXPECT_EQ(LIBRARY_GL_EXT, ut_PointerLibraries[glDrawArraysInstancedARB_Call]); //wgl EXPECT_EQ(LIBRARY_WGL, ut_PointerLibraries[wglCreateContext_Call]); //wgl-notrace EXPECT_EQ(LIBRARY_WGL, ut_PointerLibraries[wglSetPixelFormat_Call]); //wglext.h EXPECT_EQ(LIBRARY_WGL_EXT, ut_PointerLibraries[wglCreateContextAttribsARB_Call]); //egl.h EXPECT_EQ(LIBRARY_EGL, ut_PointerLibraries[eglBindAPI_Call]); EXPECT_EQ(LIBRARY_EGL, ut_PointerLibraries[eglCreateContext_Call]); EXPECT_EQ(LIBRARY_EGL, ut_PointerLibraries[eglMakeCurrent_Call]); EXPECT_EQ(LIBRARY_EGL, ut_PointerLibraries[eglGetProcAddress_Call]); //eglext.h EXPECT_EQ(LIBRARY_EGL_EXT, ut_PointerLibraries[eglCreateImageKHR_Call]); //glx.h EXPECT_EQ(LIBRARY_GLX, ut_PointerLibraries[glXChooseFBConfig_Call]); } TEST_F(DGLCommonUT, codegen_entryp_names) { EXPECT_EQ(GetEntryPointEnum("bad"), NO_ENTRYPOINT); EXPECT_EQ(GetEntryPointEnum("glDrawArrays"), glDrawArrays_Call); EXPECT_EQ(GetEntryPointName(GetEntryPointEnum("glDrawArrays")), "glDrawArrays"); EXPECT_EQ(GetEntryPointEnum(GetEntryPointName(glDrawArrays_Call)), glDrawArrays_Call); } TEST_F(DGLCommonUT, formats_iformat) { DGLPixelTransfer rgba8(std::vector<GLint>(), std::vector<GLint>(), GL_RGBA8); EXPECT_EQ(rgba8.getFormat(), GL_RGBA); EXPECT_EQ(rgba8.getType(), GL_UNSIGNED_BYTE); } TEST_F(DGLCommonUT, formats_noiformat) { std::vector<GLint>rgbaSizes(4, 0); rgbaSizes[0] = rgbaSizes[1] = rgbaSizes[2] = 8; std::vector<GLint>dsSizes(2, 0); DGLPixelTransfer rgba8(rgbaSizes, dsSizes, 0); EXPECT_EQ(rgba8.getFormat(), GL_RGB); EXPECT_EQ(rgba8.getType(), GL_UNSIGNED_BYTE); } TEST_F(DGLCommonUT, os_env) { EXPECT_EQ("", Os::getEnv("test_name")); Os::setEnv("test_name", "test_value"); EXPECT_EQ("test_value", Os::getEnv("test_name")); } } // namespace <|endoftext|>
<commit_before>#include "catch.hpp" #include "graph/expression_graph.h" #include "graph/expression_operators.h" using namespace marian; TEST_CASE("Expression graph supports basic math operations", "[operator]") { auto floatApprox = [](float x, float y) -> bool { return x == Approx(y); }; auto graph = New<ExpressionGraph>(); graph->setDevice(0); graph->reserveWorkspaceMB(16); std::vector<float> vA({1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12}); std::vector<float> vB({1, 2, 3, 4, 5, 6}); std::vector<float> values; SECTION("dot product") { graph->clear(); values.clear(); std::vector<float> vC({22, 28, 49, 64, 76, 100, 103, 136}); auto A = graph->param("A", {4, 3}, keywords::init = inits::from_vector(vA)); auto B = graph->param("B", {3, 2}, keywords::init = inits::from_vector(vB)); auto C = dot(A, B); graph->forward(); CHECK(C->shape() == Shape({4, 2})); C->val()->get(values); CHECK(values == vC); } SECTION("scalar multiplication") { graph->clear(); values.clear(); std::vector<float> vB2({2, 4, 6, 8, 10, 12}); auto B = graph->param("B", {3, 2}, keywords::init = inits::from_vector(vB)); auto B2 = B * 2.0f; graph->forward(); CHECK(B2->shape() == Shape({3, 2})); B2->val()->get(values); CHECK(values == vB2); } SECTION("softmax") { graph->clear(); values.clear(); std::vector<float> in({-.2, -.3, 4.5, 5.2, -10, 101.45, -100.05, 1.05e-5}); std::vector<float> smOut({ 0.52498f, 0.47502f, 0.33181f, 0.66819f, 0.0f, 1.0f, 0.0f, 1.0f }); std::vector<float> lsmOut({ -0.6444f, -0.7444f, -1.10319f, -0.40319f, -111.45f, 0.0f, -100.05001f, 0.0f }); auto input = graph->constant({2, 2, 2}, keywords::init = inits::from_vector(in)); auto sm = softmax(input); auto lsm = logsoftmax(input); graph->forward(); CHECK(sm->shape() == Shape({2, 2, 2})); CHECK(lsm->shape() == Shape({2, 2, 2})); sm->val()->get(values); CHECK( std::equal(values.begin(), values.end(), smOut.begin(), floatApprox) ); lsm->val()->get(values); CHECK( std::equal(values.begin(), values.end(), lsmOut.begin(), floatApprox) ); } SECTION("elementwise binary operators with broadcasting") { graph->clear(); values.clear(); std::vector<float> vA({1, -2, 3, -4}); std::vector<float> vB({0.5, 1.5}); std::vector<float> vAdd({1.5, -0.5, 3.5, -2.5}); std::vector<float> vMinus({-0.5, 3.5, -2.5, 5.5}); std::vector<float> vMult({0.5, -3.0, 1.5, -6.0}); std::vector<float> vDiv({2.0f, -1.33333f, 6.0f, -2.66667f}); auto a = graph->constant({2, 2, 1}, keywords::init = inits::from_vector(vA)); auto b = graph->constant({1, 2, 1}, keywords::init = inits::from_vector(vB)); auto add = a + b; auto minus = b - a; auto mult = a * b; auto div = a / b; graph->forward(); CHECK(add->shape() == Shape({2, 2, 1})); CHECK(minus->shape() == Shape({2, 2, 1})); CHECK(mult->shape() == Shape({2, 2, 1})); CHECK(div->shape() == Shape({2, 2, 1})); add->val()->get(values); CHECK( values == vAdd ); minus->val()->get(values); CHECK( values == vMinus ); mult->val()->get(values); CHECK( values == vMult ); div->val()->get(values); CHECK( std::equal(values.begin(), values.end(), vDiv.begin(), floatApprox) ); } } <commit_msg>tests for reshape and transpose<commit_after>#include "catch.hpp" #include "graph/expression_graph.h" #include "graph/expression_operators.h" using namespace marian; TEST_CASE("Expression graph supports basic math operations", "[operator]") { auto floatApprox = [](float x, float y) -> bool { return x == Approx(y); }; auto graph = New<ExpressionGraph>(); graph->setDevice(0); graph->reserveWorkspaceMB(16); std::vector<float> vA({1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12}); std::vector<float> vB({1, 2, 3, 4, 5, 6}); std::vector<float> values; SECTION("dot product") { graph->clear(); values.clear(); std::vector<float> vC({22, 28, 49, 64, 76, 100, 103, 136}); auto A = graph->param("A", {2, 3, 2}, keywords::init = inits::from_vector(vA)); auto B = graph->param("B", {3, 2}, keywords::init = inits::from_vector(vB)); auto C = dot(A, B); graph->forward(); CHECK(C->shape() == Shape({2, 2, 2})); C->val()->get(values); CHECK(values == vC); } SECTION("scalar multiplication") { graph->clear(); values.clear(); std::vector<float> vB2({2, 4, 6, 8, 10, 12}); auto B = graph->param("B", {3, 2}, keywords::init = inits::from_vector(vB)); auto B2 = B * 2.0f; graph->forward(); CHECK(B2->shape() == Shape({3, 2})); B2->val()->get(values); CHECK(values == vB2); } SECTION("softmax and logsoftmax") { graph->clear(); values.clear(); std::vector<float> in({-.2, -.3, 4.5, 5.2, -10, 101.45, -100.05, 1.05e-5}); std::vector<float> smOut({ 0.52498f, 0.47502f, 0.33181f, 0.66819f, 0.0f, 1.0f, 0.0f, 1.0f }); std::vector<float> lsmOut({ -0.6444f, -0.7444f, -1.10319f, -0.40319f, -111.45f, 0.0f, -100.05001f, 0.0f }); auto input = graph->constant({2, 2, 2}, keywords::init = inits::from_vector(in)); auto sm = softmax(input); auto lsm = logsoftmax(input); graph->forward(); CHECK(sm->shape() == Shape({2, 2, 2})); CHECK(lsm->shape() == Shape({2, 2, 2})); sm->val()->get(values); CHECK( std::equal(values.begin(), values.end(), smOut.begin(), floatApprox) ); lsm->val()->get(values); CHECK( std::equal(values.begin(), values.end(), lsmOut.begin(), floatApprox) ); } SECTION("elementwise binary operators with broadcasting") { graph->clear(); values.clear(); std::vector<float> vA({1, -2, 3, -4}); std::vector<float> vB({0.5, 1.5}); std::vector<float> vAdd({1.5, -0.5, 3.5, -2.5}); std::vector<float> vMinus({-0.5, 3.5, -2.5, 5.5}); std::vector<float> vMult({0.5, -3.0, 1.5, -6.0}); std::vector<float> vDiv({2.0f, -1.33333f, 6.0f, -2.66667f}); auto a = graph->constant({2, 2, 1}, keywords::init = inits::from_vector(vA)); auto b = graph->constant({1, 2, 1}, keywords::init = inits::from_vector(vB)); auto add = a + b; auto minus = b - a; auto mult = a * b; auto div = a / b; graph->forward(); CHECK(add->shape() == Shape({2, 2, 1})); CHECK(minus->shape() == Shape({2, 2, 1})); CHECK(mult->shape() == Shape({2, 2, 1})); CHECK(div->shape() == Shape({2, 2, 1})); add->val()->get(values); CHECK( values == vAdd ); minus->val()->get(values); CHECK( values == vMinus ); mult->val()->get(values); CHECK( values == vMult ); div->val()->get(values); CHECK( std::equal(values.begin(), values.end(), vDiv.begin(), floatApprox) ); } SECTION("transposing and reshaping") { graph->clear(); values.clear(); std::vector<float> vA({1, 2, 3, 4, 5, 6, 7, 8}); std::vector<float> vT1({1, 5, 2, 6, 3, 7, 4, 8}); std::vector<float> vT3({1, 2, 5, 6, 3, 4, 7, 8}); std::vector<float> vT4({1, 5, 3, 7, 2, 6, 4, 8}); std::vector<float> vT5({1, 3, 2, 4, 5, 7, 6, 8}); auto a = graph->constant({2, 4}, keywords::init = inits::from_vector(vA)); auto t1 = transpose(a); auto t2 = transpose(t1); auto t3 = transpose(reshape(t1, {2, 2, 2})); auto t4 = transpose(reshape(a, {2, 2, 1, 2}), {2, 3, 0, 1}); auto t5 = transpose(reshape(a, {2, 2, 1, 2}), {1, 2, 3, 0}); graph->forward(); CHECK(t1->shape() == Shape({4, 2})); CHECK(t2->shape() == Shape({2, 4})); CHECK(t3->shape() == Shape({2, 2, 2})); CHECK(t4->shape() == Shape({1, 2, 2, 2})); CHECK(t5->shape() == Shape({2, 1, 2, 2})); t1->val()->get(values); CHECK( values == vT1 ); t2->val()->get(values); CHECK( values == vA ); t3->val()->get(values); CHECK( values == vT3 ); t4->val()->get(values); CHECK( values == vT4 ); t5->val()->get(values); CHECK( values == vT5 ); } } <|endoftext|>
<commit_before>// ------------------------------------------------------------------------- // @FileName : NFCWorldNet_ClientModule.cpp // @Author : LvSheng.Huang // @Date : 2013-01-02 // @Module : NFCWorldNet_ClientModule // @Desc : // ------------------------------------------------------------------------- #include "NFCWorldToMasterModule.h" #include "NFWorldNet_ClientPlugin.h" #include "NFComm/NFCore/NFCDataList.h" #include "NFComm/NFMessageDefine/NFMsgPreGame.pb.h" bool NFCWorldToMasterModule::Init() { return true; } bool NFCWorldToMasterModule::Shut() { return true; } bool NFCWorldToMasterModule::AfterInit() { m_pWorldLogicModule = pPluginManager->FindModule<NFIWorldLogicModule>("NFCWorldLogicModule"); m_pLogicClassModule = pPluginManager->FindModule<NFILogicClassModule>("NFCLogicClassModule"); m_pElementInfoModule = pPluginManager->FindModule<NFIElementInfoModule>("NFCElementInfoModule"); m_pLogModule = pPluginManager->FindModule<NFILogModule>("NFCLogModule"); m_pWorldNet_ServerModule = pPluginManager->FindModule<NFIWorldNet_ServerModule>("NFCWorldNet_ServerModule"); assert(NULL != m_pWorldLogicModule); assert(NULL != m_pLogicClassModule); assert(NULL != m_pElementInfoModule); assert(NULL != m_pLogModule); assert(NULL != m_pWorldNet_ServerModule); NFIClusterClientModule::Bind(this, &NFCWorldToMasterModule::OnReciveMSPack, &NFCWorldToMasterModule::OnSocketMSEvent); NF_SHARE_PTR<NFILogicClass> xLogicClass = m_pLogicClassModule->GetElement("Server"); if (xLogicClass.get()) { NFList<std::string>& xNameList = xLogicClass->GetConfigNameList(); std::string strConfigName; for (bool bRet = xNameList.First(strConfigName); bRet; bRet = xNameList.Next(strConfigName)) { const int nServerType = m_pElementInfoModule->GetPropertyInt(strConfigName, "Type"); const int nServerID = m_pElementInfoModule->GetPropertyInt(strConfigName, "ServerID"); if (nServerType == NF_SERVER_TYPES::NF_ST_MASTER) { const int nPort = m_pElementInfoModule->GetPropertyInt(strConfigName, "Port"); const int nMaxConnect = m_pElementInfoModule->GetPropertyInt(strConfigName, "MaxOnline"); const int nCpus = m_pElementInfoModule->GetPropertyInt(strConfigName, "CpuCount"); const std::string& strName = m_pElementInfoModule->GetPropertyString(strConfigName, "Name"); const std::string& strIP = m_pElementInfoModule->GetPropertyString(strConfigName, "IP"); ConnectData xServerData; xServerData.nGameID = nServerID; xServerData.eServerType = (NF_SERVER_TYPES)nServerType; xServerData.strIP = strIP; xServerData.nPort = nPort; xServerData.strName = strName; NFIClusterClientModule::AddServer(xServerData); } } } return true; } bool NFCWorldToMasterModule::Execute() { return NFIClusterClientModule::Execute(); } void NFCWorldToMasterModule::Register(NFINet* pNet) { NF_SHARE_PTR<NFILogicClass> xLogicClass = m_pLogicClassModule->GetElement("Server"); if (xLogicClass.get()) { NFList<std::string>& xNameList = xLogicClass->GetConfigNameList(); std::string strConfigName; for (bool bRet = xNameList.First(strConfigName); bRet; bRet = xNameList.Next(strConfigName)) { const int nServerType = m_pElementInfoModule->GetPropertyInt(strConfigName, "Type"); const int nServerID = m_pElementInfoModule->GetPropertyInt(strConfigName, "ServerID"); if (nServerType == NF_SERVER_TYPES::NF_ST_WORLD && pPluginManager->AppID() == nServerID) { const int nPort = m_pElementInfoModule->GetPropertyInt(strConfigName, "Port"); const int nMaxConnect = m_pElementInfoModule->GetPropertyInt(strConfigName, "MaxOnline"); const int nCpus = m_pElementInfoModule->GetPropertyInt(strConfigName, "CpuCount"); const std::string& strName = m_pElementInfoModule->GetPropertyString(strConfigName, "Name"); const std::string& strIP = m_pElementInfoModule->GetPropertyString(strConfigName, "IP"); NFMsg::ServerInfoReportList xMsg; NFMsg::ServerInfoReport* pData = xMsg.add_server_list(); pData->set_server_id(nServerID); pData->set_server_name(strName); pData->set_server_cur_count(0); pData->set_server_ip(strIP); pData->set_server_port(nPort); pData->set_server_max_online(nMaxConnect); pData->set_server_state(NFMsg::EST_NARMAL); pData->set_server_type(nServerType); NF_SHARE_PTR<ConnectData> pServerData = GetServerNetInfo(pNet); if (pServerData) { int nTargetID = pServerData->nGameID; SendToServerByPB(nTargetID, NFMsg::EGameMsgID::EGMI_MTL_WORLD_REGISTERED, xMsg); m_pLogModule->LogNormal(NFILogModule::NLL_INFO_NORMAL, NFGUID(0, pData->server_id()), pData->server_name(), "Register"); } } } } } void NFCWorldToMasterModule::RefreshWorldInfo() { } int NFCWorldToMasterModule::OnSelectServerProcess(const int nSockIndex, const int nMsgID, const char* msg, const uint32_t nLen) { NFGUID nPlayerID; NFMsg::ReqConnectWorld xMsg; if (!NFINetModule::RecivePB(nSockIndex, nMsgID, msg, nLen, xMsg, nPlayerID)) { return 0; } NF_SHARE_PTR<ServerData> xServerData = m_pWorldNet_ServerModule->GetSuitProxyForEnter(); if (xServerData) { NFMsg::AckConnectWorldResult xData; xData.set_world_id(xMsg.world_id()); xData.mutable_sender()->CopyFrom(xMsg.sender()); xData.set_login_id(xMsg.login_id()); xData.set_account(xMsg.account()); xData.set_world_ip(xServerData->pData->server_ip()); xData.set_world_port(xServerData->pData->server_port()); xData.set_world_key(xMsg.account()); m_pWorldNet_ServerModule->SendMsgPB(NFMsg::EGMI_ACK_CONNECT_WORLD, xData, xServerData->nFD); SendSuitByPB(NFMsg::EGMI_ACK_CONNECT_WORLD, xMsg); } return 0; } int NFCWorldToMasterModule::OnKickClientProcess(const int nSockIndex, const int nMsgID, const char* msg, const uint32_t nLen) { NFGUID nPlayerID; NFMsg::ReqKickFromWorld xMsg; if (!NFINetModule::RecivePB(nSockIndex, nMsgID, msg, nLen, xMsg, nPlayerID)) { return 0; } //T, // NFCDataList var; // var << xMsg.world_id() << xMsg.account(); // m_pEventProcessModule->DoEvent(NFGUID(), NFED_ON_KICK_FROM_SERVER, var); return 0; } void NFCWorldToMasterModule::OnReciveMSPack(const int nSockIndex, const int nMsgID, const char* msg, const uint32_t nLen) { switch (nMsgID) { case NFMsg::EGameMsgID::EGMI_REQ_CONNECT_WORLD: OnSelectServerProcess(nSockIndex, nMsgID, msg, nLen); break; case NFMsg::EGameMsgID::EGMI_REQ_KICK_CLIENT_INWORLD: OnKickClientProcess(nSockIndex, nMsgID, msg, nLen); break; default: printf("NFNet || ǷϢ:unMsgID=%d\n", nMsgID); break; } } void NFCWorldToMasterModule::OnSocketMSEvent( const int nSockIndex, const NF_NET_EVENT eEvent, NFINet* pNet ) { if (eEvent & NF_NET_EVENT_EOF) { m_pLogModule->LogNormal(NFILogModule::NLL_INFO_NORMAL, NFGUID(0, nSockIndex), "NF_NET_EVENT_EOF", "Connection closed", __FUNCTION__, __LINE__); } else if (eEvent & NF_NET_EVENT_ERROR) { m_pLogModule->LogNormal(NFILogModule::NLL_INFO_NORMAL, NFGUID(0, nSockIndex), "NF_NET_EVENT_ERROR", "Got an error on the connection", __FUNCTION__, __LINE__); } else if (eEvent & NF_NET_EVENT_TIMEOUT) { m_pLogModule->LogNormal(NFILogModule::NLL_INFO_NORMAL, NFGUID(0, nSockIndex), "NF_NET_EVENT_TIMEOUT", "read timeout", __FUNCTION__, __LINE__); } else if (eEvent == NF_NET_EVENT_CONNECTED) { m_pLogModule->LogNormal(NFILogModule::NLL_INFO_NORMAL, NFGUID(0, nSockIndex), "NF_NET_EVENT_CONNECTED", "connectioned success", __FUNCTION__, __LINE__); Register(pNet); } } void NFCWorldToMasterModule::OnClientDisconnect( const int nAddress ) { } void NFCWorldToMasterModule::OnClientConnected( const int nAddress ) { } bool NFCWorldToMasterModule::BeforeShut() { return true; } void NFCWorldToMasterModule::LogServerInfo( const std::string& strServerInfo ) { m_pLogModule->LogNormal(NFILogModule::NLL_INFO_NORMAL, NFGUID(), strServerInfo, ""); } <commit_msg>fixed write error<commit_after>// ------------------------------------------------------------------------- // @FileName : NFCWorldNet_ClientModule.cpp // @Author : LvSheng.Huang // @Date : 2013-01-02 // @Module : NFCWorldNet_ClientModule // @Desc : // ------------------------------------------------------------------------- #include "NFCWorldToMasterModule.h" #include "NFWorldNet_ClientPlugin.h" #include "NFComm/NFCore/NFCDataList.h" #include "NFComm/NFMessageDefine/NFMsgPreGame.pb.h" bool NFCWorldToMasterModule::Init() { return true; } bool NFCWorldToMasterModule::Shut() { return true; } bool NFCWorldToMasterModule::AfterInit() { m_pWorldLogicModule = pPluginManager->FindModule<NFIWorldLogicModule>("NFCWorldLogicModule"); m_pLogicClassModule = pPluginManager->FindModule<NFILogicClassModule>("NFCLogicClassModule"); m_pElementInfoModule = pPluginManager->FindModule<NFIElementInfoModule>("NFCElementInfoModule"); m_pLogModule = pPluginManager->FindModule<NFILogModule>("NFCLogModule"); m_pWorldNet_ServerModule = pPluginManager->FindModule<NFIWorldNet_ServerModule>("NFCWorldNet_ServerModule"); assert(NULL != m_pWorldLogicModule); assert(NULL != m_pLogicClassModule); assert(NULL != m_pElementInfoModule); assert(NULL != m_pLogModule); assert(NULL != m_pWorldNet_ServerModule); NFIClusterClientModule::Bind(this, &NFCWorldToMasterModule::OnReciveMSPack, &NFCWorldToMasterModule::OnSocketMSEvent); NF_SHARE_PTR<NFILogicClass> xLogicClass = m_pLogicClassModule->GetElement("Server"); if (xLogicClass.get()) { NFList<std::string>& xNameList = xLogicClass->GetConfigNameList(); std::string strConfigName; for (bool bRet = xNameList.First(strConfigName); bRet; bRet = xNameList.Next(strConfigName)) { const int nServerType = m_pElementInfoModule->GetPropertyInt(strConfigName, "Type"); const int nServerID = m_pElementInfoModule->GetPropertyInt(strConfigName, "ServerID"); if (nServerType == NF_SERVER_TYPES::NF_ST_MASTER) { const int nPort = m_pElementInfoModule->GetPropertyInt(strConfigName, "Port"); const int nMaxConnect = m_pElementInfoModule->GetPropertyInt(strConfigName, "MaxOnline"); const int nCpus = m_pElementInfoModule->GetPropertyInt(strConfigName, "CpuCount"); const std::string& strName = m_pElementInfoModule->GetPropertyString(strConfigName, "Name"); const std::string& strIP = m_pElementInfoModule->GetPropertyString(strConfigName, "IP"); ConnectData xServerData; xServerData.nGameID = nServerID; xServerData.eServerType = (NF_SERVER_TYPES)nServerType; xServerData.strIP = strIP; xServerData.nPort = nPort; xServerData.strName = strName; NFIClusterClientModule::AddServer(xServerData); } } } return true; } bool NFCWorldToMasterModule::Execute() { return NFIClusterClientModule::Execute(); } void NFCWorldToMasterModule::Register(NFINet* pNet) { NF_SHARE_PTR<NFILogicClass> xLogicClass = m_pLogicClassModule->GetElement("Server"); if (xLogicClass.get()) { NFList<std::string>& xNameList = xLogicClass->GetConfigNameList(); std::string strConfigName; for (bool bRet = xNameList.First(strConfigName); bRet; bRet = xNameList.Next(strConfigName)) { const int nServerType = m_pElementInfoModule->GetPropertyInt(strConfigName, "Type"); const int nServerID = m_pElementInfoModule->GetPropertyInt(strConfigName, "ServerID"); if (nServerType == NF_SERVER_TYPES::NF_ST_WORLD && pPluginManager->AppID() == nServerID) { const int nPort = m_pElementInfoModule->GetPropertyInt(strConfigName, "Port"); const int nMaxConnect = m_pElementInfoModule->GetPropertyInt(strConfigName, "MaxOnline"); const int nCpus = m_pElementInfoModule->GetPropertyInt(strConfigName, "CpuCount"); const std::string& strName = m_pElementInfoModule->GetPropertyString(strConfigName, "Name"); const std::string& strIP = m_pElementInfoModule->GetPropertyString(strConfigName, "IP"); NFMsg::ServerInfoReportList xMsg; NFMsg::ServerInfoReport* pData = xMsg.add_server_list(); pData->set_server_id(nServerID); pData->set_server_name(strName); pData->set_server_cur_count(0); pData->set_server_ip(strIP); pData->set_server_port(nPort); pData->set_server_max_online(nMaxConnect); pData->set_server_state(NFMsg::EST_NARMAL); pData->set_server_type(nServerType); NF_SHARE_PTR<ConnectData> pServerData = GetServerNetInfo(pNet); if (pServerData) { int nTargetID = pServerData->nGameID; SendToServerByPB(nTargetID, NFMsg::EGameMsgID::EGMI_MTL_WORLD_REGISTERED, xMsg); m_pLogModule->LogNormal(NFILogModule::NLL_INFO_NORMAL, NFGUID(0, pData->server_id()), pData->server_name(), "Register"); } } } } } void NFCWorldToMasterModule::RefreshWorldInfo() { } int NFCWorldToMasterModule::OnSelectServerProcess(const int nSockIndex, const int nMsgID, const char* msg, const uint32_t nLen) { NFGUID nPlayerID; NFMsg::ReqConnectWorld xMsg; if (!NFINetModule::RecivePB(nSockIndex, nMsgID, msg, nLen, xMsg, nPlayerID)) { return 0; } NF_SHARE_PTR<ServerData> xServerData = m_pWorldNet_ServerModule->GetSuitProxyForEnter(); if (xServerData) { NFMsg::AckConnectWorldResult xData; xData.set_world_id(xMsg.world_id()); xData.mutable_sender()->CopyFrom(xMsg.sender()); xData.set_login_id(xMsg.login_id()); xData.set_account(xMsg.account()); xData.set_world_ip(xServerData->pData->server_ip()); xData.set_world_port(xServerData->pData->server_port()); xData.set_world_key(xMsg.account()); m_pWorldNet_ServerModule->SendMsgPB(NFMsg::EGMI_ACK_CONNECT_WORLD, xData, xServerData->nFD); SendSuitByPB(NFMsg::EGMI_ACK_CONNECT_WORLD, xData); } return 0; } int NFCWorldToMasterModule::OnKickClientProcess(const int nSockIndex, const int nMsgID, const char* msg, const uint32_t nLen) { NFGUID nPlayerID; NFMsg::ReqKickFromWorld xMsg; if (!NFINetModule::RecivePB(nSockIndex, nMsgID, msg, nLen, xMsg, nPlayerID)) { return 0; } //T, // NFCDataList var; // var << xMsg.world_id() << xMsg.account(); // m_pEventProcessModule->DoEvent(NFGUID(), NFED_ON_KICK_FROM_SERVER, var); return 0; } void NFCWorldToMasterModule::OnReciveMSPack(const int nSockIndex, const int nMsgID, const char* msg, const uint32_t nLen) { switch (nMsgID) { case NFMsg::EGameMsgID::EGMI_REQ_CONNECT_WORLD: OnSelectServerProcess(nSockIndex, nMsgID, msg, nLen); break; case NFMsg::EGameMsgID::EGMI_REQ_KICK_CLIENT_INWORLD: OnKickClientProcess(nSockIndex, nMsgID, msg, nLen); break; default: printf("NFNet || ǷϢ:unMsgID=%d\n", nMsgID); break; } } void NFCWorldToMasterModule::OnSocketMSEvent( const int nSockIndex, const NF_NET_EVENT eEvent, NFINet* pNet ) { if (eEvent & NF_NET_EVENT_EOF) { m_pLogModule->LogNormal(NFILogModule::NLL_INFO_NORMAL, NFGUID(0, nSockIndex), "NF_NET_EVENT_EOF", "Connection closed", __FUNCTION__, __LINE__); } else if (eEvent & NF_NET_EVENT_ERROR) { m_pLogModule->LogNormal(NFILogModule::NLL_INFO_NORMAL, NFGUID(0, nSockIndex), "NF_NET_EVENT_ERROR", "Got an error on the connection", __FUNCTION__, __LINE__); } else if (eEvent & NF_NET_EVENT_TIMEOUT) { m_pLogModule->LogNormal(NFILogModule::NLL_INFO_NORMAL, NFGUID(0, nSockIndex), "NF_NET_EVENT_TIMEOUT", "read timeout", __FUNCTION__, __LINE__); } else if (eEvent == NF_NET_EVENT_CONNECTED) { m_pLogModule->LogNormal(NFILogModule::NLL_INFO_NORMAL, NFGUID(0, nSockIndex), "NF_NET_EVENT_CONNECTED", "connectioned success", __FUNCTION__, __LINE__); Register(pNet); } } void NFCWorldToMasterModule::OnClientDisconnect( const int nAddress ) { } void NFCWorldToMasterModule::OnClientConnected( const int nAddress ) { } bool NFCWorldToMasterModule::BeforeShut() { return true; } void NFCWorldToMasterModule::LogServerInfo( const std::string& strServerInfo ) { m_pLogModule->LogNormal(NFILogModule::NLL_INFO_NORMAL, NFGUID(), strServerInfo, ""); } <|endoftext|>
<commit_before>#include "muteexecutor.h" #include <QDebug> #include <alsa/asoundlib.h> MuteExecutor::MuteExecutor() { } void MuteExecutor::execute(const QJsonObject &jobj) { qDebug()<<"Mute execute"; long min, max; snd_mixer_t *handle; snd_mixer_selem_id_t *sid; const char *card = "default"; const char *selem_name = "Master"; snd_mixer_open(&handle, 0); snd_mixer_attach(handle, card); snd_mixer_selem_register(handle, NULL, NULL); snd_mixer_load(handle); snd_mixer_selem_id_alloca(&sid); snd_mixer_selem_id_set_index(sid, 0); snd_mixer_selem_id_set_name(sid, selem_name); snd_mixer_elem_t* elem = snd_mixer_find_selem(handle, sid); if (snd_mixer_selem_has_playback_switch(elem)) { snd_mixer_selem_set_playback_switch_all(elem, 0); } snd_mixer_close(handle); } <commit_msg>mute behaves like mute/unmute<commit_after>#include "muteexecutor.h" #include <QDebug> #include <alsa/asoundlib.h> MuteExecutor::MuteExecutor() { } void MuteExecutor::execute(const QJsonObject &jobj) { qDebug()<<"Mute execute"; long min, max, volume, cur_vol; snd_mixer_t *handle; snd_mixer_selem_id_t *sid; const char *card = "default"; const char *selem_name = "Master"; snd_mixer_open(&handle, 0); snd_mixer_attach(handle, card); snd_mixer_selem_register(handle, NULL, NULL); snd_mixer_load(handle); snd_mixer_selem_id_alloca(&sid); snd_mixer_selem_id_set_index(sid, 0); snd_mixer_selem_id_set_name(sid, selem_name); snd_mixer_elem_t* elem = snd_mixer_find_selem(handle, sid); snd_mixer_selem_get_playback_volume(elem, snd_mixer_selem_channel_id_t(0), &cur_vol); snd_mixer_selem_get_playback_volume_range(elem, &min, &max); volume = (cur_vol > 0) ? 0 : 0.8*max; int err = snd_mixer_selem_set_playback_volume_all(elem, volume); qDebug()<<volume<<min<<max<<cur_vol<<err; snd_mixer_close(handle); } <|endoftext|>
<commit_before>/* BEGIN_COMMON_COPYRIGHT_HEADER * (c)LGPL2+ * * lxqt-connman-applet - a gui frontend for connman * * Copyright: 2014-2015 Christian Surlykke * * This program or library is free software; you can redistribute it * and/or modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * You should have received a copy of the GNU Lesser General * Public License along with this library; if not, write to the * Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, * Boston, MA 02110-1301 USA * * END_COMMON_COPYRIGHT_HEADER */ #include "iconfinder.h" #include "connectionstate.h" #include <XdgIcon> class IconNameFinder { public: virtual QString wirelessConnectedIconName(int strength) = 0; virtual QString bluetoothConnectedIconName(int strength) { return wirelessConnectedIconName(strength); } virtual QString ethernetConnectedIconName() = 0; virtual QString notConnectedIconName() = 0; }; class IconNameFinderForOxygen : public IconNameFinder { public: virtual QString wirelessConnectedIconName(int strength) { if (strength < 13) return "network-wireless-connected-00"; else if (strength < 28) return "network-wireless-connected-25"; else if (strength < 63) return "network-wireless-connected-50"; else if (strength < 88) return "network-wireless-connected-75"; else return "network-wireless-connected-100"; } virtual QString ethernetConnectedIconName() { return "network-connnect";} virtual QString notConnectedIconName() { return "network-disconnect"; } }; class IconNameFinderForGnome : public IconNameFinder { public: virtual QString wirelessConnectedIconName(int strength) { if (strength < 13) return "network-wireless-signal-none"; else if (strength < 28) return "network-wireless-signal-weak"; else if (strength < 63) return "network-wireless-signal-ok"; else if (strength < 88) return "network-wireless-signal-good"; else return "network-wireless-signal-excellent"; } virtual QString ethernetConnectedIconName() { return "network-wired"; } virtual QString notConnectedIconName() { return "network-offline"; } }; IconFinder* IconFinder::instance() { static IconFinder *_instance = new IconFinder(); return _instance; } QIcon& IconFinder::icon() { qDebug() << "icon(), themename:" << QIcon::themeName(); qDebug() << "xdgIcon.themeName:" << XdgIcon::themeName(); qDebug() << "iconTheme:" << IconNameFinder *iconNameFinder; if (QIcon::themeName() == "Oxygen") { qDebug() << "Oxygen"; iconNameFinder = new IconNameFinderForOxygen(); } else { qDebug() << "Gnome"; iconNameFinder = new IconNameFinderForGnome(); } QString iconName; ConnectionState *connectionState = ConnectionState::instance(); if (connectionState->connectedWireless()) { iconName = iconNameFinder->wirelessConnectedIconName(connectionState->connectedWireless()->signalStrength()); } else if (connectionState->connectedBluetooth()) { iconName = iconNameFinder->bluetoothConnectedIconName(connectionState->connectedBluetooth()->signalStrength()); } else if (connectionState->connectedEthernet()) { iconName = iconNameFinder->ethernetConnectedIconName(); } else { iconName = iconNameFinder->notConnectedIconName(); } qDebug() << "IconFinder found: " << iconName; qDebug() << QIcon::hasThemeIcon(iconName); mIcon = QIcon::fromTheme(iconName); return mIcon; } IconFinder::IconFinder() { } <commit_msg>Fix spelling error in iconfinder.cpp<commit_after>/* BEGIN_COMMON_COPYRIGHT_HEADER * (c)LGPL2+ * * lxqt-connman-applet - a gui frontend for connman * * Copyright: 2014-2015 Christian Surlykke * * This program or library is free software; you can redistribute it * and/or modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * You should have received a copy of the GNU Lesser General * Public License along with this library; if not, write to the * Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, * Boston, MA 02110-1301 USA * * END_COMMON_COPYRIGHT_HEADER */ #include "iconfinder.h" #include "connectionstate.h" #include <XdgIcon> class IconNameFinder { public: virtual QString wirelessConnectedIconName(int strength) = 0; virtual QString bluetoothConnectedIconName(int strength) { return wirelessConnectedIconName(strength); } virtual QString ethernetConnectedIconName() = 0; virtual QString notConnectedIconName() = 0; }; class IconNameFinderForOxygen : public IconNameFinder { public: virtual QString wirelessConnectedIconName(int strength) { if (strength < 13) return "network-wireless-connected-00"; else if (strength < 28) return "network-wireless-connected-25"; else if (strength < 63) return "network-wireless-connected-50"; else if (strength < 88) return "network-wireless-connected-75"; else return "network-wireless-connected-100"; } virtual QString ethernetConnectedIconName() { return "network-connect";} virtual QString notConnectedIconName() { return "network-disconnect"; } }; class IconNameFinderForGnome : public IconNameFinder { public: virtual QString wirelessConnectedIconName(int strength) { if (strength < 13) return "network-wireless-signal-none"; else if (strength < 28) return "network-wireless-signal-weak"; else if (strength < 63) return "network-wireless-signal-ok"; else if (strength < 88) return "network-wireless-signal-good"; else return "network-wireless-signal-excellent"; } virtual QString ethernetConnectedIconName() { return "network-wired"; } virtual QString notConnectedIconName() { return "network-offline"; } }; IconFinder* IconFinder::instance() { static IconFinder *_instance = new IconFinder(); return _instance; } QIcon& IconFinder::icon() { qDebug() << "icon(), themename:" << QIcon::themeName(); qDebug() << "xdgIcon.themeName:" << XdgIcon::themeName(); qDebug() << "iconTheme:" << IconNameFinder *iconNameFinder; if (QIcon::themeName() == "Oxygen") { qDebug() << "Oxygen"; iconNameFinder = new IconNameFinderForOxygen(); } else { qDebug() << "Gnome"; iconNameFinder = new IconNameFinderForGnome(); } QString iconName; ConnectionState *connectionState = ConnectionState::instance(); if (connectionState->connectedWireless()) { iconName = iconNameFinder->wirelessConnectedIconName(connectionState->connectedWireless()->signalStrength()); } else if (connectionState->connectedBluetooth()) { iconName = iconNameFinder->bluetoothConnectedIconName(connectionState->connectedBluetooth()->signalStrength()); } else if (connectionState->connectedEthernet()) { iconName = iconNameFinder->ethernetConnectedIconName(); } else { iconName = iconNameFinder->notConnectedIconName(); } qDebug() << "IconFinder found: " << iconName; qDebug() << QIcon::hasThemeIcon(iconName); mIcon = QIcon::fromTheme(iconName); return mIcon; } IconFinder::IconFinder() { } <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: TSkipDeletedSet.cxx,v $ * * $Revision: 1.3 $ * * last change: $Author: oj $ $Date: 2001-11-30 14:09:45 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (the License); You may not use this file * except in compliance with the License. You may obtain a copy of the * License at http://www.openoffice.org/license.html. * * Software provided under this License is provided on an AS IS basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #ifndef CONNECTIVITY_SKIPDELETEDSSET_HXX #include "TSkipDeletedSet.hxx" #endif #ifndef _OSL_DIAGNOSE_H_ #include <osl/diagnose.h> #endif using namespace connectivity; // ----------------------------------------------------------------------------- OSkipDeletedSet::OSkipDeletedSet(IResultSetHelper* _pHelper) : m_pHelper(_pHelper) { } // ----------------------------------------------------------------------------- sal_Bool OSkipDeletedSet::skipDeleted(IResultSetHelper::Movement _eCursorPosition, sal_Int32 _nOffset, sal_Bool _bRetrieveData) { OSL_ENSURE(_eCursorPosition != IResultSetHelper::BOOKMARK,"OSkipDeletedSet::SkipDeleted can't be called for BOOKMARK"); IResultSetHelper::Movement eDelPosition = _eCursorPosition; sal_Int32 nDelOffset = abs(_nOffset); switch (_eCursorPosition) { case IResultSetHelper::ABSOLUTE: case IResultSetHelper::FIRST: // set the movement when positioning failed eDelPosition = IResultSetHelper::NEXT; nDelOffset = 1; break; case IResultSetHelper::LAST: eDelPosition = IResultSetHelper::PRIOR; // lsat row is invalid so position before nDelOffset = 1; break; case IResultSetHelper::RELATIVE: eDelPosition = (_nOffset >= 0) ? IResultSetHelper::NEXT : IResultSetHelper::PRIOR; break; } sal_Int32 nNewOffset = _nOffset; sal_Bool bDone = sal_True; sal_Bool bDataFound = sal_False; if (_eCursorPosition == IResultSetHelper::ABSOLUTE) { return moveAbsolute(_nOffset,_bRetrieveData); } else if (_eCursorPosition == IResultSetHelper::LAST) { sal_Int32 nBookmark = 0; sal_Int32 nCurPos = 1; // first position on the last known row if(m_aBookmarks.empty()) { bDataFound = m_pHelper->move(IResultSetHelper::FIRST, 0, _bRetrieveData); if(bDataFound && (m_pHelper->deletedVisible() || !m_pHelper->isRowDeleted())) m_aBookmarksPositions.push_back(m_aBookmarks.insert(TInt2IntMap::value_type(m_pHelper->getDriverPos(),m_aBookmarksPositions.size()+1)).first); } else { // I already have a bookmark so we can positioned on that and look if it is the last one nBookmark = (*m_aBookmarksPositions.rbegin())->first; bDataFound = m_pHelper->move(IResultSetHelper::BOOKMARK, nBookmark, _bRetrieveData); OSL_ENSURE((m_pHelper->deletedVisible() || !m_pHelper->isRowDeleted()),"A bookmark should not be deleted!"); nCurPos = (*m_aBookmarksPositions.rbegin())->second; } // and than move forward until we are after the last row while(bDataFound) { bDataFound = m_pHelper->move(IResultSetHelper::NEXT, 1, sal_False); // we don't need the data here if(bDataFound && (m_pHelper->deletedVisible() || !m_pHelper->isRowDeleted())) { // we weren't on the last row we remember it and move on ++nCurPos; m_aBookmarksPositions.push_back(m_aBookmarks.insert(TInt2IntMap::value_type(m_pHelper->getDriverPos(),m_aBookmarksPositions.size()+1)).first); } else if(!bDataFound && m_aBookmarks.size()) { // i already know the last bookmark :-) // now we only have to repositioning us to the last row nBookmark = (*m_aBookmarksPositions.rbegin())->first; bDataFound = m_pHelper->move(IResultSetHelper::BOOKMARK, nBookmark, _bRetrieveData); break; } } return bDataFound; } else if (_eCursorPosition != IResultSetHelper::RELATIVE) { bDataFound = m_pHelper->move(_eCursorPosition, _nOffset, _bRetrieveData); bDone = bDataFound && (m_pHelper->deletedVisible() || !m_pHelper->isRowDeleted()); } else { bDataFound = m_pHelper->move(eDelPosition, 1, _bRetrieveData); if (bDataFound && (m_pHelper->deletedVisible() || !m_pHelper->isRowDeleted())) { m_aBookmarksPositions.push_back(m_aBookmarks.insert(TInt2IntMap::value_type(m_pHelper->getDriverPos(),m_aBookmarksPositions.size()+1)).first); bDone = (--nDelOffset) == 0; } else bDone = sal_False; } while (bDataFound && !bDone) // solange iterieren bis man auf einem gltigen Satz ist { bDataFound = m_pHelper->move(eDelPosition, 1, _bRetrieveData); if (_eCursorPosition != IResultSetHelper::RELATIVE) bDone = bDataFound && (m_pHelper->deletedVisible() || !m_pHelper->isRowDeleted()); else if (bDataFound && (m_pHelper->deletedVisible() || !m_pHelper->isRowDeleted())) { m_aBookmarksPositions.push_back(m_aBookmarks.insert(TInt2IntMap::value_type(m_pHelper->getDriverPos(),m_aBookmarksPositions.size()+1)).first); bDone = (--nDelOffset) == 0; } else bDone = sal_False; } if(bDataFound && bDone) { sal_Int32 nDriverPos = m_pHelper->getDriverPos(); if(m_aBookmarks.find(nDriverPos) == m_aBookmarks.end()) m_aBookmarksPositions.push_back(m_aBookmarks.insert(TInt2IntMap::value_type(nDriverPos,m_aBookmarksPositions.size()+1)).first); } return bDataFound; } // ------------------------------------------------------------------------- sal_Bool OSkipDeletedSet::moveAbsolute(sal_Int32 _nOffset,sal_Bool _bRetrieveData) { sal_Bool bDataFound = sal_False; sal_Int32 nNewOffset = _nOffset; if(nNewOffset > 0) { if((sal_Int32)m_aBookmarks.size() < nNewOffset) { // bookmark isn't known yet // start at the last position sal_Int32 nCurPos = 0,nLastBookmark = 1; IResultSetHelper::Movement eFilePos = IResultSetHelper::FIRST; if(!m_aBookmarks.empty()) { nLastBookmark = (*m_aBookmarksPositions.rbegin())->first; nCurPos = (*m_aBookmarksPositions.rbegin())->second; nNewOffset = nNewOffset - nCurPos; bDataFound = m_pHelper->move(IResultSetHelper::BOOKMARK, nLastBookmark, _bRetrieveData); } else { bDataFound = m_pHelper->move(IResultSetHelper::FIRST, 0, _bRetrieveData ); if(bDataFound && (m_pHelper->deletedVisible() || !m_pHelper->isRowDeleted())) { ++nCurPos; m_aBookmarksPositions.push_back(m_aBookmarks.insert(TInt2IntMap::value_type(m_pHelper->getDriverPos(),m_aBookmarksPositions.size()+1)).first); --nNewOffset; } } // now move to that row we need and don't count deleted rows while (bDataFound && nNewOffset) { bDataFound = m_pHelper->move(IResultSetHelper::NEXT, 1, _bRetrieveData); if(bDataFound && (m_pHelper->deletedVisible() || !m_pHelper->isRowDeleted())) { ++nCurPos; m_aBookmarksPositions.push_back(m_aBookmarks.insert(TInt2IntMap::value_type(m_pHelper->getDriverPos(),m_aBookmarksPositions.size()+1)).first); --nNewOffset; } } } else { sal_Int32 nBookmark = m_aBookmarksPositions[nNewOffset-1]->first; bDataFound = m_pHelper->move(IResultSetHelper::BOOKMARK,nBookmark, _bRetrieveData); OSL_ENSURE((m_pHelper->deletedVisible() || !m_pHelper->isRowDeleted()),"moveAbsolute: row can't be deleted!"); } } else { ++nNewOffset; bDataFound = skipDeleted(IResultSetHelper::LAST,0,nNewOffset == 0); for(sal_Int32 i=nNewOffset+1;bDataFound && i <= 0;++i) bDataFound = skipDeleted(IResultSetHelper::PRIOR,1,i == 0); } return bDataFound; } // ----------------------------------------------------------------------------- void OSkipDeletedSet::clear() { ::std::vector<TInt2IntMap::iterator>().swap(m_aBookmarksPositions); TInt2IntMap().swap(m_aBookmarks); } // ----------------------------------------------------------------------------- sal_Int32 OSkipDeletedSet::getMappedPosition(sal_Int32 _nPos) const { TInt2IntMap::const_iterator aFind = m_aBookmarks.find(_nPos); OSL_ENSURE(aFind != m_aBookmarks.end(),"OSkipDeletedSet::getMappedPosition() invalid bookmark!"); return aFind->second; } // ----------------------------------------------------------------------------- void OSkipDeletedSet::insertNewPosition(sal_Int32 _nPos) { m_aBookmarksPositions.push_back(m_aBookmarks.insert(TInt2IntMap::value_type(_nPos,m_aBookmarksPositions.size()+1)).first); } // ----------------------------------------------------------------------------- void OSkipDeletedSet::deletePosition(sal_Int32 _nPos) { TInt2IntMap::iterator aFind = m_aBookmarks.find(_nPos); OSL_ENSURE(aFind != m_aBookmarks.end(),"OSkipDeletedSet::deletePosition() bookmark not found!"); TInt2IntMap::iterator aIter = aFind; ++aIter; for (; aIter != m_aBookmarks.end() ; ++aIter) --(aIter->second); m_aBookmarksPositions.erase(m_aBookmarksPositions.begin() + aFind->second-1); m_aBookmarks.erase(_nPos); } // ----------------------------------------------------------------------------- <commit_msg>#96476# insert assertion<commit_after>/************************************************************************* * * $RCSfile: TSkipDeletedSet.cxx,v $ * * $Revision: 1.4 $ * * last change: $Author: oj $ $Date: 2002-10-08 13:40:38 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (the License); You may not use this file * except in compliance with the License. You may obtain a copy of the * License at http://www.openoffice.org/license.html. * * Software provided under this License is provided on an AS IS basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #ifndef CONNECTIVITY_SKIPDELETEDSSET_HXX #include "TSkipDeletedSet.hxx" #endif #ifndef _OSL_DIAGNOSE_H_ #include <osl/diagnose.h> #endif using namespace connectivity; // ----------------------------------------------------------------------------- OSkipDeletedSet::OSkipDeletedSet(IResultSetHelper* _pHelper) : m_pHelper(_pHelper) { } // ----------------------------------------------------------------------------- sal_Bool OSkipDeletedSet::skipDeleted(IResultSetHelper::Movement _eCursorPosition, sal_Int32 _nOffset, sal_Bool _bRetrieveData) { OSL_ENSURE(_eCursorPosition != IResultSetHelper::BOOKMARK,"OSkipDeletedSet::SkipDeleted can't be called for BOOKMARK"); IResultSetHelper::Movement eDelPosition = _eCursorPosition; sal_Int32 nDelOffset = abs(_nOffset); switch (_eCursorPosition) { case IResultSetHelper::ABSOLUTE: case IResultSetHelper::FIRST: // set the movement when positioning failed eDelPosition = IResultSetHelper::NEXT; nDelOffset = 1; break; case IResultSetHelper::LAST: eDelPosition = IResultSetHelper::PRIOR; // lsat row is invalid so position before nDelOffset = 1; break; case IResultSetHelper::RELATIVE: eDelPosition = (_nOffset >= 0) ? IResultSetHelper::NEXT : IResultSetHelper::PRIOR; break; } sal_Int32 nNewOffset = _nOffset; sal_Bool bDone = sal_True; sal_Bool bDataFound = sal_False; if (_eCursorPosition == IResultSetHelper::ABSOLUTE) { return moveAbsolute(_nOffset,_bRetrieveData); } else if (_eCursorPosition == IResultSetHelper::LAST) { sal_Int32 nBookmark = 0; sal_Int32 nCurPos = 1; // first position on the last known row if(m_aBookmarks.empty()) { bDataFound = m_pHelper->move(IResultSetHelper::FIRST, 0, _bRetrieveData); if(bDataFound && (m_pHelper->deletedVisible() || !m_pHelper->isRowDeleted())) m_aBookmarksPositions.push_back(m_aBookmarks.insert(TInt2IntMap::value_type(m_pHelper->getDriverPos(),m_aBookmarksPositions.size()+1)).first); } else { // I already have a bookmark so we can positioned on that and look if it is the last one nBookmark = (*m_aBookmarksPositions.rbegin())->first; bDataFound = m_pHelper->move(IResultSetHelper::BOOKMARK, nBookmark, _bRetrieveData); OSL_ENSURE((m_pHelper->deletedVisible() || !m_pHelper->isRowDeleted()),"A bookmark should not be deleted!"); nCurPos = (*m_aBookmarksPositions.rbegin())->second; } // and than move forward until we are after the last row while(bDataFound) { bDataFound = m_pHelper->move(IResultSetHelper::NEXT, 1, sal_False); // we don't need the data here if(bDataFound && (m_pHelper->deletedVisible() || !m_pHelper->isRowDeleted())) { // we weren't on the last row we remember it and move on ++nCurPos; m_aBookmarksPositions.push_back(m_aBookmarks.insert(TInt2IntMap::value_type(m_pHelper->getDriverPos(),m_aBookmarksPositions.size()+1)).first); } else if(!bDataFound && m_aBookmarks.size()) { // i already know the last bookmark :-) // now we only have to repositioning us to the last row nBookmark = (*m_aBookmarksPositions.rbegin())->first; bDataFound = m_pHelper->move(IResultSetHelper::BOOKMARK, nBookmark, _bRetrieveData); break; } } return bDataFound; } else if (_eCursorPosition != IResultSetHelper::RELATIVE) { bDataFound = m_pHelper->move(_eCursorPosition, _nOffset, _bRetrieveData); bDone = bDataFound && (m_pHelper->deletedVisible() || !m_pHelper->isRowDeleted()); } else { bDataFound = m_pHelper->move(eDelPosition, 1, _bRetrieveData); if (bDataFound && (m_pHelper->deletedVisible() || !m_pHelper->isRowDeleted())) { m_aBookmarksPositions.push_back(m_aBookmarks.insert(TInt2IntMap::value_type(m_pHelper->getDriverPos(),m_aBookmarksPositions.size()+1)).first); bDone = (--nDelOffset) == 0; } else bDone = sal_False; } while (bDataFound && !bDone) // solange iterieren bis man auf einem gltigen Satz ist { bDataFound = m_pHelper->move(eDelPosition, 1, _bRetrieveData); if (_eCursorPosition != IResultSetHelper::RELATIVE) bDone = bDataFound && (m_pHelper->deletedVisible() || !m_pHelper->isRowDeleted()); else if (bDataFound && (m_pHelper->deletedVisible() || !m_pHelper->isRowDeleted())) { m_aBookmarksPositions.push_back(m_aBookmarks.insert(TInt2IntMap::value_type(m_pHelper->getDriverPos(),m_aBookmarksPositions.size()+1)).first); bDone = (--nDelOffset) == 0; } else bDone = sal_False; } if(bDataFound && bDone) { sal_Int32 nDriverPos = m_pHelper->getDriverPos(); if(m_aBookmarks.find(nDriverPos) == m_aBookmarks.end()) m_aBookmarksPositions.push_back(m_aBookmarks.insert(TInt2IntMap::value_type(nDriverPos,m_aBookmarksPositions.size()+1)).first); } return bDataFound; } // ------------------------------------------------------------------------- sal_Bool OSkipDeletedSet::moveAbsolute(sal_Int32 _nOffset,sal_Bool _bRetrieveData) { sal_Bool bDataFound = sal_False; sal_Int32 nNewOffset = _nOffset; if(nNewOffset > 0) { if((sal_Int32)m_aBookmarks.size() < nNewOffset) { // bookmark isn't known yet // start at the last position sal_Int32 nCurPos = 0,nLastBookmark = 1; IResultSetHelper::Movement eFilePos = IResultSetHelper::FIRST; if(!m_aBookmarks.empty()) { nLastBookmark = (*m_aBookmarksPositions.rbegin())->first; nCurPos = (*m_aBookmarksPositions.rbegin())->second; nNewOffset = nNewOffset - nCurPos; bDataFound = m_pHelper->move(IResultSetHelper::BOOKMARK, nLastBookmark, _bRetrieveData); } else { bDataFound = m_pHelper->move(IResultSetHelper::FIRST, 0, _bRetrieveData ); if(bDataFound && (m_pHelper->deletedVisible() || !m_pHelper->isRowDeleted())) { ++nCurPos; m_aBookmarksPositions.push_back(m_aBookmarks.insert(TInt2IntMap::value_type(m_pHelper->getDriverPos(),m_aBookmarksPositions.size()+1)).first); --nNewOffset; } } // now move to that row we need and don't count deleted rows while (bDataFound && nNewOffset) { bDataFound = m_pHelper->move(IResultSetHelper::NEXT, 1, _bRetrieveData); if(bDataFound && (m_pHelper->deletedVisible() || !m_pHelper->isRowDeleted())) { ++nCurPos; m_aBookmarksPositions.push_back(m_aBookmarks.insert(TInt2IntMap::value_type(m_pHelper->getDriverPos(),m_aBookmarksPositions.size()+1)).first); --nNewOffset; } } } else { sal_Int32 nBookmark = m_aBookmarksPositions[nNewOffset-1]->first; bDataFound = m_pHelper->move(IResultSetHelper::BOOKMARK,nBookmark, _bRetrieveData); OSL_ENSURE((m_pHelper->deletedVisible() || !m_pHelper->isRowDeleted()),"moveAbsolute: row can't be deleted!"); } } else { ++nNewOffset; bDataFound = skipDeleted(IResultSetHelper::LAST,0,nNewOffset == 0); for(sal_Int32 i=nNewOffset+1;bDataFound && i <= 0;++i) bDataFound = skipDeleted(IResultSetHelper::PRIOR,1,i == 0); } return bDataFound; } // ----------------------------------------------------------------------------- void OSkipDeletedSet::clear() { ::std::vector<TInt2IntMap::iterator>().swap(m_aBookmarksPositions); TInt2IntMap().swap(m_aBookmarks); } // ----------------------------------------------------------------------------- sal_Int32 OSkipDeletedSet::getMappedPosition(sal_Int32 _nPos) const { TInt2IntMap::const_iterator aFind = m_aBookmarks.find(_nPos); OSL_ENSURE(aFind != m_aBookmarks.end(),"OSkipDeletedSet::getMappedPosition() invalid bookmark!"); return aFind->second; } // ----------------------------------------------------------------------------- void OSkipDeletedSet::insertNewPosition(sal_Int32 _nPos) { OSL_ENSURE(m_aBookmarks.find(_nPos) == m_aBookmarks.end(),"OSkipDeletedSet::insertNewPosition: Invalid position"); m_aBookmarksPositions.push_back(m_aBookmarks.insert(TInt2IntMap::value_type(_nPos,m_aBookmarksPositions.size()+1)).first); } // ----------------------------------------------------------------------------- void OSkipDeletedSet::deletePosition(sal_Int32 _nPos) { TInt2IntMap::iterator aFind = m_aBookmarks.find(_nPos); OSL_ENSURE(aFind != m_aBookmarks.end(),"OSkipDeletedSet::deletePosition() bookmark not found!"); TInt2IntMap::iterator aIter = aFind; ++aIter; for (; aIter != m_aBookmarks.end() ; ++aIter) --(aIter->second); m_aBookmarksPositions.erase(m_aBookmarksPositions.begin() + aFind->second-1); m_aBookmarks.erase(_nPos); } // ----------------------------------------------------------------------------- <|endoftext|>
<commit_before>/*************************************************************************** main.cpp - description ------------------- begin : Wed Dec 26 03:12:10 CLST 2001 copyright : (C) 2001 by Duncan Mac-Vicar Prett email : [email protected] ***************************************************************************/ /*************************************************************************** * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * ***************************************************************************/ #include <kcmdlineargs.h> #include <kaboutdata.h> #include <klocale.h> #include "kopete.h" static const char *description = I18N_NOOP("Kopete, the KDE Instant Messenger"); #define KOPETE_VERSION "0.4.1" static KCmdLineOptions options[] = { { 0, 0, 0 } }; int main(int argc, char *argv[]) { KAboutData aboutData( "kopete", I18N_NOOP("Kopete"), KOPETE_VERSION, description, KAboutData::License_GPL, "(c) 2001,2002, Duncan Mac-Vicar Prett\n(c) 2002, The Kopete Development Team", "[email protected]", "http://kopete.kde.org"); aboutData.addAuthor ( "Duncan Mac-Vicar Prett", I18N_NOOP("Original author, core developer"), "[email protected]", "http://www.mac-vicar.com" ); aboutData.addAuthor ( "Nick Betcher", I18N_NOOP("Core developer, fastest plugin developer on earth."), "[email protected]", "http://www.kdedevelopers.net" ); aboutData.addAuthor ( "Ryan Cumming", I18N_NOOP("Core developer"), "[email protected]" ); aboutData.addAuthor ( "Martijn Klingens", I18N_NOOP("Patches, bugfixes"), "[email protected]" ); aboutData.addAuthor ( "Richard Stellingwerff", I18N_NOOP("features and bugfixes"), "[email protected]"); aboutData.addAuthor ( "Daniel Stone", I18N_NOOP("Core developer, Jabber plugin"), "[email protected]", "http://raging.dropbear.id.au/daniel/"); aboutData.addAuthor ( "Andres Krapf", I18N_NOOP("random hacks and bugfixes"), "[email protected]" ); aboutData.addCredit ( "Herwin Jan Steehouwer", I18N_NOOP("KxEngine ICQ code") ); aboutData.addCredit ( "Olaf Lueg", I18N_NOOP("Kmerlin MSN code") ); aboutData.addCredit ( "Neil Stevens", I18N_NOOP("TAim engine AIM code") ); aboutData.addCredit ( "Justin Karneges", I18N_NOOP("Psi Jabber code") ); KCmdLineArgs::init( argc, argv, &aboutData ); KCmdLineArgs::addCmdLineOptions( options ); // Add our own options. KUniqueApplication::addCmdLineOptions(); Kopete kopete; kopete.exec(); } <commit_msg><commit_after>/*************************************************************************** main.cpp - description ------------------- begin : Wed Dec 26 03:12:10 CLST 2001 copyright : (C) 2001 by Duncan Mac-Vicar Prett email : [email protected] ***************************************************************************/ /*************************************************************************** * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * ***************************************************************************/ #include <kcmdlineargs.h> #include <kaboutdata.h> #include <klocale.h> #include "kopete.h" static const char *description = I18N_NOOP("Kopete, the KDE Instant Messenger"); #define KOPETE_VERSION "0.4.1" static KCmdLineOptions options[] = { { 0, 0, 0 } }; int main(int argc, char *argv[]) { KAboutData aboutData( "kopete", I18N_NOOP("Kopete"), KOPETE_VERSION, description, KAboutData::License_GPL, "(c) 2001,2002, Duncan Mac-Vicar Prett\n(c) 2002, The Kopete Development Team", "[email protected]", "http://kopete.kde.org"); aboutData.addAuthor ( "Duncan Mac-Vicar Prett", I18N_NOOP("Original author, core developer"), "[email protected]", "http://www.mac-vicar.com" ); aboutData.addAuthor ( "Nick Betcher", I18N_NOOP("Core developer, fastest plugin developer on earth."), "[email protected]", "http://www.kdedevelopers.net" ); aboutData.addAuthor ( "Ryan Cumming", I18N_NOOP("Core developer"), "[email protected]" ); aboutData.addAuthor ( "Martijn Klingens", I18N_NOOP("Core developer"), "[email protected]" ); aboutData.addAuthor ( "Richard Stellingwerff", I18N_NOOP("Developer"), "[email protected]"); aboutData.addAuthor ( "Daniel Stone", I18N_NOOP("Core developer, Jabber plugin"), "[email protected]", "http://raging.dropbear.id.au/daniel/"); aboutData.addAuthor ( "Hendrik vom Lehn", I18N_NOOP("Developer"), "[email protected]", "http://www.hennevl.de"); aboutData.addAuthor ( "Andres Krapf", I18N_NOOP("Random hacks and bugfixes"), "[email protected]" ); aboutData.addCredit ( "Herwin Jan Steehouwer", I18N_NOOP("KxEngine ICQ code") ); aboutData.addCredit ( "Olaf Lueg", I18N_NOOP("Kmerlin MSN code") ); aboutData.addCredit ( "Neil Stevens", I18N_NOOP("TAim engine AIM code") ); aboutData.addCredit ( "Justin Karneges", I18N_NOOP("Psi Jabber code") ); KCmdLineArgs::init( argc, argv, &aboutData ); KCmdLineArgs::addCmdLineOptions( options ); // Add our own options. KUniqueApplication::addCmdLineOptions(); Kopete kopete; kopete.exec(); } <|endoftext|>
<commit_before>// Copyright (C) 2019 Egor Pugin <[email protected]> // // This Source Code Form is subject to the terms of the Mozilla Public // License, v. 2.0. If a copy of the MPL was not distributed with this // file, You can obtain one at http://mozilla.org/MPL/2.0/. #include <boost/algorithm/string.hpp> #include <primitives/command.h> #include <primitives/sw/main.h> #include <primitives/sw/cl.h> #include <primitives/sw/settings_program_name.h> static cl::opt<path> git(cl::Positional, cl::Required); static cl::opt<path> wdir(cl::Positional, cl::Required); static cl::opt<path> outfn(cl::Positional, cl::Required); int main(int argc, char *argv[]) { cl::ParseCommandLineOptions(argc, argv); String rev, status, time; { primitives::Command c; c.working_directory = wdir; c.arguments.push_back(git.u8string()); c.arguments.push_back("rev-parse"); c.arguments.push_back("HEAD"); try { error_code ec; c.execute(ec); if (ec) { rev = "unknown"; } else { rev = boost::trim_copy(c.out.text); } } catch (std::exception &) { rev = "unknown"; } } { primitives::Command c; c.working_directory = wdir; c.arguments.push_back(git.u8string()); c.arguments.push_back("status"); c.arguments.push_back("--porcelain"); c.arguments.push_back("-uno"); error_code ec; c.execute(ec); if (ec) { status = "0"; } else { status = boost::trim_copy(c.out.text); if (status.empty()) status = "0"; else status = std::to_string(split_lines(status).size()); } } { time = std::to_string(std::chrono::system_clock::to_time_t(std::chrono::system_clock::now())); } String t; t += "#define SW_GIT_REV \"" + rev + "\"\n"; t += "#define SW_GIT_CHANGED_FILES " + status + "\n"; t += "#define SW_BUILD_TIME_T " + time + "LL\n"; write_file(outfn, t); return 0; } <commit_msg>Debug.<commit_after>// Copyright (C) 2019 Egor Pugin <[email protected]> // // This Source Code Form is subject to the terms of the Mozilla Public // License, v. 2.0. If a copy of the MPL was not distributed with this // file, You can obtain one at http://mozilla.org/MPL/2.0/. #include <boost/algorithm/string.hpp> #include <primitives/command.h> #include <primitives/sw/main.h> #include <primitives/sw/cl.h> #include <primitives/sw/settings_program_name.h> #include <iostream> static cl::opt<path> git(cl::Positional, cl::Required); static cl::opt<path> wdir(cl::Positional, cl::Required); static cl::opt<path> outfn(cl::Positional, cl::Required); int main(int argc, char *argv[]) { cl::ParseCommandLineOptions(argc, argv); String rev, status, time; { std::cerr << "1" << std::endl; primitives::Command c; c.working_directory = wdir; c.arguments.push_back(git.u8string()); c.arguments.push_back("rev-parse"); c.arguments.push_back("HEAD"); std::cerr << "2" << std::endl; try { std::cerr << "3" << std::endl; error_code ec; c.execute(ec); std::cerr << "4" << std::endl; if (ec) { std::cerr << "5" << std::endl; rev = "unknown"; } else { std::cerr << "6" << std::endl; rev = boost::trim_copy(c.out.text); } std::cerr << "7" << std::endl; } catch (...) { std::cerr << "8" << std::endl; rev = "unknown"; } std::cerr << "9" << std::endl; } { primitives::Command c; c.working_directory = wdir; c.arguments.push_back(git.u8string()); c.arguments.push_back("status"); c.arguments.push_back("--porcelain"); c.arguments.push_back("-uno"); error_code ec; c.execute(ec); if (ec) { status = "0"; } else { status = boost::trim_copy(c.out.text); if (status.empty()) status = "0"; else status = std::to_string(split_lines(status).size()); } } { time = std::to_string(std::chrono::system_clock::to_time_t(std::chrono::system_clock::now())); } String t; t += "#define SW_GIT_REV \"" + rev + "\"\n"; t += "#define SW_GIT_CHANGED_FILES " + status + "\n"; t += "#define SW_BUILD_TIME_T " + time + "LL\n"; write_file(outfn, t); return 0; } <|endoftext|>
<commit_before> // Qt include. #include <QCoreApplication> #include <QFileInfo> #include <QFile> #include <QTextStream> // QtArg include. #include <QtArg/Arg> #include <QtArg/Help> #include <QtArg/CmdLine> #include <QtArg/Exceptions> // QtConfFile include. #include <QtConfFile/Utils> // Generator include. #include "generator.hpp" // // ForGeneration // //! Data uses to generate. class ForGeneration { public: ForGeneration() { } ForGeneration( const QString & inputFile, const QString & outputFile ) : m_inputFileName( inputFile ) , m_outputFileName( outputFile ) { } ~ForGeneration() { } ForGeneration( const ForGeneration & other ) : m_inputFileName( other.inputFile() ) , m_outputFileName( other.outputFile() ) { } ForGeneration & operator = ( const ForGeneration & other ) { if( this != &other ) { m_inputFileName = other.inputFile(); m_outputFileName = other.outputFile(); } return *this; } //! \return Input file name. const QString & inputFile() const { return m_inputFileName; } //! \return Output file name. const QString & outputFile() const { return m_outputFileName; } private: //! Input file name. QString m_inputFileName; //! Output file name. QString m_outputFileName; }; // class ForGeneration // // parseCommandLineArguments // static inline ForGeneration parseCommandLineArguments( int argc, char ** argv ) { QtArg input( QLatin1Char( 'i' ), QLatin1String( "input" ), QLatin1String( "Input file name" ), true, true ); QtArg output( QLatin1Char( 'o' ), QLatin1String( "output" ), QLatin1String( "Output file name" ), true, true ); QtArgCmdLine cmd( argc, argv ); QtArgHelp help( &cmd ); help.printer()->setProgramDescription( QLatin1String( "C++ header generator for QtConfFile." ) ); help.printer()->setExecutableName( QLatin1String( argv[ 0 ] ) ); cmd.addArg( &input ); cmd.addArg( &output ); cmd.addArg( &help ); cmd.parse(); ForGeneration data( input.value().toString(), output.value().toString() ); QTextStream stream( stdout ); if( data.inputFile().isEmpty() ) { stream << QLatin1String( "Please specify input file." ); exit( 1 ); } if( !QFileInfo( data.inputFile() ).exists() ) { stream << QLatin1String( "Specified input file doesn't exist." ); exit( 1 ); } if( data.outputFile().isEmpty() ) { stream << QLatin1String( "Please specify output file." ); exit( 1 ); } return data; } int main( int argc, char ** argv ) { ForGeneration data; try { data = parseCommandLineArguments( argc, argv ); } catch( const QtArgHelpHasPrintedEx & x ) { return 0; } catch( const QtArgBaseException & x ) { QTextStream stream( stdout ); stream << x.whatAsQString(); return 1; } QtConfFile::Generator::Cfg::Model model; try { QtConfFile::Generator::Cfg::TagModel tag; QtConfFile::readQtConfFile( tag, data.inputFile(), QTextCodec::codecForName( "UTF-8" ) ); model = tag.cfg(); model.prepare(); model.check(); } catch( const QtConfFile::Exception & x ) { QTextStream stream( stdout ); stream << x.whatAsQString(); return 1; } QFile output( data.outputFile() ); if( output.open( QIODevice::WriteOnly | QIODevice::Truncate ) ) { QTextStream stream( &output ); QtConfFile::Generator::CppGenerator gen( model ); gen.generate( stream ); output.close(); return 0; } else { QTextStream stream( stdout ); stream << QLatin1String( "Couldn't open output file for writting." ); return 1; } } <commit_msg>Added line endings in generator console output.<commit_after> // Qt include. #include <QCoreApplication> #include <QFileInfo> #include <QFile> #include <QTextStream> // QtArg include. #include <QtArg/Arg> #include <QtArg/Help> #include <QtArg/CmdLine> #include <QtArg/Exceptions> // QtConfFile include. #include <QtConfFile/Utils> // Generator include. #include "generator.hpp" // // ForGeneration // //! Data uses to generate. class ForGeneration { public: ForGeneration() { } ForGeneration( const QString & inputFile, const QString & outputFile ) : m_inputFileName( inputFile ) , m_outputFileName( outputFile ) { } ~ForGeneration() { } ForGeneration( const ForGeneration & other ) : m_inputFileName( other.inputFile() ) , m_outputFileName( other.outputFile() ) { } ForGeneration & operator = ( const ForGeneration & other ) { if( this != &other ) { m_inputFileName = other.inputFile(); m_outputFileName = other.outputFile(); } return *this; } //! \return Input file name. const QString & inputFile() const { return m_inputFileName; } //! \return Output file name. const QString & outputFile() const { return m_outputFileName; } private: //! Input file name. QString m_inputFileName; //! Output file name. QString m_outputFileName; }; // class ForGeneration // // parseCommandLineArguments // static inline ForGeneration parseCommandLineArguments( int argc, char ** argv ) { QtArg input( QLatin1Char( 'i' ), QLatin1String( "input" ), QLatin1String( "Input file name" ), true, true ); QtArg output( QLatin1Char( 'o' ), QLatin1String( "output" ), QLatin1String( "Output file name" ), true, true ); QtArgCmdLine cmd( argc, argv ); QtArgHelp help( &cmd ); help.printer()->setProgramDescription( QLatin1String( "C++ header generator for QtConfFile." ) ); help.printer()->setExecutableName( QLatin1String( argv[ 0 ] ) ); cmd.addArg( &input ); cmd.addArg( &output ); cmd.addArg( &help ); cmd.parse(); ForGeneration data( input.value().toString(), output.value().toString() ); QTextStream stream( stdout ); if( data.inputFile().isEmpty() ) { stream << QLatin1String( "Please specify input file." ) << endl; exit( 1 ); } if( !QFileInfo( data.inputFile() ).exists() ) { stream << QLatin1String( "Specified input file doesn't exist." ) << endl; exit( 1 ); } if( data.outputFile().isEmpty() ) { stream << QLatin1String( "Please specify output file." ) << endl; exit( 1 ); } return data; } int main( int argc, char ** argv ) { ForGeneration data; try { data = parseCommandLineArguments( argc, argv ); } catch( const QtArgHelpHasPrintedEx & x ) { return 0; } catch( const QtArgBaseException & x ) { QTextStream stream( stdout ); stream << x.whatAsQString() << endl; return 1; } QtConfFile::Generator::Cfg::Model model; try { QtConfFile::Generator::Cfg::TagModel tag; QtConfFile::readQtConfFile( tag, data.inputFile(), QTextCodec::codecForName( "UTF-8" ) ); model = tag.cfg(); model.prepare(); model.check(); } catch( const QtConfFile::Exception & x ) { QTextStream stream( stdout ); stream << x.whatAsQString() << endl; return 1; } QFile output( data.outputFile() ); if( output.open( QIODevice::WriteOnly | QIODevice::Truncate ) ) { QTextStream stream( &output ); QtConfFile::Generator::CppGenerator gen( model ); gen.generate( stream ); output.close(); return 0; } else { QTextStream stream( stdout ); stream << QLatin1String( "Couldn't open output file for writting." ) << endl; return 1; } } <|endoftext|>
<commit_before>/* Kopete , The KDE Instant Messenger Copyright (c) 2001-2002 by Duncan Mac-Vicar Prett <[email protected]> Viva Chile Mierda! Started at Wed Dec 26 03:12:10 CLST 2001, Santiago de Chile Kopete (c) 2002-2005 by the Kopete developers <[email protected]> ************************************************************************* * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * ************************************************************************* */ #include <kcmdlineargs.h> #include <kaboutdata.h> #include "kopeteapplication.h" #include <klocale.h> #include "kopeteversion.h" static const char description[] = I18N_NOOP( "Kopete, the KDE Instant Messenger" ); static KCmdLineOptions options[] = { { "noplugins", I18N_NOOP( "Do not load plugins. This option overrides all other options." ), 0 }, { "noconnect", I18N_NOOP( "Disable auto-connection" ), 0 }, { "autoconnect <accounts>", I18N_NOOP( "Auto-connect the specified accounts. Use a comma-separated list\n" "to auto-connect multiple accounts." ), 0 }, { "disable <plugins>", I18N_NOOP( "Do not load the specified plugin. Use a comma-separated list\n" "to disable multiple plugins." ), 0 }, { "load-plugins <plugins>", I18N_NOOP( "Load only the specified plugins. Use a comma-separated list\n" "to load multiple plugins. This option has no effect when\n" "--noplugins is set and overrides all other plugin related\n" "command line options." ), 0 }, // { "url <url>", I18N_NOOP( "Load the given Kopete URL" ), 0 }, // { "!+[plugin]", I18N_NOOP( "Load specified plugins" ), 0 }, { "!+[URL]", I18N_NOOP("URLs to pass to kopete / emoticon themes to install"), 0}, KCmdLineLastOption }; int main( int argc, char *argv[] ) { KAboutData aboutData( "kopete", I18N_NOOP("Kopete"), KOPETE_VERSION_STRING, description, KAboutData::License_GPL, I18N_NOOP("(c) 2001-2004, Duncan Mac-Vicar Prett\n(c) 2002-2005, Kopete Development Team"), "[email protected]", "http://kopete.kde.org"); aboutData.addAuthor ( "Duncan Mac-Vicar Prett", I18N_NOOP("Developer and Project founder"), "[email protected]", "http://www.mac-vicar.org/~duncan" ); aboutData.addAuthor ( "Andre Duffeck", I18N_NOOP("Developer, Yahoo plugin maintainer"), "[email protected]" ); aboutData.addAuthor ( "Andy Goossens", I18N_NOOP("Developer"), "[email protected]" ); aboutData.addAuthor ( "Chris Howells", I18N_NOOP("Developer, Connection status plugin author"), "[email protected]", "http://chrishowells.co.uk"); aboutData.addAuthor ( "Cláudio da Silveira Pinheiro", I18N_NOOP("Developer, Video device support"), "[email protected]", "http://taupter.homelinux.org" ); aboutData.addAuthor ( "Gregg Edghill", I18N_NOOP("Developer, MSN"), "[email protected]"); aboutData.addAuthor ( "Grzegorz Jaskiewicz", I18N_NOOP("Developer, Gadu plugin maintainer"), "[email protected]" ); aboutData.addAuthor ( "Jason Keirstead", I18N_NOOP("Developer"), "[email protected]", "http://www.keirstead.org"); aboutData.addAuthor ( "Matt Rogers", I18N_NOOP("Lead Developer, AIM and ICQ plugin maintainer"), "[email protected]" ); aboutData.addAuthor ( "Michel Hermier", I18N_NOOP("IRC plugin maintainer"), "[email protected]" ); aboutData.addAuthor ( "Michaël Larouche", I18N_NOOP("Lead Developer"), "[email protected]", "http://www.tehbisnatch.org/" ); aboutData.addAuthor ( "Olivier Goffart", I18N_NOOP("Lead Developer, MSN plugin maintainer"), "ogoffart @ kde.org"); aboutData.addAuthor ( "Ollivier Lapeyre Johann", I18N_NOOP("Artist / Developer, Artwork maintainer"), "[email protected]" ); aboutData.addAuthor ( "Richard Smith", I18N_NOOP("Developer, UI maintainer"), "[email protected]" ); aboutData.addAuthor ( "Till Gerken", I18N_NOOP("Developer, Jabber plugin maintainer"), "[email protected]"); aboutData.addAuthor ( "Will Stephenson", I18N_NOOP("Lead Developer, GroupWise maintainer"), "[email protected]" ); aboutData.addAuthor ( "Rafael Fernández López", I18N_NOOP("Developer"), "[email protected]" ); aboutData.addCredit ( "Vally8", I18N_NOOP("Konki style author"), "[email protected]", "http://vally8.free.fr/" ); aboutData.addCredit ( "Tm_T", I18N_NOOP("Hacker style author"), "[email protected]"); aboutData.addCredit ( "Luciash d' Being", I18N_NOOP("Kopete's icon author") ); aboutData.addCredit ( "Steve Cable", I18N_NOOP("Sounds") ); aboutData.addCredit ( "Jessica Hall", I18N_NOOP("Kopete Docugoddess, Bug and Patch Testing.") ); aboutData.addCredit ( "Justin Karneges", I18N_NOOP("Iris Jabber Backend Library") ); aboutData.addCredit ( "Tom Linsky", I18N_NOOP("OscarSocket author"), "[email protected]" ); aboutData.addCredit ( "Olaf Lueg", I18N_NOOP("Kmerlin MSN code") ); aboutData.addCredit ( "Chetan Reddy", I18N_NOOP("Former developer"), "[email protected]" ); aboutData.addCredit ( "Nick Betcher", I18N_NOOP("Former developer, project co-founder"), "[email protected]"); aboutData.addCredit ( "Ryan Cumming", I18N_NOOP("Former developer"), "[email protected]" ); aboutData.addCredit ( "Stefan Gehn", I18N_NOOP("Former developer"), "[email protected]", "http://metz.gehn.net" ); aboutData.addCredit ( "Martijn Klingens", I18N_NOOP("Former developer"), "[email protected]" ); aboutData.addCredit ( "Andres Krapf", I18N_NOOP("Former developer"), "[email protected]" ); aboutData.addCredit ( "Carsten Pfeiffer", I18N_NOOP("Misc bugfixes and enhancements"), "[email protected]" ); aboutData.addCredit ( "Zack Rusin", I18N_NOOP("Former developer, original Gadu plugin author"), "[email protected]" ); aboutData.addCredit ( "Richard Stellingwerff", I18N_NOOP("Former developer"), "[email protected]"); aboutData.addCredit ( "Daniel Stone", I18N_NOOP("Former developer, Jabber plugin author"), "[email protected]", "http://fooishbar.org"); aboutData.addCredit ( "Chris TenHarmsel", I18N_NOOP("Former developer, Oscar plugin"), "[email protected]"); aboutData.addCredit ( "Hendrik vom Lehn", I18N_NOOP("Former developer"), "[email protected]", "http://www.hennevl.de"); aboutData.addCredit ( "Gav Wood", I18N_NOOP("Former developer and WinPopup maintainer"), "[email protected]" ); aboutData.setTranslator( ki18nc("NAME OF TRANSLATORS","Your names"), ki18nc("EMAIL OF TRANSLATORS","Your emails") ); KCmdLineArgs::init( argc, argv, &aboutData ); KCmdLineArgs::addCmdLineOptions( options ); // Add our own options. KUniqueApplication::addCmdLineOptions(); KopeteApplication kopete; // new KIMIfaceImpl(); // kapp->dcopClient()->registerAs( "kopete", false ); // kapp->dcopClient()->setDefaultObject( (new KopeteIface())->objId() ); // Has to be called before exec return kopete.exec(); } // vim: set noet ts=4 sts=4 sw=4: <commit_msg>Update my status in Kopete<commit_after>/* Kopete , The KDE Instant Messenger Copyright (c) 2001-2002 by Duncan Mac-Vicar Prett <[email protected]> Viva Chile Mierda! Started at Wed Dec 26 03:12:10 CLST 2001, Santiago de Chile Kopete (c) 2002-2005 by the Kopete developers <[email protected]> ************************************************************************* * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * ************************************************************************* */ #include <kcmdlineargs.h> #include <kaboutdata.h> #include "kopeteapplication.h" #include <klocale.h> #include "kopeteversion.h" static const char description[] = I18N_NOOP( "Kopete, the KDE Instant Messenger" ); static KCmdLineOptions options[] = { { "noplugins", I18N_NOOP( "Do not load plugins. This option overrides all other options." ), 0 }, { "noconnect", I18N_NOOP( "Disable auto-connection" ), 0 }, { "autoconnect <accounts>", I18N_NOOP( "Auto-connect the specified accounts. Use a comma-separated list\n" "to auto-connect multiple accounts." ), 0 }, { "disable <plugins>", I18N_NOOP( "Do not load the specified plugin. Use a comma-separated list\n" "to disable multiple plugins." ), 0 }, { "load-plugins <plugins>", I18N_NOOP( "Load only the specified plugins. Use a comma-separated list\n" "to load multiple plugins. This option has no effect when\n" "--noplugins is set and overrides all other plugin related\n" "command line options." ), 0 }, // { "url <url>", I18N_NOOP( "Load the given Kopete URL" ), 0 }, // { "!+[plugin]", I18N_NOOP( "Load specified plugins" ), 0 }, { "!+[URL]", I18N_NOOP("URLs to pass to kopete / emoticon themes to install"), 0}, KCmdLineLastOption }; int main( int argc, char *argv[] ) { KAboutData aboutData( "kopete", I18N_NOOP("Kopete"), KOPETE_VERSION_STRING, description, KAboutData::License_GPL, I18N_NOOP("(c) 2001-2004, Duncan Mac-Vicar Prett\n(c) 2002-2005, Kopete Development Team"), "[email protected]", "http://kopete.kde.org"); aboutData.addAuthor ( "Duncan Mac-Vicar Prett", I18N_NOOP("Developer and Project founder"), "[email protected]", "http://www.mac-vicar.org/~duncan" ); aboutData.addAuthor ( "Andre Duffeck", I18N_NOOP("Developer, Yahoo plugin maintainer"), "[email protected]" ); aboutData.addAuthor ( "Andy Goossens", I18N_NOOP("Developer"), "[email protected]" ); aboutData.addAuthor ( "Chris Howells", I18N_NOOP("Developer, Connection status plugin author"), "[email protected]", "http://chrishowells.co.uk"); aboutData.addAuthor ( "Cláudio da Silveira Pinheiro", I18N_NOOP("Developer, Video device support"), "[email protected]", "http://taupter.homelinux.org" ); aboutData.addAuthor ( "Gregg Edghill", I18N_NOOP("Developer, MSN"), "[email protected]"); aboutData.addAuthor ( "Grzegorz Jaskiewicz", I18N_NOOP("Developer, Gadu plugin maintainer"), "[email protected]" ); aboutData.addAuthor ( "Jason Keirstead", I18N_NOOP("Developer"), "[email protected]", "http://www.keirstead.org"); aboutData.addAuthor ( "Matt Rogers", I18N_NOOP("Lead Developer, AIM and ICQ plugin maintainer"), "[email protected]" ); aboutData.addAuthor ( "Michel Hermier", I18N_NOOP("IRC plugin maintainer"), "[email protected]" ); aboutData.addAuthor ( "Michaël Larouche", I18N_NOOP("Lead Developer, Telepathy and Messenger plugin maintainer"), "[email protected]", "http://www.tehbisnatch.org/" ); aboutData.addAuthor ( "Olivier Goffart", I18N_NOOP("Lead Developer, MSN plugin maintainer"), "ogoffart @ kde.org"); aboutData.addAuthor ( "Ollivier Lapeyre Johann", I18N_NOOP("Artist / Developer, Artwork maintainer"), "[email protected]" ); aboutData.addAuthor ( "Richard Smith", I18N_NOOP("Developer, UI maintainer"), "[email protected]" ); aboutData.addAuthor ( "Till Gerken", I18N_NOOP("Developer, Jabber plugin maintainer"), "[email protected]"); aboutData.addAuthor ( "Will Stephenson", I18N_NOOP("Lead Developer, GroupWise maintainer"), "[email protected]" ); aboutData.addAuthor ( "Rafael Fernández López", I18N_NOOP("Developer"), "[email protected]" ); aboutData.addCredit ( "Vally8", I18N_NOOP("Konki style author"), "[email protected]", "http://vally8.free.fr/" ); aboutData.addCredit ( "Tm_T", I18N_NOOP("Hacker style author"), "[email protected]"); aboutData.addCredit ( "Luciash d' Being", I18N_NOOP("Kopete's icon author") ); aboutData.addCredit ( "Steve Cable", I18N_NOOP("Sounds") ); aboutData.addCredit ( "Jessica Hall", I18N_NOOP("Kopete Docugoddess, Bug and Patch Testing.") ); aboutData.addCredit ( "Justin Karneges", I18N_NOOP("Iris Jabber Backend Library") ); aboutData.addCredit ( "Tom Linsky", I18N_NOOP("OscarSocket author"), "[email protected]" ); aboutData.addCredit ( "Olaf Lueg", I18N_NOOP("Kmerlin MSN code") ); aboutData.addCredit ( "Chetan Reddy", I18N_NOOP("Former developer"), "[email protected]" ); aboutData.addCredit ( "Nick Betcher", I18N_NOOP("Former developer, project co-founder"), "[email protected]"); aboutData.addCredit ( "Ryan Cumming", I18N_NOOP("Former developer"), "[email protected]" ); aboutData.addCredit ( "Stefan Gehn", I18N_NOOP("Former developer"), "[email protected]", "http://metz.gehn.net" ); aboutData.addCredit ( "Martijn Klingens", I18N_NOOP("Former developer"), "[email protected]" ); aboutData.addCredit ( "Andres Krapf", I18N_NOOP("Former developer"), "[email protected]" ); aboutData.addCredit ( "Carsten Pfeiffer", I18N_NOOP("Misc bugfixes and enhancements"), "[email protected]" ); aboutData.addCredit ( "Zack Rusin", I18N_NOOP("Former developer, original Gadu plugin author"), "[email protected]" ); aboutData.addCredit ( "Richard Stellingwerff", I18N_NOOP("Former developer"), "[email protected]"); aboutData.addCredit ( "Daniel Stone", I18N_NOOP("Former developer, Jabber plugin author"), "[email protected]", "http://fooishbar.org"); aboutData.addCredit ( "Chris TenHarmsel", I18N_NOOP("Former developer, Oscar plugin"), "[email protected]"); aboutData.addCredit ( "Hendrik vom Lehn", I18N_NOOP("Former developer"), "[email protected]", "http://www.hennevl.de"); aboutData.addCredit ( "Gav Wood", I18N_NOOP("Former developer and WinPopup maintainer"), "[email protected]" ); aboutData.setTranslator( ki18nc("NAME OF TRANSLATORS","Your names"), ki18nc("EMAIL OF TRANSLATORS","Your emails") ); KCmdLineArgs::init( argc, argv, &aboutData ); KCmdLineArgs::addCmdLineOptions( options ); // Add our own options. KUniqueApplication::addCmdLineOptions(); KopeteApplication kopete; // new KIMIfaceImpl(); // kapp->dcopClient()->registerAs( "kopete", false ); // kapp->dcopClient()->setDefaultObject( (new KopeteIface())->objId() ); // Has to be called before exec return kopete.exec(); } // vim: set noet ts=4 sts=4 sw=4: <|endoftext|>
<commit_before>#include "ignnetwork.h" ignnetwork::ignnetwork(QObject *parent): QObject(parent) { } QString ignnetwork::myIP(){ QString host; Q_FOREACH(QHostAddress address, QNetworkInterface::allAddresses()) { if (!address.isLoopback() && (address.protocol() == QAbstractSocket::IPv4Protocol)) { host = address.toString(); break; } } if(host.isEmpty()){ return "IP not found"; } else{ return host; } } void ignnetwork::setProxy(const QVariant &config){ /* json parsing */ QJsonParseError *err = new QJsonParseError(); QJsonDocument json = QJsonDocument::fromVariant(config); if (err->error != 0) { qDebug() << err->errorString(); exit (1); } QJsonObject jObject = json.object(); QVariantMap set_proxy = jObject.toVariantMap(); if(set_proxy["type"].toString() != ""){ QNetworkProxy proxy; QString proxy_type = set_proxy["type"].toString(); if(proxy_type == "http"){ proxy.setType(QNetworkProxy::HttpProxy); } else if(proxy_type == "socks5"){ proxy.setType(QNetworkProxy::Socks5Proxy); } else if(proxy_type == "ftp"){ proxy.setType(QNetworkProxy::FtpCachingProxy); } else if(proxy_type == "httpCaching"){ proxy.setType(QNetworkProxy::HttpCachingProxy); } else{ qDebug()<<"Please input your type proxy (http,socks5,ftp,httpCaching)!"; } if(set_proxy["url"].toString() != ""){ QString url = set_proxy["url"].toString(); QStringList url_proxy = url.split(":"); proxy.setHostName(url_proxy.at(0)); proxy.setPort(url_proxy.at(1).toInt()); } else{ qDebug()<<"Please input your hostname:port Ex: 127.0.0.1:8080!"; } if(set_proxy["username"].toString() != ""){ proxy.setUser(set_proxy["username"].toString()); } if(set_proxy["password"].toString() != ""){ proxy.setPassword(set_proxy["password"].toString()); } QNetworkProxy::setApplicationProxy(proxy); } } <commit_msg>ignnetwork.cpp: Fix typography<commit_after>#include "ignnetwork.h" ignnetwork::ignnetwork(QObject *parent): QObject(parent) { } QString ignnetwork::myIP(){ QString host; Q_FOREACH(QHostAddress address, QNetworkInterface::allAddresses()) { if (!address.isLoopback() && (address.protocol() == QAbstractSocket::IPv4Protocol)) { host = address.toString(); break; } } if(host.isEmpty()){ return "IP not found"; } else{ return host; } } void ignnetwork::setProxy(const QVariant &config){ /* json parsing */ QJsonParseError *err = new QJsonParseError(); QJsonDocument json = QJsonDocument::fromVariant(config); if (err->error != 0) { qDebug() << err->errorString(); exit (1); } QJsonObject jObject = json.object(); QVariantMap set_proxy = jObject.toVariantMap(); if(set_proxy["type"].toString() != ""){ QNetworkProxy proxy; QString proxy_type = set_proxy["type"].toString(); if(proxy_type == "http"){ proxy.setType(QNetworkProxy::HttpProxy); } else if(proxy_type == "socks5"){ proxy.setType(QNetworkProxy::Socks5Proxy); } else if(proxy_type == "ftp"){ proxy.setType(QNetworkProxy::FtpCachingProxy); } else if(proxy_type == "httpCaching"){ proxy.setType(QNetworkProxy::HttpCachingProxy); } else{ qDebug()<<"Proxy type is not specified. Available options: http, socks5, ftp, httpCaching."; } if(set_proxy["url"].toString() != ""){ QString url = set_proxy["url"].toString(); QStringList url_proxy = url.split(":"); proxy.setHostName(url_proxy.at(0)); proxy.setPort(url_proxy.at(1).toInt()); } else{ qDebug()<<"Proxy address is not specified."; } if(set_proxy["username"].toString() != ""){ proxy.setUser(set_proxy["username"].toString()); } if(set_proxy["password"].toString() != ""){ proxy.setPassword(set_proxy["password"].toString()); } QNetworkProxy::setApplicationProxy(proxy); } } <|endoftext|>
<commit_before>/** * Copyright (C) 2019 3D Repo Ltd * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include <gtest/gtest.h> #include <repo/core/handler/fileservice/repo_file_handler_gridfs.h> #include <repo/core/model/bson/repo_node.h> #include <repo/lib/repo_exception.h> #include <repo/lib/repo_utils.h> #include "../../../../repo_test_database_info.h" using namespace repo::core::handler::fileservice; TEST(GridFSFileHandlerTest, Constructor) { EXPECT_NO_THROW({ auto fileHandler = GridFSFileHandler(getHandler()); }); EXPECT_THROW(GridFSFileHandler(nullptr), repo::lib::RepoException); } GridFSFileHandler getGridFSHandler() { auto dbHandler = getHandler(); return GridFSFileHandler(dbHandler); } // //TEST(GridFSFileHandlerTest, deleteFile) //{ // auto handler = createHandler(); // auto pathToFile = getDataPath("fileShare/deleteTest"); // ASSERT_TRUE(repo::lib::doesFileExist(pathToFile)); // EXPECT_TRUE(handler.deleteFile("a", "b", "deleteTest")); // EXPECT_FALSE(repo::lib::doesFileExist(pathToFile)); // EXPECT_FALSE(handler.deleteFile("a", "b", "ThisFileDoesNotExist")); // //} // TEST(GridFSFileHandlerTest, writeFile) { auto handler = getGridFSHandler(); std::vector<uint8_t> buffer; buffer.resize(1024); std::string fName = "gridFSFile"; auto linker = handler.uploadFile("testFileManager", "testFileUpload", fName, buffer); EXPECT_EQ(fName, linker); } <commit_msg>ISSUE #320 more gridFS test<commit_after>/** * Copyright (C) 2019 3D Repo Ltd * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include <gtest/gtest.h> #include <repo/core/handler/fileservice/repo_file_handler_gridfs.h> #include <repo/core/model/bson/repo_node.h> #include <repo/lib/repo_exception.h> #include <repo/lib/repo_utils.h> #include "../../../../repo_test_database_info.h" using namespace repo::core::handler::fileservice; TEST(GridFSFileHandlerTest, Constructor) { EXPECT_NO_THROW({ auto fileHandler = GridFSFileHandler(getHandler()); }); EXPECT_THROW(GridFSFileHandler(nullptr), repo::lib::RepoException); } GridFSFileHandler getGridFSHandler() { auto dbHandler = getHandler(); return GridFSFileHandler(dbHandler); } TEST(GridFSFileHandlerTest, deleteFile) { auto handler = getGridFSHandler(); auto dbHandler = getHandler(); std::string db = "testFileManager"; std::string col = "testFileUpload"; std::string fName = "gridFSFile"; ASSERT_TRUE(dbHandler->getRawFile(db, col, fName).size() > 0); EXPECT_TRUE(handler.deleteFile(db, col, fName)); EXPECT_EQ(dbHandler->getRawFile(db, col, fName).size(), 0); } TEST(GridFSFileHandlerTest, writeFile) { auto handler = getGridFSHandler(); std::vector<uint8_t> buffer; uint32_t fSize = 1024; buffer.resize(fSize); std::string db = "testFileManager"; std::string col = "testFileUpload"; std::string fName = "testFileWrite"; auto linker = handler.uploadFile(db, col, fName, buffer); EXPECT_EQ(fName, linker); auto dbHandler = getHandler(); EXPECT_EQ(dbHandler->getRawFile(db, col, fName).size(), fSize); } <|endoftext|>
<commit_before>/* This file is part of Magnum. Original authors — credit is appreciated but not required: 2010, 2011, 2012, 2013, 2014, 2015, 2016, 2017, 2018, 2019, 2020, 2021 — Vladimír Vondruš <[email protected]> 2021 — Pablo Escobar <[email protected]> This is free and unencumbered software released into the public domain. Anyone is free to copy, modify, publish, use, compile, sell, or distribute this software, either in source code form or as a compiled binary, for any purpose, commercial or non-commercial, and by any means. In jurisdictions that recognize copyright laws, the author or authors of this software dedicate any and all copyright interest in the software to the public domain. We make this dedication for the benefit of the public at large and to the detriment of our heirs and successors. We intend this dedication to be an overt act of relinquishment in perpetuity of all present and future rights to this software under copyright law. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #include <Corrade/Containers/Array.h> #include <Corrade/Containers/StringView.h> #include <Corrade/Utility/Assert.h> #include <Corrade/PluginManager/Manager.h> #include <Magnum/Magnum.h> #include <Magnum/Mesh.h> #include <Magnum/ImageView.h> #include <Magnum/PixelFormat.h> #include <Magnum/VertexFormat.h> #include <Magnum/Math/Color.h> #include <Magnum/Math/Range.h> #include <Magnum/ShaderTools/AbstractConverter.h> #include <Magnum/Trade/AbstractImageConverter.h> #include <Magnum/Vk/Assert.h> #include <Magnum/Vk/BufferCreateInfo.h> #include <Magnum/Vk/CommandBuffer.h> #include <Magnum/Vk/CommandPoolCreateInfo.h> #include <Magnum/Vk/DeviceCreateInfo.h> #include <Magnum/Vk/DeviceProperties.h> #include <Magnum/Vk/Fence.h> #include <Magnum/Vk/FramebufferCreateInfo.h> #include <Magnum/Vk/ImageCreateInfo.h> #include <Magnum/Vk/ImageViewCreateInfo.h> #include <Magnum/Vk/InstanceCreateInfo.h> #include <Magnum/Vk/Memory.h> #include <Magnum/Vk/Mesh.h> #include <Magnum/Vk/Pipeline.h> #include <Magnum/Vk/PipelineLayoutCreateInfo.h> #include <Magnum/Vk/Queue.h> #include <Magnum/Vk/RasterizationPipelineCreateInfo.h> #include <Magnum/Vk/RenderPassCreateInfo.h> #include <Magnum/Vk/ShaderCreateInfo.h> #include <Magnum/Vk/ShaderSet.h> using namespace Corrade::Containers::Literals; using namespace Magnum; using namespace Magnum::Math::Literals; int main(int argc, char** argv) { /* Create an instance */ Vk::Instance instance{Vk::InstanceCreateInfo{argc, argv} .setApplicationInfo("Magnum Vulkan Triangle Example"_s, {}) }; /* Create a device with a graphics queue */ Vk::Queue queue{NoCreate}; Vk::Device device{instance, Vk::DeviceCreateInfo{Vk::pickDevice(instance)} .addQueues(Vk::QueueFlag::Graphics, {0.0f}, {queue}) }; /* Allocate a command buffer */ Vk::CommandPool commandPool{device, Vk::CommandPoolCreateInfo{ device.properties().pickQueueFamily(Vk::QueueFlag::Graphics) }}; Vk::CommandBuffer cmd = commandPool.allocate(); /* Render pass. We'll want to transfer the image back to the host though a buffer once done, so additionally set up a corresponding final image layout and a dependency that performs the layout transition before we execute the copy command. */ Vk::RenderPass renderPass{device, Vk::RenderPassCreateInfo{} .setAttachments({ Vk::AttachmentDescription{PixelFormat::RGBA8Srgb, Vk::AttachmentLoadOperation::Clear, Vk::AttachmentStoreOperation::Store, Vk::ImageLayout::Undefined, Vk::ImageLayout::TransferSource } }) .addSubpass(Vk::SubpassDescription{} .setColorAttachments({ Vk::AttachmentReference{0, Vk::ImageLayout::ColorAttachment} }) ) .setDependencies({ Vk::SubpassDependency{ /* An operation external to the render pass depends on the first subpass */ 0, Vk::SubpassDependency::External, /* where transfer gets executed only after color output is done */ Vk::PipelineStage::ColorAttachmentOutput, Vk::PipelineStage::Transfer, /* and color data written are available for the transfer to read */ Vk::Access::ColorAttachmentWrite, Vk::Access::TransferRead } }) }; /* Framebuffer image. It doesn't need to be host-visible, however we'll copy it to the host through a buffer so enable corresponding usage. */ Vk::Image image{device, Vk::ImageCreateInfo2D{ Vk::ImageUsage::ColorAttachment|Vk::ImageUsage::TransferSource, PixelFormat::RGBA8Srgb, {800, 600}, 1 }, Vk::MemoryFlag::DeviceLocal}; /* Create the triangle mesh */ Vk::Mesh mesh{Vk::MeshLayout{MeshPrimitive::Triangles} .addBinding(0, 2*4*4) .addAttribute(0, 0, VertexFormat::Vector4, 0) .addAttribute(1, 0, VertexFormat::Vector4, 4*4) }; { Vk::Buffer buffer{device, Vk::BufferCreateInfo{ Vk::BufferUsage::VertexBuffer, 3*2*4*4 /* Three vertices, each is four-element pos & color */ }, Vk::MemoryFlag::HostVisible}; /** @todo arrayCast for an array rvalue */ Containers::Array<char, Vk::MemoryMapDeleter> data = buffer.dedicatedMemory().map(); auto view = Containers::arrayCast<Vector4>(data); view[0] = {-0.5f, -0.5f, 0.0f, 1.0f}; /* Left vertex, red color */ view[1] = 0xff0000ff_srgbaf; view[2] = { 0.5f, -0.5f, 0.0f, 1.0f}; /* Right vertex, green color */ view[3] = 0x00ff00ff_srgbaf; view[4] = { 0.0f, 0.5f, 0.0f, 1.0f}; /* Top vertex, blue color */ view[5] = 0x0000ffff_srgbaf; mesh.addVertexBuffer(0, std::move(buffer), 0) .setCount(3); } /* Buffer to which the rendered image gets linearized */ Vk::Buffer pixels{device, Vk::BufferCreateInfo{ Vk::BufferUsage::TransferDestination, 800*600*4 }, Vk::MemoryFlag::HostVisible}; /* Framebuffer */ Vk::ImageView color{device, Vk::ImageViewCreateInfo2D{image}}; Vk::Framebuffer framebuffer{device, Vk::FramebufferCreateInfo{renderPass, { color }, {800, 600}}}; /* Create the shader */ constexpr Containers::StringView assembly = R"( OpCapability Shader OpMemoryModel Logical GLSL450 ; Function %1 is vertex shader and has %12, %13 as input and %15, %16 as output OpEntryPoint Vertex %1 "ver" %12 %13 %gl_Position %16 ; Function %2 is fragment shader and has %5 as input and %6 as output OpEntryPoint Fragment %2 "fra" %5 %6 OpExecutionMode %2 OriginUpperLeft ; Input/output layouts OpDecorate %12 Location 0 OpDecorate %13 Location 1 OpDecorate %gl_Position BuiltIn Position OpDecorate %16 Location 0 OpDecorate %5 Location 0 OpDecorate %6 Location 0 ; Types %void = OpTypeVoid %8 = OpTypeFunction %void %float = OpTypeFloat 32 %v4float = OpTypeVector %float 4 %_ptr_Input_v4float = OpTypePointer Input %v4float %12 = OpVariable %_ptr_Input_v4float Input %13 = OpVariable %_ptr_Input_v4float Input %_ptr_Output_v4float = OpTypePointer Output %v4float %gl_Position = OpVariable %_ptr_Output_v4float Output %16 = OpVariable %_ptr_Output_v4float Output %5 = OpVariable %_ptr_Input_v4float Input %6 = OpVariable %_ptr_Output_v4float Output ; %1 = void ver() %1 = OpFunction %void None %8 %33 = OpLabel %30 = OpLoad %v4float %12 %31 = OpLoad %v4float %13 OpStore %gl_Position %30 OpStore %16 %31 OpReturn OpFunctionEnd ; %2 = void fra() %2 = OpFunction %void None %8 %34 = OpLabel %32 = OpLoad %v4float %5 OpStore %6 %32 OpReturn OpFunctionEnd )"_s; Vk::Shader shader{device, Vk::ShaderCreateInfo{ CORRADE_INTERNAL_ASSERT_EXPRESSION(CORRADE_INTERNAL_ASSERT_EXPRESSION( PluginManager::Manager<ShaderTools::AbstractConverter>{} .loadAndInstantiate("SpirvAssemblyToSpirvShaderConverter") )->convertDataToData({}, assembly))}}; /* Create a graphics pipeline */ Vk::ShaderSet shaderSet; shaderSet .addShader(Vk::ShaderStage::Vertex, shader, "ver"_s) .addShader(Vk::ShaderStage::Fragment, shader, "fra"_s); Vk::PipelineLayout pipelineLayout{device, Vk::PipelineLayoutCreateInfo{}}; Vk::Pipeline pipeline{device, Vk::RasterizationPipelineCreateInfo{shaderSet, mesh.layout(), pipelineLayout, renderPass, 0, 1} .setViewport({{}, {800.0f, 600.0f}}) }; /* Record the command buffer: - render pass being converts the framebuffer attachment from Undefined to ColorAttachment and clears it - the pipeline barrier is needed in order to make the image data copied to the buffer visible in time for the host read happening below */ cmd.begin() .beginRenderPass(Vk::RenderPassBeginInfo{renderPass, framebuffer} .clearColor(0, 0x1f1f1f_srgbf) ) .bindPipeline(pipeline) .draw(mesh) .endRenderPass() .copyImageToBuffer({image, Vk::ImageLayout::TransferSource, pixels, { Vk::BufferImageCopy2D{0, Vk::ImageAspect::Color, 0, {{}, {800, 600}}} }}) .pipelineBarrier(Vk::PipelineStage::Transfer, Vk::PipelineStage::Host, { {Vk::Access::TransferWrite, Vk::Access::HostRead, pixels} }) .end(); /* Submit the command buffer and wait until done */ queue.submit({Vk::SubmitInfo{}.setCommandBuffers({cmd})}).wait(); /* Read the image back from the buffer */ CORRADE_INTERNAL_ASSERT_EXPRESSION( PluginManager::Manager<Trade::AbstractImageConverter>{} .loadAndInstantiate("AnyImageConverter") )->exportToFile(ImageView2D{ PixelFormat::RGBA8Unorm, {800, 600}, pixels.dedicatedMemory().mapRead() }, "image.png"); Debug{} << "Saved an image to image.png"; } <commit_msg>triangle-vulkan: comment your assembly, kids.<commit_after>/* This file is part of Magnum. Original authors — credit is appreciated but not required: 2010, 2011, 2012, 2013, 2014, 2015, 2016, 2017, 2018, 2019, 2020, 2021 — Vladimír Vondruš <[email protected]> 2021 — Pablo Escobar <[email protected]> This is free and unencumbered software released into the public domain. Anyone is free to copy, modify, publish, use, compile, sell, or distribute this software, either in source code form or as a compiled binary, for any purpose, commercial or non-commercial, and by any means. In jurisdictions that recognize copyright laws, the author or authors of this software dedicate any and all copyright interest in the software to the public domain. We make this dedication for the benefit of the public at large and to the detriment of our heirs and successors. We intend this dedication to be an overt act of relinquishment in perpetuity of all present and future rights to this software under copyright law. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #include <Corrade/Containers/Array.h> #include <Corrade/Containers/StringView.h> #include <Corrade/Utility/Assert.h> #include <Corrade/PluginManager/Manager.h> #include <Magnum/Magnum.h> #include <Magnum/Mesh.h> #include <Magnum/ImageView.h> #include <Magnum/PixelFormat.h> #include <Magnum/VertexFormat.h> #include <Magnum/Math/Color.h> #include <Magnum/Math/Range.h> #include <Magnum/ShaderTools/AbstractConverter.h> #include <Magnum/Trade/AbstractImageConverter.h> #include <Magnum/Vk/Assert.h> #include <Magnum/Vk/BufferCreateInfo.h> #include <Magnum/Vk/CommandBuffer.h> #include <Magnum/Vk/CommandPoolCreateInfo.h> #include <Magnum/Vk/DeviceCreateInfo.h> #include <Magnum/Vk/DeviceProperties.h> #include <Magnum/Vk/Fence.h> #include <Magnum/Vk/FramebufferCreateInfo.h> #include <Magnum/Vk/ImageCreateInfo.h> #include <Magnum/Vk/ImageViewCreateInfo.h> #include <Magnum/Vk/InstanceCreateInfo.h> #include <Magnum/Vk/Memory.h> #include <Magnum/Vk/Mesh.h> #include <Magnum/Vk/Pipeline.h> #include <Magnum/Vk/PipelineLayoutCreateInfo.h> #include <Magnum/Vk/Queue.h> #include <Magnum/Vk/RasterizationPipelineCreateInfo.h> #include <Magnum/Vk/RenderPassCreateInfo.h> #include <Magnum/Vk/ShaderCreateInfo.h> #include <Magnum/Vk/ShaderSet.h> using namespace Corrade::Containers::Literals; using namespace Magnum; using namespace Magnum::Math::Literals; int main(int argc, char** argv) { /* Create an instance */ Vk::Instance instance{Vk::InstanceCreateInfo{argc, argv} .setApplicationInfo("Magnum Vulkan Triangle Example"_s, {}) }; /* Create a device with a graphics queue */ Vk::Queue queue{NoCreate}; Vk::Device device{instance, Vk::DeviceCreateInfo{Vk::pickDevice(instance)} .addQueues(Vk::QueueFlag::Graphics, {0.0f}, {queue}) }; /* Allocate a command buffer */ Vk::CommandPool commandPool{device, Vk::CommandPoolCreateInfo{ device.properties().pickQueueFamily(Vk::QueueFlag::Graphics) }}; Vk::CommandBuffer cmd = commandPool.allocate(); /* Render pass. We'll want to transfer the image back to the host though a buffer once done, so additionally set up a corresponding final image layout and a dependency that performs the layout transition before we execute the copy command. */ Vk::RenderPass renderPass{device, Vk::RenderPassCreateInfo{} .setAttachments({ Vk::AttachmentDescription{PixelFormat::RGBA8Srgb, Vk::AttachmentLoadOperation::Clear, Vk::AttachmentStoreOperation::Store, Vk::ImageLayout::Undefined, Vk::ImageLayout::TransferSource } }) .addSubpass(Vk::SubpassDescription{} .setColorAttachments({ Vk::AttachmentReference{0, Vk::ImageLayout::ColorAttachment} }) ) .setDependencies({ Vk::SubpassDependency{ /* An operation external to the render pass depends on the first subpass */ 0, Vk::SubpassDependency::External, /* where transfer gets executed only after color output is done */ Vk::PipelineStage::ColorAttachmentOutput, Vk::PipelineStage::Transfer, /* and color data written are available for the transfer to read */ Vk::Access::ColorAttachmentWrite, Vk::Access::TransferRead } }) }; /* Framebuffer image. It doesn't need to be host-visible, however we'll copy it to the host through a buffer so enable corresponding usage. */ Vk::Image image{device, Vk::ImageCreateInfo2D{ Vk::ImageUsage::ColorAttachment|Vk::ImageUsage::TransferSource, PixelFormat::RGBA8Srgb, {800, 600}, 1 }, Vk::MemoryFlag::DeviceLocal}; /* Create the triangle mesh */ Vk::Mesh mesh{Vk::MeshLayout{MeshPrimitive::Triangles} .addBinding(0, 2*4*4) .addAttribute(0, 0, VertexFormat::Vector4, 0) .addAttribute(1, 0, VertexFormat::Vector4, 4*4) }; { Vk::Buffer buffer{device, Vk::BufferCreateInfo{ Vk::BufferUsage::VertexBuffer, 3*2*4*4 /* Three vertices, each is four-element pos & color */ }, Vk::MemoryFlag::HostVisible}; /** @todo arrayCast for an array rvalue */ Containers::Array<char, Vk::MemoryMapDeleter> data = buffer.dedicatedMemory().map(); auto view = Containers::arrayCast<Vector4>(data); view[0] = {-0.5f, -0.5f, 0.0f, 1.0f}; /* Left vertex, red color */ view[1] = 0xff0000ff_srgbaf; view[2] = { 0.5f, -0.5f, 0.0f, 1.0f}; /* Right vertex, green color */ view[3] = 0x00ff00ff_srgbaf; view[4] = { 0.0f, 0.5f, 0.0f, 1.0f}; /* Top vertex, blue color */ view[5] = 0x0000ffff_srgbaf; mesh.addVertexBuffer(0, std::move(buffer), 0) .setCount(3); } /* Buffer to which the rendered image gets linearized */ Vk::Buffer pixels{device, Vk::BufferCreateInfo{ Vk::BufferUsage::TransferDestination, 800*600*4 }, Vk::MemoryFlag::HostVisible}; /* Framebuffer */ Vk::ImageView color{device, Vk::ImageViewCreateInfo2D{image}}; Vk::Framebuffer framebuffer{device, Vk::FramebufferCreateInfo{renderPass, { color }, {800, 600}}}; /* Create the shader */ constexpr Containers::StringView assembly = R"( OpCapability Shader OpMemoryModel Logical GLSL450 OpEntryPoint Vertex %ver "ver" %position %color %gl_Position %interpolatedColorOut OpEntryPoint Fragment %fra "fra" %interpolatedColorIn %fragmentColor OpExecutionMode %fra OriginUpperLeft OpDecorate %position Location 0 OpDecorate %color Location 1 OpDecorate %gl_Position BuiltIn Position OpDecorate %interpolatedColorOut Location 0 OpDecorate %interpolatedColorIn Location 0 OpDecorate %fragmentColor Location 0 %void = OpTypeVoid %fn_void = OpTypeFunction %void %float = OpTypeFloat 32 %vec4 = OpTypeVector %float 4 %ptr_in_vec4 = OpTypePointer Input %vec4 %position = OpVariable %ptr_in_vec4 Input %color = OpVariable %ptr_in_vec4 Input %ptr_out_vec4 = OpTypePointer Output %vec4 %gl_Position = OpVariable %ptr_out_vec4 Output %interpolatedColorOut = OpVariable %ptr_out_vec4 Output %interpolatedColorIn = OpVariable %ptr_in_vec4 Input %fragmentColor = OpVariable %ptr_out_vec4 Output %ver = OpFunction %void None %fn_void %ver_ = OpLabel %1 = OpLoad %vec4 %position %2 = OpLoad %vec4 %color OpStore %gl_Position %1 OpStore %interpolatedColorOut %2 OpReturn OpFunctionEnd %fra = OpFunction %void None %fn_void %fra_ = OpLabel %3 = OpLoad %vec4 %interpolatedColorIn OpStore %fragmentColor %3 OpReturn OpFunctionEnd )"_s; Vk::Shader shader{device, Vk::ShaderCreateInfo{ CORRADE_INTERNAL_ASSERT_EXPRESSION(CORRADE_INTERNAL_ASSERT_EXPRESSION( PluginManager::Manager<ShaderTools::AbstractConverter>{} .loadAndInstantiate("SpirvAssemblyToSpirvShaderConverter") )->convertDataToData({}, assembly))}}; /* Create a graphics pipeline */ Vk::ShaderSet shaderSet; shaderSet .addShader(Vk::ShaderStage::Vertex, shader, "ver"_s) .addShader(Vk::ShaderStage::Fragment, shader, "fra"_s); Vk::PipelineLayout pipelineLayout{device, Vk::PipelineLayoutCreateInfo{}}; Vk::Pipeline pipeline{device, Vk::RasterizationPipelineCreateInfo{shaderSet, mesh.layout(), pipelineLayout, renderPass, 0, 1} .setViewport({{}, {800.0f, 600.0f}}) }; /* Record the command buffer: - render pass being converts the framebuffer attachment from Undefined to ColorAttachment and clears it - the pipeline barrier is needed in order to make the image data copied to the buffer visible in time for the host read happening below */ cmd.begin() .beginRenderPass(Vk::RenderPassBeginInfo{renderPass, framebuffer} .clearColor(0, 0x1f1f1f_srgbf) ) .bindPipeline(pipeline) .draw(mesh) .endRenderPass() .copyImageToBuffer({image, Vk::ImageLayout::TransferSource, pixels, { Vk::BufferImageCopy2D{0, Vk::ImageAspect::Color, 0, {{}, {800, 600}}} }}) .pipelineBarrier(Vk::PipelineStage::Transfer, Vk::PipelineStage::Host, { {Vk::Access::TransferWrite, Vk::Access::HostRead, pixels} }) .end(); /* Submit the command buffer and wait until done */ queue.submit({Vk::SubmitInfo{}.setCommandBuffers({cmd})}).wait(); /* Read the image back from the buffer */ CORRADE_INTERNAL_ASSERT_EXPRESSION( PluginManager::Manager<Trade::AbstractImageConverter>{} .loadAndInstantiate("AnyImageConverter") )->exportToFile(ImageView2D{ PixelFormat::RGBA8Unorm, {800, 600}, pixels.dedicatedMemory().mapRead() }, "image.png"); Debug{} << "Saved an image to image.png"; } <|endoftext|>
<commit_before>/* Highly Optimized Object-Oriented Molecular Dynamics (HOOMD) Open Source Software License Copyright (c) 2008 Ames Laboratory Iowa State University All rights reserved. Redistribution and use of HOOMD, 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 the copyright holder nor the names HOOMD's contributors may be used to endorse or promote products derived from this software without specific prior written permission. Disclaimer THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER AND CONTRIBUTORS ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER 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$ // $URL$ #ifdef WIN32 #pragma warning( push ) #pragma warning( disable : 4103 4244 ) #endif #include <iostream> //! Name the unit test module #define BOOST_TEST_MODULE UtilityClassesTests #include "boost_utf_configure.h" #include <math.h> #include "ClockSource.h" #include "Profiler.h" #include "Variant.h" //! Helper macro for testing if two numbers are close #define MY_BOOST_CHECK_CLOSE(a,b,c) BOOST_CHECK_CLOSE(a,double(b),double(c)) //! Helper macro for testing if a number is small #define MY_BOOST_CHECK_SMALL(a,c) BOOST_CHECK_SMALL(a,double(c)) //! Tolerance double tol = 1e-3; /*! \file utils_test.cc \brief Unit tests for ClockSource, Profiler, and Variant \ingroup unit_tests */ using namespace std; // the clock test depends on timing and thus should not be run in automatic builds. // uncomment to test by hand if the test seems to be behaving poorly //! perform some simple checks on the clock source code /*BOOST_AUTO_TEST_CASE(ClockSource_test) { ClockSource c1; int64_t t = c1.getTime(); // c.getTime() should read 0, but we can't expect it to be exact, so allow a tolerance BOOST_CHECK(abs(int(t)) <= 1000000); // test timing a whole second ClockSource c2; int64_t t1 = c2.getTime(); Sleep(1000); int64_t t2 = c2.getTime(); BOOST_CHECK(abs(int(t2 - t1 - int64_t(1000000000))) <= 20000000);*/ // unfortunately, testing of microsecond timing with a sleep routine is out of the question // the following test code tests the ability of the timer to read nearby values /*ClockSource c4; int64_t times[100]; for (int i = 0; i < 100; i++) { times[i] = c4.getTime(); } for (int i = 0; i < 100; i++) { cout << times[i] << endl; }*/ // test copying timers // operator= /* c1 = c2; t1 = c1.getTime(); t2 = c2.getTime(); BOOST_CHECK(abs(int(t1-t2)) <= 1000000); // copy constructor ClockSource c3(c1); t1 = c1.getTime(); t2 = c3.getTime(); BOOST_CHECK(abs(int(t1-t2)) <= 1000000); // test the ability of the clock source to format values BOOST_CHECK_EQUAL(ClockSource::formatHMS(0), string("00:00:00")); BOOST_CHECK_EQUAL(ClockSource::formatHMS(int64_t(1000000000)), string("00:00:01")); BOOST_CHECK_EQUAL(ClockSource::formatHMS(int64_t(1000000000)*int64_t(11)), string("00:00:11")); BOOST_CHECK_EQUAL(ClockSource::formatHMS(int64_t(1000000000)*int64_t(65)), string("00:01:05")); BOOST_CHECK_EQUAL(ClockSource::formatHMS(int64_t(1000000000)*int64_t(3678)), string("01:01:18")); }*/ //! perform some simple checks on the profiler code BOOST_AUTO_TEST_CASE(Profiler_test) { // ProfileDataElem tests // constructor test ProfileDataElem p; BOOST_CHECK(p.getChildElapsedTime() == 0); BOOST_CHECK(p.getTotalFlopCount() == 0); BOOST_CHECK(p.getTotalMemByteCount() == 0); // build up a tree and test its getTotal members p.m_elapsed_time = 1; p.m_flop_count = 2; p.m_mem_byte_count = 3; BOOST_CHECK(p.getChildElapsedTime() == 0); BOOST_CHECK(p.getTotalFlopCount() == 2); BOOST_CHECK(p.getTotalMemByteCount() == 3); p.m_children["A"].m_elapsed_time = 4; p.m_children["A"].m_flop_count = 5; p.m_children["A"].m_mem_byte_count = 6; BOOST_CHECK(p.getChildElapsedTime() == 4); BOOST_CHECK(p.getTotalFlopCount() == 7); BOOST_CHECK(p.getTotalMemByteCount() == 9); p.m_children["B"].m_elapsed_time = 7; p.m_children["B"].m_flop_count = 8; p.m_children["B"].m_mem_byte_count = 9; BOOST_CHECK(p.getChildElapsedTime() == 4+7); BOOST_CHECK(p.getTotalFlopCount() == 7+8); BOOST_CHECK(p.getTotalMemByteCount() == 9+9); p.m_children["A"].m_children["C"].m_elapsed_time = 10; p.m_children["A"].m_children["C"].m_flop_count = 11; p.m_children["A"].m_children["C"].m_mem_byte_count = 12; BOOST_CHECK(p.getChildElapsedTime() == 4+7); BOOST_CHECK(p.getTotalFlopCount() == 7+8+11); BOOST_CHECK(p.getTotalMemByteCount() == 9+9+12); Profiler prof("Main"); prof.push("Loading"); Sleep(500); prof.pop(); prof.push("Neighbor"); Sleep(1000); prof.pop(int64_t(1e6), int64_t(1e6)); prof.push("Pair"); prof.push("Load"); Sleep(1000); prof.pop(int64_t(1e9), int64_t(1e9)); prof.push("Work"); Sleep(1000); prof.pop(int64_t(10e9), int64_t(100)); prof.push("Unload"); Sleep(1000); prof.pop(int64_t(100), int64_t(1e9)); prof.pop(); std::cout << prof; // This code attempts to reproduce the problem found in ticket #50 Profiler prof2("test"); prof2.push("test1"); //Changing this slep value much lower than 100 results in the bug. Sleep(000); prof2.pop(100, 100); std::cout << prof2; } //! perform some simple checks on the variant types BOOST_AUTO_TEST_CASE(Variant_test) { Variant v; BOOST_CHECK_EQUAL(v.getValue(0), 0.0); BOOST_CHECK_EQUAL(v.getValue(100000), 0.0); v.setOffset(1000); BOOST_CHECK_EQUAL(v.getValue(0), 0.0); BOOST_CHECK_EQUAL(v.getValue(100000), 0.0); } //! perform some simple checks on the variant types BOOST_AUTO_TEST_CASE(VariantConst_test) { double val = 10.5; VariantConst v(val); BOOST_CHECK_EQUAL(v.getValue(0), val); BOOST_CHECK_EQUAL(v.getValue(100000), val); v.setOffset(1000); BOOST_CHECK_EQUAL(v.getValue(0), val); BOOST_CHECK_EQUAL(v.getValue(100000), val); } //! perform some simple checks on the variant types BOOST_AUTO_TEST_CASE(VariantLinear_test1) { double val = 10.5; VariantLinear v; v.setPoint(500, val); BOOST_CHECK_EQUAL(v.getValue(0), val); BOOST_CHECK_EQUAL(v.getValue(500), val); BOOST_CHECK_EQUAL(v.getValue(100000), val); v.setOffset(1000); BOOST_CHECK_EQUAL(v.getValue(0), val); BOOST_CHECK_EQUAL(v.getValue(500), val); BOOST_CHECK_EQUAL(v.getValue(100000), val); } //! perform some simple checks on the variant types BOOST_AUTO_TEST_CASE(VariantLinear_test2) { VariantLinear v; v.setPoint(500, 10.0); v.setPoint(1000, 20.0); MY_BOOST_CHECK_CLOSE(v.getValue(0), 10.0, tol); MY_BOOST_CHECK_CLOSE(v.getValue(500), 10.0, tol); MY_BOOST_CHECK_CLOSE(v.getValue(750), 15.0, tol); MY_BOOST_CHECK_CLOSE(v.getValue(1000), 20.0, tol); MY_BOOST_CHECK_CLOSE(v.getValue(1500), 20.0, tol); v.setOffset(1000); MY_BOOST_CHECK_CLOSE(v.getValue(0), 10.0, tol); MY_BOOST_CHECK_CLOSE(v.getValue(1000), 10.0, tol); MY_BOOST_CHECK_CLOSE(v.getValue(1500), 10.0, tol); MY_BOOST_CHECK_CLOSE(v.getValue(1750), 15.0, tol); MY_BOOST_CHECK_CLOSE(v.getValue(2000), 20.0, tol); MY_BOOST_CHECK_CLOSE(v.getValue(2500), 20.0, tol); } //! perform some simple checks on the variant types BOOST_AUTO_TEST_CASE(VariantLinear_test3) { VariantLinear v; v.setPoint(500, 10.0); v.setPoint(1000, 20.0); v.setPoint(2000, 50.0); MY_BOOST_CHECK_CLOSE(v.getValue(0), 10.0, tol); MY_BOOST_CHECK_CLOSE(v.getValue(500), 10.0, tol); MY_BOOST_CHECK_CLOSE(v.getValue(750), 15.0, tol); MY_BOOST_CHECK_CLOSE(v.getValue(1000), 20.0, tol); MY_BOOST_CHECK_CLOSE(v.getValue(1500), 35.0, tol); MY_BOOST_CHECK_CLOSE(v.getValue(2000), 50.0, tol); MY_BOOST_CHECK_CLOSE(v.getValue(2500), 50.0, tol); v.setOffset(1000); MY_BOOST_CHECK_CLOSE(v.getValue(0), 10.0, tol); MY_BOOST_CHECK_CLOSE(v.getValue(1000), 10.0, tol); MY_BOOST_CHECK_CLOSE(v.getValue(1500), 10.0, tol); MY_BOOST_CHECK_CLOSE(v.getValue(1750), 15.0, tol); MY_BOOST_CHECK_CLOSE(v.getValue(2000), 20.0, tol); MY_BOOST_CHECK_CLOSE(v.getValue(2500), 35.0, tol); MY_BOOST_CHECK_CLOSE(v.getValue(3000), 50.0, tol); MY_BOOST_CHECK_CLOSE(v.getValue(3500), 50.0, tol); // mix up the order to make sure it works no matter what MY_BOOST_CHECK_CLOSE(v.getValue(3000), 50.0, tol); MY_BOOST_CHECK_CLOSE(v.getValue(1500), 10.0, tol); MY_BOOST_CHECK_CLOSE(v.getValue(0), 10.0, tol); MY_BOOST_CHECK_CLOSE(v.getValue(2000), 20.0, tol); MY_BOOST_CHECK_CLOSE(v.getValue(2500), 35.0, tol); MY_BOOST_CHECK_CLOSE(v.getValue(1000), 10.0, tol); MY_BOOST_CHECK_CLOSE(v.getValue(1750), 15.0, tol); MY_BOOST_CHECK_CLOSE(v.getValue(3500), 50.0, tol); } #ifdef WIN32 #pragma warning( pop ) #endif <commit_msg>Added missing boost include needed for older boost versions.<commit_after>/* Highly Optimized Object-Oriented Molecular Dynamics (HOOMD) Open Source Software License Copyright (c) 2008 Ames Laboratory Iowa State University All rights reserved. Redistribution and use of HOOMD, 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 the copyright holder nor the names HOOMD's contributors may be used to endorse or promote products derived from this software without specific prior written permission. Disclaimer THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER AND CONTRIBUTORS ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER 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$ // $URL$ #ifdef WIN32 #pragma warning( push ) #pragma warning( disable : 4103 4244 ) #endif #include <iostream> //! Name the unit test module #define BOOST_TEST_MODULE UtilityClassesTests #include "boost_utf_configure.h" #include <math.h> #include "ClockSource.h" #include "Profiler.h" #include "Variant.h" #include <boost/test/floating_point_comparison.hpp> //! Helper macro for testing if two numbers are close #define MY_BOOST_CHECK_CLOSE(a,b,c) BOOST_CHECK_CLOSE(a,double(b),double(c)) //! Helper macro for testing if a number is small #define MY_BOOST_CHECK_SMALL(a,c) BOOST_CHECK_SMALL(a,double(c)) //! Tolerance double tol = 1e-3; /*! \file utils_test.cc \brief Unit tests for ClockSource, Profiler, and Variant \ingroup unit_tests */ using namespace std; // the clock test depends on timing and thus should not be run in automatic builds. // uncomment to test by hand if the test seems to be behaving poorly //! perform some simple checks on the clock source code /*BOOST_AUTO_TEST_CASE(ClockSource_test) { ClockSource c1; int64_t t = c1.getTime(); // c.getTime() should read 0, but we can't expect it to be exact, so allow a tolerance BOOST_CHECK(abs(int(t)) <= 1000000); // test timing a whole second ClockSource c2; int64_t t1 = c2.getTime(); Sleep(1000); int64_t t2 = c2.getTime(); BOOST_CHECK(abs(int(t2 - t1 - int64_t(1000000000))) <= 20000000);*/ // unfortunately, testing of microsecond timing with a sleep routine is out of the question // the following test code tests the ability of the timer to read nearby values /*ClockSource c4; int64_t times[100]; for (int i = 0; i < 100; i++) { times[i] = c4.getTime(); } for (int i = 0; i < 100; i++) { cout << times[i] << endl; }*/ // test copying timers // operator= /* c1 = c2; t1 = c1.getTime(); t2 = c2.getTime(); BOOST_CHECK(abs(int(t1-t2)) <= 1000000); // copy constructor ClockSource c3(c1); t1 = c1.getTime(); t2 = c3.getTime(); BOOST_CHECK(abs(int(t1-t2)) <= 1000000); // test the ability of the clock source to format values BOOST_CHECK_EQUAL(ClockSource::formatHMS(0), string("00:00:00")); BOOST_CHECK_EQUAL(ClockSource::formatHMS(int64_t(1000000000)), string("00:00:01")); BOOST_CHECK_EQUAL(ClockSource::formatHMS(int64_t(1000000000)*int64_t(11)), string("00:00:11")); BOOST_CHECK_EQUAL(ClockSource::formatHMS(int64_t(1000000000)*int64_t(65)), string("00:01:05")); BOOST_CHECK_EQUAL(ClockSource::formatHMS(int64_t(1000000000)*int64_t(3678)), string("01:01:18")); }*/ //! perform some simple checks on the profiler code BOOST_AUTO_TEST_CASE(Profiler_test) { // ProfileDataElem tests // constructor test ProfileDataElem p; BOOST_CHECK(p.getChildElapsedTime() == 0); BOOST_CHECK(p.getTotalFlopCount() == 0); BOOST_CHECK(p.getTotalMemByteCount() == 0); // build up a tree and test its getTotal members p.m_elapsed_time = 1; p.m_flop_count = 2; p.m_mem_byte_count = 3; BOOST_CHECK(p.getChildElapsedTime() == 0); BOOST_CHECK(p.getTotalFlopCount() == 2); BOOST_CHECK(p.getTotalMemByteCount() == 3); p.m_children["A"].m_elapsed_time = 4; p.m_children["A"].m_flop_count = 5; p.m_children["A"].m_mem_byte_count = 6; BOOST_CHECK(p.getChildElapsedTime() == 4); BOOST_CHECK(p.getTotalFlopCount() == 7); BOOST_CHECK(p.getTotalMemByteCount() == 9); p.m_children["B"].m_elapsed_time = 7; p.m_children["B"].m_flop_count = 8; p.m_children["B"].m_mem_byte_count = 9; BOOST_CHECK(p.getChildElapsedTime() == 4+7); BOOST_CHECK(p.getTotalFlopCount() == 7+8); BOOST_CHECK(p.getTotalMemByteCount() == 9+9); p.m_children["A"].m_children["C"].m_elapsed_time = 10; p.m_children["A"].m_children["C"].m_flop_count = 11; p.m_children["A"].m_children["C"].m_mem_byte_count = 12; BOOST_CHECK(p.getChildElapsedTime() == 4+7); BOOST_CHECK(p.getTotalFlopCount() == 7+8+11); BOOST_CHECK(p.getTotalMemByteCount() == 9+9+12); Profiler prof("Main"); prof.push("Loading"); Sleep(500); prof.pop(); prof.push("Neighbor"); Sleep(1000); prof.pop(int64_t(1e6), int64_t(1e6)); prof.push("Pair"); prof.push("Load"); Sleep(1000); prof.pop(int64_t(1e9), int64_t(1e9)); prof.push("Work"); Sleep(1000); prof.pop(int64_t(10e9), int64_t(100)); prof.push("Unload"); Sleep(1000); prof.pop(int64_t(100), int64_t(1e9)); prof.pop(); std::cout << prof; // This code attempts to reproduce the problem found in ticket #50 Profiler prof2("test"); prof2.push("test1"); //Changing this slep value much lower than 100 results in the bug. Sleep(000); prof2.pop(100, 100); std::cout << prof2; } //! perform some simple checks on the variant types BOOST_AUTO_TEST_CASE(Variant_test) { Variant v; BOOST_CHECK_EQUAL(v.getValue(0), 0.0); BOOST_CHECK_EQUAL(v.getValue(100000), 0.0); v.setOffset(1000); BOOST_CHECK_EQUAL(v.getValue(0), 0.0); BOOST_CHECK_EQUAL(v.getValue(100000), 0.0); } //! perform some simple checks on the variant types BOOST_AUTO_TEST_CASE(VariantConst_test) { double val = 10.5; VariantConst v(val); BOOST_CHECK_EQUAL(v.getValue(0), val); BOOST_CHECK_EQUAL(v.getValue(100000), val); v.setOffset(1000); BOOST_CHECK_EQUAL(v.getValue(0), val); BOOST_CHECK_EQUAL(v.getValue(100000), val); } //! perform some simple checks on the variant types BOOST_AUTO_TEST_CASE(VariantLinear_test1) { double val = 10.5; VariantLinear v; v.setPoint(500, val); BOOST_CHECK_EQUAL(v.getValue(0), val); BOOST_CHECK_EQUAL(v.getValue(500), val); BOOST_CHECK_EQUAL(v.getValue(100000), val); v.setOffset(1000); BOOST_CHECK_EQUAL(v.getValue(0), val); BOOST_CHECK_EQUAL(v.getValue(500), val); BOOST_CHECK_EQUAL(v.getValue(100000), val); } //! perform some simple checks on the variant types BOOST_AUTO_TEST_CASE(VariantLinear_test2) { VariantLinear v; v.setPoint(500, 10.0); v.setPoint(1000, 20.0); MY_BOOST_CHECK_CLOSE(v.getValue(0), 10.0, tol); MY_BOOST_CHECK_CLOSE(v.getValue(500), 10.0, tol); MY_BOOST_CHECK_CLOSE(v.getValue(750), 15.0, tol); MY_BOOST_CHECK_CLOSE(v.getValue(1000), 20.0, tol); MY_BOOST_CHECK_CLOSE(v.getValue(1500), 20.0, tol); v.setOffset(1000); MY_BOOST_CHECK_CLOSE(v.getValue(0), 10.0, tol); MY_BOOST_CHECK_CLOSE(v.getValue(1000), 10.0, tol); MY_BOOST_CHECK_CLOSE(v.getValue(1500), 10.0, tol); MY_BOOST_CHECK_CLOSE(v.getValue(1750), 15.0, tol); MY_BOOST_CHECK_CLOSE(v.getValue(2000), 20.0, tol); MY_BOOST_CHECK_CLOSE(v.getValue(2500), 20.0, tol); } //! perform some simple checks on the variant types BOOST_AUTO_TEST_CASE(VariantLinear_test3) { VariantLinear v; v.setPoint(500, 10.0); v.setPoint(1000, 20.0); v.setPoint(2000, 50.0); MY_BOOST_CHECK_CLOSE(v.getValue(0), 10.0, tol); MY_BOOST_CHECK_CLOSE(v.getValue(500), 10.0, tol); MY_BOOST_CHECK_CLOSE(v.getValue(750), 15.0, tol); MY_BOOST_CHECK_CLOSE(v.getValue(1000), 20.0, tol); MY_BOOST_CHECK_CLOSE(v.getValue(1500), 35.0, tol); MY_BOOST_CHECK_CLOSE(v.getValue(2000), 50.0, tol); MY_BOOST_CHECK_CLOSE(v.getValue(2500), 50.0, tol); v.setOffset(1000); MY_BOOST_CHECK_CLOSE(v.getValue(0), 10.0, tol); MY_BOOST_CHECK_CLOSE(v.getValue(1000), 10.0, tol); MY_BOOST_CHECK_CLOSE(v.getValue(1500), 10.0, tol); MY_BOOST_CHECK_CLOSE(v.getValue(1750), 15.0, tol); MY_BOOST_CHECK_CLOSE(v.getValue(2000), 20.0, tol); MY_BOOST_CHECK_CLOSE(v.getValue(2500), 35.0, tol); MY_BOOST_CHECK_CLOSE(v.getValue(3000), 50.0, tol); MY_BOOST_CHECK_CLOSE(v.getValue(3500), 50.0, tol); // mix up the order to make sure it works no matter what MY_BOOST_CHECK_CLOSE(v.getValue(3000), 50.0, tol); MY_BOOST_CHECK_CLOSE(v.getValue(1500), 10.0, tol); MY_BOOST_CHECK_CLOSE(v.getValue(0), 10.0, tol); MY_BOOST_CHECK_CLOSE(v.getValue(2000), 20.0, tol); MY_BOOST_CHECK_CLOSE(v.getValue(2500), 35.0, tol); MY_BOOST_CHECK_CLOSE(v.getValue(1000), 10.0, tol); MY_BOOST_CHECK_CLOSE(v.getValue(1750), 15.0, tol); MY_BOOST_CHECK_CLOSE(v.getValue(3500), 50.0, tol); } #ifdef WIN32 #pragma warning( pop ) #endif <|endoftext|>
<commit_before>// // Multigrid.cpp // Vortex2D // #include "Multigrid.h" #include <Vortex2D/Engine/Pressure.h> namespace Vortex2D { namespace Fluid { Depth::Depth(const glm::ivec2& size) { auto s = size; mDepths.push_back(s); const float min_size = 16.0f; while (s.x > min_size && s.y > min_size) { if (s.x % 2 != 0 || s.y % 2 != 0) throw std::runtime_error("Invalid multigrid size"); s = s / glm::ivec2(2); mDepths.push_back(s); } } int Depth::GetMaxDepth() const { return mDepths.size() - 1; } glm::ivec2 Depth::GetDepthSize(int i) const { assert(i < mDepths.size()); return mDepths[i]; } Multigrid::Multigrid(const Renderer::Device& device, const glm::ivec2& size, float delta, bool statistics) : mDepth(size) , mDelta(delta) , mResidualWork(device, size, "../Vortex2D/Residual.comp.spv") , mTransfer(device) , mPhiScaleWork(device, size, "../Vortex2D/PhiScale.comp.spv") , mDampedJacobi(device, size, "../Vortex2D/DampedJacobi.comp.spv") , mBuildHierarchies(device, false) , mEnableStatistics(statistics) , mStatistics(device) { for (int i = 1; i <= mDepth.GetMaxDepth(); i++) { auto s = mDepth.GetDepthSize(i); mDatas.emplace_back(device, s); mSolidPhis.emplace_back(device, s); mLiquidPhis.emplace_back(device, s); mLiquidPhis.back().ExtrapolateInit(mSolidPhis.back()); } for (int i = 0; i < mDepth.GetMaxDepth(); i++) { auto s = mDepth.GetDepthSize(i); mResiduals.emplace_back(device, s.x*s.y); } for (int i = 0; i <= mDepth.GetMaxDepth(); i++) { auto s = mDepth.GetDepthSize(i); mXs.emplace_back(device, s.x*s.y); } mSmoothers.resize(2 * (mDepth.GetMaxDepth() + 1)); mResidualWorkBound.resize(mDepth.GetMaxDepth() + 1); } void Multigrid::Init(Renderer::GenericBuffer& d, Renderer::GenericBuffer& l, Renderer::GenericBuffer& b, Renderer::GenericBuffer& pressure) { mPressure = &pressure; mResidualWorkBound[0] = mResidualWork.Bind({pressure, d, l, b, mResiduals[0]}); mSmoothers[0] = mDampedJacobi.Bind({pressure, mXs[0], d, l, b}); mSmoothers[1] = mDampedJacobi.Bind({mXs[0], pressure, d, l, b}); auto s = mDepth.GetDepthSize(0); mTransfer.InitRestrict(0, s, mResiduals[0], d, mDatas[0].B, mDatas[0].Diagonal); mTransfer.InitProlongate(0, s, pressure, d, mDatas[0].X, mDatas[0].Diagonal); } void Multigrid::BuildHierarchiesInit(Pressure& pressure, Renderer::Texture& solidPhi, Renderer::Texture& liquidPhi) { auto s = mDepth.GetDepthSize(1); mLiquidPhiScaleWorkBound.push_back(mPhiScaleWork.Bind(s, {liquidPhi, mLiquidPhis[0]})); mSolidPhiScaleWorkBound.push_back(mPhiScaleWork.Bind(s, {solidPhi, mSolidPhis[0]})); BindRecursive(pressure, 1); mBuildHierarchies.Record([&](vk::CommandBuffer commandBuffer) { for (std::size_t i = 0; i < mDepth.GetMaxDepth(); i++) { mLiquidPhiScaleWorkBound[i].Record(commandBuffer); mLiquidPhis[i].Barrier(commandBuffer, vk::ImageLayout::eGeneral, vk::AccessFlagBits::eShaderWrite, vk::ImageLayout::eGeneral, vk::AccessFlagBits::eShaderRead); mSolidPhiScaleWorkBound[i].Record(commandBuffer); mSolidPhis[i].Barrier(commandBuffer, vk::ImageLayout::eGeneral, vk::AccessFlagBits::eShaderWrite, vk::ImageLayout::eGeneral, vk::AccessFlagBits::eShaderRead); mLiquidPhis[i].ExtrapolateRecord(commandBuffer); mMatrixBuildBound[i].PushConstant(commandBuffer, 8, mDelta); mMatrixBuildBound[i].Record(commandBuffer); mDatas[i].Diagonal.Barrier(commandBuffer, vk::AccessFlagBits::eShaderWrite, vk::AccessFlagBits::eShaderRead); mDatas[i].Lower.Barrier(commandBuffer, vk::AccessFlagBits::eShaderWrite, vk::AccessFlagBits::eShaderRead); mDatas[i].B.Clear(commandBuffer); } std::size_t maxDepth = mDepth.GetMaxDepth(); mMatrixBuildBound[maxDepth - 1].PushConstant(commandBuffer, 8, mDelta); mMatrixBuildBound[maxDepth - 1].Record(commandBuffer); mDatas[maxDepth - 1].Diagonal.Barrier(commandBuffer, vk::AccessFlagBits::eShaderWrite, vk::AccessFlagBits::eShaderRead); mDatas[maxDepth - 1].Lower.Barrier(commandBuffer, vk::AccessFlagBits::eShaderWrite, vk::AccessFlagBits::eShaderRead); }); } void Multigrid::BindRecursive(Pressure& pressure, std::size_t depth) { auto s0 = mDepth.GetDepthSize(depth); if (depth < mDepth.GetMaxDepth()) { auto s1 = mDepth.GetDepthSize(depth + 1); mLiquidPhiScaleWorkBound.push_back(mPhiScaleWork.Bind(s1, {mLiquidPhis[depth - 1], mLiquidPhis[depth]})); mSolidPhiScaleWorkBound.push_back(mPhiScaleWork.Bind(s1, {mSolidPhis[depth - 1], mSolidPhis[depth]})); mResidualWorkBound[depth] = mResidualWork.Bind(s0, {mDatas[depth-1].X, mDatas[depth-1].Diagonal, mDatas[depth-1].Lower, mDatas[depth-1].B, mResiduals[depth]}); mTransfer.InitRestrict(depth, s0, mResiduals[depth], mDatas[depth-1].Diagonal, mDatas[depth].B, mDatas[depth].Diagonal); mTransfer.InitProlongate(depth, s0, mDatas[depth-1].X, mDatas[depth-1].Diagonal, mDatas[depth].X, mDatas[depth].Diagonal); BindRecursive(pressure, depth+1); } mMatrixBuildBound.push_back( pressure.BindMatrixBuild(s0, mDatas[depth-1].Diagonal, mDatas[depth-1].Lower, mLiquidPhis[depth-1], mSolidPhis[depth-1])); mSmoothers[2 * depth] = mDampedJacobi.Bind(s0, {mDatas[depth-1].X, mXs[depth], mDatas[depth-1].Diagonal, mDatas[depth-1].Lower, mDatas[depth-1].B}); mSmoothers[2 * depth + 1] = mDampedJacobi.Bind(s0, {mXs[depth], mDatas[depth-1].X, mDatas[depth-1].Diagonal, mDatas[depth-1].Lower, mDatas[depth-1].B}); } void Multigrid::BuildHierarchies() { mBuildHierarchies.Submit(); } void Multigrid::Smoother(vk::CommandBuffer commandBuffer, int n, int iterations) { float w = 2.0f / 3.0f; int level = n * 2; for (int i = 0; i < iterations; i++) { mSmoothers[level].PushConstant(commandBuffer, 8, w); mSmoothers[level].Record(commandBuffer); mXs[n].Barrier(commandBuffer, vk::AccessFlagBits::eShaderWrite, vk::AccessFlagBits::eShaderRead); mSmoothers[level + 1].PushConstant(commandBuffer, 8, w); mSmoothers[level + 1].Record(commandBuffer); if (n == 0) mPressure->Barrier(commandBuffer, vk::AccessFlagBits::eShaderWrite, vk::AccessFlagBits::eShaderRead); else mDatas[n - 1].X.Barrier(commandBuffer, vk::AccessFlagBits::eShaderWrite, vk::AccessFlagBits::eShaderRead); } } void Multigrid::Record(vk::CommandBuffer commandBuffer) { const int numIterations = 2; if (mEnableStatistics) mStatistics.Start(commandBuffer); assert(mPressure != nullptr); mPressure->Clear(commandBuffer); mXs[0].Clear(commandBuffer); if (mEnableStatistics) mStatistics.Tick(commandBuffer, "clear"); for (int i = 0; i < mDepth.GetMaxDepth(); i++) { Smoother(commandBuffer, i, numIterations); if (mEnableStatistics) mStatistics.Tick(commandBuffer, "smoother " + std::to_string(i)); mResidualWorkBound[i].Record(commandBuffer); mResiduals[i].Barrier(commandBuffer, vk::AccessFlagBits::eShaderWrite, vk::AccessFlagBits::eShaderRead); if (mEnableStatistics) mStatistics.Tick(commandBuffer, "residual " + std::to_string(i)); mTransfer.Restrict(commandBuffer, i); if (mEnableStatistics) mStatistics.Tick(commandBuffer, "transfer " + std::to_string(i)); mDatas[i].X.Clear(commandBuffer); mXs[i-1].Clear(commandBuffer); if (mEnableStatistics) mStatistics.Tick(commandBuffer, "clear " + std::to_string(i)); } Smoother(commandBuffer, mDepth.GetMaxDepth(), numIterations); if (mEnableStatistics) mStatistics.Tick(commandBuffer, "smoother max"); for (int i = mDepth.GetMaxDepth() - 1; i >= 0; --i) { mTransfer.Prolongate(commandBuffer, i); if (mEnableStatistics) mStatistics.Tick(commandBuffer, "prolongate " + std::to_string(i)); Smoother(commandBuffer, i, numIterations); if (mEnableStatistics) mStatistics.Tick(commandBuffer, "smoother " + std::to_string(i)); } if (mEnableStatistics) mStatistics.End(commandBuffer, "end"); } Renderer::Statistics::Timestamps Multigrid::GetStatistics() { return mStatistics.GetTimestamps(); } }} <commit_msg>fix typo<commit_after>// // Multigrid.cpp // Vortex2D // #include "Multigrid.h" #include <Vortex2D/Engine/Pressure.h> namespace Vortex2D { namespace Fluid { Depth::Depth(const glm::ivec2& size) { auto s = size; mDepths.push_back(s); const float min_size = 16.0f; while (s.x > min_size && s.y > min_size) { if (s.x % 2 != 0 || s.y % 2 != 0) throw std::runtime_error("Invalid multigrid size"); s = s / glm::ivec2(2); mDepths.push_back(s); } } int Depth::GetMaxDepth() const { return mDepths.size() - 1; } glm::ivec2 Depth::GetDepthSize(int i) const { assert(i < mDepths.size()); return mDepths[i]; } Multigrid::Multigrid(const Renderer::Device& device, const glm::ivec2& size, float delta, bool statistics) : mDepth(size) , mDelta(delta) , mResidualWork(device, size, "../Vortex2D/Residual.comp.spv") , mTransfer(device) , mPhiScaleWork(device, size, "../Vortex2D/PhiScale.comp.spv") , mDampedJacobi(device, size, "../Vortex2D/DampedJacobi.comp.spv") , mBuildHierarchies(device, false) , mEnableStatistics(statistics) , mStatistics(device) { for (int i = 1; i <= mDepth.GetMaxDepth(); i++) { auto s = mDepth.GetDepthSize(i); mDatas.emplace_back(device, s); mSolidPhis.emplace_back(device, s); mLiquidPhis.emplace_back(device, s); mLiquidPhis.back().ExtrapolateInit(mSolidPhis.back()); } for (int i = 0; i < mDepth.GetMaxDepth(); i++) { auto s = mDepth.GetDepthSize(i); mResiduals.emplace_back(device, s.x*s.y); } for (int i = 0; i <= mDepth.GetMaxDepth(); i++) { auto s = mDepth.GetDepthSize(i); mXs.emplace_back(device, s.x*s.y); } mSmoothers.resize(2 * (mDepth.GetMaxDepth() + 1)); mResidualWorkBound.resize(mDepth.GetMaxDepth() + 1); } void Multigrid::Init(Renderer::GenericBuffer& d, Renderer::GenericBuffer& l, Renderer::GenericBuffer& b, Renderer::GenericBuffer& pressure) { mPressure = &pressure; mResidualWorkBound[0] = mResidualWork.Bind({pressure, d, l, b, mResiduals[0]}); mSmoothers[0] = mDampedJacobi.Bind({pressure, mXs[0], d, l, b}); mSmoothers[1] = mDampedJacobi.Bind({mXs[0], pressure, d, l, b}); auto s = mDepth.GetDepthSize(0); mTransfer.InitRestrict(0, s, mResiduals[0], d, mDatas[0].B, mDatas[0].Diagonal); mTransfer.InitProlongate(0, s, pressure, d, mDatas[0].X, mDatas[0].Diagonal); } void Multigrid::BuildHierarchiesInit(Pressure& pressure, Renderer::Texture& solidPhi, Renderer::Texture& liquidPhi) { auto s = mDepth.GetDepthSize(1); mLiquidPhiScaleWorkBound.push_back(mPhiScaleWork.Bind(s, {liquidPhi, mLiquidPhis[0]})); mSolidPhiScaleWorkBound.push_back(mPhiScaleWork.Bind(s, {solidPhi, mSolidPhis[0]})); BindRecursive(pressure, 1); mBuildHierarchies.Record([&](vk::CommandBuffer commandBuffer) { for (std::size_t i = 0; i < mDepth.GetMaxDepth(); i++) { mLiquidPhiScaleWorkBound[i].Record(commandBuffer); mLiquidPhis[i].Barrier(commandBuffer, vk::ImageLayout::eGeneral, vk::AccessFlagBits::eShaderWrite, vk::ImageLayout::eGeneral, vk::AccessFlagBits::eShaderRead); mSolidPhiScaleWorkBound[i].Record(commandBuffer); mSolidPhis[i].Barrier(commandBuffer, vk::ImageLayout::eGeneral, vk::AccessFlagBits::eShaderWrite, vk::ImageLayout::eGeneral, vk::AccessFlagBits::eShaderRead); mLiquidPhis[i].ExtrapolateRecord(commandBuffer); mMatrixBuildBound[i].PushConstant(commandBuffer, 8, mDelta); mMatrixBuildBound[i].Record(commandBuffer); mDatas[i].Diagonal.Barrier(commandBuffer, vk::AccessFlagBits::eShaderWrite, vk::AccessFlagBits::eShaderRead); mDatas[i].Lower.Barrier(commandBuffer, vk::AccessFlagBits::eShaderWrite, vk::AccessFlagBits::eShaderRead); mDatas[i].B.Clear(commandBuffer); } std::size_t maxDepth = mDepth.GetMaxDepth(); mMatrixBuildBound[maxDepth - 1].PushConstant(commandBuffer, 8, mDelta); mMatrixBuildBound[maxDepth - 1].Record(commandBuffer); mDatas[maxDepth - 1].Diagonal.Barrier(commandBuffer, vk::AccessFlagBits::eShaderWrite, vk::AccessFlagBits::eShaderRead); mDatas[maxDepth - 1].Lower.Barrier(commandBuffer, vk::AccessFlagBits::eShaderWrite, vk::AccessFlagBits::eShaderRead); }); } void Multigrid::BindRecursive(Pressure& pressure, std::size_t depth) { auto s0 = mDepth.GetDepthSize(depth); if (depth < mDepth.GetMaxDepth()) { auto s1 = mDepth.GetDepthSize(depth + 1); mLiquidPhiScaleWorkBound.push_back(mPhiScaleWork.Bind(s1, {mLiquidPhis[depth - 1], mLiquidPhis[depth]})); mSolidPhiScaleWorkBound.push_back(mPhiScaleWork.Bind(s1, {mSolidPhis[depth - 1], mSolidPhis[depth]})); mResidualWorkBound[depth] = mResidualWork.Bind(s0, {mDatas[depth-1].X, mDatas[depth-1].Diagonal, mDatas[depth-1].Lower, mDatas[depth-1].B, mResiduals[depth]}); mTransfer.InitRestrict(depth, s0, mResiduals[depth], mDatas[depth-1].Diagonal, mDatas[depth].B, mDatas[depth].Diagonal); mTransfer.InitProlongate(depth, s0, mDatas[depth-1].X, mDatas[depth-1].Diagonal, mDatas[depth].X, mDatas[depth].Diagonal); BindRecursive(pressure, depth+1); } mMatrixBuildBound.push_back( pressure.BindMatrixBuild(s0, mDatas[depth-1].Diagonal, mDatas[depth-1].Lower, mLiquidPhis[depth-1], mSolidPhis[depth-1])); mSmoothers[2 * depth] = mDampedJacobi.Bind(s0, {mDatas[depth-1].X, mXs[depth], mDatas[depth-1].Diagonal, mDatas[depth-1].Lower, mDatas[depth-1].B}); mSmoothers[2 * depth + 1] = mDampedJacobi.Bind(s0, {mXs[depth], mDatas[depth-1].X, mDatas[depth-1].Diagonal, mDatas[depth-1].Lower, mDatas[depth-1].B}); } void Multigrid::BuildHierarchies() { mBuildHierarchies.Submit(); } void Multigrid::Smoother(vk::CommandBuffer commandBuffer, int n, int iterations) { float w = 2.0f / 3.0f; int level = n * 2; for (int i = 0; i < iterations; i++) { mSmoothers[level].PushConstant(commandBuffer, 8, w); mSmoothers[level].Record(commandBuffer); mXs[n].Barrier(commandBuffer, vk::AccessFlagBits::eShaderWrite, vk::AccessFlagBits::eShaderRead); mSmoothers[level + 1].PushConstant(commandBuffer, 8, w); mSmoothers[level + 1].Record(commandBuffer); if (n == 0) mPressure->Barrier(commandBuffer, vk::AccessFlagBits::eShaderWrite, vk::AccessFlagBits::eShaderRead); else mDatas[n - 1].X.Barrier(commandBuffer, vk::AccessFlagBits::eShaderWrite, vk::AccessFlagBits::eShaderRead); } } void Multigrid::Record(vk::CommandBuffer commandBuffer) { const int numIterations = 2; if (mEnableStatistics) mStatistics.Start(commandBuffer); assert(mPressure != nullptr); mPressure->Clear(commandBuffer); mXs[0].Clear(commandBuffer); if (mEnableStatistics) mStatistics.Tick(commandBuffer, "clear"); for (int i = 0; i < mDepth.GetMaxDepth(); i++) { Smoother(commandBuffer, i, numIterations); if (mEnableStatistics) mStatistics.Tick(commandBuffer, "smoother " + std::to_string(i)); mResidualWorkBound[i].Record(commandBuffer); mResiduals[i].Barrier(commandBuffer, vk::AccessFlagBits::eShaderWrite, vk::AccessFlagBits::eShaderRead); if (mEnableStatistics) mStatistics.Tick(commandBuffer, "residual " + std::to_string(i)); mTransfer.Restrict(commandBuffer, i); if (mEnableStatistics) mStatistics.Tick(commandBuffer, "transfer " + std::to_string(i)); mDatas[i].X.Clear(commandBuffer); mXs[i].Clear(commandBuffer); if (mEnableStatistics) mStatistics.Tick(commandBuffer, "clear " + std::to_string(i)); } Smoother(commandBuffer, mDepth.GetMaxDepth(), numIterations); if (mEnableStatistics) mStatistics.Tick(commandBuffer, "smoother max"); for (int i = mDepth.GetMaxDepth() - 1; i >= 0; --i) { mTransfer.Prolongate(commandBuffer, i); if (mEnableStatistics) mStatistics.Tick(commandBuffer, "prolongate " + std::to_string(i)); Smoother(commandBuffer, i, numIterations); if (mEnableStatistics) mStatistics.Tick(commandBuffer, "smoother " + std::to_string(i)); } if (mEnableStatistics) mStatistics.End(commandBuffer, "end"); } Renderer::Statistics::Timestamps Multigrid::GetStatistics() { return mStatistics.GetTimestamps(); } }} <|endoftext|>
<commit_before>#include "src/meta/zp_meta_election.h" #include <glog/logging.h> #include "slash/include/env.h" #include "slash/include/slash_string.h" #include "include/zp_const.h" #include "include/zp_conf.h" extern ZpConf* g_zp_conf; const std::string kElectLockKey = "##elect_lock"; const std::string kLeaderKey = "##meta_leader11111"; static bool IsLeaderTimeout(uint64_t last_active, uint64_t timeout) { return last_active + timeout * 1000 > slash::NowMicros(); } ZPMetaElection::ZPMetaElection(floyd::Floyd* f) : floyd_(f) { } ZPMetaElection::~ZPMetaElection() { } Status ZPMetaElection::ReadLeaderRecord(ZPMeta::MetaLeader* cleader) { std::string value; Status s = floyd_->Read(kLeaderKey, &value); if (!s.ok()) { LOG(WARNING) << "Read Leader Key failed: " << s.ToString(); return s; } if (!cleader->ParseFromString(value)) { LOG(WARNING) << "Parse MetaLeader failed," << value << "###"; return Status::Corruption("Parse MetaLeader failed"); } return Status::OK(); } Status ZPMetaElection::WriteLeaderRecord(const ZPMeta::MetaLeader& cleader) { std::string value; // Write back if (!cleader.SerializeToString(&value)) { LOG(WARNING) << "SerializeToString ZPMeta::MetaLeader failed."; return Status::Corruption("Serialize MetaLeader failed"); } Status s = floyd_->Write(kLeaderKey, value); if (!s.ok()) { LOG(WARNING) << "Write MetaLeader failed." << s.ToString(); return s; } return Status::OK(); } bool ZPMetaElection::Jeopardy(std::string* ip, int* port) { if (!last_leader_.IsInitialized() // no last || IsLeaderTimeout(last_leader_.last_active(), // timeout kNodeCronInterval * kNodeCronWaitCount)) { return false; } *ip = last_leader_.leader().ip(); *port = last_leader_.leader().port(); return true; } // Check leader ip and port // return false means faled to check leader for some time bool ZPMetaElection::GetLeader(std::string* ip, int* port) { std::string local_ip = g_zp_conf->local_ip(); int local_port = g_zp_conf->local_port(); std::string mine = slash::IpPortString(local_ip, local_port); // Read first to avoid follower locking everytime ZPMeta::MetaLeader cleader; Status s = ReadLeaderRecord(&cleader); if (!s.ok() && !s.IsNotFound()) { return Jeopardy(ip, port); } else if (s.ok()) { last_leader_.CopyFrom(cleader); if ((local_ip != cleader.leader().ip() || local_port != cleader.leader().port()) && !IsLeaderTimeout(cleader.last_active(), kMetaLeaderTimeout)) { // I'm not leader and current leader is not timeout *ip = cleader.leader().ip(); *port = cleader.leader().port(); return true; } } // Lock and update s = floyd_->TryLock(kElectLockKey, mine, kMetaLeaderLockTimeout * 1000); if (!s.ok()) { LOG(WARNING) << "TryLock ElectLock failed." << s.ToString(); return Jeopardy(ip, port); } cleader.Clear(); s = ReadLeaderRecord(&cleader); if (!s.ok() && !s.IsNotFound()) { LOG(WARNING) << "ReadLeaderRecord after lock failed, Jeopardy then. Error:" << s.ToString(); floyd_->UnLock(kElectLockKey, mine); return Jeopardy(ip, port); } else if (s.ok()) { last_leader_.CopyFrom(cleader); } // 1. NotFound // 2, Ok, leader need refresh timeout // 3, Ok, follwer try elect if (s.IsNotFound() // No leader yet || (cleader.leader().ip() == local_ip && cleader.leader().port() == local_port) // I'm Leader || IsLeaderTimeout(cleader.last_active(), kMetaLeaderTimeout)) { // Old leader timeout // Update cleader.mutable_leader()->set_ip(local_ip); cleader.mutable_leader()->set_port(local_port); cleader.set_last_active(slash::NowMicros()); s = WriteLeaderRecord(cleader); if (s.ok()) { // Refresh cache last_leader_.CopyFrom(cleader); } } *ip = cleader.leader().ip(); *port = cleader.leader().port(); floyd_->UnLock(kElectLockKey, mine); return true; } <commit_msg>fix meta election jeopardy timeout too small problem<commit_after>#include "src/meta/zp_meta_election.h" #include <glog/logging.h> #include "slash/include/env.h" #include "slash/include/slash_string.h" #include "include/zp_const.h" #include "include/zp_conf.h" extern ZpConf* g_zp_conf; const std::string kElectLockKey = "##elect_lock"; const std::string kLeaderKey = "##meta_leader11111"; static bool IsLeaderTimeout(uint64_t last_active, uint64_t timeout) { return last_active + timeout * 1000 > slash::NowMicros(); } ZPMetaElection::ZPMetaElection(floyd::Floyd* f) : floyd_(f) { } ZPMetaElection::~ZPMetaElection() { } Status ZPMetaElection::ReadLeaderRecord(ZPMeta::MetaLeader* cleader) { std::string value; Status s = floyd_->Read(kLeaderKey, &value); if (!s.ok()) { LOG(WARNING) << "Read Leader Key failed: " << s.ToString(); return s; } if (!cleader->ParseFromString(value)) { LOG(WARNING) << "Parse MetaLeader failed," << value << "###"; return Status::Corruption("Parse MetaLeader failed"); } return Status::OK(); } Status ZPMetaElection::WriteLeaderRecord(const ZPMeta::MetaLeader& cleader) { std::string value; // Write back if (!cleader.SerializeToString(&value)) { LOG(WARNING) << "SerializeToString ZPMeta::MetaLeader failed."; return Status::Corruption("Serialize MetaLeader failed"); } Status s = floyd_->Write(kLeaderKey, value); if (!s.ok()) { LOG(WARNING) << "Write MetaLeader failed." << s.ToString(); return s; } return Status::OK(); } bool ZPMetaElection::Jeopardy(std::string* ip, int* port) { if (!last_leader_.IsInitialized()) { // no last LOG(WARNING) << "Jeopardy finished since no last leader"; return false; } uint64_t timeout = kMetaLeaderTimeout; if (last_leader_.leader().ip() == g_zp_conf->local_ip() && last_leader_.leader().port() == g_zp_conf->local_port()) { // Smaller timeout for leader so that it could give up leadership on time // before any follower think it could be leader timeout -= kMetaLeaderRemainThreshold; } if (IsLeaderTimeout(last_leader_.last_active(), timeout)) { LOG(WARNING) << "Jeopardy finished since timeout"; return false; } *ip = last_leader_.leader().ip(); *port = last_leader_.leader().port(); return true; } // Check leader ip and port // return false means faled to check leader for some time bool ZPMetaElection::GetLeader(std::string* ip, int* port) { std::string local_ip = g_zp_conf->local_ip(); int local_port = g_zp_conf->local_port(); std::string mine = slash::IpPortString(local_ip, local_port); // Read first to avoid follower locking everytime ZPMeta::MetaLeader cleader; Status s = ReadLeaderRecord(&cleader); if (!s.ok() && !s.IsNotFound()) { LOG(WARNING) << "pre-ReadLeaderRecord failed: " << s.ToString() << ", check jeopardy"; return Jeopardy(ip, port); } else if (s.ok()) { last_leader_.CopyFrom(cleader); if ((local_ip != cleader.leader().ip() || local_port != cleader.leader().port()) && !IsLeaderTimeout(cleader.last_active(), kMetaLeaderTimeout)) { // I'm not leader and current leader is not timeout *ip = cleader.leader().ip(); *port = cleader.leader().port(); return true; } } // Lock and update s = floyd_->TryLock(kElectLockKey, mine, kMetaLeaderLockTimeout * 1000); if (!s.ok()) { LOG(WARNING) << "TryLock ElectLock failed." << s.ToString(); return Jeopardy(ip, port); } cleader.Clear(); s = ReadLeaderRecord(&cleader); if (!s.ok() && !s.IsNotFound()) { LOG(WARNING) << "ReadLeaderRecord after lock failed, Jeopardy then. Error:" << s.ToString(); floyd_->UnLock(kElectLockKey, mine); LOG(WARNING) << "ReadLeaderRecord failed: " << s.ToString() << ", check jeopardy"; return Jeopardy(ip, port); } else if (s.ok()) { last_leader_.CopyFrom(cleader); } // 1. NotFound // 2, Ok, leader need refresh timeout // 3, Ok, follwer try elect if (s.IsNotFound() // No leader yet || (cleader.leader().ip() == local_ip && cleader.leader().port() == local_port) // I'm Leader || IsLeaderTimeout(cleader.last_active(), kMetaLeaderTimeout)) { // Old leader timeout if (cleader.leader().ip() != local_ip || cleader.leader().port() != local_port) { LOG(INFO) << "Take over the leadership, since: " << (s.IsNotFound() ? "no leader record" : "old leader timeout"); } // Update cleader.mutable_leader()->set_ip(local_ip); cleader.mutable_leader()->set_port(local_port); cleader.set_last_active(slash::NowMicros()); s = WriteLeaderRecord(cleader); if (s.ok()) { // Refresh cache last_leader_.CopyFrom(cleader); } } *ip = cleader.leader().ip(); *port = cleader.leader().port(); floyd_->UnLock(kElectLockKey, mine); return true; } <|endoftext|>
<commit_before>/* This file is part of the Pangolin Project. * http://github.com/stevenlovegrove/Pangolin * * Copyright (c) 2015 Steven Lovegrove * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without * restriction, including without limitation the rights to use, * copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following * conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR * OTHER DEALINGS IN THE SOFTWARE. */ #include <pangolin/video/drivers/pleora.h> namespace pangolin { template<typename T> struct PleoraParamTraits; template<> struct PleoraParamTraits<bool> { typedef PvGenBoolean PvType; }; template<> struct PleoraParamTraits<int64_t> { typedef PvGenInteger PvType; }; template<> struct PleoraParamTraits<float> { typedef PvGenFloat PvType; }; template<> struct PleoraParamTraits<std::string> { typedef PvGenString PvType; }; template<typename T> T GetParam(PvGenParameterArray* params, const char* name) { typedef typename PleoraParamTraits<T>::PvType PvType; PvType* param = dynamic_cast<PvType*>( params->Get(name) ); if(!param) { throw std::runtime_error("Incorrect type"); } T ret; PvResult res = param->GetValue(ret); if(res.IsFailure()) { throw std::runtime_error(res.GetCodeString().GetAscii()); } return ret; } inline const PvDeviceInfo* SelectDevice( PvSystem& aSystem, const char* model_name = 0, const char* serial_num = 0, size_t index = 0 ) { aSystem.Find(); // Enumerate all devices, select first that matches criteria size_t matches = 0; for ( uint32_t i = 0; i < aSystem.GetInterfaceCount(); i++ ) { const PvInterface *lInterface = dynamic_cast<const PvInterface *>( aSystem.GetInterface( i ) ); if ( lInterface ) { for ( uint32_t j = 0; j < lInterface->GetDeviceCount(); j++ ) { const PvDeviceInfo *lDI = dynamic_cast<const PvDeviceInfo *>( lInterface->GetDeviceInfo( j ) ); if ( lDI && lDI->IsConfigurationValid() ) { if( model_name && strcmp(lDI->GetModelName().GetAscii(), model_name) ) continue; if( serial_num && strcmp(lDI->GetSerialNumber().GetAscii(), serial_num) ) continue; if(matches == index) { return lDI; } ++matches; } } } } return 0; } VideoPixelFormat PleoraFormat(const PvGenEnum* pfmt) { std::string spfmt = pfmt->ToString().GetAscii(); if( !spfmt.compare("Mono8") ) { return VideoFormatFromString("GRAY8"); }else if( !spfmt.compare("Mono10p") ) { return VideoFormatFromString("GRAY10"); }else if( !spfmt.compare("Mono12p") ) { return VideoFormatFromString("GRAY12"); }else{ throw VideoException("Unknown Pleora pixel format", spfmt); } } PleoraVideo::PleoraVideo(const char* model_name, const char* serial_num, size_t index, size_t bpp, size_t buffer_count) : lPvSystem(0), lDevice(0), lStream(0) { lPvSystem = new PvSystem(); if ( !lPvSystem ) { throw pangolin::VideoException("Pleora: Unable to create PvSystem"); } const PvDeviceInfo *lDeviceInfo = SelectDevice(*lPvSystem, model_name, serial_num, index); if ( !lDeviceInfo ) { throw pangolin::VideoException("Pleora: Unable to select device"); } PvResult lResult; lDevice = PvDevice::CreateAndConnect( lDeviceInfo, &lResult ); if ( !lDevice ) { throw pangolin::VideoException("Pleora: Unable to connect to device", lResult.GetDescription().GetAscii() ); } lStream = PvStream::CreateAndOpen( lDeviceInfo->GetConnectionID(), &lResult ); if ( !lStream ) { throw pangolin::VideoException("Pleora: Unable to open stream", lResult.GetDescription().GetAscii() ); } lDeviceParams = lDevice->GetParameters(); lStart = dynamic_cast<PvGenCommand*>( lDeviceParams->Get( "AcquisitionStart" ) ); lStop = dynamic_cast<PvGenCommand*>( lDeviceParams->Get( "AcquisitionStop" ) ); if( bpp == 8) { lDeviceParams->SetEnumValue("PixelFormat", PvString("Mono8") ); }else if(bpp == 10) { lDeviceParams->SetEnumValue("PixelFormat", PvString("Mono10p") ); }else if(bpp == 12) { lDeviceParams->SetEnumValue("PixelFormat", PvString("Mono12p") ); } lStreamParams = lStream->GetParameters(); // Reading payload size from device const uint32_t lSize = lDevice->GetPayloadSize(); // Use buffer_count or the maximum number of buffers, whichever is smaller const uint32_t lBufferCount = ( lStream->GetQueuedBufferMaximum() < buffer_count ) ? lStream->GetQueuedBufferMaximum() : buffer_count; // Allocate buffers and queue for ( uint32_t i = 0; i < lBufferCount; i++ ) { PvBuffer *lBuffer = new PvBuffer; lBuffer->Alloc( static_cast<uint32_t>( lSize ) ); lBufferList.push_back( lBuffer ); } const int w = DeviceParam<int64_t>("Width"); const int h = DeviceParam<int64_t>("Height"); // Setup pangolin for stream PvGenEnum* lpixfmt = dynamic_cast<PvGenEnum*>( lDeviceParams->Get("PixelFormat") ); const VideoPixelFormat fmt = PleoraFormat(lpixfmt); streams.push_back(StreamInfo(fmt, w, h, (w*fmt.bpp)/8)); size_bytes = lSize; Start(); } PleoraVideo::~PleoraVideo() { Stop(); // Free buffers for( BufferList::iterator lIt = lBufferList.begin(); lIt != lBufferList.end(); lIt++ ) { delete *lIt; } if(lStream) { lStream->Close(); PvStream::Free( lStream ); } if(lDevice) { lDevice->Disconnect(); PvDevice::Free( lDevice ); } delete lPvSystem; } void PleoraVideo::Start() { // Queue all buffers in the stream for( BufferList::iterator lIt = lBufferList.begin(); lIt != lBufferList.end(); lIt++ ) { lStream->QueueBuffer( *lIt ); } lDevice->StreamEnable(); lStart->Execute(); } void PleoraVideo::Stop() { lStop->Execute(); lDevice->StreamDisable(); // Abort all buffers from the stream and dequeue lStream->AbortQueuedBuffers(); while ( lStream->GetQueuedBufferCount() > 0 ) { PvBuffer *lBuffer = NULL; PvResult lOperationResult; lStream->RetrieveBuffer( &lBuffer, &lOperationResult ); } } size_t PleoraVideo::SizeBytes() const { return size_bytes; } const std::vector<StreamInfo>& PleoraVideo::Streams() const { return streams; } bool PleoraVideo::GrabNext( unsigned char* image, bool /*wait*/ ) { PvBuffer *lBuffer = NULL; PvResult lOperationResult; // Retrieve next buffer PvResult lResult = lStream->RetrieveBuffer( &lBuffer, &lOperationResult, 1000 ); if ( !lResult.IsOK() ) { pango_print_warn("Pleora error: %s\n", lResult.GetCodeString().GetAscii() ); return false; } bool good = false; if ( lOperationResult.IsOK() ) { PvPayloadType lType = lBuffer->GetPayloadType(); if ( lType == PvPayloadTypeImage ) { PvImage *lImage = lBuffer->GetImage(); std::memcpy(image, lImage->GetDataPointer(), size_bytes); good = true; } } else { pango_print_warn("Pleora error: %s\n", lOperationResult.GetCodeString().GetAscii() ); } lStream->QueueBuffer( lBuffer ); return good; } bool PleoraVideo::GrabNewest( unsigned char* image, bool wait ) { PvBuffer *lBuffer0 = NULL; PvBuffer *lBuffer = NULL; PvResult lOperationResult; const uint32_t timeout = wait ? 0xFFFFFFFF : 0; PvResult lResult = lStream->RetrieveBuffer( &lBuffer, &lOperationResult, timeout ); if ( !lResult.IsOK() ) { pango_print_warn("Pleora error: %s\n", lResult.GetCodeString().GetAscii() ); return false; }else if( !lOperationResult.IsOK() ) { pango_print_warn("Pleora error: %s\n", lOperationResult.GetCodeString().GetAscii() ); lStream->QueueBuffer( lBuffer ); return false; } // We have at least one frame. Capture more until we fail, 0 timeout while(true) { PvResult lResult = lStream->RetrieveBuffer( &lBuffer0, &lOperationResult, 0 ); if ( !lResult.IsOK() ) { break; }else if( !lOperationResult.IsOK() ) { lStream->QueueBuffer( lBuffer0 ); break; }else{ lStream->QueueBuffer( lBuffer ); lBuffer = lBuffer0; } } bool good = false; PvPayloadType lType = lBuffer->GetPayloadType(); if ( lType == PvPayloadTypeImage ) { PvImage *lImage = lBuffer->GetImage(); std::memcpy(image, lImage->GetDataPointer(), size_bytes); good = true; } lStream->QueueBuffer( lBuffer ); return good; } template<typename T> T PleoraVideo::DeviceParam(const char* name) { return GetParam<T>(lDeviceParams, name); } template<typename T> T PleoraVideo::StreamParam(const char* name) { return GetParam<T>(lStreamParams, name); } } <commit_msg>Pleora: Free lDevice if stream fails to open.<commit_after>/* This file is part of the Pangolin Project. * http://github.com/stevenlovegrove/Pangolin * * Copyright (c) 2015 Steven Lovegrove * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without * restriction, including without limitation the rights to use, * copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following * conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR * OTHER DEALINGS IN THE SOFTWARE. */ #include <pangolin/video/drivers/pleora.h> namespace pangolin { template<typename T> struct PleoraParamTraits; template<> struct PleoraParamTraits<bool> { typedef PvGenBoolean PvType; }; template<> struct PleoraParamTraits<int64_t> { typedef PvGenInteger PvType; }; template<> struct PleoraParamTraits<float> { typedef PvGenFloat PvType; }; template<> struct PleoraParamTraits<std::string> { typedef PvGenString PvType; }; template<typename T> T GetParam(PvGenParameterArray* params, const char* name) { typedef typename PleoraParamTraits<T>::PvType PvType; PvType* param = dynamic_cast<PvType*>( params->Get(name) ); if(!param) { throw std::runtime_error("Incorrect type"); } T ret; PvResult res = param->GetValue(ret); if(res.IsFailure()) { throw std::runtime_error(res.GetCodeString().GetAscii()); } return ret; } inline const PvDeviceInfo* SelectDevice( PvSystem& aSystem, const char* model_name = 0, const char* serial_num = 0, size_t index = 0 ) { aSystem.Find(); // Enumerate all devices, select first that matches criteria size_t matches = 0; for ( uint32_t i = 0; i < aSystem.GetInterfaceCount(); i++ ) { const PvInterface *lInterface = dynamic_cast<const PvInterface *>( aSystem.GetInterface( i ) ); if ( lInterface ) { for ( uint32_t j = 0; j < lInterface->GetDeviceCount(); j++ ) { const PvDeviceInfo *lDI = dynamic_cast<const PvDeviceInfo *>( lInterface->GetDeviceInfo( j ) ); if ( lDI && lDI->IsConfigurationValid() ) { if( model_name && strcmp(lDI->GetModelName().GetAscii(), model_name) ) continue; if( serial_num && strcmp(lDI->GetSerialNumber().GetAscii(), serial_num) ) continue; if(matches == index) { return lDI; } ++matches; } } } } return 0; } VideoPixelFormat PleoraFormat(const PvGenEnum* pfmt) { std::string spfmt = pfmt->ToString().GetAscii(); if( !spfmt.compare("Mono8") ) { return VideoFormatFromString("GRAY8"); }else if( !spfmt.compare("Mono10p") ) { return VideoFormatFromString("GRAY10"); }else if( !spfmt.compare("Mono12p") ) { return VideoFormatFromString("GRAY12"); }else{ throw VideoException("Unknown Pleora pixel format", spfmt); } } PleoraVideo::PleoraVideo(const char* model_name, const char* serial_num, size_t index, size_t bpp, size_t buffer_count) : lPvSystem(0), lDevice(0), lStream(0) { lPvSystem = new PvSystem(); if ( !lPvSystem ) { throw pangolin::VideoException("Pleora: Unable to create PvSystem"); } const PvDeviceInfo *lDeviceInfo = SelectDevice(*lPvSystem, model_name, serial_num, index); if ( !lDeviceInfo ) { throw pangolin::VideoException("Pleora: Unable to select device"); } PvResult lResult; lDevice = PvDevice::CreateAndConnect( lDeviceInfo, &lResult ); if ( !lDevice ) { throw pangolin::VideoException("Pleora: Unable to connect to device", lResult.GetDescription().GetAscii() ); } lStream = PvStream::CreateAndOpen( lDeviceInfo->GetConnectionID(), &lResult ); if ( !lStream ) { lDevice->Disconnect(); PvDevice::Free(lDevice); throw pangolin::VideoException("Pleora: Unable to open stream", lResult.GetDescription().GetAscii() ); } lDeviceParams = lDevice->GetParameters(); lStart = dynamic_cast<PvGenCommand*>( lDeviceParams->Get( "AcquisitionStart" ) ); lStop = dynamic_cast<PvGenCommand*>( lDeviceParams->Get( "AcquisitionStop" ) ); if( bpp == 8) { lDeviceParams->SetEnumValue("PixelFormat", PvString("Mono8") ); }else if(bpp == 10) { lDeviceParams->SetEnumValue("PixelFormat", PvString("Mono10p") ); }else if(bpp == 12) { lDeviceParams->SetEnumValue("PixelFormat", PvString("Mono12p") ); } lStreamParams = lStream->GetParameters(); // Reading payload size from device const uint32_t lSize = lDevice->GetPayloadSize(); // Use buffer_count or the maximum number of buffers, whichever is smaller const uint32_t lBufferCount = ( lStream->GetQueuedBufferMaximum() < buffer_count ) ? lStream->GetQueuedBufferMaximum() : buffer_count; // Allocate buffers and queue for ( uint32_t i = 0; i < lBufferCount; i++ ) { PvBuffer *lBuffer = new PvBuffer; lBuffer->Alloc( static_cast<uint32_t>( lSize ) ); lBufferList.push_back( lBuffer ); } const int w = DeviceParam<int64_t>("Width"); const int h = DeviceParam<int64_t>("Height"); // Setup pangolin for stream PvGenEnum* lpixfmt = dynamic_cast<PvGenEnum*>( lDeviceParams->Get("PixelFormat") ); const VideoPixelFormat fmt = PleoraFormat(lpixfmt); streams.push_back(StreamInfo(fmt, w, h, (w*fmt.bpp)/8)); size_bytes = lSize; Start(); } PleoraVideo::~PleoraVideo() { Stop(); // Free buffers for( BufferList::iterator lIt = lBufferList.begin(); lIt != lBufferList.end(); lIt++ ) { delete *lIt; } if(lStream) { lStream->Close(); PvStream::Free( lStream ); } if(lDevice) { lDevice->Disconnect(); PvDevice::Free( lDevice ); } delete lPvSystem; } void PleoraVideo::Start() { // Queue all buffers in the stream for( BufferList::iterator lIt = lBufferList.begin(); lIt != lBufferList.end(); lIt++ ) { lStream->QueueBuffer( *lIt ); } lDevice->StreamEnable(); lStart->Execute(); } void PleoraVideo::Stop() { lStop->Execute(); lDevice->StreamDisable(); // Abort all buffers from the stream and dequeue lStream->AbortQueuedBuffers(); while ( lStream->GetQueuedBufferCount() > 0 ) { PvBuffer *lBuffer = NULL; PvResult lOperationResult; lStream->RetrieveBuffer( &lBuffer, &lOperationResult ); } } size_t PleoraVideo::SizeBytes() const { return size_bytes; } const std::vector<StreamInfo>& PleoraVideo::Streams() const { return streams; } bool PleoraVideo::GrabNext( unsigned char* image, bool /*wait*/ ) { PvBuffer *lBuffer = NULL; PvResult lOperationResult; // Retrieve next buffer PvResult lResult = lStream->RetrieveBuffer( &lBuffer, &lOperationResult, 1000 ); if ( !lResult.IsOK() ) { pango_print_warn("Pleora error: %s\n", lResult.GetCodeString().GetAscii() ); return false; } bool good = false; if ( lOperationResult.IsOK() ) { PvPayloadType lType = lBuffer->GetPayloadType(); if ( lType == PvPayloadTypeImage ) { PvImage *lImage = lBuffer->GetImage(); std::memcpy(image, lImage->GetDataPointer(), size_bytes); good = true; } } else { pango_print_warn("Pleora error: %s\n", lOperationResult.GetCodeString().GetAscii() ); } lStream->QueueBuffer( lBuffer ); return good; } bool PleoraVideo::GrabNewest( unsigned char* image, bool wait ) { PvBuffer *lBuffer0 = NULL; PvBuffer *lBuffer = NULL; PvResult lOperationResult; const uint32_t timeout = wait ? 0xFFFFFFFF : 0; PvResult lResult = lStream->RetrieveBuffer( &lBuffer, &lOperationResult, timeout ); if ( !lResult.IsOK() ) { pango_print_warn("Pleora error: %s\n", lResult.GetCodeString().GetAscii() ); return false; }else if( !lOperationResult.IsOK() ) { pango_print_warn("Pleora error: %s\n", lOperationResult.GetCodeString().GetAscii() ); lStream->QueueBuffer( lBuffer ); return false; } // We have at least one frame. Capture more until we fail, 0 timeout while(true) { PvResult lResult = lStream->RetrieveBuffer( &lBuffer0, &lOperationResult, 0 ); if ( !lResult.IsOK() ) { break; }else if( !lOperationResult.IsOK() ) { lStream->QueueBuffer( lBuffer0 ); break; }else{ lStream->QueueBuffer( lBuffer ); lBuffer = lBuffer0; } } bool good = false; PvPayloadType lType = lBuffer->GetPayloadType(); if ( lType == PvPayloadTypeImage ) { PvImage *lImage = lBuffer->GetImage(); std::memcpy(image, lImage->GetDataPointer(), size_bytes); good = true; } lStream->QueueBuffer( lBuffer ); return good; } template<typename T> T PleoraVideo::DeviceParam(const char* name) { return GetParam<T>(lDeviceParams, name); } template<typename T> T PleoraVideo::StreamParam(const char* name) { return GetParam<T>(lStreamParams, name); } } <|endoftext|>
<commit_before>/*ckwg +5 * Copyright 2011-2012 by Kitware, Inc. All Rights Reserved. Please refer to * KITWARE_LICENSE.TXT for licensing information, or contact General Counsel, * Kitware, Inc., 28 Corporate Drive, Clifton Park, NY 12065. */ #include "datum.h" #include <sstream> /** * \file datum.cxx * * \brief Implementation of a piece of \link vistk::datum data\endlink in the pipeline. */ namespace vistk { datum_t datum::new_datum(boost::any const& dat) { return datum_t(new datum(dat)); } datum_t datum ::empty_datum() { return datum_t(new datum(empty)); } datum_t datum ::flush_datum() { return datum_t(new datum(flush)); } datum_t datum ::complete_datum() { return datum_t(new datum(complete)); } datum_t datum ::error_datum(error_t const& error) { return datum_t(new datum(error)); } datum::type_t datum ::type() const { return m_type; } datum::error_t datum ::get_error() const { return m_error; } datum ::datum(type_t ty) : m_type(ty) , m_error() , m_datum() { } datum ::datum(error_t const& err) : m_type(error) , m_error(err) , m_datum() { } datum ::datum(boost::any const& dat) : m_type(data) , m_error() , m_datum(dat) { } datum_exception ::datum_exception() throw() : pipeline_exception() { } datum_exception ::~datum_exception() throw() { } bad_datum_cast_exception ::bad_datum_cast_exception(std::string const& typeid_, datum::type_t const& type, datum::error_t const& error, char const* reason) throw() : datum_exception() , m_typeid(typeid_) , m_type(type) , m_error(error) , m_reason(reason) { std::ostringstream sstr; if (m_type == datum::error) { sstr << "Failed to cast datum of type " "\'" << m_type << "\' (" << m_error << ") into " << m_typeid << ": " << m_reason << "."; } else { sstr << "Failed to cast datum of type " "\'" << m_type << "\' into " << m_typeid << ": " << m_reason << "."; } m_what = sstr.str(); } bad_datum_cast_exception ::~bad_datum_cast_exception() throw() { } } <commit_msg>Output strings instead of integers<commit_after>/*ckwg +5 * Copyright 2011-2012 by Kitware, Inc. All Rights Reserved. Please refer to * KITWARE_LICENSE.TXT for licensing information, or contact General Counsel, * Kitware, Inc., 28 Corporate Drive, Clifton Park, NY 12065. */ #include "datum.h" #include <sstream> /** * \file datum.cxx * * \brief Implementation of a piece of \link vistk::datum data\endlink in the pipeline. */ namespace vistk { datum_t datum::new_datum(boost::any const& dat) { return datum_t(new datum(dat)); } datum_t datum ::empty_datum() { return datum_t(new datum(empty)); } datum_t datum ::flush_datum() { return datum_t(new datum(flush)); } datum_t datum ::complete_datum() { return datum_t(new datum(complete)); } datum_t datum ::error_datum(error_t const& error) { return datum_t(new datum(error)); } datum::type_t datum ::type() const { return m_type; } datum::error_t datum ::get_error() const { return m_error; } datum ::datum(type_t ty) : m_type(ty) , m_error() , m_datum() { } datum ::datum(error_t const& err) : m_type(error) , m_error(err) , m_datum() { } datum ::datum(boost::any const& dat) : m_type(data) , m_error() , m_datum(dat) { } datum_exception ::datum_exception() throw() : pipeline_exception() { } datum_exception ::~datum_exception() throw() { } static char const* string_for_type(datum::type_t type); bad_datum_cast_exception ::bad_datum_cast_exception(std::string const& typeid_, datum::type_t const& type, datum::error_t const& error, char const* reason) throw() : datum_exception() , m_typeid(typeid_) , m_type(type) , m_error(error) , m_reason(reason) { std::ostringstream sstr; if (m_type == datum::error) { sstr << "Failed to cast datum of type " "\'" << string_for_type(m_type) << "\' (" << m_error << ") into " << m_typeid << ": " << m_reason << "."; } else { sstr << "Failed to cast datum of type " "\'" << string_for_type(m_type) << "\' into " << m_typeid << ": " << m_reason << "."; } m_what = sstr.str(); } bad_datum_cast_exception ::~bad_datum_cast_exception() throw() { } char const* string_for_type(datum::type_t type) { switch (type) { #define STRING_FOR_TYPE(type) \ case datum::type: \ return #type STRING_FOR_TYPE(data); STRING_FOR_TYPE(empty); STRING_FOR_TYPE(error); STRING_FOR_TYPE(invalid); STRING_FOR_TYPE(flush); STRING_FOR_TYPE(complete); #undef STRING_FOR_TYPE default: break; } return "unknown"; } } <|endoftext|>
<commit_before>/*ckwg +5 * Copyright 2011 by Kitware, Inc. All Rights Reserved. Please refer to * KITWARE_LICENSE.TXT for licensing information, or contact General Counsel, * Kitware, Inc., 28 Corporate Drive, Clifton Park, NY 12065. */ #include "datum.h" #include <sstream> /** * \file datum.cxx * * \brief Implementation of a piece of \link vistk::datum data\endlink in the pipeline. */ namespace vistk { datum_t datum ::empty_datum() { return datum_t(new datum(false)); } datum_t datum ::complete_datum() { return datum_t(new datum(true)); } datum_t datum ::error_datum(error_t const& error) { return datum_t(new datum(error)); } datum::datum_type_t datum ::type() const { return m_type; } datum::error_t datum ::get_error() const { return m_error; } datum ::datum(bool is_complete) : m_type(is_complete ? DATUM_EMPTY : DATUM_COMPLETE) { } datum ::datum(error_t const& error) : m_type(DATUM_ERROR) , m_error(error) { } datum ::datum(boost::any const& dat) : m_type(DATUM_DATA) , m_datum(dat) { } bad_datum_cast_exception ::bad_datum_cast_exception(datum::datum_type_t const& type, char const* reason) throw() : datum_exception() , m_type(type) , m_reason(reason) { std::ostringstream sstr; sstr << "Failed to cast key datum of type " << "\'" << m_type << "\': " << m_reason << "."; m_what = sstr.str(); } bad_datum_cast_exception ::~bad_datum_cast_exception() throw() { } char const* bad_datum_cast_exception ::what() const throw() { return m_what.c_str(); } } <commit_msg>Flip backwards logic around<commit_after>/*ckwg +5 * Copyright 2011 by Kitware, Inc. All Rights Reserved. Please refer to * KITWARE_LICENSE.TXT for licensing information, or contact General Counsel, * Kitware, Inc., 28 Corporate Drive, Clifton Park, NY 12065. */ #include "datum.h" #include <sstream> /** * \file datum.cxx * * \brief Implementation of a piece of \link vistk::datum data\endlink in the pipeline. */ namespace vistk { datum_t datum ::empty_datum() { return datum_t(new datum(false)); } datum_t datum ::complete_datum() { return datum_t(new datum(true)); } datum_t datum ::error_datum(error_t const& error) { return datum_t(new datum(error)); } datum::datum_type_t datum ::type() const { return m_type; } datum::error_t datum ::get_error() const { return m_error; } datum ::datum(bool is_complete) : m_type(is_complete ? DATUM_COMPLETE : DATUM_EMPTY) { } datum ::datum(error_t const& error) : m_type(DATUM_ERROR) , m_error(error) { } datum ::datum(boost::any const& dat) : m_type(DATUM_DATA) , m_datum(dat) { } bad_datum_cast_exception ::bad_datum_cast_exception(datum::datum_type_t const& type, char const* reason) throw() : datum_exception() , m_type(type) , m_reason(reason) { std::ostringstream sstr; sstr << "Failed to cast key datum of type " << "\'" << m_type << "\': " << m_reason << "."; m_what = sstr.str(); } bad_datum_cast_exception ::~bad_datum_cast_exception() throw() { } char const* bad_datum_cast_exception ::what() const throw() { return m_what.c_str(); } } <|endoftext|>
<commit_before>#include "replayState.h" #include <deque> #include <boost/bind.hpp> #include <boost/thread.hpp> #include "libwatcher/message.h" #include "serverConnection.h" #include "Assert.h" #include "database.h" #include "watcherd.h" using namespace util; using namespace watcher; using namespace watcher::event; //< default value for number of events to prefetch from the database const unsigned int DEFAULT_BUFFER_SIZE = 20U; /* db rows */ const unsigned int DEFAULT_STEP = 250U /* ms */; /** Internal structure used for implementing the class. Used to avoid * dependencies for the user of the class. These would normally be private * members of ReplayState. */ struct ReplayState::impl { boost::weak_ptr<ServerConnection> conn; std::deque<MessagePtr> events; boost::asio::deadline_timer timer; Timestamp ts; // the current effective time Timestamp last_event; // timestamp of last event retrieved from db float speed; //< playback speed unsigned int bufsiz; //< number of database rows to prefetch Timestamp step; enum run_state { paused, running } state; timeval wall_time; //< used to correct for clock skew Timestamp delta; /* * Lock used for event queue. This is required due to the seek() member * function, which can be called from a different thread. */ boost::mutex lock; impl(ServerConnectionPtr& ptr) : conn(ptr), timer(ptr->io_service()), ts(0), last_event(0), bufsiz(DEFAULT_BUFFER_SIZE), step(DEFAULT_STEP), state(paused), delta(0) { TRACE_ENTER(); wall_time.tv_sec = 0; wall_time.tv_usec = 0; TRACE_EXIT(); } }; ReplayState::ReplayState(ServerConnectionPtr ptr, Timestamp t, float playback_speed) : impl_(new impl(ptr)) { TRACE_ENTER(); Assert<Bad_arg>(t >= 0); impl_->ts = t; impl_->last_event = t; speed(playback_speed); TRACE_EXIT(); } Timestamp ReplayState::tell() const { TRACE_ENTER(); TRACE_EXIT_RET(impl_->ts); return impl_->ts; } ReplayState& ReplayState::pause() { TRACE_ENTER(); LOG_DEBUG("cancelling timer"); impl_->timer.cancel(); impl_->state = impl::paused; TRACE_EXIT(); return *this; } ReplayState& ReplayState::seek(Timestamp t) { TRACE_ENTER(); impl::run_state oldstate; { boost::mutex::scoped_lock L(impl_->lock); oldstate = impl_->state; pause(); impl_->events.clear(); impl_->ts = t; if (t == -1) impl_->last_event = std::numeric_limits<Timestamp>::max(); else impl_->last_event = t; } if (oldstate == impl::running) run(); TRACE_EXIT(); return *this; } ReplayState& ReplayState::speed(float f) { TRACE_ENTER(); Assert<Bad_arg>(f != 0); /* If speed changes direction, need to clear the event list. * Check for sign change by noting that positive*negative==negative */ if (impl_->speed * f < 0) { impl::run_state oldstate; { boost::mutex::scoped_lock L(impl_->lock); oldstate = impl_->state; pause(); impl_->events.clear(); /* * Avoid setting .last_event when SpeedMessage is received * prior to the first StartMessage. */ if (impl_->ts != 0 && impl_->ts != -1) impl_->last_event = impl_->ts; impl_->speed = f; } if (oldstate == impl::running) run(); } else impl_->speed = f; LOG_DEBUG("ts=" << impl_->ts << " last_event=" << impl_->last_event); TRACE_EXIT(); return *this; } ReplayState& ReplayState::buffer_size(unsigned int n) { TRACE_ENTER(); Assert<Bad_arg>(n != 0); impl_->bufsiz = n; TRACE_EXIT(); return *this; } ReplayState& ReplayState::time_step(unsigned int n) { TRACE_ENTER(); Assert<Bad_arg>(n != 0); impl_->step = n; TRACE_EXIT(); return *this; } /* function object for accepting events output from Database::getEvents() */ struct event_output { std::deque<MessagePtr>& q; event_output(std::deque<MessagePtr>& qq) : q(qq) {} void operator() (MessagePtr m) { q.push_back(m); } }; /** Schedule an asynchronous task to replay events from the database to a GUI * client. If the local cache of upcoming events is empty, prefetch a block of * events from the database. * * The code is written such that it will work when playing events forward or in * reverse. */ void ReplayState::run() { TRACE_ENTER(); boost::mutex::scoped_lock L(impl_->lock); if (impl_->events.empty()) { // queue is empty, pre-fetch more items from the DB boost::function<void(MessagePtr)> cb(event_output(impl_->events)); LOG_DEBUG("fetching events " << (impl_->speed > 0 ? "> " : "< ") << impl_->last_event); get_db_handle().getEvents(cb, impl_->last_event, (impl_->speed >= 0) ? Database::forward : Database::reverse, impl_->bufsiz); if (!impl_->events.empty()) { LOG_DEBUG("got " << impl_->events.size() << " events from the db query"); /* When starting to replay, assume that time T=0 is the time of the * first event in the stream. * T= -1 is EOF. * Convert to timestamp of first item in the returned events. * * When playing in reverse, the first item in the list is the last event in the database. */ if (impl_->ts == 0 || impl_->ts == -1) impl_->ts = impl_->events.front()->timestamp; // save timestamp of last event retrieved to avoid duplication impl_->last_event = impl_->events.back()->timestamp; } } if (! impl_->events.empty()) { /* * Calculate for the skew introduced by the time required to process the events. Skew is calculated * as the difference between the actual time taken and the expected time. This gets * subtracted from the wait for the next event to catch up. */ timeval tv; gettimeofday(&tv, 0); Timestamp skew = (tv.tv_sec - impl_->wall_time.tv_sec) * 1000 + (tv.tv_usec - impl_->wall_time.tv_usec) / 1000; skew -= impl_->delta; LOG_DEBUG("calculated skew of " << skew << " ms"); memcpy(&impl_->wall_time, &tv, sizeof(tv)); // time until next event impl_->delta = impl_->events.front()->timestamp - impl_->ts; // update our notion of the current time after the timer expires impl_->ts = impl_->events.front()->timestamp; /* Adjust for playback speed. Note that when playing events in reverse, both speed * delta will be negative, which will turn delta into a positive value for the * async_wait() call, which is exactly what is required. */ impl_->delta /= (Timestamp)impl_->speed; /* Correct for skew */ impl_->delta -= skew; if (impl_->delta < 0) impl_->delta = 0; LOG_DEBUG("Next event in " << impl_->delta << " ms"); impl_->timer.expires_from_now(boost::posix_time::millisec(impl_->delta)); impl_->timer.async_wait(boost::bind(&ReplayState::timer_handler, shared_from_this(), boost::asio::placeholders::error)); impl_->state = impl::running; } else { /* * FIXME what should happen when the end of the event stream is reached? * One option would be to convert to live stream at this point. */ LOG_DEBUG("reached end of database, pausing playback"); impl_->state = impl::paused; } TRACE_EXIT(); } /** Replay events to a GUI client when a timer expires. * * The run() member function is reponsible for prefetching events from the * database and storing them in the class object. When a timer expires, run * through the locally stored events and send those that occurred within the * last time slice. The task is then rescheduled when the next most recent * event needs to be transmitted. */ void ReplayState::timer_handler(const boost::system::error_code& ec) { TRACE_ENTER(); if (ec == boost::asio::error::operation_aborted) LOG_DEBUG("timer was cancelled"); else if (impl_->state == impl::paused) { LOG_DEBUG("timer expired but state is paused!"); } else { std::vector<MessagePtr> msgs; { boost::mutex::scoped_lock L(impl_->lock); while (! impl_->events.empty()) { MessagePtr m = impl_->events.front(); /* Replay all events in the current time step. Use the absolute value * of the difference in order for forward and reverse replay to work * properly. */ if (abs(m->timestamp - impl_->ts) >= impl_->step) break; msgs.push_back(m); impl_->events.pop_front(); } } ServerConnectionPtr srv = impl_->conn.lock(); if (srv) { /* connection is still alive */ srv->sendMessage(msgs); run(); // reschedule this task } } TRACE_EXIT(); } /* This is required to be defined, otherwise a the default dtor will cause a * compiler error due to use of scoped_ptr with an incomplete type. */ ReplayState::~ReplayState() { TRACE_ENTER(); TRACE_EXIT(); } float ReplayState::speed() const { return impl_->speed; } <commit_msg>do correct casting.<commit_after>#include "replayState.h" #include <deque> #include <boost/bind.hpp> #include <boost/thread.hpp> #include "libwatcher/message.h" #include "serverConnection.h" #include "Assert.h" #include "database.h" #include "watcherd.h" using namespace util; using namespace watcher; using namespace watcher::event; //< default value for number of events to prefetch from the database const unsigned int DEFAULT_BUFFER_SIZE = 20U; /* db rows */ const unsigned int DEFAULT_STEP = 250U /* ms */; /** Internal structure used for implementing the class. Used to avoid * dependencies for the user of the class. These would normally be private * members of ReplayState. */ struct ReplayState::impl { boost::weak_ptr<ServerConnection> conn; std::deque<MessagePtr> events; boost::asio::deadline_timer timer; Timestamp ts; // the current effective time Timestamp last_event; // timestamp of last event retrieved from db float speed; //< playback speed unsigned int bufsiz; //< number of database rows to prefetch Timestamp step; enum run_state { paused, running } state; timeval wall_time; //< used to correct for clock skew Timestamp delta; /* * Lock used for event queue. This is required due to the seek() member * function, which can be called from a different thread. */ boost::mutex lock; impl(ServerConnectionPtr& ptr) : conn(ptr), timer(ptr->io_service()), ts(0), last_event(0), bufsiz(DEFAULT_BUFFER_SIZE), step(DEFAULT_STEP), state(paused), delta(0) { TRACE_ENTER(); wall_time.tv_sec = 0; wall_time.tv_usec = 0; TRACE_EXIT(); } }; ReplayState::ReplayState(ServerConnectionPtr ptr, Timestamp t, float playback_speed) : impl_(new impl(ptr)) { TRACE_ENTER(); Assert<Bad_arg>(t >= 0); impl_->ts = t; impl_->last_event = t; speed(playback_speed); TRACE_EXIT(); } Timestamp ReplayState::tell() const { TRACE_ENTER(); TRACE_EXIT_RET(impl_->ts); return impl_->ts; } ReplayState& ReplayState::pause() { TRACE_ENTER(); LOG_DEBUG("cancelling timer"); impl_->timer.cancel(); impl_->state = impl::paused; TRACE_EXIT(); return *this; } ReplayState& ReplayState::seek(Timestamp t) { TRACE_ENTER(); impl::run_state oldstate; { boost::mutex::scoped_lock L(impl_->lock); oldstate = impl_->state; pause(); impl_->events.clear(); impl_->ts = t; if (t == -1) impl_->last_event = std::numeric_limits<Timestamp>::max(); else impl_->last_event = t; } if (oldstate == impl::running) run(); TRACE_EXIT(); return *this; } ReplayState& ReplayState::speed(float f) { TRACE_ENTER(); Assert<Bad_arg>(f != 0); /* If speed changes direction, need to clear the event list. * Check for sign change by noting that positive*negative==negative */ if (impl_->speed * f < 0) { impl::run_state oldstate; { boost::mutex::scoped_lock L(impl_->lock); oldstate = impl_->state; pause(); impl_->events.clear(); /* * Avoid setting .last_event when SpeedMessage is received * prior to the first StartMessage. */ if (impl_->ts != 0 && impl_->ts != -1) impl_->last_event = impl_->ts; impl_->speed = f; } if (oldstate == impl::running) run(); } else impl_->speed = f; LOG_DEBUG("ts=" << impl_->ts << " last_event=" << impl_->last_event); TRACE_EXIT(); return *this; } ReplayState& ReplayState::buffer_size(unsigned int n) { TRACE_ENTER(); Assert<Bad_arg>(n != 0); impl_->bufsiz = n; TRACE_EXIT(); return *this; } ReplayState& ReplayState::time_step(unsigned int n) { TRACE_ENTER(); Assert<Bad_arg>(n != 0); impl_->step = n; TRACE_EXIT(); return *this; } /* function object for accepting events output from Database::getEvents() */ struct event_output { std::deque<MessagePtr>& q; event_output(std::deque<MessagePtr>& qq) : q(qq) {} void operator() (MessagePtr m) { q.push_back(m); } }; /** Schedule an asynchronous task to replay events from the database to a GUI * client. If the local cache of upcoming events is empty, prefetch a block of * events from the database. * * The code is written such that it will work when playing events forward or in * reverse. */ void ReplayState::run() { TRACE_ENTER(); boost::mutex::scoped_lock L(impl_->lock); if (impl_->events.empty()) { // queue is empty, pre-fetch more items from the DB boost::function<void(MessagePtr)> cb(event_output(impl_->events)); LOG_DEBUG("fetching events " << (impl_->speed > 0 ? "> " : "< ") << impl_->last_event); get_db_handle().getEvents(cb, impl_->last_event, (impl_->speed >= 0) ? Database::forward : Database::reverse, impl_->bufsiz); if (!impl_->events.empty()) { LOG_DEBUG("got " << impl_->events.size() << " events from the db query"); /* When starting to replay, assume that time T=0 is the time of the * first event in the stream. * T= -1 is EOF. * Convert to timestamp of first item in the returned events. * * When playing in reverse, the first item in the list is the last event in the database. */ if (impl_->ts == 0 || impl_->ts == -1) impl_->ts = impl_->events.front()->timestamp; // save timestamp of last event retrieved to avoid duplication impl_->last_event = impl_->events.back()->timestamp; } } if (! impl_->events.empty()) { /* * Calculate for the skew introduced by the time required to process the events. Skew is calculated * as the difference between the actual time taken and the expected time. This gets * subtracted from the wait for the next event to catch up. */ timeval tv; gettimeofday(&tv, 0); Timestamp skew = (tv.tv_sec - impl_->wall_time.tv_sec) * 1000 + (tv.tv_usec - impl_->wall_time.tv_usec) / 1000; skew -= impl_->delta; LOG_DEBUG("calculated skew of " << skew << " ms"); memcpy(&impl_->wall_time, &tv, sizeof(tv)); // time until next event impl_->delta = impl_->events.front()->timestamp - impl_->ts; // update our notion of the current time after the timer expires impl_->ts = impl_->events.front()->timestamp; /* Adjust for playback speed. Note that when playing events in reverse, both speed * delta will be negative, which will turn delta into a positive value for the * async_wait() call, which is exactly what is required. */ impl_->delta = (Timestamp)(impl_->delta/impl_->speed); /* Correct for skew */ impl_->delta -= skew; if (impl_->delta < 0) impl_->delta = 0; LOG_DEBUG("Next event in " << impl_->delta << " ms"); impl_->timer.expires_from_now(boost::posix_time::millisec(impl_->delta)); impl_->timer.async_wait(boost::bind(&ReplayState::timer_handler, shared_from_this(), boost::asio::placeholders::error)); impl_->state = impl::running; } else { /* * FIXME what should happen when the end of the event stream is reached? * One option would be to convert to live stream at this point. */ LOG_DEBUG("reached end of database, pausing playback"); impl_->state = impl::paused; } TRACE_EXIT(); } /** Replay events to a GUI client when a timer expires. * * The run() member function is reponsible for prefetching events from the * database and storing them in the class object. When a timer expires, run * through the locally stored events and send those that occurred within the * last time slice. The task is then rescheduled when the next most recent * event needs to be transmitted. */ void ReplayState::timer_handler(const boost::system::error_code& ec) { TRACE_ENTER(); if (ec == boost::asio::error::operation_aborted) LOG_DEBUG("timer was cancelled"); else if (impl_->state == impl::paused) { LOG_DEBUG("timer expired but state is paused!"); } else { std::vector<MessagePtr> msgs; { boost::mutex::scoped_lock L(impl_->lock); while (! impl_->events.empty()) { MessagePtr m = impl_->events.front(); /* Replay all events in the current time step. Use the absolute value * of the difference in order for forward and reverse replay to work * properly. */ if (abs(m->timestamp - impl_->ts) >= impl_->step) break; msgs.push_back(m); impl_->events.pop_front(); } } ServerConnectionPtr srv = impl_->conn.lock(); if (srv) { /* connection is still alive */ srv->sendMessage(msgs); run(); // reschedule this task } } TRACE_EXIT(); } /* This is required to be defined, otherwise a the default dtor will cause a * compiler error due to use of scoped_ptr with an incomplete type. */ ReplayState::~ReplayState() { TRACE_ENTER(); TRACE_EXIT(); } float ReplayState::speed() const { return impl_->speed; } <|endoftext|>
<commit_before>/* * STLL Simple Text Layouting Library * * STLL is the legal property of its developers, whose * names are listed in the COPYRIGHT file, which is included * within the source distribution. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License * as published by the Free Software Foundation; either version 2.1 * of the License, or (at your option) any later version. * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ #include "layouterCSS.h" #include <vector> #include <string> #include <memory> #include <algorithm> namespace STLL { static bool ruleFits(const std::string & sel, const pugi::xml_node & node) { if (sel == node.name()) return true; if (sel[0] == '.') { for (auto attr: node.attributes()) if ((std::string("class") == attr.name()) && (attr.value() == sel.substr(1))) { return true; } } if (sel.find_first_of('[') != sel.npos) { size_t st = sel.find_first_of('['); size_t en = sel.find_first_of(']'); size_t mi = sel.find_first_of('='); if (sel[mi-1] == '|') { std::string tag = sel.substr(0, st); std::string attr = sel.substr(st+1, mi-2-st); std::string val = sel.substr(mi+1, en-mi-1); if (tag == node.name()) { auto a = node.attribute(attr.c_str()); if (!a.empty()) { std::string nodeattrval = std::string(a.value()); if (val.length() <= nodeattrval.length() && nodeattrval.substr(0, val.length()) == val) return true; } } } } return false; } static uint16_t rulePrio(const std::string & sel) { if (sel[0] == '.') return 2; if (sel.find_first_of('[') != sel.npos) return 2; return 1; } static bool isInheriting(const std::string & attribute) { if (attribute == "color") return true; if (attribute == "font-family") return true; if (attribute == "font-style") return true; if (attribute == "font-size") return true; if (attribute == "font-variant") return true; if (attribute == "font-weight") return true; if (attribute == "padding") return false; if (attribute == "padding-left") return false; if (attribute == "padding-right") return false; if (attribute == "padding-top") return false; if (attribute == "padding-bottom") return false; if (attribute == "margin") return false; if (attribute == "margin-left") return false; if (attribute == "margin-right") return false; if (attribute == "margin-top") return false; if (attribute == "margin-bottom") return false; if (attribute == "text-align") return true; if (attribute == "text-align-last") return true; if (attribute == "text-indent") return true; if (attribute == "direction") return true; if (attribute == "border-top-width") return false; if (attribute == "border-bottom-width") return false; if (attribute == "border-left-width") return false; if (attribute == "border-right-width") return false; if (attribute == "border-width") return false; if (attribute == "border-left-color") return false; if (attribute == "border-right-color") return false; if (attribute == "border-top-color") return false; if (attribute == "border-bottom-color") return false; if (attribute == "border-color") return false; if (attribute == "background-color") return false; if (attribute == "text-decoration") return false; if (attribute == "text-shadow") return true; if (attribute == "width") return false; if (attribute == "border-collapse") return true; assert(0); } static const std::string & getDefault(const std::string & attribute) { static std::string defaults[]= { "sans", "normal", "0px", "", "ltr", "transparent", "separate" }; if (attribute == "color") throw XhtmlException_c("You must specify the required colors, there is no default"); if (attribute == "font-family") return defaults[0]; if (attribute == "font-style") return defaults[1]; if (attribute == "font-size") throw XhtmlException_c("You must specify all required font sizes, there is no default"); if (attribute == "font-variant") return defaults[1]; if (attribute == "font-weight") return defaults[1]; if (attribute == "padding") return defaults[2]; if (attribute == "padding-left") return defaults[3]; if (attribute == "padding-right") return defaults[3]; if (attribute == "padding-top") return defaults[3]; if (attribute == "padding-bottom") return defaults[3]; if (attribute == "margin") return defaults[2]; if (attribute == "margin-left") return defaults[3]; if (attribute == "margin-right") return defaults[3]; if (attribute == "margin-top") return defaults[3]; if (attribute == "margin-bottom") return defaults[3]; if (attribute == "text-align") return defaults[3]; if (attribute == "text-align-last") return defaults[3]; if (attribute == "text-indent") return defaults[2]; if (attribute == "direction") return defaults[4]; if (attribute == "border-width") return defaults[2]; if (attribute == "border-left-width") return defaults[3]; if (attribute == "border-right-width") return defaults[3]; if (attribute == "border-top-width") return defaults[3]; if (attribute == "border-bottom-width") return defaults[3]; if (attribute == "border-color") return defaults[3]; if (attribute == "border-top-color") return defaults[3]; if (attribute == "border-bottom-color") return defaults[3]; if (attribute == "border-left-color") return defaults[3]; if (attribute == "border-right-color") return defaults[3]; if (attribute == "background-color") return defaults[5]; if (attribute == "text-decoration") return defaults[3]; if (attribute == "text-shadow") return defaults[3]; if (attribute == "width") throw XhtmlException_c("You must specify the width, there is no default"); if (attribute == "border-collapse") return defaults[6]; assert(0); } static bool isValidAttribute(const std::string & attribute) { if (attribute == "color") return true; if (attribute == "font-family") return true; if (attribute == "font-style") return true; if (attribute == "font-size") return true; if (attribute == "font-variant") return true; if (attribute == "font-weight") return true; if (attribute == "padding") return true; if (attribute == "padding-left") return true; if (attribute == "padding-right") return true; if (attribute == "padding-top") return true; if (attribute == "padding-bottom") return true; if (attribute == "margin") return true; if (attribute == "margin-left") return true; if (attribute == "margin-right") return true; if (attribute == "margin-top") return true; if (attribute == "margin-bottom") return true; if (attribute == "text-align") return true; if (attribute == "text-align-last") return true; if (attribute == "text-indent") return true; if (attribute == "direction") return true; if (attribute == "border-width") return true; if (attribute == "border-left-width") return true; if (attribute == "border-right-width") return true; if (attribute == "border-top-width") return true; if (attribute == "border-bottom-width") return true; if (attribute == "border-color") return true; if (attribute == "border-left-color") return true; if (attribute == "border-right-color") return true; if (attribute == "border-top-color") return true; if (attribute == "border-bottom-color") return true; if (attribute == "background-color") return true; if (attribute == "text-decoration") return true; if (attribute == "text-shadow") return true; if (attribute == "width") return true; if (attribute == "border-collapse") return true; return false; } const std::string & textStyleSheet_c::getValue(pugi::xml_node node, const std::string & attribute) const { // go through all rules, check only the ones that give a value to the requested attribute // evaluate rule by priority (look at the CSS priority rules // choose the highest priority while (!node.empty()) { uint16_t prio = 0; size_t bestI; for (size_t i = 0; i < rules.size(); i++) { if ( rules[i].attribute == attribute && ruleFits(rules[i].selector, node) && rulePrio(rules[i].selector) > prio ) { prio = rulePrio(rules[i].selector); bestI = i; } } if (prio) return rules[bestI].value; if (!isInheriting(attribute)) return getDefault(attribute); node = node.parent(); } return getDefault(attribute); } void textStyleSheet_c::font(const std::string& family, const fontResource_c & res, const std::string& style, const std::string& variant, const std::string& weight, const std::string& stretch) { auto i = families.find(family); if (i == families.end()) { i = families.insert(std::make_pair(family, std::make_shared<fontFamily_c>(cache))).first; } i->second->addFont(res, style, variant, weight, stretch); } void textStyleSheet_c::addRule(const std::string sel, const std::string attr, const std::string val) { if (!isValidAttribute(attr)) throw XhtmlException_c(std::string("attribute not supported: ") + attr); rule r; r.selector = sel; r.attribute = attr; r.value = val; rules.push_back(r); } textStyleSheet_c::textStyleSheet_c(std::shared_ptr< fontCache_c > c) { if (c) { cache = c; } else { cache = std::make_shared<fontCache_c>(); } } } <commit_msg>make text-decoration inherited, this is closer to the actual behavior than not inheriting<commit_after>/* * STLL Simple Text Layouting Library * * STLL is the legal property of its developers, whose * names are listed in the COPYRIGHT file, which is included * within the source distribution. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License * as published by the Free Software Foundation; either version 2.1 * of the License, or (at your option) any later version. * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ #include "layouterCSS.h" #include <vector> #include <string> #include <memory> #include <algorithm> namespace STLL { static bool ruleFits(const std::string & sel, const pugi::xml_node & node) { if (sel == node.name()) return true; if (sel[0] == '.') { for (auto attr: node.attributes()) if ((std::string("class") == attr.name()) && (attr.value() == sel.substr(1))) { return true; } } if (sel.find_first_of('[') != sel.npos) { size_t st = sel.find_first_of('['); size_t en = sel.find_first_of(']'); size_t mi = sel.find_first_of('='); if (sel[mi-1] == '|') { std::string tag = sel.substr(0, st); std::string attr = sel.substr(st+1, mi-2-st); std::string val = sel.substr(mi+1, en-mi-1); if (tag == node.name()) { auto a = node.attribute(attr.c_str()); if (!a.empty()) { std::string nodeattrval = std::string(a.value()); if (val.length() <= nodeattrval.length() && nodeattrval.substr(0, val.length()) == val) return true; } } } } return false; } static uint16_t rulePrio(const std::string & sel) { if (sel[0] == '.') return 2; if (sel.find_first_of('[') != sel.npos) return 2; return 1; } static bool isInheriting(const std::string & attribute) { if (attribute == "color") return true; if (attribute == "font-family") return true; if (attribute == "font-style") return true; if (attribute == "font-size") return true; if (attribute == "font-variant") return true; if (attribute == "font-weight") return true; if (attribute == "padding") return false; if (attribute == "padding-left") return false; if (attribute == "padding-right") return false; if (attribute == "padding-top") return false; if (attribute == "padding-bottom") return false; if (attribute == "margin") return false; if (attribute == "margin-left") return false; if (attribute == "margin-right") return false; if (attribute == "margin-top") return false; if (attribute == "margin-bottom") return false; if (attribute == "text-align") return true; if (attribute == "text-align-last") return true; if (attribute == "text-indent") return true; if (attribute == "direction") return true; if (attribute == "border-top-width") return false; if (attribute == "border-bottom-width") return false; if (attribute == "border-left-width") return false; if (attribute == "border-right-width") return false; if (attribute == "border-width") return false; if (attribute == "border-left-color") return false; if (attribute == "border-right-color") return false; if (attribute == "border-top-color") return false; if (attribute == "border-bottom-color") return false; if (attribute == "border-color") return false; if (attribute == "background-color") return false; if (attribute == "text-decoration") return true; if (attribute == "text-shadow") return true; if (attribute == "width") return false; if (attribute == "border-collapse") return true; assert(0); } static const std::string & getDefault(const std::string & attribute) { static std::string defaults[]= { "sans", "normal", "0px", "", "ltr", "transparent", "separate" }; if (attribute == "color") throw XhtmlException_c("You must specify the required colors, there is no default"); if (attribute == "font-family") return defaults[0]; if (attribute == "font-style") return defaults[1]; if (attribute == "font-size") throw XhtmlException_c("You must specify all required font sizes, there is no default"); if (attribute == "font-variant") return defaults[1]; if (attribute == "font-weight") return defaults[1]; if (attribute == "padding") return defaults[2]; if (attribute == "padding-left") return defaults[3]; if (attribute == "padding-right") return defaults[3]; if (attribute == "padding-top") return defaults[3]; if (attribute == "padding-bottom") return defaults[3]; if (attribute == "margin") return defaults[2]; if (attribute == "margin-left") return defaults[3]; if (attribute == "margin-right") return defaults[3]; if (attribute == "margin-top") return defaults[3]; if (attribute == "margin-bottom") return defaults[3]; if (attribute == "text-align") return defaults[3]; if (attribute == "text-align-last") return defaults[3]; if (attribute == "text-indent") return defaults[2]; if (attribute == "direction") return defaults[4]; if (attribute == "border-width") return defaults[2]; if (attribute == "border-left-width") return defaults[3]; if (attribute == "border-right-width") return defaults[3]; if (attribute == "border-top-width") return defaults[3]; if (attribute == "border-bottom-width") return defaults[3]; if (attribute == "border-color") return defaults[3]; if (attribute == "border-top-color") return defaults[3]; if (attribute == "border-bottom-color") return defaults[3]; if (attribute == "border-left-color") return defaults[3]; if (attribute == "border-right-color") return defaults[3]; if (attribute == "background-color") return defaults[5]; if (attribute == "text-decoration") return defaults[3]; if (attribute == "text-shadow") return defaults[3]; if (attribute == "width") throw XhtmlException_c("You must specify the width, there is no default"); if (attribute == "border-collapse") return defaults[6]; assert(0); } static bool isValidAttribute(const std::string & attribute) { if (attribute == "color") return true; if (attribute == "font-family") return true; if (attribute == "font-style") return true; if (attribute == "font-size") return true; if (attribute == "font-variant") return true; if (attribute == "font-weight") return true; if (attribute == "padding") return true; if (attribute == "padding-left") return true; if (attribute == "padding-right") return true; if (attribute == "padding-top") return true; if (attribute == "padding-bottom") return true; if (attribute == "margin") return true; if (attribute == "margin-left") return true; if (attribute == "margin-right") return true; if (attribute == "margin-top") return true; if (attribute == "margin-bottom") return true; if (attribute == "text-align") return true; if (attribute == "text-align-last") return true; if (attribute == "text-indent") return true; if (attribute == "direction") return true; if (attribute == "border-width") return true; if (attribute == "border-left-width") return true; if (attribute == "border-right-width") return true; if (attribute == "border-top-width") return true; if (attribute == "border-bottom-width") return true; if (attribute == "border-color") return true; if (attribute == "border-left-color") return true; if (attribute == "border-right-color") return true; if (attribute == "border-top-color") return true; if (attribute == "border-bottom-color") return true; if (attribute == "background-color") return true; if (attribute == "text-decoration") return true; if (attribute == "text-shadow") return true; if (attribute == "width") return true; if (attribute == "border-collapse") return true; return false; } const std::string & textStyleSheet_c::getValue(pugi::xml_node node, const std::string & attribute) const { // go through all rules, check only the ones that give a value to the requested attribute // evaluate rule by priority (look at the CSS priority rules // choose the highest priority while (!node.empty()) { uint16_t prio = 0; size_t bestI; for (size_t i = 0; i < rules.size(); i++) { if ( rules[i].attribute == attribute && ruleFits(rules[i].selector, node) && rulePrio(rules[i].selector) > prio ) { prio = rulePrio(rules[i].selector); bestI = i; } } if (prio) return rules[bestI].value; if (!isInheriting(attribute)) return getDefault(attribute); node = node.parent(); } return getDefault(attribute); } void textStyleSheet_c::font(const std::string& family, const fontResource_c & res, const std::string& style, const std::string& variant, const std::string& weight, const std::string& stretch) { auto i = families.find(family); if (i == families.end()) { i = families.insert(std::make_pair(family, std::make_shared<fontFamily_c>(cache))).first; } i->second->addFont(res, style, variant, weight, stretch); } void textStyleSheet_c::addRule(const std::string sel, const std::string attr, const std::string val) { if (!isValidAttribute(attr)) throw XhtmlException_c(std::string("attribute not supported: ") + attr); rule r; r.selector = sel; r.attribute = attr; r.value = val; rules.push_back(r); } textStyleSheet_c::textStyleSheet_c(std::shared_ptr< fontCache_c > c) { if (c) { cache = c; } else { cache = std::make_shared<fontCache_c>(); } } } <|endoftext|>
<commit_before>//////////////////////////////////////////////////////////////////////////////// // Name: link.cpp // Purpose: Implementation of class wxExLink // Author: Anton van Wezenbeek // Copyright: (c) 2013 Anton van Wezenbeek //////////////////////////////////////////////////////////////////////////////// #include <wx/wxprec.h> #ifndef WX_PRECOMP #include <wx/wx.h> #endif #include <wx/config.h> #include <wx/tokenzr.h> #include <wx/utils.h> // for wxGetEnv #include <wx/extension/link.h> #include <wx/extension/lexer.h> #include <wx/extension/stc.h> #include <wx/extension/util.h> //#define DEBUG wxExLink::wxExLink(wxExSTC* stc) : m_STC(stc) { } bool wxExLink::AddBasePath() { if (m_STC == NULL) { return false; } // Find the base path, if this is not yet on the list, add it. const wxString basepath_text = "Basepath: "; const int find = m_STC->FindText( 0, 1000, // the max pos to look for, this seems enough basepath_text); if (find == -1) { return false; } const int line = m_STC->LineFromPosition(find); m_PathList.Add(m_STC->GetTextRange( find + basepath_text.length(), m_STC->GetLineEndPosition(line) - 3)); return true; } const wxString wxExLink::FindPath(const wxString& text) const { if ( text.empty() || // wxPathList cannot handle links over several lines. // add trimmed argument, to skip eol wxExGetNumberOfLines(text, true) > 1) { return wxEmptyString; } // Path in .po files. if ( m_STC != NULL && m_STC->GetLexer().GetScintillaLexer() == "po" && text.StartsWith("#: ")) { return text.Mid(3); } // Better first try to find "...", then <...>, as in next example. // <A HREF="http://www.scintilla.org">scintilla</A> component. // So, first get text between " signs. size_t pos_char1 = text.find("\""); size_t pos_char2 = text.rfind("\""); // If that did not succeed, then get text between < and >. if (pos_char1 == wxString::npos || pos_char2 == wxString::npos || pos_char2 <= pos_char1) { pos_char1 = text.find("<"); pos_char2 = text.rfind(">"); } // If that did not succeed, then get text between ' and '. if (pos_char1 == wxString::npos || pos_char2 == wxString::npos || pos_char2 <= pos_char1) { pos_char1 = text.find("'"); pos_char2 = text.rfind("'"); } wxString out; // If we did not find anything. if (pos_char1 == wxString::npos || pos_char2 == wxString::npos || pos_char2 <= pos_char1) { out = text; } else { // Okay, get everything inbetween. out = text.substr(pos_char1 + 1, pos_char2 - pos_char1 - 1); } // And make sure we skip white space. out.Trim(true); out.Trim(false); return out; } const wxString wxExLink::GetPath( const wxString& text, int& line_no, int& column_no) const { const wxString path(FindPath(text)); wxString link(path); #ifdef DEBUG wxLogMessage("+wxExLink::GetPath. text: " + text + "\nlink: " + link + "\ncwd: " + wxGetCwd()); #endif SetLink(link, line_no, column_no); if ( link.empty() || // Otherwise, if you happen to select text that // ends with a separator, wx asserts. wxFileName::IsPathSeparator(link.Last())) { return wxEmptyString; } wxFileName file(link); wxString fullpath; if (file.FileExists()) { file.MakeAbsolute(); fullpath = file.GetFullPath(); } else { #ifdef DEBUG wxLogMessage("File " + link + " does not exist"); #endif if ( file.IsRelative() && m_STC != NULL && m_STC->GetFileName().FileExists()) { if (file.MakeAbsolute(m_STC->GetFileName().GetPath())) { if (file.FileExists()) { fullpath = file.GetFullPath(); } } else { wxString pwd; if (wxGetEnv("PWD", &pwd)) { if (file.MakeAbsolute(pwd)) { if (file.FileExists()) { fullpath = file.GetFullPath(); } } } } #ifdef DEBUG wxLogMessage("Fullpath " + fullpath); #endif } if (fullpath.empty()) { // Check whether last word is a file. wxString word = path.AfterLast(' ').Trim(); if ( !word.empty() && !wxFileName::IsPathSeparator(link.Last()) && wxFileExists(word)) { wxFileName file(word); file.MakeAbsolute(); fullpath = file.GetFullPath(); // And reset line or column. line_no = 0; column_no = 0; #ifdef DEBUG wxLogMessage("Fullpath updated " + fullpath); #endif } if (fullpath.empty() && !m_PathList.empty()) { fullpath = m_PathList.FindAbsoluteValidPath(link); if ( fullpath.empty() && !word.empty() && SetLink(word, line_no, column_no)) { fullpath = m_PathList.FindAbsoluteValidPath(word); } } // Do nothing if fullpath.empty(), // as we return empty string if no path could be found. #ifdef DEBUG wxLogMessage("Fullpath after pathlist update " + fullpath); #endif } } #ifdef DEBUG wxLogMessage("-wxExLink::GetPath: " + fullpath); #endif return fullpath; } bool wxExLink::SetLink( wxString& link, int& line_no, int& column_no) const { if (link.size() < 2) { return false; } // Using backslash as separator does not yet work. link.Replace("\\\\", "/"); link.Replace("\\", "/"); // The harddrive letter is filtererd, it does not work // when adding it to wxExMatch. wxString prefix; #ifdef __WXMSW__ if (isalpha(link[0]) && link[1] == ':') { prefix = link.SubString(0,1); link = link.Mid(2); } #endif // file[:line[:column]] std::vector <wxString> v; if (wxExMatch("([0-9A-Za-z _/.-]+):([0-9]*):?([0-9]*)", link, v)) { link = v[0]; line_no = 0; column_no = 0; if (v.size() > 1) { line_no = atoi(v[1]); if (v.size() > 2) { column_no = atoi(v[2]); } } link = prefix + link; return true; } return false; } void wxExLink::SetFromConfig() { wxStringTokenizer tkz( wxConfigBase::Get()->Read(_("Include directory")), "\r\n"); m_PathList.Empty(); while (tkz.HasMoreTokens()) { m_PathList.Add(tkz.GetNextToken()); } } <commit_msg>removed PWD<commit_after>//////////////////////////////////////////////////////////////////////////////// // Name: link.cpp // Purpose: Implementation of class wxExLink // Author: Anton van Wezenbeek // Copyright: (c) 2013 Anton van Wezenbeek //////////////////////////////////////////////////////////////////////////////// #include <wx/wxprec.h> #ifndef WX_PRECOMP #include <wx/wx.h> #endif #include <wx/config.h> #include <wx/tokenzr.h> #include <wx/extension/link.h> #include <wx/extension/lexer.h> #include <wx/extension/stc.h> #include <wx/extension/util.h> //#define DEBUG wxExLink::wxExLink(wxExSTC* stc) : m_STC(stc) { } bool wxExLink::AddBasePath() { if (m_STC == NULL) { return false; } // Find the base path, if this is not yet on the list, add it. const wxString basepath_text = "Basepath: "; const int find = m_STC->FindText( 0, 1000, // the max pos to look for, this seems enough basepath_text); if (find == -1) { return false; } const int line = m_STC->LineFromPosition(find); m_PathList.Add(m_STC->GetTextRange( find + basepath_text.length(), m_STC->GetLineEndPosition(line) - 3)); return true; } const wxString wxExLink::FindPath(const wxString& text) const { if ( text.empty() || // wxPathList cannot handle links over several lines. // add trimmed argument, to skip eol wxExGetNumberOfLines(text, true) > 1) { return wxEmptyString; } // Path in .po files. if ( m_STC != NULL && m_STC->GetLexer().GetScintillaLexer() == "po" && text.StartsWith("#: ")) { return text.Mid(3); } // Better first try to find "...", then <...>, as in next example. // <A HREF="http://www.scintilla.org">scintilla</A> component. // So, first get text between " signs. size_t pos_char1 = text.find("\""); size_t pos_char2 = text.rfind("\""); // If that did not succeed, then get text between < and >. if (pos_char1 == wxString::npos || pos_char2 == wxString::npos || pos_char2 <= pos_char1) { pos_char1 = text.find("<"); pos_char2 = text.rfind(">"); } // If that did not succeed, then get text between ' and '. if (pos_char1 == wxString::npos || pos_char2 == wxString::npos || pos_char2 <= pos_char1) { pos_char1 = text.find("'"); pos_char2 = text.rfind("'"); } wxString out; // If we did not find anything. if (pos_char1 == wxString::npos || pos_char2 == wxString::npos || pos_char2 <= pos_char1) { out = text; } else { // Okay, get everything inbetween. out = text.substr(pos_char1 + 1, pos_char2 - pos_char1 - 1); } // And make sure we skip white space. out.Trim(true); out.Trim(false); return out; } const wxString wxExLink::GetPath( const wxString& text, int& line_no, int& column_no) const { const wxString path(FindPath(text)); wxString link(path); #ifdef DEBUG wxLogMessage("+wxExLink::GetPath. text: " + text + "\nlink: " + link + "\ncwd: " + wxGetCwd()); #endif SetLink(link, line_no, column_no); if ( link.empty() || // Otherwise, if you happen to select text that // ends with a separator, wx asserts. wxFileName::IsPathSeparator(link.Last())) { return wxEmptyString; } wxFileName file(link); wxString fullpath; if (file.FileExists()) { file.MakeAbsolute(); fullpath = file.GetFullPath(); } else { #ifdef DEBUG wxLogMessage("File " + link + " does not exist"); #endif if ( file.IsRelative() && m_STC != NULL && m_STC->GetFileName().FileExists()) { if (file.MakeAbsolute(m_STC->GetFileName().GetPath())) { if (file.FileExists()) { fullpath = file.GetFullPath(); } } #ifdef DEBUG wxLogMessage("Fullpath " + fullpath); #endif } if (fullpath.empty()) { // Check whether last word is a file. wxString word = path.AfterLast(' ').Trim(); if ( !word.empty() && !wxFileName::IsPathSeparator(link.Last()) && wxFileExists(word)) { wxFileName file(word); file.MakeAbsolute(); fullpath = file.GetFullPath(); // And reset line or column. line_no = 0; column_no = 0; #ifdef DEBUG wxLogMessage("Fullpath updated " + fullpath); #endif } if (fullpath.empty() && !m_PathList.empty()) { fullpath = m_PathList.FindAbsoluteValidPath(link); if ( fullpath.empty() && !word.empty() && SetLink(word, line_no, column_no)) { fullpath = m_PathList.FindAbsoluteValidPath(word); } } // Do nothing if fullpath.empty(), // as we return empty string if no path could be found. #ifdef DEBUG wxLogMessage("Fullpath after pathlist update " + fullpath); #endif } } #ifdef DEBUG wxLogMessage("-wxExLink::GetPath: " + fullpath); #endif return fullpath; } bool wxExLink::SetLink( wxString& link, int& line_no, int& column_no) const { if (link.size() < 2) { return false; } // Using backslash as separator does not yet work. link.Replace("\\\\", "/"); link.Replace("\\", "/"); // The harddrive letter is filtererd, it does not work // when adding it to wxExMatch. wxString prefix; #ifdef __WXMSW__ if (isalpha(link[0]) && link[1] == ':') { prefix = link.SubString(0,1); link = link.Mid(2); } #endif // file[:line[:column]] std::vector <wxString> v; if (wxExMatch("([0-9A-Za-z _/.-]+):([0-9]*):?([0-9]*)", link, v)) { link = v[0]; line_no = 0; column_no = 0; if (v.size() > 1) { line_no = atoi(v[1]); if (v.size() > 2) { column_no = atoi(v[2]); } } link = prefix + link; return true; } return false; } void wxExLink::SetFromConfig() { wxStringTokenizer tkz( wxConfigBase::Get()->Read(_("Include directory")), "\r\n"); m_PathList.Empty(); while (tkz.HasMoreTokens()) { m_PathList.Add(tkz.GetNextToken()); } } <|endoftext|>
<commit_before>/** ************************************************************* * @file webserver.cpp * @brief Breve descripción * Pequeña documentación del archivo * * * * * * @author Gaspar Fernández <[email protected]> * @version * @date 03 abr 2015 * Changelog: * * * * * Compilation: * $ g++ -g -o webserver webserver.cpp glovehttpserver.cpp glove.o -std=c++11 -lpthread -lcrypto -lssl * *************************************************************/ #include "glovehttpserver.hpp" #include <iostream> #include <chrono> #include <thread> #include <zlib.h> void hello(GloveHttpRequest &request, GloveHttpResponse& response) { std::cout << "TESTING"<<std::endl; response << "This is the response\n"; response << "This is another tesxt" << std::endl; } void chatengine(GloveHttpRequest &request, GloveHttpResponse& response) { response << "Chat with me waaraaaanaaaa\n"; } void chatreceive(GloveWebSocketData& data, GloveWebSocketHandler& ws) { if (data.length()>300) ws.send("Message too long"); else ws.send("ECHO: "+data.data()); /* ws.ping("PINGIO", [] (GloveWebSocketHandler& ws) */ /* { */ /* std::cout << "SE EJECUTA EL CALLBACK Y TODO\n"; */ /* }); */ } void chatmaintenance(GloveWebSocketHandler& ws) { } int main(int argc, char *argv[]) { GloveHttpServer serv(8080, "", 2048); std::cout << "Compression: "<< serv.compression("deflate") << std::endl; std::cout << "Timeout: "<<serv.timeout()<<std::endl; std::cout << "Keepalive: "<<serv.keepalive_timeout()<<std::endl; serv.addVhost("testing"); /* Necesitamos callback de inicializacion (chatengine), de recepcion de mensaje, de salida de cliente y de mantenimiento (que se llamara cada cierto tiempo). Mirar si desde client podemos acceder a un ID.*/ serv.addWebSocket("/chat/", chatengine, chatreceive, chatmaintenance); serv.addRoute("/hello/$anycon/$anything", hello); serv.addRoute("/files/$filename/", GloveHttpServer::fileServer, "testing"); std::cout << "READY"<<std::endl; while(1) { std::this_thread::sleep_for(std::chrono::seconds(1)); } std::cout << "TEST"<<std::endl; } <commit_msg>Fixed webserver example to support gloveWebSocket changes<commit_after>/** ************************************************************* * @file webserver.cpp * @brief Breve descripción * Pequeña documentación del archivo * * * * * * @author Gaspar Fernández <[email protected]> * @version * @date 03 abr 2015 * Changelog: * * * * * Compilation: * $ g++ -g -o webserver webserver.cpp glovehttpserver.cpp glove.o -std=c++11 -lpthread -lcrypto -lssl * *************************************************************/ #include "glovehttpserver.hpp" #include <iostream> #include <chrono> #include <thread> #include <zlib.h> void hello(GloveHttpRequest &request, GloveHttpResponse& response) { std::cout << "TESTING"<<std::endl; response << "This is the response\n"; response << "This is another tesxt" << std::endl; } void chatengine(GloveHttpRequest &request, GloveHttpResponse& response) { response << "Chat with me waaraaaanaaaa\n"; } void chatreceive(GloveWebSocketData& data, GloveWebSocketHandler& ws) { if (data.length()>300) ws.send("Message too long"); else ws.send("ECHO: "+data.data()); /* ws.ping("PINGIO", [] (GloveWebSocketHandler& ws) */ /* { */ /* std::cout << "EXECUTING CALLBACK\n"; */ /* }); */ } bool chatmaintenance(GloveWebSocketHandler& ws) { } int main(int argc, char *argv[]) { GloveHttpServer serv(8080, "", 2048); std::cout << "Compression: "<< serv.compression("deflate") << std::endl; std::cout << "Timeout: "<<serv.timeout()<<std::endl; std::cout << "Keepalive: "<<serv.keepalive_timeout()<<std::endl; serv.addVhost("testing"); /* Necesitamos callback de inicializacion (chatengine), de recepcion de mensaje, de salida de cliente y de mantenimiento (que se llamara cada cierto tiempo). Mirar si desde client podemos acceder a un ID.*/ serv.addWebSocket("/chat/", chatengine, nullptr, chatreceive, chatmaintenance); serv.addRoute("/hello/$anycon/$anything", hello); serv.addRoute("/files/$filename/", GloveHttpServer::fileServer, "testing"); std::cout << "READY"<<std::endl; while(1) { std::this_thread::sleep_for(std::chrono::seconds(1)); } std::cout << "TEST"<<std::endl; } <|endoftext|>
<commit_before>#include "Prefix.pch" #include <boost/log/core.hpp> #include <boost/log/sinks.hpp> #if BOOST_VERSION >= 105600 #include <boost/core/demangle.hpp> #define MSC_BOOST_DEMANGLE boost::core::demangle #else #include <boost/units/detail/utility.hpp> #define MSC_BOOST_DEMANGLE boost::units::detail::demangle #endif #include "Logging.hpp" #include "Utils.hpp" #include "Exceptions.hpp" namespace logging = boost::log; namespace attrs = boost::log::attributes; namespace sinks = boost::log::sinks; namespace mcore { Logger::Logger(const std::string &source) { add_attribute("Source", attrs::constant<std::string>(source)); } Logger::Logger(const std::type_info &source): Logger(MSC_BOOST_DEMANGLE(source.name())) { setHost("Local"); } void Logger::setChannel(const std::string &channel) { auto r = add_attribute("Channel", attrs::constant<std::string>(channel)); r.first->second = attrs::constant<std::string>(channel); } void Logger::setHost(const std::string &host) { auto r = add_attribute("Host", attrs::constant<std::string>(host)); r.first->second = attrs::constant<std::string>(host); } class CustomLogSink: public boost::log::sinks::basic_sink_backend <sinks::combine_requirements< sinks::concurrent_feeding >::type>, public boost::enable_shared_from_this<CustomLogSink> { struct Sink { MSCLogSink func; void *userdata; }; std::list<Sink> sinks; std::mutex mutex; public: CustomLogSink() { } void consume(boost::log::record_view const &rec) { const auto& values = rec.attribute_values(); const auto& sev = logging::extract_or_default<LogLevel>(values["Severity"], LogLevel::Info); const auto& source = logging::extract_or_default<std::string>(values["Source"], std::string("(null)")); const auto& channel = logging::extract_or_default<std::string>(values["Channel"], std::string("(null)")); const auto& host = logging::extract_or_default<std::string>(values["Host"], std::string("(null)")); const auto& msg = logging::extract_or_default<std::string>(values["Message"], std::string("(null)")); std::lock_guard<std::mutex> lock(mutex); for (const auto& s: sinks) s.func(static_cast<MSCLogSeverity>(sev), source.c_str(), host.c_str(), channel.c_str(), msg.c_str(), s.userdata); } MSCLogSinkHandle addSink(MSCLogSink sink, void *userdata) { std::lock_guard<std::mutex> lock(mutex); Sink s = {sink, userdata}; sinks.emplace_front(s); return reinterpret_cast<MSCLogSinkHandle>(new std::list<Sink>::iterator(sinks.begin())); } void removeSink(MSCLogSinkHandle handle) { if (handle == nullptr) { MSCThrow(InvalidArgumentException("handle")); } auto *it = reinterpret_cast<std::list<Sink>::iterator *>(handle); std::lock_guard<std::mutex> lock(mutex); sinks.erase(*it); delete it; } }; static boost::shared_ptr<CustomLogSink> sink = boost::make_shared<CustomLogSink>(); struct CustomLogSinkInitializer { CustomLogSinkInitializer() { auto core = boost::log::core::get(); auto s = boost::make_shared<sinks::unlocked_sink<CustomLogSink>>(sink); core->add_sink(s); } }; } extern "C" MSCResult MSCAddLogSink(MSCLogSink sink, void *userdata, MSCLogSinkHandle *outHandle) { return mcore::convertExceptionsToResultCode([&] { static mcore::CustomLogSinkInitializer initializer; if (sink == nullptr) { MSCThrow(mcore::InvalidArgumentException("sink")); } auto h = mcore::sink->addSink(sink, userdata); if (outHandle) *outHandle = h; }); } extern "C" MSCResult MSCRemoveLogSink(MSCLogSinkHandle handle) { return mcore::convertExceptionsToResultCode([&] { mcore::sink->removeSink(handle); }); } <commit_msg>Work-around for uninitialized static variable<commit_after>#include "Prefix.pch" #include <boost/log/core.hpp> #include <boost/log/sinks.hpp> #if BOOST_VERSION >= 105600 #include <boost/core/demangle.hpp> #define MSC_BOOST_DEMANGLE boost::core::demangle #else #include <boost/units/detail/utility.hpp> #define MSC_BOOST_DEMANGLE boost::units::detail::demangle #endif #include "Logging.hpp" #include "Utils.hpp" #include "Exceptions.hpp" namespace logging = boost::log; namespace attrs = boost::log::attributes; namespace sinks = boost::log::sinks; namespace mcore { Logger::Logger(const std::string &source) { add_attribute("Source", attrs::constant<std::string>(source)); } Logger::Logger(const std::type_info &source): Logger(MSC_BOOST_DEMANGLE(source.name())) { setHost("Local"); } void Logger::setChannel(const std::string &channel) { auto r = add_attribute("Channel", attrs::constant<std::string>(channel)); r.first->second = attrs::constant<std::string>(channel); } void Logger::setHost(const std::string &host) { auto r = add_attribute("Host", attrs::constant<std::string>(host)); r.first->second = attrs::constant<std::string>(host); } class CustomLogSink: public boost::log::sinks::basic_sink_backend <sinks::combine_requirements< sinks::concurrent_feeding >::type>, public boost::enable_shared_from_this<CustomLogSink> { struct Sink { MSCLogSink func; void *userdata; }; std::list<Sink> sinks; std::mutex mutex; public: CustomLogSink() { } void consume(boost::log::record_view const &rec) { const auto& values = rec.attribute_values(); const auto& sev = logging::extract_or_default<LogLevel>(values["Severity"], LogLevel::Info); const auto& source = logging::extract_or_default<std::string>(values["Source"], std::string("(null)")); const auto& channel = logging::extract_or_default<std::string>(values["Channel"], std::string("(null)")); const auto& host = logging::extract_or_default<std::string>(values["Host"], std::string("(null)")); const auto& msg = logging::extract_or_default<std::string>(values["Message"], std::string("(null)")); std::lock_guard<std::mutex> lock(mutex); for (const auto& s: sinks) s.func(static_cast<MSCLogSeverity>(sev), source.c_str(), host.c_str(), channel.c_str(), msg.c_str(), s.userdata); } MSCLogSinkHandle addSink(MSCLogSink sink, void *userdata) { std::lock_guard<std::mutex> lock(mutex); Sink s = {sink, userdata}; sinks.emplace_front(s); return reinterpret_cast<MSCLogSinkHandle>(new std::list<Sink>::iterator(sinks.begin())); } void removeSink(MSCLogSinkHandle handle) { if (handle == nullptr) { MSCThrow(InvalidArgumentException("handle")); } auto *it = reinterpret_cast<std::list<Sink>::iterator *>(handle); std::lock_guard<std::mutex> lock(mutex); sinks.erase(*it); delete it; } }; static boost::shared_ptr<CustomLogSink> sink = boost::make_shared<CustomLogSink>(); struct CustomLogSinkInitializer { CustomLogSinkInitializer() { auto core = boost::log::core::get(); if (sink == nullptr) { sink = boost::make_shared<CustomLogSink>(); } auto s = boost::make_shared<sinks::unlocked_sink<CustomLogSink>>(sink); core->add_sink(s); } }; } extern "C" MSCResult MSCAddLogSink(MSCLogSink sink, void *userdata, MSCLogSinkHandle *outHandle) { return mcore::convertExceptionsToResultCode([&] { static mcore::CustomLogSinkInitializer initializer; if (sink == nullptr) { MSCThrow(mcore::InvalidArgumentException("sink")); } auto h = mcore::sink->addSink(sink, userdata); if (outHandle) *outHandle = h; }); } extern "C" MSCResult MSCRemoveLogSink(MSCLogSinkHandle handle) { return mcore::convertExceptionsToResultCode([&] { mcore::sink->removeSink(handle); }); } <|endoftext|>
<commit_before>#ifndef FALCON_STRING_STOX_HPP #define FALCON_STRING_STOX_HPP #include <falcon/type_traits/is_same.hpp> #include <string> #include <limits> #include <stdexcept> #include <cerrno> #include <cstdarg> #if __cplusplus < 201103L # if defined __USE_GNU || defined __USE_BSD || defined __USE_MISC # include <alloca.h> # endif #endif namespace falcon { namespace detail { template<typename TRet, typename Ret, typename CharT> Ret __stoa_aux(const TRet& __tmp, Ret& __ret, const char* __name, const CharT* __str, std::size_t* __idx, CharT* __endptr) { if (__endptr == __str) throw std::invalid_argument(__name); else if (errno == ERANGE || (falcon::is_same<Ret, int>::value && (__tmp < static_cast<TRet>(std::numeric_limits<int>::min()) || __tmp > static_cast<TRet>(std::numeric_limits<int>::max())))) throw std::out_of_range(__name); else __ret = static_cast<Ret>(__tmp); if (__idx) *__idx = __endptr - __str; } // Helper for all the sto* functions. template<typename Ret, typename TRet, typename CharT> Ret stoa(TRet (*__convf) (const CharT*, CharT**), const char* __name, const CharT* __str, std::size_t* __idx) { Ret __ret; CharT* __endptr; errno = 0; const TRet __tmp = __convf(__str, &__endptr); __stoa_aux(__tmp, __ret, __name, __str, __idx, __endptr); return __ret; } template<typename Ret, typename TRet, typename CharT> Ret stoa(TRet (*__convf) (const CharT*, CharT**, int base), const char* __name, const CharT* __str, std::size_t* __idx, int __base) { Ret __ret; CharT* __endptr; errno = 0; const TRet __tmp = __convf(__str, &__endptr, __base); __stoa_aux(__tmp, __ret, __name, __str, __idx, __endptr); return __ret; } // Helper for the to_string / to_wstring functions. template<typename String, typename CharT> String to_xstring(int (*__convf) (CharT*, std::size_t, const CharT*, std::va_list), std::size_t __n, const CharT* __fmt, ...) { #if __cplusplus >= 201103L String ret; ret.resize(__n); CharT* __s = &ret[0]; #elif defined __USE_GNU || defined __USE_BSD || defined __USE_MISC CharT* __s = static_cast<CharT*>(alloca(sizeof(CharT) * __n)); #else CharT* __s = new CharT[__n]; #endif std::va_list __args; va_start(__args, __fmt); const int __len = __convf(__s, __n, __fmt, __args); va_end(__args); #if __cplusplus >= 201103L (void)__len; return ret; #elif defined __USE_GNU || defined __USE_BSD || defined __USE_MISC return String(__s, __s + __len); # else String ret(__s, __s + __len); delete [] __s; return ret; #endif } } #define FALCON_BASIC_CSTRING_TO_IMPL(result_type, fname, std_fname) \ template<typename CharT, typename Allocator> \ inline result_type \ fname(const std::basic_string<CharT, std::char_traits<CharT>, Allocator>& s, \ std::size_t* __idx = 0, int __base = 10) \ { return ::falcon::detail::stoa<result_type> \ (&std_fname, #fname, s.c_str(), __idx, __base); } #define FALCON_BASIC_CSTRING_TO(result_type, fname, type) \ FALCON_BASIC_CSTRING_TO_IMPL(result_type, fname, strto##type) FALCON_BASIC_CSTRING_TO(int, stoi, l) FALCON_BASIC_CSTRING_TO(long, stol, l) FALCON_BASIC_CSTRING_TO(unsigned long, stoul, ul) #if __cplusplus >= 201103L FALCON_BASIC_CSTRING_TO(long long, stoll, ll) FALCON_BASIC_CSTRING_TO(unsigned long long, stoull, ull) #endif #undef FALCON_BASIC_CSTRING_TO_IMPL #define FALCON_BASIC_CSTRING_TO_IMPL(result_type, fname, std_fname) \ template<typename CharT, typename Allocator> \ inline result_type \ fname(const std::basic_string<CharT, std::char_traits<CharT>, Allocator>& s, \ std::size_t* __idx = 0) \ { return ::falcon::detail::stoa<result_type> \ (&std_fname, #fname, s.c_str(), __idx); } FALCON_BASIC_CSTRING_TO(float, stof, f) FALCON_BASIC_CSTRING_TO(double, stod, d) #if __cplusplus >= 201103L FALCON_BASIC_CSTRING_TO(double long, stold, ld) #endif #undef FALCON_BASIC_CSTRING_TO #undef FALCON_BASIC_CSTRING_TO_IMPL } #endif <commit_msg>new interface for sto* and removing detail::xstring<commit_after>#ifndef FALCON_STRING_STOX_HPP #define FALCON_STRING_STOX_HPP #include <falcon/type_traits/is_same.hpp> #include <string> #include <limits> #include <stdexcept> #include <cerrno> namespace falcon { namespace aux_ { template<typename TRet, typename Ret, typename CharT> void stoa_aux(const TRet tmp, Ret& ret, const char* name, const CharT* str, std::size_t* idx, CharT* endptr) { if (endptr == str) throw std::invalid_argument(name); else if (errno == ERANGE || (falcon::is_same<Ret, int>::value && (tmp < static_cast<TRet>(std::numeric_limits<int>::min()) || tmp > static_cast<TRet>(std::numeric_limits<int>::max())))) throw std::out_of_range(name); else ret = static_cast<Ret>(tmp); if (idx) *idx = std::size_t(endptr - str); } // Helper for all the sto* functions. template<typename Ret, typename Conv, typename CharT> Ret stoa(Conv conv, const char* name, const CharT* str, std::size_t* idx) { Ret ret; CharT* endptr; errno = 0; stoa_aux(conv(str, &endptr), ret, name, str, idx, endptr); return ret; } template<typename Ret, typename Conv, typename CharT> Ret stoa(Conv conv, const char* name, const CharT* str, std::size_t* idx, int base) { Ret ret; CharT* endptr; errno = 0; stoa_aux(conv(str, &endptr, base), ret, name, str, idx, endptr); return ret; } } #define FALCON_BASIC_CSTRING_TO_WRAPPER(result_type, std_fname, std_wfname) \ namespace aux_ { \ struct std_fname##_wrapper { \ result_type \ operator()(const char * str, char ** endptr = 0, int base = 10) const { \ return static_cast<result_type>(::std::std_fname(str, endptr, base)); \ } \ \ result_type \ operator()(const wchar_t * str, wchar_t ** endptr = 0, \ int base = 10) const { \ return static_cast<result_type>( \ ::std::std_wfname(str, endptr, base)); \ } \ }; \ } #define FALCON_BASIC_CSTRING_TO_IMPL(result_type, char_type, fname, std_fname) \ template<typename Trait, typename Allocator> \ inline result_type \ fname(const std::basic_string<char_type, Trait, Allocator>& s, \ std::size_t* idx = 0, int base = 10) \ { return ::falcon::aux_::stoa<result_type> \ (::falcon::aux_::std_fname##_wrapper(), #fname, s.c_str(), idx, base); } #define FALCON_BASIC_CSTRING_TO(result_type, fname, type) \ FALCON_BASIC_CSTRING_TO_WRAPPER(result_type, strto##type, wcsto##type) \ FALCON_BASIC_CSTRING_TO_IMPL(result_type, char, fname, strto##type) \ FALCON_BASIC_CSTRING_TO_IMPL(result_type, const char, fname, strto##type) \ FALCON_BASIC_CSTRING_TO_IMPL(result_type, wchar_t, fname, strto##type) \ FALCON_BASIC_CSTRING_TO_IMPL(result_type, const wchar_t, fname, strto##type) FALCON_BASIC_CSTRING_TO(long, stol, l) FALCON_BASIC_CSTRING_TO(unsigned long, stoul, ul) #if __cplusplus >= 201103L FALCON_BASIC_CSTRING_TO(long long, stoll, ll) FALCON_BASIC_CSTRING_TO(unsigned long long, stoull, ull) #endif # undef FALCON_BASIC_CSTRING_TO_WRAPPER #define FALCON_BASIC_CSTRING_TO_WRAPPER(result_type, std_fname, std_wfname) FALCON_BASIC_CSTRING_TO(int, stoi, l) # undef FALCON_BASIC_CSTRING_TO_WRAPPER #define FALCON_BASIC_CSTRING_TO_WRAPPER(result_type, std_fname, std_wfname) \ namespace aux_ { \ struct std_fname##_wrapper { \ result_type \ operator()(const char * str, char ** endptr = 0) const { \ return ::std::std_fname(str, endptr); \ } \ \ result_type \ operator()(const wchar_t * str, wchar_t ** endptr = 0) const { \ return ::std::std_wfname(str, endptr); \ } \ }; \ } # undef FALCON_BASIC_CSTRING_TO_IMPL #define FALCON_BASIC_CSTRING_TO_IMPL(result_type, char_type, fname, std_fname) \ template<typename Trait, typename Allocator> \ inline result_type \ fname(const std::basic_string<char_type, Trait, Allocator>& s, \ std::size_t* idx = 0) \ { return ::falcon::aux_::stoa<result_type> \ (::falcon::aux_::std_fname##_wrapper(), #fname, s.c_str(), idx); } FALCON_BASIC_CSTRING_TO(float, stof, f) FALCON_BASIC_CSTRING_TO(double, stod, d) #if __cplusplus >= 201103L FALCON_BASIC_CSTRING_TO(double long, stold, ld) #endif #undef FALCON_BASIC_CSTRING_TO #undef FALCON_BASIC_CSTRING_TO_IMPL #undef FALCON_BASIC_CSTRING_TO_WRAPPER } #endif <|endoftext|>
<commit_before>/*! * This file is part of CameraPlus. * * Copyright (C) 2012-2014 Mohammed Sameer <[email protected]> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include "qtcammetadata.h" #include <gst/gsttaglist.h> #include "qtcamdevice.h" #include "qtcamdevice_p.h" #include <QDebug> #include <QDate> #include <QTime> #include <QDateTime> #include <QPointer> #include <ctime> class QtCamMetaDataPrivate { public: void addTag(const char *tag, const QString& value) { GstTagSetter *s = setter(); if (!s) { return; } gst_tag_setter_add_tags(s, GST_TAG_MERGE_REPLACE, tag, value.toUtf8().data(), NULL); gst_object_unref(s); } void addTag(const char *tag, double value) { GstTagSetter *s = setter(); if (!s) { return; } gst_tag_setter_add_tags(s, GST_TAG_MERGE_REPLACE, tag, value, NULL); gst_object_unref(s); } void addTag(const char *tag, GstDateTime *value) { GstTagSetter *s = setter(); if (!s) { return; } gst_tag_setter_add_tags(s, GST_TAG_MERGE_REPLACE, tag, value, NULL); gst_object_unref(s); } GstTagSetter *setter() { if (!device || !device->d_ptr->cameraBin) { return 0; } if (!GST_IS_TAG_SETTER(device->d_ptr->cameraBin)) { return 0; } return GST_TAG_SETTER(gst_object_ref(device->d_ptr->cameraBin)); } QPointer<QtCamDevice> device; }; QtCamMetaData::QtCamMetaData(QObject *parent) : QObject(parent), d_ptr(new QtCamMetaDataPrivate) { } QtCamMetaData::~QtCamMetaData() { setDevice(0); delete d_ptr; d_ptr = 0; } void QtCamMetaData::setDevice(QtCamDevice *device) { if (device != d_ptr->device) { d_ptr->device = device; } } void QtCamMetaData::setManufacturer(const QString& manufacturer) { d_ptr->addTag(GST_TAG_DEVICE_MANUFACTURER, manufacturer); } void QtCamMetaData::setModel(const QString& model) { d_ptr->addTag(GST_TAG_DEVICE_MODEL, model); } void QtCamMetaData::setCountry(const QString& country) { d_ptr->addTag(GST_TAG_GEO_LOCATION_COUNTRY, country); } void QtCamMetaData::setCity(const QString& city) { d_ptr->addTag(GST_TAG_GEO_LOCATION_CITY, city); } void QtCamMetaData::setSuburb(const QString& suburb) { d_ptr->addTag(GST_TAG_GEO_LOCATION_SUBLOCATION, suburb); } void QtCamMetaData::setLongitude(double longitude) { d_ptr->addTag(GST_TAG_GEO_LOCATION_LONGITUDE, longitude); } void QtCamMetaData::setLatitude(double latitude) { d_ptr->addTag(GST_TAG_GEO_LOCATION_LATITUDE, latitude); } void QtCamMetaData::setElevation(double elevation) { d_ptr->addTag(GST_TAG_GEO_LOCATION_ELEVATION, elevation); } void QtCamMetaData::setOrientationAngle(int angle) { if (angle == -1) { qWarning() << "QtCamMetaData::setOrientationAngle called with an unknown angle"; return; } gchar *orientation = g_strdup_printf("rotate-%d", angle); d_ptr->addTag(GST_TAG_IMAGE_ORIENTATION, orientation); g_free(orientation); } void QtCamMetaData::setArtist(const QString& artist) { /* try the shortcut first */ if (!artist.contains('%')) { d_ptr->addTag(GST_TAG_ARTIST, artist); return; } std::vector<char> result(artist.size()); struct tm tm; time_t t; t = time(NULL); if (t == -1) { qWarning() << "Failed to get current time"; d_ptr->addTag(GST_TAG_ARTIST, artist); return; } if (!localtime_r(&t, &tm)) { qWarning() << "Failed to get local time"; d_ptr->addTag(GST_TAG_ARTIST, artist); return; } while (!strftime(result.data(), result.size(), artist.toUtf8().constData(), &tm)) { result.resize(result.size() * 2); } d_ptr->addTag(GST_TAG_ARTIST, QString::fromUtf8(result.data())); } void QtCamMetaData::setDateTime(const QDateTime& dateTime) { QDate d = dateTime.date(); QTime t = dateTime.time(); int day = d.day(); int month = d.month(); int year = d.year(); int hour = t.hour(); int minute = t.minute(); // GstDateTime seconds expects microseconds to be there too :| gdouble seconds = t.second(); seconds += t.msec()/(1000.0); // Current UTC time. Created through string so that the link between // current and utc is lost and secsTo returns non-zero values. QDateTime utcTime = QDateTime::fromString(dateTime.toUTC().toString()); gfloat tzoffset = (utcTime.secsTo(dateTime)/3600.0); GstDateTime *dt = gst_date_time_new(tzoffset, year, month, day, hour, minute, seconds); d_ptr->addTag(GST_TAG_DATE_TIME, dt); gst_date_time_unref(dt); } void QtCamMetaData::setCaptureDirection(double direction) { d_ptr->addTag(GST_TAG_GEO_LOCATION_CAPTURE_DIRECTION, direction); } void QtCamMetaData::setHorizontalError(double error) { d_ptr->addTag(GST_TAG_GEO_LOCATION_HORIZONTAL_ERROR, error); } void QtCamMetaData::reset() { GstTagSetter *s = d_ptr->setter(); if (!s) { return; } gst_tag_setter_reset_tags(s); gst_object_unref(s); } <commit_msg>libqtcamera: fix compilation error under sailfish<commit_after>/*! * This file is part of CameraPlus. * * Copyright (C) 2012-2014 Mohammed Sameer <[email protected]> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include "qtcammetadata.h" #include <gst/gst.h> #include "qtcamdevice.h" #include "qtcamdevice_p.h" #include <QDebug> #include <QDate> #include <QTime> #include <QDateTime> #include <QPointer> #include <ctime> class QtCamMetaDataPrivate { public: void addTag(const char *tag, const QString& value) { GstTagSetter *s = setter(); if (!s) { return; } gst_tag_setter_add_tags(s, GST_TAG_MERGE_REPLACE, tag, value.toUtf8().data(), NULL); gst_object_unref(s); } void addTag(const char *tag, double value) { GstTagSetter *s = setter(); if (!s) { return; } gst_tag_setter_add_tags(s, GST_TAG_MERGE_REPLACE, tag, value, NULL); gst_object_unref(s); } void addTag(const char *tag, GstDateTime *value) { GstTagSetter *s = setter(); if (!s) { return; } gst_tag_setter_add_tags(s, GST_TAG_MERGE_REPLACE, tag, value, NULL); gst_object_unref(s); } GstTagSetter *setter() { if (!device || !device->d_ptr->cameraBin) { return 0; } if (!GST_IS_TAG_SETTER(device->d_ptr->cameraBin)) { return 0; } return GST_TAG_SETTER(gst_object_ref(device->d_ptr->cameraBin)); } QPointer<QtCamDevice> device; }; QtCamMetaData::QtCamMetaData(QObject *parent) : QObject(parent), d_ptr(new QtCamMetaDataPrivate) { } QtCamMetaData::~QtCamMetaData() { setDevice(0); delete d_ptr; d_ptr = 0; } void QtCamMetaData::setDevice(QtCamDevice *device) { if (device != d_ptr->device) { d_ptr->device = device; } } void QtCamMetaData::setManufacturer(const QString& manufacturer) { d_ptr->addTag(GST_TAG_DEVICE_MANUFACTURER, manufacturer); } void QtCamMetaData::setModel(const QString& model) { d_ptr->addTag(GST_TAG_DEVICE_MODEL, model); } void QtCamMetaData::setCountry(const QString& country) { d_ptr->addTag(GST_TAG_GEO_LOCATION_COUNTRY, country); } void QtCamMetaData::setCity(const QString& city) { d_ptr->addTag(GST_TAG_GEO_LOCATION_CITY, city); } void QtCamMetaData::setSuburb(const QString& suburb) { d_ptr->addTag(GST_TAG_GEO_LOCATION_SUBLOCATION, suburb); } void QtCamMetaData::setLongitude(double longitude) { d_ptr->addTag(GST_TAG_GEO_LOCATION_LONGITUDE, longitude); } void QtCamMetaData::setLatitude(double latitude) { d_ptr->addTag(GST_TAG_GEO_LOCATION_LATITUDE, latitude); } void QtCamMetaData::setElevation(double elevation) { d_ptr->addTag(GST_TAG_GEO_LOCATION_ELEVATION, elevation); } void QtCamMetaData::setOrientationAngle(int angle) { if (angle == -1) { qWarning() << "QtCamMetaData::setOrientationAngle called with an unknown angle"; return; } gchar *orientation = g_strdup_printf("rotate-%d", angle); d_ptr->addTag(GST_TAG_IMAGE_ORIENTATION, orientation); g_free(orientation); } void QtCamMetaData::setArtist(const QString& artist) { /* try the shortcut first */ if (!artist.contains('%')) { d_ptr->addTag(GST_TAG_ARTIST, artist); return; } std::vector<char> result(artist.size()); struct tm tm; time_t t; t = time(NULL); if (t == -1) { qWarning() << "Failed to get current time"; d_ptr->addTag(GST_TAG_ARTIST, artist); return; } if (!localtime_r(&t, &tm)) { qWarning() << "Failed to get local time"; d_ptr->addTag(GST_TAG_ARTIST, artist); return; } while (!strftime(result.data(), result.size(), artist.toUtf8().constData(), &tm)) { result.resize(result.size() * 2); } d_ptr->addTag(GST_TAG_ARTIST, QString::fromUtf8(result.data())); } void QtCamMetaData::setDateTime(const QDateTime& dateTime) { QDate d = dateTime.date(); QTime t = dateTime.time(); int day = d.day(); int month = d.month(); int year = d.year(); int hour = t.hour(); int minute = t.minute(); // GstDateTime seconds expects microseconds to be there too :| gdouble seconds = t.second(); seconds += t.msec()/(1000.0); // Current UTC time. Created through string so that the link between // current and utc is lost and secsTo returns non-zero values. QDateTime utcTime = QDateTime::fromString(dateTime.toUTC().toString()); gfloat tzoffset = (utcTime.secsTo(dateTime)/3600.0); GstDateTime *dt = gst_date_time_new(tzoffset, year, month, day, hour, minute, seconds); d_ptr->addTag(GST_TAG_DATE_TIME, dt); gst_date_time_unref(dt); } void QtCamMetaData::setCaptureDirection(double direction) { d_ptr->addTag(GST_TAG_GEO_LOCATION_CAPTURE_DIRECTION, direction); } void QtCamMetaData::setHorizontalError(double error) { d_ptr->addTag(GST_TAG_GEO_LOCATION_HORIZONTAL_ERROR, error); } void QtCamMetaData::reset() { GstTagSetter *s = d_ptr->setter(); if (!s) { return; } gst_tag_setter_reset_tags(s); gst_object_unref(s); } <|endoftext|>
<commit_before>/* * This file is part of the AzerothCore Project. See AUTHORS file for Copyright information * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU Affero General Public License as published by the * Free Software Foundation; either version 3 of the License, or (at your * option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for * more details. * * You should have received a copy of the GNU General Public License along * with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "ScriptMgr.h" #include "ScriptedCreature.h" #include "azjol_nerub.h" DoorData const doorData[] = { { GO_KRIKTHIR_DOORS, DATA_KRIKTHIR_THE_GATEWATCHER_EVENT, DOOR_TYPE_PASSAGE }, { GO_ANUBARAK_DOORS1, DATA_ANUBARAK_EVENT, DOOR_TYPE_ROOM }, { GO_ANUBARAK_DOORS2, DATA_ANUBARAK_EVENT, DOOR_TYPE_ROOM }, { GO_ANUBARAK_DOORS3, DATA_ANUBARAK_EVENT, DOOR_TYPE_ROOM }, { 0, 0, DOOR_TYPE_ROOM } }; ObjectData const creatureData[] = { { NPC_KRIKTHIR_THE_GATEWATCHER, DATA_KRIKTHIR_THE_GATEWATCHER_EVENT }, { NPC_HADRONOX, DATA_HADRONOX_EVENT } }; class instance_azjol_nerub : public InstanceMapScript { public: instance_azjol_nerub() : InstanceMapScript("instance_azjol_nerub", 601) { } struct instance_azjol_nerub_InstanceScript : public InstanceScript { instance_azjol_nerub_InstanceScript(Map* map) : InstanceScript(map) { SetBossNumber(MAX_ENCOUNTERS); LoadDoorData(doorData); LoadObjectData(creatureData, nullptr); }; void OnCreatureCreate(Creature* creature) override { switch (creature->GetEntry()) { case NPC_SKITTERING_SWARMER: case NPC_SKITTERING_INFECTIOR: if (Creature* krikthir = GetCreature((DATA_KRIKTHIR_THE_GATEWATCHER_EVENT))) krikthir->AI()->JustSummoned(creature); break; case NPC_ANUB_AR_CHAMPION: case NPC_ANUB_AR_NECROMANCER: case NPC_ANUB_AR_CRYPTFIEND: if (Creature* hadronox = GetCreature(DATA_HADRONOX_EVENT)) hadronox->AI()->JustSummoned(creature); break; } InstanceScript::OnCreatureCreate(creature); } void OnGameObjectCreate(GameObject* go) override { switch (go->GetEntry()) { case GO_KRIKTHIR_DOORS: case GO_ANUBARAK_DOORS1: case GO_ANUBARAK_DOORS2: case GO_ANUBARAK_DOORS3: AddDoor(go, true); break; } } void OnGameObjectRemove(GameObject* go) override { switch (go->GetEntry()) { case GO_KRIKTHIR_DOORS: case GO_ANUBARAK_DOORS1: case GO_ANUBARAK_DOORS2: case GO_ANUBARAK_DOORS3: AddDoor(go, false); break; } } bool SetBossState(uint32 id, EncounterState state) override { return InstanceScript::SetBossState(id, state); } std::string GetSaveData() override { std::ostringstream saveStream; saveStream << "A N " << GetBossSaveData(); return saveStream.str(); } void Load(const char* in) override { if( !in ) return; char dataHead1, dataHead2; std::istringstream loadStream(in); loadStream >> dataHead1 >> dataHead2; if (dataHead1 == 'A' && dataHead2 == 'N') { for (uint8 i = 0; i < MAX_ENCOUNTERS; ++i) { uint32 tmpState; loadStream >> tmpState; if (tmpState == IN_PROGRESS || tmpState > SPECIAL) tmpState = NOT_STARTED; SetBossState(i, EncounterState(tmpState)); } } } }; InstanceScript* GetInstanceScript(InstanceMap* map) const override { return new instance_azjol_nerub_InstanceScript(map); } }; class spell_azjol_nerub_fixate : public SpellScriptLoader { public: spell_azjol_nerub_fixate() : SpellScriptLoader("spell_azjol_nerub_fixate") { } class spell_azjol_nerub_fixate_SpellScript : public SpellScript { PrepareSpellScript(spell_azjol_nerub_fixate_SpellScript); void HandleScriptEffect(SpellEffIndex effIndex) { PreventHitDefaultEffect(effIndex); if (Unit* target = GetHitUnit()) target->CastSpell(GetCaster(), GetEffectValue(), true); } void Register() override { OnEffectHitTarget += SpellEffectFn(spell_azjol_nerub_fixate_SpellScript::HandleScriptEffect, EFFECT_0, SPELL_EFFECT_SCRIPT_EFFECT); } }; SpellScript* GetSpellScript() const override { return new spell_azjol_nerub_fixate_SpellScript(); } }; class spell_azjol_nerub_web_wrap : public SpellScriptLoader { public: spell_azjol_nerub_web_wrap() : SpellScriptLoader("spell_azjol_nerub_web_wrap") { } class spell_azjol_nerub_web_wrap_AuraScript : public AuraScript { PrepareAuraScript(spell_azjol_nerub_web_wrap_AuraScript); void OnRemove(AuraEffect const* /*aurEff*/, AuraEffectHandleModes /*mode*/) { Unit* target = GetTarget(); if (!target->HasAura(SPELL_WEB_WRAP_TRIGGER)) target->CastSpell(target, SPELL_WEB_WRAP_TRIGGER, true); } void Register() override { OnEffectRemove += AuraEffectRemoveFn(spell_azjol_nerub_web_wrap_AuraScript::OnRemove, EFFECT_0, SPELL_AURA_MOD_ROOT, AURA_EFFECT_HANDLE_REAL); } }; AuraScript* GetAuraScript() const override { return new spell_azjol_nerub_web_wrap_AuraScript(); } }; void AddSC_instance_azjol_nerub() { new instance_azjol_nerub(); new spell_azjol_nerub_fixate(); new spell_azjol_nerub_web_wrap(); } <commit_msg>feat(Core/Scripts): Added Boundary in Azjol nerub (#12159)<commit_after>/* * This file is part of the AzerothCore Project. See AUTHORS file for Copyright information * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU Affero General Public License as published by the * Free Software Foundation; either version 3 of the License, or (at your * option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for * more details. * * You should have received a copy of the GNU General Public License along * with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "AreaBoundary.h" #include "ScriptMgr.h" #include "ScriptedCreature.h" #include "azjol_nerub.h" DoorData const doorData[] = { { GO_KRIKTHIR_DOORS, DATA_KRIKTHIR_THE_GATEWATCHER_EVENT, DOOR_TYPE_PASSAGE }, { GO_ANUBARAK_DOORS1, DATA_ANUBARAK_EVENT, DOOR_TYPE_ROOM }, { GO_ANUBARAK_DOORS2, DATA_ANUBARAK_EVENT, DOOR_TYPE_ROOM }, { GO_ANUBARAK_DOORS3, DATA_ANUBARAK_EVENT, DOOR_TYPE_ROOM }, { 0, 0, DOOR_TYPE_ROOM } }; ObjectData const creatureData[] = { { NPC_KRIKTHIR_THE_GATEWATCHER, DATA_KRIKTHIR_THE_GATEWATCHER_EVENT }, { NPC_HADRONOX, DATA_HADRONOX_EVENT } }; BossBoundaryData const boundaries = { { DATA_KRIKTHIR_THE_GATEWATCHER_EVENT, new RectangleBoundary(400.0f, 580.0f, 623.5f, 810.0f) }, { DATA_HADRONOX_EVENT, new ZRangeBoundary(666.0f, 776.0f) }, { DATA_ANUBARAK_EVENT, new CircleBoundary(Position(550.6178f, 253.5917f), 26.0f) } }; class instance_azjol_nerub : public InstanceMapScript { public: instance_azjol_nerub() : InstanceMapScript("instance_azjol_nerub", 601) { } struct instance_azjol_nerub_InstanceScript : public InstanceScript { instance_azjol_nerub_InstanceScript(Map* map) : InstanceScript(map) { SetBossNumber(MAX_ENCOUNTERS); LoadBossBoundaries(boundaries); LoadDoorData(doorData); LoadObjectData(creatureData, nullptr); }; void OnCreatureCreate(Creature* creature) override { switch (creature->GetEntry()) { case NPC_SKITTERING_SWARMER: case NPC_SKITTERING_INFECTIOR: if (Creature* krikthir = GetCreature((DATA_KRIKTHIR_THE_GATEWATCHER_EVENT))) krikthir->AI()->JustSummoned(creature); break; case NPC_ANUB_AR_CHAMPION: case NPC_ANUB_AR_NECROMANCER: case NPC_ANUB_AR_CRYPTFIEND: if (Creature* hadronox = GetCreature(DATA_HADRONOX_EVENT)) hadronox->AI()->JustSummoned(creature); break; } InstanceScript::OnCreatureCreate(creature); } void OnGameObjectCreate(GameObject* go) override { switch (go->GetEntry()) { case GO_KRIKTHIR_DOORS: case GO_ANUBARAK_DOORS1: case GO_ANUBARAK_DOORS2: case GO_ANUBARAK_DOORS3: AddDoor(go, true); break; } } void OnGameObjectRemove(GameObject* go) override { switch (go->GetEntry()) { case GO_KRIKTHIR_DOORS: case GO_ANUBARAK_DOORS1: case GO_ANUBARAK_DOORS2: case GO_ANUBARAK_DOORS3: AddDoor(go, false); break; } } bool SetBossState(uint32 id, EncounterState state) override { return InstanceScript::SetBossState(id, state); } std::string GetSaveData() override { std::ostringstream saveStream; saveStream << "A N " << GetBossSaveData(); return saveStream.str(); } void Load(const char* in) override { if( !in ) return; char dataHead1, dataHead2; std::istringstream loadStream(in); loadStream >> dataHead1 >> dataHead2; if (dataHead1 == 'A' && dataHead2 == 'N') { for (uint8 i = 0; i < MAX_ENCOUNTERS; ++i) { uint32 tmpState; loadStream >> tmpState; if (tmpState == IN_PROGRESS || tmpState > SPECIAL) tmpState = NOT_STARTED; SetBossState(i, EncounterState(tmpState)); } } } }; InstanceScript* GetInstanceScript(InstanceMap* map) const override { return new instance_azjol_nerub_InstanceScript(map); } }; class spell_azjol_nerub_fixate : public SpellScriptLoader { public: spell_azjol_nerub_fixate() : SpellScriptLoader("spell_azjol_nerub_fixate") { } class spell_azjol_nerub_fixate_SpellScript : public SpellScript { PrepareSpellScript(spell_azjol_nerub_fixate_SpellScript); void HandleScriptEffect(SpellEffIndex effIndex) { PreventHitDefaultEffect(effIndex); if (Unit* target = GetHitUnit()) target->CastSpell(GetCaster(), GetEffectValue(), true); } void Register() override { OnEffectHitTarget += SpellEffectFn(spell_azjol_nerub_fixate_SpellScript::HandleScriptEffect, EFFECT_0, SPELL_EFFECT_SCRIPT_EFFECT); } }; SpellScript* GetSpellScript() const override { return new spell_azjol_nerub_fixate_SpellScript(); } }; class spell_azjol_nerub_web_wrap : public SpellScriptLoader { public: spell_azjol_nerub_web_wrap() : SpellScriptLoader("spell_azjol_nerub_web_wrap") { } class spell_azjol_nerub_web_wrap_AuraScript : public AuraScript { PrepareAuraScript(spell_azjol_nerub_web_wrap_AuraScript); void OnRemove(AuraEffect const* /*aurEff*/, AuraEffectHandleModes /*mode*/) { Unit* target = GetTarget(); if (!target->HasAura(SPELL_WEB_WRAP_TRIGGER)) target->CastSpell(target, SPELL_WEB_WRAP_TRIGGER, true); } void Register() override { OnEffectRemove += AuraEffectRemoveFn(spell_azjol_nerub_web_wrap_AuraScript::OnRemove, EFFECT_0, SPELL_AURA_MOD_ROOT, AURA_EFFECT_HANDLE_REAL); } }; AuraScript* GetAuraScript() const override { return new spell_azjol_nerub_web_wrap_AuraScript(); } }; void AddSC_instance_azjol_nerub() { new instance_azjol_nerub(); new spell_azjol_nerub_fixate(); new spell_azjol_nerub_web_wrap(); } <|endoftext|>
<commit_before>/* LICENSE NOTICE Copyright (c) 2009, Frederick Emmott <[email protected]> Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ #include "Request.h" #include "Request_Private.h" #include <QDebug> #include <QNetworkCookie> #include <QRegExp> #include <QUrl> namespace FastCgiQt { Request::Request(Private* _d, QObject* parent) : QIODevice(parent) , d(_d) { open(QIODevice::ReadWrite); d->device->setParent(this); connect( d->device, SIGNAL(readyRead()), this, SIGNAL(readyRead()) ); } bool Request::atEnd() const { const bool atEnd = d->device->atEnd() && QIODevice::atEnd(); return atEnd; } bool Request::isSequential() const { return true; } qint64 Request::readData(char* data, qint64 maxSize) { Q_ASSERT(d->postDataMode == Private::UnknownPostData || d->postDataMode == Private::RawPostData); d->postDataMode = Private::RawPostData; Q_ASSERT(d->device->isOpen()); Q_ASSERT(d->device->isReadable()); const qint64 bytesRead = d->device->read(data, maxSize); return bytesRead; } qint64 Request::writeData(const char* data, qint64 maxSize) { QIODevice* device = d->device; if(!d->haveSentHeaders) { d->haveSentHeaders = true; for(ClientIODevice::HeaderMap::ConstIterator it = d->responseHeaders.constBegin(); it != d->responseHeaders.constEnd(); ++it) { device->write(it.key()); device->write(": "); device->write(it.value()); device->write("\r\n"); } device->write("\r\n"); } return device->write(data, maxSize); } qint64 Request::size() const { return QString::fromLatin1(rawValue(ServerData, "CONTENT_LENGTH")).toLongLong(); } QUrl Request::url(UrlPart part) const { QUrl url; // Protocol and host are needed, regardless of part ///@fixme - HTTPS support url.setScheme("http"); // authority == user:password@host:port - as HTTP_HOST contains user and port, go with that url.setAuthority(value(ServerData, "HTTP_HOST")); const int queryStringOffset = rawValue(ServerData, "REQUEST_URI").contains('?') ? 1 : 0; const int queryStringLength = rawValue(ServerData, "QUERY_STRING").length() + queryStringOffset; switch(part) { case RootUrl: { const int pathInfoLength = rawValue(ServerData, "PATH_INFO").length(); QByteArray basePath = rawValue(ServerData, "REQUEST_URI"); basePath.chop(queryStringLength + pathInfoLength); url.setEncodedPath(basePath); break; } case LocationUrl: case RequestUrl: { QByteArray basePath = rawValue(ServerData, "REQUEST_URI"); basePath.chop(queryStringLength); url.setEncodedPath(basePath); if(part == RequestUrl) { url.setEncodedQuery(rawValue(ServerData, "QUERY_STRING")); } break; } default: qFatal("Unknown URL part: %d", part); } return url; } QList<QNetworkCookie> Request::cookies() const { QList<QNetworkCookie> cookies; for(ClientIODevice::HeaderMap::ConstIterator it = d->serverData.constBegin(); it != d->serverData.constEnd(); ++it) { if(it.key().toUpper() == "HTTP_COOKIE") { QList<QByteArray> list = it.value().split(';'); for(int i = 0; i < list.length(); ++i) { cookies.append(QNetworkCookie::parseCookies(list.at(i))); } } } return cookies; } void Request::sendCookie(const QNetworkCookie& cookie) { addHeader("set-cookie", cookie.toRawForm()); } void Request::setHeader(const QByteArray& name, const QByteArray& value) { Q_ASSERT(!d->haveSentHeaders); d->responseHeaders[name] = value; } void Request::addHeader(const QByteArray& name, const QByteArray& value) { Q_ASSERT(!d->haveSentHeaders); d->responseHeaders.insertMulti(name, value); } QByteArray Request::responseHeader(const QByteArray& name) { return d->responseHeaders.value(name); } QHash<QByteArray, QByteArray> Request::rawValues(DataSource source) const { switch(source) { case GetData: return d->getData; case PostData: d->loadPostVariables(); return d->postData; case ServerData: return d->serverData; default: qFatal("Unknown value type: %d", source); } return QHash<QByteArray, QByteArray>(); } QByteArray Request::rawValue(DataSource source, const QByteArray& name) const { return rawValues(source).value(name); } QString Request::value(DataSource source, const QByteArray& name) const { return QUrl::fromPercentEncoding(rawValue(source, name)); } Request::~Request() { emit finished(this); delete d; } } <commit_msg>Support HTTPS base URLs - Thanks to Hauke Wintjen<commit_after>/* LICENSE NOTICE Copyright (c) 2009, Frederick Emmott <[email protected]> Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ #include "Request.h" #include "Request_Private.h" #include <QDebug> #include <QNetworkCookie> #include <QRegExp> #include <QUrl> namespace FastCgiQt { Request::Request(Private* _d, QObject* parent) : QIODevice(parent) , d(_d) { open(QIODevice::ReadWrite); d->device->setParent(this); connect( d->device, SIGNAL(readyRead()), this, SIGNAL(readyRead()) ); } bool Request::atEnd() const { const bool atEnd = d->device->atEnd() && QIODevice::atEnd(); return atEnd; } bool Request::isSequential() const { return true; } qint64 Request::readData(char* data, qint64 maxSize) { Q_ASSERT(d->postDataMode == Private::UnknownPostData || d->postDataMode == Private::RawPostData); d->postDataMode = Private::RawPostData; Q_ASSERT(d->device->isOpen()); Q_ASSERT(d->device->isReadable()); const qint64 bytesRead = d->device->read(data, maxSize); return bytesRead; } qint64 Request::writeData(const char* data, qint64 maxSize) { QIODevice* device = d->device; if(!d->haveSentHeaders) { d->haveSentHeaders = true; for(ClientIODevice::HeaderMap::ConstIterator it = d->responseHeaders.constBegin(); it != d->responseHeaders.constEnd(); ++it) { device->write(it.key()); device->write(": "); device->write(it.value()); device->write("\r\n"); } device->write("\r\n"); } return device->write(data, maxSize); } qint64 Request::size() const { return QString::fromLatin1(rawValue(ServerData, "CONTENT_LENGTH")).toLongLong(); } QUrl Request::url(UrlPart part) const { QUrl url; // Protocol and host are needed, regardless of part if(rawValue(ServerData,"HTTPS") == "on") { url.setScheme("https"); } else { url.setScheme("http"); } // authority == user:password@host:port - as HTTP_HOST contains user and port, go with that url.setAuthority(value(ServerData, "HTTP_HOST")); const int queryStringOffset = rawValue(ServerData, "REQUEST_URI").contains('?') ? 1 : 0; const int queryStringLength = rawValue(ServerData, "QUERY_STRING").length() + queryStringOffset; switch(part) { case RootUrl: { const int pathInfoLength = rawValue(ServerData, "PATH_INFO").length(); QByteArray basePath = rawValue(ServerData, "REQUEST_URI"); basePath.chop(queryStringLength + pathInfoLength); url.setEncodedPath(basePath); break; } case LocationUrl: case RequestUrl: { QByteArray basePath = rawValue(ServerData, "REQUEST_URI"); basePath.chop(queryStringLength); url.setEncodedPath(basePath); if(part == RequestUrl) { url.setEncodedQuery(rawValue(ServerData, "QUERY_STRING")); } break; } default: qFatal("Unknown URL part: %d", part); } return url; } QList<QNetworkCookie> Request::cookies() const { QList<QNetworkCookie> cookies; for(ClientIODevice::HeaderMap::ConstIterator it = d->serverData.constBegin(); it != d->serverData.constEnd(); ++it) { if(it.key().toUpper() == "HTTP_COOKIE") { QList<QByteArray> list = it.value().split(';'); for(int i = 0; i < list.length(); ++i) { cookies.append(QNetworkCookie::parseCookies(list.at(i))); } } } return cookies; } void Request::sendCookie(const QNetworkCookie& cookie) { addHeader("set-cookie", cookie.toRawForm()); } void Request::setHeader(const QByteArray& name, const QByteArray& value) { Q_ASSERT(!d->haveSentHeaders); d->responseHeaders[name] = value; } void Request::addHeader(const QByteArray& name, const QByteArray& value) { Q_ASSERT(!d->haveSentHeaders); d->responseHeaders.insertMulti(name, value); } QByteArray Request::responseHeader(const QByteArray& name) { return d->responseHeaders.value(name); } QHash<QByteArray, QByteArray> Request::rawValues(DataSource source) const { switch(source) { case GetData: return d->getData; case PostData: d->loadPostVariables(); return d->postData; case ServerData: return d->serverData; default: qFatal("Unknown value type: %d", source); } return QHash<QByteArray, QByteArray>(); } QByteArray Request::rawValue(DataSource source, const QByteArray& name) const { return rawValues(source).value(name); } QString Request::value(DataSource source, const QByteArray& name) const { return QUrl::fromPercentEncoding(rawValue(source, name)); } Request::~Request() { emit finished(this); delete d; } } <|endoftext|>
<commit_before>/** ****************************************************************************** * Xenia : Xbox 360 Emulator Research Project * ****************************************************************************** * Copyright 2013 Ben Vanik. All rights reserved. * * Released under the BSD license - see LICENSE in the root for more details. * ****************************************************************************** */ #include "xenia/base/logging.h" #include "xenia/kernel/kernel_state.h" #include "xenia/kernel/objects/xenumerator.h" #include "xenia/kernel/objects/xuser_module.h" #include "xenia/kernel/util/shim_utils.h" #include "xenia/kernel/util/xex2.h" #include "xenia/kernel/xam_private.h" #include "xenia/xbox.h" namespace xe { namespace kernel { SHIM_CALL XamGetSystemVersion_shim(PPCContext* ppc_state, KernelState* state) { XELOGD("XamGetSystemVersion()"); // eh, just picking one. If we go too low we may break new games, but // this value seems to be used for conditionally loading symbols and if // we pretend to be old we have less to worry with implementing. // 0x200A3200 // 0x20096B00 SHIM_SET_RETURN_64(0); } SHIM_CALL XGetAVPack_shim(PPCContext* ppc_state, KernelState* state) { // DWORD // Not sure what the values are for this, but 6 is VGA. // Other likely values are 3/4/8 for HDMI or something. // Games seem to use this as a PAL check - if the result is not 3/4/6/8 // they explode with errors if not in PAL mode. SHIM_SET_RETURN_64(6); } SHIM_CALL XGetGameRegion_shim(PPCContext* ppc_state, KernelState* state) { XELOGD("XGetGameRegion()"); SHIM_SET_RETURN_64(0xFFFF); } SHIM_CALL XGetLanguage_shim(PPCContext* ppc_state, KernelState* state) { XELOGD("XGetLanguage()"); uint32_t desired_language = X_LANGUAGE_ENGLISH; // Switch the language based on game region. // TODO(benvanik): pull from xex header. uint32_t game_region = XEX_REGION_NTSCU; if (game_region & XEX_REGION_NTSCU) { desired_language = X_LANGUAGE_ENGLISH; } else if (game_region & XEX_REGION_NTSCJ) { desired_language = X_LANGUAGE_JAPANESE; } // Add more overrides? SHIM_SET_RETURN_64(desired_language); } SHIM_CALL XamVoiceIsActiveProcess_shim(PPCContext* ppc_state, KernelState* state) { XELOGD("XamVoiceIsActiveProcess()"); // Returning 0 here will short-circuit a bunch of voice stuff. SHIM_SET_RETURN_32(0); } SHIM_CALL XamGetExecutionId_shim(PPCContext* ppc_state, KernelState* state) { uint32_t info_ptr = SHIM_GET_ARG_32(0); XELOGD("XamGetExecutionId(%.8X)", info_ptr); auto module = state->GetExecutableModule(); assert_not_null(module); SHIM_SET_MEM_32(info_ptr, module->execution_info_ptr()); SHIM_SET_RETURN_32(0); } SHIM_CALL XamLoaderSetLaunchData_shim(PPCContext* ppc_state, KernelState* state) { uint32_t data_ptr = SHIM_GET_ARG_32(0); uint32_t data_size = SHIM_GET_ARG_32(1); XELOGD("XamLoaderSetLaunchData(%.8X, %d)", data_ptr, data_size); // Unknown return value. SHIM_SET_RETURN_32(0); } SHIM_CALL XamLoaderGetLaunchDataSize_shim(PPCContext* ppc_state, KernelState* state) { uint32_t size_ptr = SHIM_GET_ARG_32(0); XELOGD("XamLoaderGetLaunchDataSize(%.8X)", size_ptr); SHIM_SET_MEM_32(size_ptr, 0); SHIM_SET_RETURN_32(1); } SHIM_CALL XamLoaderGetLaunchData_shim(PPCContext* ppc_state, KernelState* state) { uint32_t buffer_ptr = SHIM_GET_ARG_32(0); uint32_t buffer_size = SHIM_GET_ARG_32(1); XELOGD("XamLoaderGetLaunchData(%.8X, %d)", buffer_ptr, buffer_size); SHIM_SET_RETURN_32(0); } SHIM_CALL XamLoaderLaunchTitle_shim(PPCContext* ppc_state, KernelState* state) { uint32_t name_ptr = SHIM_GET_ARG_32(0); const char* name = (const char*)SHIM_MEM_ADDR(name_ptr); uint32_t unk2 = SHIM_GET_ARG_32(1); XELOGD("XamLoaderLaunchTitle(%.8X(%s), %.8X)", name_ptr, name, unk2); assert_always(); } SHIM_CALL XamLoaderTerminateTitle_shim(PPCContext* ppc_state, KernelState* state) { XELOGD("XamLoaderTerminateTitle()"); assert_always(); } SHIM_CALL XamAlloc_shim(PPCContext* ppc_state, KernelState* state) { uint32_t unk = SHIM_GET_ARG_32(0); uint32_t size = SHIM_GET_ARG_32(1); uint32_t out_ptr = SHIM_GET_ARG_32(2); XELOGD("XamAlloc(%d, %d, %.8X)", unk, size, out_ptr); assert_true(unk == 0); // Allocate from the heap. Not sure why XAM does this specially, perhaps // it keeps stuff in a separate heap? uint32_t ptr = state->memory()->SystemHeapAlloc(size); SHIM_SET_MEM_32(out_ptr, ptr); SHIM_SET_RETURN_32(X_ERROR_SUCCESS); } SHIM_CALL XamFree_shim(PPCContext* ppc_state, KernelState* state) { uint32_t ptr = SHIM_GET_ARG_32(0); XELOGD("XamFree(%.8X)", ptr); state->memory()->SystemHeapFree(ptr); SHIM_SET_RETURN_32(X_ERROR_SUCCESS); } SHIM_CALL XamEnumerate_shim(PPCContext* ppc_state, KernelState* state) { uint32_t handle = SHIM_GET_ARG_32(0); uint32_t zero = SHIM_GET_ARG_32(1); uint32_t buffer_ptr = SHIM_GET_ARG_32(2); uint32_t buffer_length = SHIM_GET_ARG_32(3); uint32_t item_count_ptr = SHIM_GET_ARG_32(4); uint32_t overlapped_ptr = SHIM_GET_ARG_32(5); assert_true(zero == 0); XELOGD("XamEnumerate(%.8X, %d, %.8X, %d, %.8X, %.8X)", handle, zero, buffer_ptr, buffer_length, item_count_ptr, overlapped_ptr); auto e = state->object_table()->LookupObject<XEnumerator>(handle); if (!e) { if (overlapped_ptr) { state->CompleteOverlappedImmediateEx(overlapped_ptr, 0, X_ERROR_INVALID_HANDLE, 0); SHIM_SET_RETURN_64(X_ERROR_IO_PENDING); } else { SHIM_SET_RETURN_64(X_ERROR_INVALID_HANDLE); } return; } auto item_count = e->item_count(); e->WriteItems(SHIM_MEM_ADDR(buffer_ptr)); X_RESULT result = item_count ? X_ERROR_SUCCESS : X_ERROR_NO_MORE_FILES; if (item_count_ptr) { assert_zero(overlapped_ptr); SHIM_SET_MEM_32(item_count_ptr, item_count); } else if (overlapped_ptr) { assert_zero(item_count_ptr); state->CompleteOverlappedImmediateEx(overlapped_ptr, result, result, item_count); result = X_ERROR_IO_PENDING; } else { assert_always(); result = X_ERROR_INVALID_PARAMETER; } SHIM_SET_RETURN_64(result); } } // namespace kernel } // namespace xe void xe::kernel::xam::RegisterInfoExports( xe::cpu::ExportResolver* export_resolver, KernelState* state) { SHIM_SET_MAPPING("xam.xex", XamGetSystemVersion, state); SHIM_SET_MAPPING("xam.xex", XGetAVPack, state); SHIM_SET_MAPPING("xam.xex", XGetGameRegion, state); SHIM_SET_MAPPING("xam.xex", XGetLanguage, state); SHIM_SET_MAPPING("xam.xex", XamVoiceIsActiveProcess, state); SHIM_SET_MAPPING("xam.xex", XamGetExecutionId, state); SHIM_SET_MAPPING("xam.xex", XamLoaderSetLaunchData, state); SHIM_SET_MAPPING("xam.xex", XamLoaderGetLaunchDataSize, state); SHIM_SET_MAPPING("xam.xex", XamLoaderGetLaunchData, state); SHIM_SET_MAPPING("xam.xex", XamLoaderLaunchTitle, state); SHIM_SET_MAPPING("xam.xex", XamLoaderTerminateTitle, state); SHIM_SET_MAPPING("xam.xex", XamAlloc, state); SHIM_SET_MAPPING("xam.xex", XamFree, state); SHIM_SET_MAPPING("xam.xex", XamEnumerate, state); } <commit_msg>Hurf. SHIM_SET_RETURN_64 -> SHIM_SET_RETURN_32.<commit_after>/** ****************************************************************************** * Xenia : Xbox 360 Emulator Research Project * ****************************************************************************** * Copyright 2013 Ben Vanik. All rights reserved. * * Released under the BSD license - see LICENSE in the root for more details. * ****************************************************************************** */ #include "xenia/base/logging.h" #include "xenia/kernel/kernel_state.h" #include "xenia/kernel/objects/xenumerator.h" #include "xenia/kernel/objects/xuser_module.h" #include "xenia/kernel/util/shim_utils.h" #include "xenia/kernel/util/xex2.h" #include "xenia/kernel/xam_private.h" #include "xenia/xbox.h" namespace xe { namespace kernel { SHIM_CALL XamGetSystemVersion_shim(PPCContext* ppc_state, KernelState* state) { XELOGD("XamGetSystemVersion()"); // eh, just picking one. If we go too low we may break new games, but // this value seems to be used for conditionally loading symbols and if // we pretend to be old we have less to worry with implementing. // 0x200A3200 // 0x20096B00 SHIM_SET_RETURN_64(0); } SHIM_CALL XGetAVPack_shim(PPCContext* ppc_state, KernelState* state) { // DWORD // Not sure what the values are for this, but 6 is VGA. // Other likely values are 3/4/8 for HDMI or something. // Games seem to use this as a PAL check - if the result is not 3/4/6/8 // they explode with errors if not in PAL mode. SHIM_SET_RETURN_64(6); } SHIM_CALL XGetGameRegion_shim(PPCContext* ppc_state, KernelState* state) { XELOGD("XGetGameRegion()"); SHIM_SET_RETURN_64(0xFFFF); } SHIM_CALL XGetLanguage_shim(PPCContext* ppc_state, KernelState* state) { XELOGD("XGetLanguage()"); uint32_t desired_language = X_LANGUAGE_ENGLISH; // Switch the language based on game region. // TODO(benvanik): pull from xex header. uint32_t game_region = XEX_REGION_NTSCU; if (game_region & XEX_REGION_NTSCU) { desired_language = X_LANGUAGE_ENGLISH; } else if (game_region & XEX_REGION_NTSCJ) { desired_language = X_LANGUAGE_JAPANESE; } // Add more overrides? SHIM_SET_RETURN_64(desired_language); } SHIM_CALL XamVoiceIsActiveProcess_shim(PPCContext* ppc_state, KernelState* state) { XELOGD("XamVoiceIsActiveProcess()"); // Returning 0 here will short-circuit a bunch of voice stuff. SHIM_SET_RETURN_32(0); } SHIM_CALL XamGetExecutionId_shim(PPCContext* ppc_state, KernelState* state) { uint32_t info_ptr = SHIM_GET_ARG_32(0); XELOGD("XamGetExecutionId(%.8X)", info_ptr); auto module = state->GetExecutableModule(); assert_not_null(module); SHIM_SET_MEM_32(info_ptr, module->execution_info_ptr()); SHIM_SET_RETURN_32(0); } SHIM_CALL XamLoaderSetLaunchData_shim(PPCContext* ppc_state, KernelState* state) { uint32_t data_ptr = SHIM_GET_ARG_32(0); uint32_t data_size = SHIM_GET_ARG_32(1); XELOGD("XamLoaderSetLaunchData(%.8X, %d)", data_ptr, data_size); // Unknown return value. SHIM_SET_RETURN_32(0); } SHIM_CALL XamLoaderGetLaunchDataSize_shim(PPCContext* ppc_state, KernelState* state) { uint32_t size_ptr = SHIM_GET_ARG_32(0); XELOGD("XamLoaderGetLaunchDataSize(%.8X)", size_ptr); SHIM_SET_MEM_32(size_ptr, 0); SHIM_SET_RETURN_32(1); } SHIM_CALL XamLoaderGetLaunchData_shim(PPCContext* ppc_state, KernelState* state) { uint32_t buffer_ptr = SHIM_GET_ARG_32(0); uint32_t buffer_size = SHIM_GET_ARG_32(1); XELOGD("XamLoaderGetLaunchData(%.8X, %d)", buffer_ptr, buffer_size); SHIM_SET_RETURN_32(0); } SHIM_CALL XamLoaderLaunchTitle_shim(PPCContext* ppc_state, KernelState* state) { uint32_t name_ptr = SHIM_GET_ARG_32(0); const char* name = (const char*)SHIM_MEM_ADDR(name_ptr); uint32_t unk2 = SHIM_GET_ARG_32(1); XELOGD("XamLoaderLaunchTitle(%.8X(%s), %.8X)", name_ptr, name, unk2); assert_always(); } SHIM_CALL XamLoaderTerminateTitle_shim(PPCContext* ppc_state, KernelState* state) { XELOGD("XamLoaderTerminateTitle()"); assert_always(); } SHIM_CALL XamAlloc_shim(PPCContext* ppc_state, KernelState* state) { uint32_t unk = SHIM_GET_ARG_32(0); uint32_t size = SHIM_GET_ARG_32(1); uint32_t out_ptr = SHIM_GET_ARG_32(2); XELOGD("XamAlloc(%d, %d, %.8X)", unk, size, out_ptr); assert_true(unk == 0); // Allocate from the heap. Not sure why XAM does this specially, perhaps // it keeps stuff in a separate heap? uint32_t ptr = state->memory()->SystemHeapAlloc(size); SHIM_SET_MEM_32(out_ptr, ptr); SHIM_SET_RETURN_32(X_ERROR_SUCCESS); } SHIM_CALL XamFree_shim(PPCContext* ppc_state, KernelState* state) { uint32_t ptr = SHIM_GET_ARG_32(0); XELOGD("XamFree(%.8X)", ptr); state->memory()->SystemHeapFree(ptr); SHIM_SET_RETURN_32(X_ERROR_SUCCESS); } SHIM_CALL XamEnumerate_shim(PPCContext* ppc_state, KernelState* state) { uint32_t handle = SHIM_GET_ARG_32(0); uint32_t zero = SHIM_GET_ARG_32(1); uint32_t buffer_ptr = SHIM_GET_ARG_32(2); uint32_t buffer_length = SHIM_GET_ARG_32(3); uint32_t item_count_ptr = SHIM_GET_ARG_32(4); uint32_t overlapped_ptr = SHIM_GET_ARG_32(5); assert_true(zero == 0); XELOGD("XamEnumerate(%.8X, %d, %.8X, %d, %.8X, %.8X)", handle, zero, buffer_ptr, buffer_length, item_count_ptr, overlapped_ptr); auto e = state->object_table()->LookupObject<XEnumerator>(handle); if (!e) { if (overlapped_ptr) { state->CompleteOverlappedImmediateEx(overlapped_ptr, 0, X_ERROR_INVALID_HANDLE, 0); SHIM_SET_RETURN_32(X_ERROR_IO_PENDING); } else { SHIM_SET_RETURN_32(X_ERROR_INVALID_HANDLE); } return; } auto item_count = e->item_count(); e->WriteItems(SHIM_MEM_ADDR(buffer_ptr)); X_RESULT result = item_count ? X_ERROR_SUCCESS : X_ERROR_NO_MORE_FILES; if (item_count_ptr) { assert_zero(overlapped_ptr); SHIM_SET_MEM_32(item_count_ptr, item_count); } else if (overlapped_ptr) { assert_zero(item_count_ptr); state->CompleteOverlappedImmediateEx(overlapped_ptr, result, result, item_count); result = X_ERROR_IO_PENDING; } else { assert_always(); result = X_ERROR_INVALID_PARAMETER; } SHIM_SET_RETURN_32(result); } } // namespace kernel } // namespace xe void xe::kernel::xam::RegisterInfoExports( xe::cpu::ExportResolver* export_resolver, KernelState* state) { SHIM_SET_MAPPING("xam.xex", XamGetSystemVersion, state); SHIM_SET_MAPPING("xam.xex", XGetAVPack, state); SHIM_SET_MAPPING("xam.xex", XGetGameRegion, state); SHIM_SET_MAPPING("xam.xex", XGetLanguage, state); SHIM_SET_MAPPING("xam.xex", XamVoiceIsActiveProcess, state); SHIM_SET_MAPPING("xam.xex", XamGetExecutionId, state); SHIM_SET_MAPPING("xam.xex", XamLoaderSetLaunchData, state); SHIM_SET_MAPPING("xam.xex", XamLoaderGetLaunchDataSize, state); SHIM_SET_MAPPING("xam.xex", XamLoaderGetLaunchData, state); SHIM_SET_MAPPING("xam.xex", XamLoaderLaunchTitle, state); SHIM_SET_MAPPING("xam.xex", XamLoaderTerminateTitle, state); SHIM_SET_MAPPING("xam.xex", XamAlloc, state); SHIM_SET_MAPPING("xam.xex", XamFree, state); SHIM_SET_MAPPING("xam.xex", XamEnumerate, state); } <|endoftext|>
<commit_before>/**************************************************************************** ** ** Copyright (c) 2008-2009 Nokia Corporation and/or its subsidiary(-ies). ** Contact: Nokia Corporation ([email protected]) ** ** This file is part of the Qt Mobility Components. ** ** $QT_BEGIN_LICENSE:LGPL$ ** No Commercial Usage ** This file contains pre-release code and may not be distributed. ** You may use this file in accordance with the terms and conditions ** contained in the Technology Preview License Agreement accompanying ** this package. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Nokia gives you certain ** additional rights. These rights are described in the Nokia Qt LGPL ** Exception version 1.0, included in the file LGPL_EXCEPTION.txt in this ** package. ** ** If you have questions regarding the use of this file, please ** contact Nokia at http://qt.nokia.com/contact. ** $QT_END_LICENSE$ ** ****************************************************************************/ #include "support.h" #include <qmessageaccountid.h> #include <qmessagefolderid.h> #include <qmessageid.h> namespace Support { void clearMessageStore() { } QMessageAccountId addAccount(const Parameters &params) { Q_UNUSED(params) return QMessageAccountId(); } #ifdef QMESSAGING_OPTIONAL_FOLDER QMessageFolderId addFolder(const Parameters &params) { Q_UNUSED(params) return QMessageFolderId(); } #endif QMessageId addMessage(const Parameters &params) { Q_UNUSED(params) return QMessageId(); } } <commit_msg>AddAccount for MAPI.<commit_after>/**************************************************************************** ** ** Copyright (c) 2008-2009 Nokia Corporation and/or its subsidiary(-ies). ** Contact: Nokia Corporation ([email protected]) ** ** This file is part of the Qt Mobility Components. ** ** $QT_BEGIN_LICENSE:LGPL$ ** No Commercial Usage ** This file contains pre-release code and may not be distributed. ** You may use this file in accordance with the terms and conditions ** contained in the Technology Preview License Agreement accompanying ** this package. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Nokia gives you certain ** additional rights. These rights are described in the Nokia Qt LGPL ** Exception version 1.0, included in the file LGPL_EXCEPTION.txt in this ** package. ** ** If you have questions regarding the use of this file, please ** contact Nokia at http://qt.nokia.com/contact. ** $QT_END_LICENSE$ ** ****************************************************************************/ #include "support.h" #include <qmessageaccountid.h> #include <qmessagefolderid.h> #include <qmessageid.h> #include <qmessagestore.h> #include <QDataStream> #include <QDebug> #include <Mapidefs.h> #include <Mapitags.h> #include <Mapix.h> #include <MAPIUtil.h> // Missing definitions #ifndef PR_PST_CONFIG_FLAGS #define PR_PST_CONFIG_FLAGS PROP_TAG( PT_LONG, 0x6770 ) #endif #ifndef PST_CONFIG_UNICODE #define PST_CONFIG_UNICODE 0x80000000 #endif #ifndef PR_PST_PATH_A #define PR_PST_PATH_A PROP_TAG( PT_STRING8, 0x6700 ) #endif namespace { void doInit() { static QMessageStore *store(0); if (!store) { store = QMessageStore::instance(); } } typedef QPair<QByteArray, bool> ProfileDetail; QList<ProfileDetail> profileDetails(LPPROFADMIN profAdmin) { QList<ProfileDetail> result; LPMAPITABLE profileTable(0); HRESULT rv = profAdmin->GetProfileTable(0, &profileTable); if (HR_SUCCEEDED(rv)) { LPSRowSet rows(0); SizedSPropTagArray(2, cols) = {2, {PR_DISPLAY_NAME_A, PR_DEFAULT_PROFILE}}; rv = HrQueryAllRows(profileTable, reinterpret_cast<LPSPropTagArray>(&cols), NULL, NULL, 0, &rows); if (HR_SUCCEEDED(rv)) { for (uint n = 0; n < rows->cRows; ++n) { if (rows->aRow[n].lpProps[0].ulPropTag == PR_DISPLAY_NAME_A) { QByteArray profileName(rows->aRow[n].lpProps[0].Value.lpszA); bool defaultProfile(rows->aRow[n].lpProps[1].Value.b); result.append(qMakePair(profileName, defaultProfile)); } } FreeProws(rows); } else { qWarning() << "profileNames: HrQueryAllRows failed"; } profileTable->Release(); } else { qWarning() << "profileNames: GetProfileTable failed"; } return result; } typedef QPair<QByteArray, MAPIUID> ServiceDetail; QList<ServiceDetail> serviceDetails(LPSERVICEADMIN svcAdmin) { QList<ServiceDetail> result; IMAPITable *svcTable(0); HRESULT rv = svcAdmin->GetMsgServiceTable(0, &svcTable); if (HR_SUCCEEDED(rv)) { LPSRowSet rows(0); SizedSPropTagArray(2, cols) = {2, {PR_SERVICE_NAME_A, PR_SERVICE_UID}}; rv = HrQueryAllRows(svcTable, reinterpret_cast<LPSPropTagArray>(&cols), 0, 0, 0, &rows); if (HR_SUCCEEDED(rv)) { for (uint n = 0; n < rows->cRows; ++n) { if (rows->aRow[n].lpProps[0].ulPropTag == PR_SERVICE_NAME_A) { QByteArray svcName(rows->aRow[n].lpProps[0].Value.lpszA); MAPIUID svcUid(*(reinterpret_cast<MAPIUID*>(rows->aRow[n].lpProps[1].Value.bin.lpb))); result.append(qMakePair(svcName, svcUid)); } } FreeProws(rows); } else { qWarning() << "serviceDetails: HrQueryAllRows failed"; } svcTable->Release(); } else { qWarning() << "serviceDetails: GetMsgServiceTable failed"; } return result; } typedef QPair<QByteArray, QByteArray> StoreDetail; QList<StoreDetail> storeDetails(LPMAPISESSION session) { QList<StoreDetail> result; IMAPITable *storesTable(0); HRESULT rv = session->GetMsgStoresTable(0, &storesTable); if (HR_SUCCEEDED(rv)) { LPSRowSet rows(0); SizedSPropTagArray(2, cols) = {2, {PR_DISPLAY_NAME_A, PR_RECORD_KEY}}; rv = HrQueryAllRows(storesTable, reinterpret_cast<LPSPropTagArray>(&cols), 0, 0, 0, &rows); if (HR_SUCCEEDED(rv)) { for (uint n = 0; n < rows->cRows; ++n) { if (rows->aRow[n].lpProps[0].ulPropTag == PR_DISPLAY_NAME_A) { QByteArray storeName(rows->aRow[n].lpProps[0].Value.lpszA); QByteArray recordKey(reinterpret_cast<const char*>(rows->aRow[n].lpProps[1].Value.bin.lpb), rows->aRow[n].lpProps[1].Value.bin.cb); result.append(qMakePair(storeName, recordKey)); } } FreeProws(rows); } else { qWarning() << "storeDetails: HrQueryAllRows failed"; } storesTable->Release(); } else { qWarning() << "storeDetails: GetMsgStoresTable failed"; } return result; } QMessageAccountId accountIdFromRecordKey(const QByteArray &recordKey) { QByteArray encodedId; { QDataStream encodedIdStream(&encodedId, QIODevice::WriteOnly); encodedIdStream << recordKey; } return QMessageAccountId(encodedId.toBase64()); } } namespace Support { void clearMessageStore() { // Ensure the store is instantiated doInit(); } QMessageAccountId addAccount(const Parameters &params) { QMessageAccountId result; doInit(); QString accountName(params["name"]); if (!accountName.isEmpty()) { // Profile name must be ASCII QByteArray name(accountName.toAscii()); // See if a profile exists with the given name LPPROFADMIN profAdmin(0); HRESULT rv = MAPIAdminProfiles(0, &profAdmin); if (HR_SUCCEEDED(rv)) { // Find the default profile QByteArray defaultProfileName; foreach (const ProfileDetail &profile, profileDetails(profAdmin)) { if (profile.second) { defaultProfileName = profile.first; break; } } if (!defaultProfileName.isEmpty()) { // Open a session on the profile LPMAPISESSION session(0); rv = MAPILogonEx(0, reinterpret_cast<LPTSTR>(defaultProfileName.data()), 0, MAPI_EXTENDED | MAPI_NEW_SESSION | MAPI_NO_MAIL, &session); if (HR_SUCCEEDED(rv)) { LPSERVICEADMIN svcAdmin(0); rv = profAdmin->AdminServices(reinterpret_cast<LPTSTR>(defaultProfileName.data()), 0, 0, 0, &svcAdmin); if (HR_SUCCEEDED(rv)) { char *providerName = "MSUPST MS"; bool serviceExists(false); MAPIUID svcUid = { 0 }; foreach (const ServiceDetail &svc, serviceDetails(svcAdmin)) { if (svc.first.toLower() == QByteArray(providerName).toLower()) { svcUid = svc.second; serviceExists = true; break; } } if (serviceExists) { // Delete the existing service rv = svcAdmin->DeleteMsgService(&svcUid); if (HR_SUCCEEDED(rv)) { serviceExists = false; } else { qWarning() << "DeleteMsgService failed"; } } if (!serviceExists) { // Create a message service for this profile using the standard provider rv = svcAdmin->CreateMsgService(reinterpret_cast<LPTSTR>(providerName), reinterpret_cast<LPTSTR>(name.data()), 0, 0); if (HR_SUCCEEDED(rv)) { foreach (const ServiceDetail &svc, serviceDetails(svcAdmin)) { // Find the name/UID for the service we added if (svc.first.toLower() == QByteArray(providerName).toLower()) { // Create a .PST message store for this service QByteArray path(QString("%1.pst").arg(name.constData()).toAscii()); SPropValue props[3] = { 0 }; props[0].ulPropTag = PR_DISPLAY_NAME_A; props[0].Value.lpszA = name.data(); props[1].ulPropTag = PR_PST_PATH_A; props[1].Value.lpszA = path.data(); props[2].ulPropTag = PR_PST_CONFIG_FLAGS; props[2].Value.l = PST_CONFIG_UNICODE; svcUid = svc.second; rv = svcAdmin->ConfigureMsgService(&svcUid, 0, 0, 3, props); if (HR_SUCCEEDED(rv)) { serviceExists = true; } else { qWarning() << "ConfigureMsgService failed"; } break; } } } else { qWarning() << "CreateMsgService failed"; } } if (serviceExists) { foreach (const StoreDetail &store, storeDetails(session)) { if (store.first.toLower() == name.toLower()) { result = accountIdFromRecordKey(store.second); break; } } } svcAdmin->Release(); } else { qWarning() << "AdminServices failed"; } session->Release(); } else { qWarning() << "MAPILogonEx failed"; } } else { qWarning() << "No default profile found!"; } profAdmin->Release(); } else { qWarning() << "MAPIAdminProfiles failed"; } } return result; } #ifdef QMESSAGING_OPTIONAL_FOLDER QMessageFolderId addFolder(const Parameters &params) { Q_UNUSED(params) return QMessageFolderId(); } #endif QMessageId addMessage(const Parameters &params) { Q_UNUSED(params) return QMessageId(); } } <|endoftext|>
<commit_before>//---------------------------- support_point_map.cc --------------------------- // support_point_map.cc,v 1.6 2003/04/09 15:49:54 wolf Exp // Version: // // Copyright (C) 2000, 2001, 2003 by the deal.II authors // // This file is subject to QPL and may not be distributed // without copyright and license information. Please refer // to the file deal.II/doc/license.html for the text and // further information on this license. // //---------------------------- support_point_map.cc --------------------------- /* Author: Wolfgang Bangerth, University of Heidelberg, 2001 */ /* Purpose: check the map_dofs_to_support_points and map_support_points_to_dofs functions. */ #include "../tests.h" #include <base/logstream.h> #include <base/function_lib.h> #include <lac/vector.h> #include <grid/tria.h> #include <grid/tria_iterator.h> #include <grid/tria_boundary_lib.h> #include <dofs/dof_accessor.h> #include <grid/grid_generator.h> #include <dofs/dof_handler.h> #include <dofs/dof_tools.h> #include <fe/fe_q.h> #include <fe/fe_dgq.h> #include <fe/fe_system.h> #include <fe/mapping_q.h> #include <fstream> template <int dim> struct PointComp { bool operator () (const Point<dim> &, const Point<dim> &) const; }; template <> bool PointComp<1>::operator () (const Point<1> &p1, const Point<1> &p2) const { return p1(0) < p2(0); } // have somewhat weird orderings in 2d and 3d template <> bool PointComp<2>::operator () (const Point<2> &p1, const Point<2> &p2) const { return ((p1(0)+p1(1) < p2(0)+p2(1)) || ((p1(0)+p1(1) == p2(0)+p2(1)) && (p1(0)-p1(1) < p2(0)-p2(1)))); } template <> bool PointComp<3>::operator () (const Point<3> &p1, const Point<3> &p2) const { return ((p1(2) < p2(2)) || (p1(2) == p2(2)) && ((p1(0)+p1(1) < p2(0)+p2(1)) || ((p1(0)+p1(1) == p2(0)+p2(1)) && (p1(0)-p1(1) < p2(0)-p2(1))))); } template <int dim> void check () { Triangulation<dim> tr; if (dim==2) { GridGenerator::hyper_ball(tr, Point<dim>(), 1); } else GridGenerator::hyper_cube(tr, -1./sqrt(dim),1./sqrt(dim)); if (dim != 1) { static const HyperBallBoundary<dim> boundary; tr.set_boundary (0, boundary); }; tr.refine_global (1); tr.begin_active()->set_refine_flag (); tr.execute_coarsening_and_refinement (); if (dim==1) tr.refine_global(2); MappingQ<dim> mapping(3); FESystem<dim> element (FE_Q<dim>(2), 1, FE_DGQ<dim>(1), 1); DoFHandler<dim> dof(tr); dof.distribute_dofs(element); // get the forward map std::vector<Point<dim> > support_points (dof.n_dofs()); DoFTools::map_dofs_to_support_points (mapping, dof, support_points); for (unsigned int i=0; i<dof.n_dofs(); ++i) deallog << i << ": " << support_points[i] << std::endl; // now get the backward map std::map<Point<dim>,unsigned int,PointComp<dim> > point_map; DoFTools::map_support_points_to_dofs (mapping, dof, point_map); typename std::map<Point<dim>,unsigned int,PointComp<dim> >::const_iterator i = point_map.begin(), e = point_map.end(); for (; i!=e; ++i) deallog << i->first << ',' << i->second << std::endl; } int main () { std::ofstream logfile ("support_point_map.output"); logfile.precision (2); logfile.setf(std::ios::fixed); deallog.attach(logfile); deallog.depth_console (0); deallog.push ("1d"); check<1> (); deallog.pop (); deallog.push ("2d"); check<2> (); deallog.pop (); deallog.push ("3d"); check<3> (); deallog.pop (); } <commit_msg>Add some missing std.<commit_after>//---------------------------- support_point_map.cc --------------------------- // support_point_map.cc,v 1.6 2003/04/09 15:49:54 wolf Exp // Version: // // Copyright (C) 2000, 2001, 2003 by the deal.II authors // // This file is subject to QPL and may not be distributed // without copyright and license information. Please refer // to the file deal.II/doc/license.html for the text and // further information on this license. // //---------------------------- support_point_map.cc --------------------------- /* Author: Wolfgang Bangerth, University of Heidelberg, 2001 */ /* Purpose: check the map_dofs_to_support_points and map_support_points_to_dofs functions. */ #include "../tests.h" #include <base/logstream.h> #include <base/function_lib.h> #include <lac/vector.h> #include <grid/tria.h> #include <grid/tria_iterator.h> #include <grid/tria_boundary_lib.h> #include <dofs/dof_accessor.h> #include <grid/grid_generator.h> #include <dofs/dof_handler.h> #include <dofs/dof_tools.h> #include <fe/fe_q.h> #include <fe/fe_dgq.h> #include <fe/fe_system.h> #include <fe/mapping_q.h> #include <fstream> template <int dim> struct PointComp { bool operator () (const Point<dim> &, const Point<dim> &) const; }; template <> bool PointComp<1>::operator () (const Point<1> &p1, const Point<1> &p2) const { return p1(0) < p2(0); } // have somewhat weird orderings in 2d and 3d template <> bool PointComp<2>::operator () (const Point<2> &p1, const Point<2> &p2) const { return ((p1(0)+p1(1) < p2(0)+p2(1)) || ((p1(0)+p1(1) == p2(0)+p2(1)) && (p1(0)-p1(1) < p2(0)-p2(1)))); } template <> bool PointComp<3>::operator () (const Point<3> &p1, const Point<3> &p2) const { return ((p1(2) < p2(2)) || (p1(2) == p2(2)) && ((p1(0)+p1(1) < p2(0)+p2(1)) || ((p1(0)+p1(1) == p2(0)+p2(1)) && (p1(0)-p1(1) < p2(0)-p2(1))))); } template <int dim> void check () { Triangulation<dim> tr; if (dim==2) { GridGenerator::hyper_ball(tr, Point<dim>(), 1); } else GridGenerator::hyper_cube(tr, -1./std::sqrt(static_cast<double>(dim)),1./std::sqrt(static_cast<double>(dim))); if (dim != 1) { static const HyperBallBoundary<dim> boundary; tr.set_boundary (0, boundary); }; tr.refine_global (1); tr.begin_active()->set_refine_flag (); tr.execute_coarsening_and_refinement (); if (dim==1) tr.refine_global(2); MappingQ<dim> mapping(3); FESystem<dim> element (FE_Q<dim>(2), 1, FE_DGQ<dim>(1), 1); DoFHandler<dim> dof(tr); dof.distribute_dofs(element); // get the forward map std::vector<Point<dim> > support_points (dof.n_dofs()); DoFTools::map_dofs_to_support_points (mapping, dof, support_points); for (unsigned int i=0; i<dof.n_dofs(); ++i) deallog << i << ": " << support_points[i] << std::endl; // now get the backward map std::map<Point<dim>,unsigned int,PointComp<dim> > point_map; DoFTools::map_support_points_to_dofs (mapping, dof, point_map); typename std::map<Point<dim>,unsigned int,PointComp<dim> >::const_iterator i = point_map.begin(), e = point_map.end(); for (; i!=e; ++i) deallog << i->first << ',' << i->second << std::endl; } int main () { std::ofstream logfile ("support_point_map.output"); logfile.precision (2); logfile.setf(std::ios::fixed); deallog.attach(logfile); deallog.depth_console (0); deallog.push ("1d"); check<1> (); deallog.pop (); deallog.push ("2d"); check<2> (); deallog.pop (); deallog.push ("3d"); check<3> (); deallog.pop (); } <|endoftext|>
<commit_before>#include <iostream> #include <cmath> #include <matrix.h> #define WITHOUT_NUMPY #include <matplotlib-cpp/matplotlibcpp.h> namespace plt = matplotlibcpp; /////////////////////////////////////////////// // Pattern initialization int random_plus_minus_one() { return (std::rand() % 2) * 2 - 1; } void fill_with_random_noise(Pattern& pattern) { for (size_t i = 0; i < pattern.num_elements; ++i) { pattern.set_linear(i, random_plus_minus_one()); } } /////////////////////////////////////////////// // Hebb's rule related float calculate_weight_at_ij(const std::vector<Pattern>& patterns, size_t N, size_t i, size_t j) { if (i == j) return 0.0f; float weight = 0.0f; for (size_t idx = 0; idx < patterns.size(); ++idx) { auto& pattern = patterns.at(idx); weight += pattern.get_linear(i) * pattern.get_linear(j); } return weight / static_cast<float>(N); } WeightMatrix create_weight_matrix(const std::vector<Pattern>& patterns, size_t num_bits) { size_t N = num_bits; WeightMatrix weights(N, N); for (size_t i = 0; i < N; ++i) { for (size_t j = 0; j < N; ++j) { float w = calculate_weight_at_ij(patterns, N, i, j); weights.set(i, j, w); } } return weights; } /////////////////////////////////////////////// // Stochastic update rule float local_field(Pattern& pattern, size_t i, const WeightMatrix& weights) { float b = 0.0f; for (size_t j = 0; j < pattern.num_elements; ++j) { b += weights.get(i, j) * pattern.get_linear(j); } return b; } float random_float() { return static_cast<float>(std::rand()) / static_cast<float>(RAND_MAX); } #define g_func(b, beta) stochastic_signum(b, beta) float stochastic_signum(float b, float beta) { return 1.0f / (1.0f + expf(-2.0f * b * beta)); } void stochastic_update_neuron(Pattern& pattern, size_t i, const WeightMatrix& weights, float beta) { float b = local_field(pattern, i, weights); int new_value = random_float() <= g_func(b, beta) ? +1 : -1; pattern.set_linear(i, new_value); } /////////////////////////////////////////////// // Order parameter calculation float order_parameter_for_iteration(const Pattern &stored_pattern, const Pattern &test_pattern) { assert(stored_pattern.num_elements == test_pattern.num_elements); size_t N = stored_pattern.num_elements; float m = 0.0f; for (size_t i = 0; i < N; ++i) { m += test_pattern.get_linear(i) * stored_pattern.get_linear(i); } m /= static_cast<float>(N); return m; } /////////////////////////////////////////////// // Test procedure int main() { std::srand(static_cast<uint>(std::time(0))); const size_t NUM_TESTS_TO_PERFORM = 20; const size_t NUM_ASYNC_STEPS_TO_PERFORM_PER_TEST = 10000; const size_t N = 200; const size_t p = 5; const float beta = 2; std::cout << "Testing for p = " << p << ", N = " << N << ", and beta = " << beta << ":" << std::endl; // Create p random patterns to store std::vector<Pattern> stored_patterns; stored_patterns.reserve(p); for (size_t i = 0; i < p; ++i) { stored_patterns.emplace_back(N); fill_with_random_noise(stored_patterns.at(i)); } // Store patterns in the weight matrix according to Hebb's rule const WeightMatrix& weights = create_weight_matrix(stored_patterns, N); // Feed the first stored pattern to the network Pattern test_pattern = stored_patterns.at(0); // For storing data for plotting std::vector<float> iteration_step_vector; std::vector<float> order_parameter_for_iteration_vector; iteration_step_vector.resize(NUM_ASYNC_STEPS_TO_PERFORM_PER_TEST); order_parameter_for_iteration_vector.resize(NUM_ASYNC_STEPS_TO_PERFORM_PER_TEST); plt::figure(); plt::title("Phase diagram for p = 5"); for (size_t current_test = 0; current_test < NUM_TESTS_TO_PERFORM; ++current_test) { std::cout << "Performing test " << (current_test + 1) << " out of " << NUM_TESTS_TO_PERFORM << std::endl; for (size_t current_step = 0; current_step < NUM_ASYNC_STEPS_TO_PERFORM_PER_TEST; ++current_step) { // Pick random neuron to update size_t i = std::rand() % N; stochastic_update_neuron(test_pattern, i, weights, beta); float m = order_parameter_for_iteration(stored_patterns.at(0), test_pattern); // Store data for plotting iteration_step_vector.at(current_step) = current_step; order_parameter_for_iteration_vector.at(current_step) = m; } plt::plot(iteration_step_vector, order_parameter_for_iteration_vector, "r-"); } std::cout << "Tests done, plotting" << std::endl; // Draw and show graph results plt::xlabel("t"); plt::ylabel("m(t)"); plt::ylim(0.0, 1.1); plt::grid(true); plt::show(); return 0; } <commit_msg>Finish up stochastic Hopfield program<commit_after>#include <iostream> #include <sstream> #include <cmath> #include <matrix.h> #define WITHOUT_NUMPY #include <matplotlib-cpp/matplotlibcpp.h> namespace plt = matplotlibcpp; /////////////////////////////////////////////// // Pattern initialization int random_plus_minus_one() { return (std::rand() % 2) * 2 - 1; } void fill_with_random_noise(Pattern& pattern) { for (size_t i = 0; i < pattern.num_elements; ++i) { pattern.set_linear(i, random_plus_minus_one()); } } /////////////////////////////////////////////// // Hebb's rule related double calculate_weight_at_ij(const std::vector<Pattern>& patterns, size_t N, size_t i, size_t j) { if (i == j) return 0.0f; double weight = 0.0f; for (size_t idx = 0; idx < patterns.size(); ++idx) { auto& pattern = patterns.at(idx); weight += pattern.get_linear(i) * pattern.get_linear(j); } return weight / static_cast<double>(N); } WeightMatrix create_weight_matrix(const std::vector<Pattern>& patterns, size_t num_bits) { size_t N = num_bits; WeightMatrix weights(N, N); for (size_t i = 0; i < N; ++i) { for (size_t j = 0; j < N; ++j) { double w = calculate_weight_at_ij(patterns, N, i, j); weights.set(i, j, w); } } return weights; } /////////////////////////////////////////////// // Stochastic update rule double local_field(Pattern& pattern, size_t i, const WeightMatrix& weights) { double b = 0.0f; for (size_t j = 0; j < pattern.num_elements; ++j) { b += weights.get(i, j) * pattern.get_linear(j); } return b; } double random_double() { return static_cast<double>(std::rand()) / static_cast<double>(RAND_MAX); } #define g_func(b, beta) activation_function_g(b, beta) double activation_function_g(double b, double beta) { return 1.0f / (1.0f + exp(-2.0f * b * beta)); } void stochastic_update_neuron(Pattern& pattern, size_t i, const WeightMatrix& weights, double beta) { double b = local_field(pattern, i, weights); int new_value = random_double() <= g_func(b, beta) ? +1 : -1; pattern.set_linear(i, new_value); } /////////////////////////////////////////////// // Order parameter calculation double order_parameter_for_iteration(const Pattern &stored_pattern, const Pattern &test_pattern) { assert(stored_pattern.num_elements == test_pattern.num_elements); size_t N = stored_pattern.num_elements; double m = 0.0f; for (size_t i = 0; i < N; ++i) { m += test_pattern.get_linear(i) * stored_pattern.get_linear(i); } m /= static_cast<double>(N); return m; } /////////////////////////////////////////////// // Test procedure int main() { std::srand(static_cast<uint>(std::time(0))); const size_t NUM_TESTS_TO_PERFORM = 20; const size_t NUM_ASYNC_STEPS_TO_PERFORM_PER_TEST = 25000; const int SMOOTHING_KERNEL_SIZE = 1000; const size_t N = 200; const size_t p_list[] = { 5, 40 }; const double beta = 2; for (int current_p_index = 0; current_p_index < 2; ++current_p_index) { size_t p = p_list[current_p_index]; std::cout << "Testing for p = " << p << ", N = " << N << ", and beta = " << beta << ":" << std::endl; // Create p random patterns to store std::vector<Pattern> stored_patterns; stored_patterns.reserve(p); for (size_t i = 0; i < p; ++i) { stored_patterns.emplace_back(N); fill_with_random_noise(stored_patterns.at(i)); } // Store patterns in the weight matrix according to Hebb's rule const WeightMatrix& weights = create_weight_matrix(stored_patterns, N); // For storing data for plotting std::vector<double> iteration_step_vector; std::vector<double> order_parameter_for_iteration_vector; iteration_step_vector.resize(NUM_ASYNC_STEPS_TO_PERFORM_PER_TEST); order_parameter_for_iteration_vector.resize(NUM_ASYNC_STEPS_TO_PERFORM_PER_TEST); for (size_t current_test = 0; current_test < NUM_TESTS_TO_PERFORM; ++current_test) { std::cout << " test " << (current_test + 1) << "/" << NUM_TESTS_TO_PERFORM << std::endl; // Feed the first stored pattern to the network Pattern test_pattern = stored_patterns.at(0); for (size_t current_step = 0; current_step < NUM_ASYNC_STEPS_TO_PERFORM_PER_TEST; ++current_step) { // Pick random neuron to update size_t i = std::rand() % N; stochastic_update_neuron(test_pattern, i, weights, beta); double m = order_parameter_for_iteration(stored_patterns.at(0), test_pattern); // Store data for plotting iteration_step_vector.at(current_step) = current_step; order_parameter_for_iteration_vector.at(current_step) = m; } // Apply moving average filter size_t num_elements = order_parameter_for_iteration_vector.size(); std::vector<double> smooth_order_parameter_for_iteration_vector(num_elements); for (int i = 0; i < num_elements; ++i) { double sum = 0.0; int count = 0; for (int j = -SMOOTHING_KERNEL_SIZE / 2; j < SMOOTHING_KERNEL_SIZE / 2; ++j) { int idx = i + j; if (idx < 0) idx = 0; if (idx >= num_elements) idx = (int) num_elements - 1; size_t index = static_cast<size_t>(idx); sum += order_parameter_for_iteration_vector.at(index); count += 1; } double average = sum / count; smooth_order_parameter_for_iteration_vector.at((size_t)i) = average; } // Plot results { int row = 2 * current_p_index; std::stringstream title; title << "Phase diagram for p = " << p; plt::subplot(2, 2, row + 1); plt::title(title.str()); plt::plot(iteration_step_vector, order_parameter_for_iteration_vector, "r-"); plt::xlabel("t"); plt::ylabel("m(t)"); plt::ylim(0.0, 1.1); plt::grid(true); plt::subplot(2, 2, row + 2); title << " (smoothed)"; plt::title(title.str()); plt::plot(iteration_step_vector, smooth_order_parameter_for_iteration_vector, "b-"); plt::xlabel("t"); plt::ylabel("m(t)"); plt::ylim(0.0, 1.1); plt::grid(true); } } } std::cout << "Tests done, plotting" << std::endl; plt::show(); return 0; } <|endoftext|>
<commit_before>//----------------------------------- // Copyright Pierric Gimmig 2013-2017 //----------------------------------- #include "ProcessesDataView.h" #include "App.h" #include "Callstack.h" #include "Capture.h" #include "ModulesDataView.h" #include "OrbitType.h" #include "Params.h" #include "Pdb.h" #include "TcpClient.h" //----------------------------------------------------------------------------- ProcessesDataView::ProcessesDataView() { InitColumnsIfNeeded(); m_SortingOrders.insert(m_SortingOrders.end(), s_InitialOrders.begin(), s_InitialOrders.end()); UpdateProcessList(); m_UpdatePeriodMs = 1000; m_IsRemote = false; GOrbitApp->RegisterProcessesDataView(this); } //----------------------------------------------------------------------------- std::vector<std::wstring> ProcessesDataView::s_Headers; std::vector<float> ProcessesDataView::s_HeaderRatios; std::vector<DataView::SortingOrder> ProcessesDataView::s_InitialOrders; //----------------------------------------------------------------------------- void ProcessesDataView::InitColumnsIfNeeded() { if (s_Headers.empty()) { s_Headers.emplace_back(L"PID"); s_HeaderRatios.push_back(0); s_InitialOrders.push_back(AscendingOrder); s_Headers.emplace_back(L"Name"); s_HeaderRatios.push_back(0.5f); s_InitialOrders.push_back(AscendingOrder); s_Headers.emplace_back(L"CPU"); s_HeaderRatios.push_back(0); s_InitialOrders.push_back(DescendingOrder); s_Headers.emplace_back(L"Type"); s_HeaderRatios.push_back(0); s_InitialOrders.push_back(AscendingOrder); } } //----------------------------------------------------------------------------- const std::vector<std::wstring>& ProcessesDataView::GetColumnHeaders() { return s_Headers; } //----------------------------------------------------------------------------- const std::vector<float>& ProcessesDataView::GetColumnHeadersRatios() { return s_HeaderRatios; } //----------------------------------------------------------------------------- const std::vector<DataView::SortingOrder>& ProcessesDataView::GetColumnInitialOrders() { return s_InitialOrders; } //----------------------------------------------------------------------------- int ProcessesDataView::GetDefaultSortingColumn() { return PDV_CPU; } //----------------------------------------------------------------------------- std::wstring ProcessesDataView::GetValue(int row, int col) { const Process& process = *GetProcess(row); std::wstring value; switch (col) { case PDV_ProcessID: value = std::to_wstring((long)process.GetID()); break; case PDV_ProcessName: value = s2ws(process.GetName()); if (process.IsElevated()) { value += L"*"; } break; case PDV_CPU: value = Format(L"%.1f", process.GetCpuUsage()); break; case PDV_Type: value = process.GetIs64Bit() ? L"64 bit" : L"32 bit"; break; default: break; } return value; } //----------------------------------------------------------------------------- std::wstring ProcessesDataView::GetToolTip(int a_Row, int /*a_Column*/) { const Process& process = *GetProcess(a_Row); return s2ws(process.GetFullName()); } //----------------------------------------------------------------------------- #define ORBIT_PROC_SORT(Member) \ [&](int a, int b) { \ return OrbitUtils::Compare(processes[a]->Member, processes[b]->Member, \ ascending); \ } //----------------------------------------------------------------------------- void ProcessesDataView::OnSort(int a_Column, std::optional<SortingOrder> a_NewOrder) { if (a_Column == -1) { a_Column = PdvColumn::PDV_CPU; } const std::vector<std::shared_ptr<Process>>& processes = m_ProcessList.m_Processes; auto pdvColumn = static_cast<PdvColumn>(a_Column); if (a_NewOrder.has_value()) { m_SortingOrders[pdvColumn] = a_NewOrder.value(); } bool ascending = m_SortingOrders[pdvColumn] == AscendingOrder; std::function<bool(int a, int b)> sorter = nullptr; switch (pdvColumn) { case PDV_ProcessID: sorter = ORBIT_PROC_SORT(GetID()); break; case PDV_ProcessName: sorter = ORBIT_PROC_SORT(GetName()); break; case PDV_CPU: sorter = ORBIT_PROC_SORT(GetCpuUsage()); break; case PDV_Type: sorter = ORBIT_PROC_SORT(GetIs64Bit()); break; default: break; } if (sorter) { std::sort(m_Indices.begin(), m_Indices.end(), sorter); } m_LastSortedColumn = a_Column; SetSelectedItem(); } //----------------------------------------------------------------------------- void ProcessesDataView::OnSelect(int a_Index) { m_SelectedProcess = GetProcess(a_Index); if (!m_IsRemote) { m_SelectedProcess->ListModules(); } else if (m_SelectedProcess->GetModules().size() == 0) { Message msg(Msg_RemoteProcessRequest); msg.m_Header.m_GenericHeader.m_Address = m_SelectedProcess->GetID(); GTcpClient->Send(msg); } UpdateModuleDataView(m_SelectedProcess); } void ProcessesDataView::UpdateModuleDataView( std::shared_ptr<Process> a_Process) { if (m_ModulesDataView) { m_ModulesDataView->SetProcess(a_Process); Capture::SetTargetProcess(a_Process); GOrbitApp->FireRefreshCallbacks(); } } //----------------------------------------------------------------------------- void ProcessesDataView::OnTimer() { Refresh(); } //----------------------------------------------------------------------------- void ProcessesDataView::Refresh() { if (Capture::IsCapturing()) { return; } if (m_RemoteProcess) { std::shared_ptr<Process> CurrentRemoteProcess = m_ProcessList.m_Processes.size() == 1 ? m_ProcessList.m_Processes[0] : nullptr; if (m_RemoteProcess != CurrentRemoteProcess) { m_ProcessList.Clear(); m_ProcessList.m_Processes.push_back(m_RemoteProcess); UpdateProcessList(); SetFilter(L""); SelectProcess(m_RemoteProcess->GetID()); SetSelectedItem(); } } else { if (!m_IsRemote) { m_ProcessList.Refresh(); m_ProcessList.UpdateCpuTimes(); } UpdateProcessList(); OnSort(m_LastSortedColumn, {}); OnFilter(m_Filter); SetSelectedItem(); if (Capture::GTargetProcess && !Capture::IsCapturing()) { Capture::GTargetProcess->UpdateThreadUsage(); } } GParams.m_ProcessFilter = ws2s(m_Filter); } //----------------------------------------------------------------------------- void ProcessesDataView::SetSelectedItem() { int initialIndex = m_SelectedIndex; m_SelectedIndex = -1; for (uint32_t i = 0; i < (uint32_t)GetNumElements(); ++i) { if (m_SelectedProcess && GetProcess(i)->GetID() == m_SelectedProcess->GetID()) { m_SelectedIndex = i; return; } } if (GParams.m_AutoReleasePdb && initialIndex != -1) { ClearSelectedProcess(); } } //----------------------------------------------------------------------------- void ProcessesDataView::ClearSelectedProcess() { std::shared_ptr<Process> process = std::make_shared<Process>(); Capture::SetTargetProcess(process); m_ModulesDataView->SetProcess(process); m_SelectedProcess = process; GPdbDbg = nullptr; GOrbitApp->FireRefreshCallbacks(); } //----------------------------------------------------------------------------- bool ProcessesDataView::SelectProcess(const std::wstring& a_ProcessName) { for (uint32_t i = 0; i < GetNumElements(); ++i) { Process& process = *GetProcess(i); if (process.GetFullName().find(ws2s(a_ProcessName)) != std::string::npos) { OnSelect(i); Capture::GPresetToLoad = ""; return true; } } return false; } //----------------------------------------------------------------------------- std::shared_ptr<Process> ProcessesDataView::SelectProcess(DWORD a_ProcessId) { Refresh(); for (uint32_t i = 0; i < GetNumElements(); ++i) { Process& process = *GetProcess(i); if (process.GetID() == a_ProcessId) { OnSelect(i); Capture::GPresetToLoad = ""; return m_SelectedProcess; } } return nullptr; } //----------------------------------------------------------------------------- void ProcessesDataView::OnFilter(const std::wstring& a_Filter) { std::vector<uint32_t> indices; const std::vector<std::shared_ptr<Process>>& processes = m_ProcessList.m_Processes; std::vector<std::wstring> tokens = Tokenize(ToLower(a_Filter)); for (uint32_t i = 0; i < processes.size(); ++i) { const Process& process = *processes[i]; std::wstring name = s2ws(ToLower(process.GetName())); std::wstring type = process.GetIs64Bit() ? L"64" : L"32"; bool match = true; for (std::wstring& filterToken : tokens) { if (!(name.find(filterToken) != std::wstring::npos || type.find(filterToken) != std::wstring::npos)) { match = false; break; } } if (match) { indices.push_back(i); } } m_Indices = indices; if (m_LastSortedColumn != -1) { OnSort(m_LastSortedColumn, {}); } } //----------------------------------------------------------------------------- void ProcessesDataView::UpdateProcessList() { size_t numProcesses = m_ProcessList.m_Processes.size(); m_Indices.resize(numProcesses); for (uint32_t i = 0; i < numProcesses; ++i) { m_Indices[i] = i; } } //----------------------------------------------------------------------------- void ProcessesDataView::SetRemoteProcessList( std::shared_ptr<ProcessList> a_RemoteProcessList) { m_IsRemote = true; m_ProcessList = *a_RemoteProcessList; UpdateProcessList(); OnSort(m_LastSortedColumn, {}); OnFilter(m_Filter); SetSelectedItem(); } //----------------------------------------------------------------------------- void ProcessesDataView::SetRemoteProcess(std::shared_ptr<Process> a_Process) { std::shared_ptr<Process> targetProcess = m_ProcessList.GetProcess(a_Process->GetID()); if (targetProcess) { m_SelectedProcess = a_Process; UpdateModuleDataView(m_SelectedProcess); } else { m_RemoteProcess = a_Process; } } //----------------------------------------------------------------------------- std::shared_ptr<Process> ProcessesDataView::GetProcess( unsigned int a_Row) const { return m_ProcessList.m_Processes[m_Indices[a_Row]]; } <commit_msg>Make sure we can re-load module information on process selection.<commit_after>//----------------------------------- // Copyright Pierric Gimmig 2013-2017 //----------------------------------- #include "ProcessesDataView.h" #include "App.h" #include "Callstack.h" #include "Capture.h" #include "ModulesDataView.h" #include "OrbitType.h" #include "Params.h" #include "Pdb.h" #include "TcpClient.h" //----------------------------------------------------------------------------- ProcessesDataView::ProcessesDataView() { InitColumnsIfNeeded(); m_SortingOrders.insert(m_SortingOrders.end(), s_InitialOrders.begin(), s_InitialOrders.end()); UpdateProcessList(); m_UpdatePeriodMs = 1000; m_IsRemote = false; GOrbitApp->RegisterProcessesDataView(this); } //----------------------------------------------------------------------------- std::vector<std::wstring> ProcessesDataView::s_Headers; std::vector<float> ProcessesDataView::s_HeaderRatios; std::vector<DataView::SortingOrder> ProcessesDataView::s_InitialOrders; //----------------------------------------------------------------------------- void ProcessesDataView::InitColumnsIfNeeded() { if (s_Headers.empty()) { s_Headers.emplace_back(L"PID"); s_HeaderRatios.push_back(0); s_InitialOrders.push_back(AscendingOrder); s_Headers.emplace_back(L"Name"); s_HeaderRatios.push_back(0.5f); s_InitialOrders.push_back(AscendingOrder); s_Headers.emplace_back(L"CPU"); s_HeaderRatios.push_back(0); s_InitialOrders.push_back(DescendingOrder); s_Headers.emplace_back(L"Type"); s_HeaderRatios.push_back(0); s_InitialOrders.push_back(AscendingOrder); } } //----------------------------------------------------------------------------- const std::vector<std::wstring>& ProcessesDataView::GetColumnHeaders() { return s_Headers; } //----------------------------------------------------------------------------- const std::vector<float>& ProcessesDataView::GetColumnHeadersRatios() { return s_HeaderRatios; } //----------------------------------------------------------------------------- const std::vector<DataView::SortingOrder>& ProcessesDataView::GetColumnInitialOrders() { return s_InitialOrders; } //----------------------------------------------------------------------------- int ProcessesDataView::GetDefaultSortingColumn() { return PDV_CPU; } //----------------------------------------------------------------------------- std::wstring ProcessesDataView::GetValue(int row, int col) { const Process& process = *GetProcess(row); std::wstring value; switch (col) { case PDV_ProcessID: value = std::to_wstring((long)process.GetID()); break; case PDV_ProcessName: value = s2ws(process.GetName()); if (process.IsElevated()) { value += L"*"; } break; case PDV_CPU: value = Format(L"%.1f", process.GetCpuUsage()); break; case PDV_Type: value = process.GetIs64Bit() ? L"64 bit" : L"32 bit"; break; default: break; } return value; } //----------------------------------------------------------------------------- std::wstring ProcessesDataView::GetToolTip(int a_Row, int /*a_Column*/) { const Process& process = *GetProcess(a_Row); return s2ws(process.GetFullName()); } //----------------------------------------------------------------------------- #define ORBIT_PROC_SORT(Member) \ [&](int a, int b) { \ return OrbitUtils::Compare(processes[a]->Member, processes[b]->Member, \ ascending); \ } //----------------------------------------------------------------------------- void ProcessesDataView::OnSort(int a_Column, std::optional<SortingOrder> a_NewOrder) { if (a_Column == -1) { a_Column = PdvColumn::PDV_CPU; } const std::vector<std::shared_ptr<Process>>& processes = m_ProcessList.m_Processes; auto pdvColumn = static_cast<PdvColumn>(a_Column); if (a_NewOrder.has_value()) { m_SortingOrders[pdvColumn] = a_NewOrder.value(); } bool ascending = m_SortingOrders[pdvColumn] == AscendingOrder; std::function<bool(int a, int b)> sorter = nullptr; switch (pdvColumn) { case PDV_ProcessID: sorter = ORBIT_PROC_SORT(GetID()); break; case PDV_ProcessName: sorter = ORBIT_PROC_SORT(GetName()); break; case PDV_CPU: sorter = ORBIT_PROC_SORT(GetCpuUsage()); break; case PDV_Type: sorter = ORBIT_PROC_SORT(GetIs64Bit()); break; default: break; } if (sorter) { std::sort(m_Indices.begin(), m_Indices.end(), sorter); } m_LastSortedColumn = a_Column; SetSelectedItem(); } //----------------------------------------------------------------------------- void ProcessesDataView::OnSelect(int a_Index) { m_SelectedProcess = GetProcess(a_Index); if (!m_IsRemote) { m_SelectedProcess->ListModules(); } else { Message msg(Msg_RemoteProcessRequest); msg.m_Header.m_GenericHeader.m_Address = m_SelectedProcess->GetID(); GTcpClient->Send(msg); } UpdateModuleDataView(m_SelectedProcess); } void ProcessesDataView::UpdateModuleDataView( std::shared_ptr<Process> a_Process) { if (m_ModulesDataView) { m_ModulesDataView->SetProcess(a_Process); Capture::SetTargetProcess(a_Process); GOrbitApp->FireRefreshCallbacks(); } } //----------------------------------------------------------------------------- void ProcessesDataView::OnTimer() { Refresh(); } //----------------------------------------------------------------------------- void ProcessesDataView::Refresh() { if (Capture::IsCapturing()) { return; } if (m_RemoteProcess) { std::shared_ptr<Process> CurrentRemoteProcess = m_ProcessList.m_Processes.size() == 1 ? m_ProcessList.m_Processes[0] : nullptr; if (m_RemoteProcess != CurrentRemoteProcess) { m_ProcessList.Clear(); m_ProcessList.m_Processes.push_back(m_RemoteProcess); UpdateProcessList(); SetFilter(L""); SelectProcess(m_RemoteProcess->GetID()); SetSelectedItem(); } } else { if (!m_IsRemote) { m_ProcessList.Refresh(); m_ProcessList.UpdateCpuTimes(); } UpdateProcessList(); OnSort(m_LastSortedColumn, {}); OnFilter(m_Filter); SetSelectedItem(); if (Capture::GTargetProcess && !Capture::IsCapturing()) { Capture::GTargetProcess->UpdateThreadUsage(); } } GParams.m_ProcessFilter = ws2s(m_Filter); } //----------------------------------------------------------------------------- void ProcessesDataView::SetSelectedItem() { int initialIndex = m_SelectedIndex; m_SelectedIndex = -1; for (uint32_t i = 0; i < (uint32_t)GetNumElements(); ++i) { if (m_SelectedProcess && GetProcess(i)->GetID() == m_SelectedProcess->GetID()) { m_SelectedIndex = i; return; } } if (GParams.m_AutoReleasePdb && initialIndex != -1) { ClearSelectedProcess(); } } //----------------------------------------------------------------------------- void ProcessesDataView::ClearSelectedProcess() { std::shared_ptr<Process> process = std::make_shared<Process>(); Capture::SetTargetProcess(process); m_ModulesDataView->SetProcess(process); m_SelectedProcess = process; GPdbDbg = nullptr; GOrbitApp->FireRefreshCallbacks(); } //----------------------------------------------------------------------------- bool ProcessesDataView::SelectProcess(const std::wstring& a_ProcessName) { for (uint32_t i = 0; i < GetNumElements(); ++i) { Process& process = *GetProcess(i); if (process.GetFullName().find(ws2s(a_ProcessName)) != std::string::npos) { OnSelect(i); Capture::GPresetToLoad = ""; return true; } } return false; } //----------------------------------------------------------------------------- std::shared_ptr<Process> ProcessesDataView::SelectProcess(DWORD a_ProcessId) { Refresh(); for (uint32_t i = 0; i < GetNumElements(); ++i) { Process& process = *GetProcess(i); if (process.GetID() == a_ProcessId) { OnSelect(i); Capture::GPresetToLoad = ""; return m_SelectedProcess; } } return nullptr; } //----------------------------------------------------------------------------- void ProcessesDataView::OnFilter(const std::wstring& a_Filter) { std::vector<uint32_t> indices; const std::vector<std::shared_ptr<Process>>& processes = m_ProcessList.m_Processes; std::vector<std::wstring> tokens = Tokenize(ToLower(a_Filter)); for (uint32_t i = 0; i < processes.size(); ++i) { const Process& process = *processes[i]; std::wstring name = s2ws(ToLower(process.GetName())); std::wstring type = process.GetIs64Bit() ? L"64" : L"32"; bool match = true; for (std::wstring& filterToken : tokens) { if (!(name.find(filterToken) != std::wstring::npos || type.find(filterToken) != std::wstring::npos)) { match = false; break; } } if (match) { indices.push_back(i); } } m_Indices = indices; if (m_LastSortedColumn != -1) { OnSort(m_LastSortedColumn, {}); } } //----------------------------------------------------------------------------- void ProcessesDataView::UpdateProcessList() { size_t numProcesses = m_ProcessList.m_Processes.size(); m_Indices.resize(numProcesses); for (uint32_t i = 0; i < numProcesses; ++i) { m_Indices[i] = i; } } //----------------------------------------------------------------------------- void ProcessesDataView::SetRemoteProcessList( std::shared_ptr<ProcessList> a_RemoteProcessList) { m_IsRemote = true; m_ProcessList = *a_RemoteProcessList; UpdateProcessList(); OnSort(m_LastSortedColumn, {}); OnFilter(m_Filter); SetSelectedItem(); } //----------------------------------------------------------------------------- void ProcessesDataView::SetRemoteProcess(std::shared_ptr<Process> a_Process) { std::shared_ptr<Process> targetProcess = m_ProcessList.GetProcess(a_Process->GetID()); if (targetProcess) { m_SelectedProcess = a_Process; UpdateModuleDataView(m_SelectedProcess); } else { m_RemoteProcess = a_Process; } } //----------------------------------------------------------------------------- std::shared_ptr<Process> ProcessesDataView::GetProcess( unsigned int a_Row) const { return m_ProcessList.m_Processes[m_Indices[a_Row]]; } <|endoftext|>
<commit_before>#include <iostream> #include <string> #include <boost/program_options.hpp> #include <vector> #include <fstream> #include "ioHandler.h" #include <boost/iostreams/filter/gzip.hpp> #include <boost/iostreams/filtering_stream.hpp> #include <boost/iostreams/device/file_descriptor.hpp> #include <boost/iostreams/stream.hpp> #include <boost/iostreams/device/file.hpp> #include <boost/iostreams/device/mapped_file.hpp> #include <boost/filesystem/path.hpp> #include <boost/filesystem.hpp> #include <map> #include <unordered_map> #include <boost/functional/hash.hpp> #include "overlapper.h" #define AST_COUNT 4096 namespace { const size_t SUCCESS = 0; const size_t ERROR_IN_COMMAND_LINE = 1; const size_t ERROR_UNHANDLED_EXCEPTION = 2; } // namespace namespace bi = boost::iostreams; int main(int argc, char** argv) { const std::string program_name = "Overlapper"; Counter counters; setupCounter(counters); std::string prefix; std::vector<std::string> default_outfiles = {"PE1", "PE2", "SE"}; bool fastq_out; bool tab_out; bool std_out; bool std_in; bool gzip_out; bool interleaved_out; bool force; bool checkR2; size_t maxMismatch; size_t minLength; size_t minOverlap; bool adapterTrimming; bool stranded; std::string histFile; size_t checkLengths; std::string statsFile; bool appendStats; try { /** Define and parse the program options */ namespace po = boost::program_options; po::options_description desc("Options"); desc.add_options() ("version,v", "Version print") ("read1-input,1", po::value< std::vector<std::string> >(), "Read 1 input <comma sep for multiple files>") ("read2-input,2", po::value< std::vector<std::string> >(), "Read 2 input <comma sep for multiple files>") ("singleend-input,U", po::value< std::vector<std::string> >(), "Single end read input <comma sep for multiple files>") ("tab-input,T", po::value< std::vector<std::string> >(), "Tab input <comma sep for multiple files>") ("interleaved-input,I", po::value< std::vector<std::string> >(), "Interleaved input I <comma sep for multiple files>") ("stdin-input,S", po::bool_switch(&std_in)->default_value(false), "STDIN input <MUST BE TAB DELIMITED INPUT>") ("gzip-output,g", po::bool_switch(&gzip_out)->default_value(false), "Output gzipped") ("interleaved-output,i", po::bool_switch(&interleaved_out)->default_value(false), "Output to interleaved") ("fastq-output,f", po::bool_switch(&fastq_out)->default_value(false), "Fastq format output") ("force,F", po::bool_switch(&force)->default_value(false), "Forces overwrite of files") ("tab-output,t", po::bool_switch(&tab_out)->default_value(false), "Tab-delimited output") ("to-stdout,O", po::bool_switch(&std_out)->default_value(false), "Prints to STDOUT in Tab Delimited") ("prefix,p", po::value<std::string>(&prefix)->default_value("overlapped_"), "Prefix for outputted files") ("minLength,l", po::value<size_t>(&minLength)->default_value(50), "Mismatches allowed in overlapped section") ("max-mismatches,x", po::value<size_t>(&maxMismatch)->default_value(5), "Mismatches allowed in overlapped section") ("check-lengths,c", po::value<size_t>(&checkLengths)->default_value(20), "Check lengths on the ends") ("min-overlap,o", po::value<size_t>(&minOverlap)->default_value(8), "Min overlap required to merge two reads") ("adapter-trimming,a", po::bool_switch(&adapterTrimming)->default_value(false), "Trims adapters based on overlap, only returns PE reads, will correct quality scores and BP in the PE reads") ("stranded,s", po::bool_switch(&stranded)->default_value(false), "Makes sure the correct complement is returned upon overlap") ("hist-file,e", po::value<std::string>(&histFile)->default_value(""), "A tab delimited hist file with insert lengths.") ("stats-file,L", po::value<std::string>(&statsFile)->default_value("stats.log") , "String for output stats file name") ("append-stats-file,A", po::bool_switch(&appendStats)->default_value(false), "Append Stats file.") ("help,h", "Prints help."); po::variables_map vm; try { po::store(po::parse_command_line(argc, argv, desc), vm); // can throw /** --help option */ if ( vm.count("help") || vm.size() == 0) { std::cout << "Tab-Converter" << std::endl << desc << std::endl; return SUCCESS; } po::notify(vm); // throws on error, so do after help in case //Index 1 start location (making it more human friendly) std::shared_ptr<HtsOfstream> out_1 = nullptr; std::shared_ptr<HtsOfstream> out_2 = nullptr; std::shared_ptr<HtsOfstream> out_3 = nullptr; std::shared_ptr<OutputWriter> pe = nullptr; std::shared_ptr<OutputWriter> se = nullptr; if (fastq_out || (! std_out && ! tab_out) ) { for (auto& outfile: default_outfiles) { outfile = prefix + outfile + ".fastq"; } out_1.reset(new HtsOfstream(default_outfiles[0], force, gzip_out, false)); out_2.reset(new HtsOfstream(default_outfiles[1], force, gzip_out, false)); out_3.reset(new HtsOfstream(default_outfiles[2], force, gzip_out, false)); pe.reset(new PairedEndReadOutFastq(out_1, out_2)); se.reset(new SingleEndReadOutFastq(out_3)); } else if (interleaved_out) { for (auto& outfile: default_outfiles) { outfile = prefix + "INTER" + ".fastq"; } out_1.reset(new HtsOfstream(default_outfiles[0], force, gzip_out, false)); out_3.reset(new HtsOfstream(default_outfiles[1], force, gzip_out, false)); pe.reset(new PairedEndReadOutInter(out_1)); se.reset(new SingleEndReadOutFastq(out_3)); } else if (tab_out || std_out) { for (auto& outfile: default_outfiles) { outfile = prefix + "tab" + ".tastq"; } out_1.reset(new HtsOfstream(default_outfiles[0], force, gzip_out, std_out)); pe.reset(new ReadBaseOutTab(out_1)); se.reset(new ReadBaseOutTab(out_1)); } histVec insertLengths; if (histFile == "") { insertLengths = nullptr; } else { insertLengths = histVec(new std::vector<unsigned long long int>); } //setLookup(lookup, lookup_rc, readPhix); // there are any problems if(vm.count("read1-input")) { if (!vm.count("read2-input")) { throw std::runtime_error("must specify both read1 and read2 input files."); } else if (vm.count("read2-input") != vm.count("read1-input")) { throw std::runtime_error("must have same number of input files for read1 and read2"); } auto read1_files = vm["read1-input"].as<std::vector<std::string> >(); auto read2_files = vm["read2-input"].as<std::vector<std::string> >(); for(size_t i = 0; i < read1_files.size(); ++i) { bi::stream<bi::file_descriptor_source> is1{check_open_r(read1_files[i]), bi::close_handle}; bi::stream<bi::file_descriptor_source> is2{check_open_r(read2_files[i]), bi::close_handle}; InputReader<PairedEndRead, PairedEndReadFastqImpl> ifp(is1, is2); helper_overlapper(ifp, pe, se, counters, maxMismatch, minOverlap, insertLengths, stranded, minLength, checkLengths, adapterTrimming); } } if(vm.count("singleend-input")) { auto read_files = vm["singleend-input"].as<std::vector<std::string> >(); for (auto file : read_files) { bi::stream<bi::file_descriptor_source> sef{ check_open_r(file), bi::close_handle}; InputReader<SingleEndRead, SingleEndReadFastqImpl> ifs(sef); //JUST WRITE se read out - no way to overlap helper_overlapper(ifs, pe, se, counters, maxMismatch, minOverlap, insertLengths, stranded, minLength, checkLengths, adapterTrimming); } } if(vm.count("tab-input")) { auto read_files = vm["tab-input"].as<std::vector<std::string> > (); for (auto file : read_files) { bi::stream<bi::file_descriptor_source> tabin{ check_open_r(file), bi::close_handle}; InputReader<ReadBase, TabReadImpl> ift(tabin); helper_overlapper(ift, pe, se, counters, maxMismatch, minOverlap, insertLengths, stranded, minLength, checkLengths, adapterTrimming); } } if (vm.count("interleaved-input")) { auto read_files = vm["interleaved-input"].as<std::vector<std::string > >(); for (auto file : read_files) { bi::stream<bi::file_descriptor_source> inter{ check_open_r(file), bi::close_handle}; InputReader<PairedEndRead, InterReadImpl> ifp(inter); helper_overlapper(ifp, pe, se, counters, maxMismatch, minOverlap, insertLengths, stranded, minLength, checkLengths, adapterTrimming); } } if (std_in) { bi::stream<bi::file_descriptor_source> tabin {fileno(stdin), bi::close_handle}; InputReader<ReadBase, TabReadImpl> ift(tabin); helper_overlapper(ift, pe, se, counters, maxMismatch, minOverlap, insertLengths, stranded, minLength, checkLengths, adapterTrimming); } if (insertLengths) { std::ofstream histOutputFile(histFile); //0 is reserved for no overlap std::string stars; for (int i = 1; i < insertLengths->size(); ++i) { stars = ""; if ((*insertLengths)[i]) { stars = stars.insert(0, (*insertLengths)[i]/AST_COUNT, '*'); histOutputFile << i << '\t' << (*insertLengths)[i] << '\t' << stars << '\n'; } } stars = stars.insert(0, (*insertLengths)[0]/AST_COUNT, '*'); histOutputFile << "None" << '\t' << (*insertLengths)[0] << '\t' << stars << '\n'; histOutputFile.close(); } write_stats(statsFile, appendStats, counters, program_name); } catch(po::error& e) { std::cerr << "ERROR: " << e.what() << std::endl << std::endl; std::cerr << desc << std::endl; return ERROR_IN_COMMAND_LINE; } } catch(std::exception& e) { std::cerr << "\n\tUnhandled Exception: " << e.what() << std::endl; return ERROR_UNHANDLED_EXCEPTION; } return SUCCESS; } <commit_msg>Fixed help text Fixed issue #38<commit_after>#include <iostream> #include <string> #include <boost/program_options.hpp> #include <vector> #include <fstream> #include "ioHandler.h" #include <boost/iostreams/filter/gzip.hpp> #include <boost/iostreams/filtering_stream.hpp> #include <boost/iostreams/device/file_descriptor.hpp> #include <boost/iostreams/stream.hpp> #include <boost/iostreams/device/file.hpp> #include <boost/iostreams/device/mapped_file.hpp> #include <boost/filesystem/path.hpp> #include <boost/filesystem.hpp> #include <map> #include <unordered_map> #include <boost/functional/hash.hpp> #include "overlapper.h" #define AST_COUNT 4096 namespace { const size_t SUCCESS = 0; const size_t ERROR_IN_COMMAND_LINE = 1; const size_t ERROR_UNHANDLED_EXCEPTION = 2; } // namespace namespace bi = boost::iostreams; int main(int argc, char** argv) { const std::string program_name = "Overlapper"; Counter counters; setupCounter(counters); std::string prefix; std::vector<std::string> default_outfiles = {"PE1", "PE2", "SE"}; bool fastq_out; bool tab_out; bool std_out; bool std_in; bool gzip_out; bool interleaved_out; bool force; bool checkR2; size_t maxMismatch; size_t minLength; size_t minOverlap; bool adapterTrimming; bool stranded; std::string histFile; size_t checkLengths; std::string statsFile; bool appendStats; try { /** Define and parse the program options */ namespace po = boost::program_options; po::options_description desc("Options"); desc.add_options() ("version,v", "Version print") ("read1-input,1", po::value< std::vector<std::string> >(), "Read 1 input <comma sep for multiple files>") ("read2-input,2", po::value< std::vector<std::string> >(), "Read 2 input <comma sep for multiple files>") ("singleend-input,U", po::value< std::vector<std::string> >(), "Single end read input <comma sep for multiple files>") ("tab-input,T", po::value< std::vector<std::string> >(), "Tab input <comma sep for multiple files>") ("interleaved-input,I", po::value< std::vector<std::string> >(), "Interleaved input I <comma sep for multiple files>") ("stdin-input,S", po::bool_switch(&std_in)->default_value(false), "STDIN input <MUST BE TAB DELIMITED INPUT>") ("gzip-output,g", po::bool_switch(&gzip_out)->default_value(false), "Output gzipped") ("interleaved-output,i", po::bool_switch(&interleaved_out)->default_value(false), "Output to interleaved") ("fastq-output,f", po::bool_switch(&fastq_out)->default_value(false), "Fastq format output") ("force,F", po::bool_switch(&force)->default_value(false), "Forces overwrite of files") ("tab-output,t", po::bool_switch(&tab_out)->default_value(false), "Tab-delimited output") ("to-stdout,O", po::bool_switch(&std_out)->default_value(false), "Prints to STDOUT in Tab Delimited") ("prefix,p", po::value<std::string>(&prefix)->default_value("overlapped_"), "Prefix for outputted files") ("minLength,l", po::value<size_t>(&minLength)->default_value(50), "Minimum sequence length allowed without being discarded") ("max-mismatches,x", po::value<size_t>(&maxMismatch)->default_value(5), "Max number of mismatches allowed in overlapped section") ("check-lengths,c", po::value<size_t>(&checkLengths)->default_value(20), "Check lengths on the ends") ("min-overlap,o", po::value<size_t>(&minOverlap)->default_value(8), "Min overlap required to merge two reads") ("adapter-trimming,a", po::bool_switch(&adapterTrimming)->default_value(false), "Trims adapters based on overlap, only returns PE reads, will correct quality scores and BP in the PE reads") ("stranded,s", po::bool_switch(&stranded)->default_value(false), "Makes sure the correct complement is returned upon overlap") ("hist-file,e", po::value<std::string>(&histFile)->default_value(""), "A tab delimited hist file with insert lengths.") ("stats-file,L", po::value<std::string>(&statsFile)->default_value("stats.log") , "String for output stats file name") ("append-stats-file,A", po::bool_switch(&appendStats)->default_value(false), "Append Stats file.") ("help,h", "Prints help."); po::variables_map vm; try { po::store(po::parse_command_line(argc, argv, desc), vm); // can throw /** --help option */ if ( vm.count("help") || vm.size() == 0) { std::cout << "Tab-Converter" << std::endl << desc << std::endl; return SUCCESS; } po::notify(vm); // throws on error, so do after help in case //Index 1 start location (making it more human friendly) std::shared_ptr<HtsOfstream> out_1 = nullptr; std::shared_ptr<HtsOfstream> out_2 = nullptr; std::shared_ptr<HtsOfstream> out_3 = nullptr; std::shared_ptr<OutputWriter> pe = nullptr; std::shared_ptr<OutputWriter> se = nullptr; if (fastq_out || (! std_out && ! tab_out) ) { for (auto& outfile: default_outfiles) { outfile = prefix + outfile + ".fastq"; } out_1.reset(new HtsOfstream(default_outfiles[0], force, gzip_out, false)); out_2.reset(new HtsOfstream(default_outfiles[1], force, gzip_out, false)); out_3.reset(new HtsOfstream(default_outfiles[2], force, gzip_out, false)); pe.reset(new PairedEndReadOutFastq(out_1, out_2)); se.reset(new SingleEndReadOutFastq(out_3)); } else if (interleaved_out) { for (auto& outfile: default_outfiles) { outfile = prefix + "INTER" + ".fastq"; } out_1.reset(new HtsOfstream(default_outfiles[0], force, gzip_out, false)); out_3.reset(new HtsOfstream(default_outfiles[1], force, gzip_out, false)); pe.reset(new PairedEndReadOutInter(out_1)); se.reset(new SingleEndReadOutFastq(out_3)); } else if (tab_out || std_out) { for (auto& outfile: default_outfiles) { outfile = prefix + "tab" + ".tastq"; } out_1.reset(new HtsOfstream(default_outfiles[0], force, gzip_out, std_out)); pe.reset(new ReadBaseOutTab(out_1)); se.reset(new ReadBaseOutTab(out_1)); } histVec insertLengths; if (histFile == "") { insertLengths = nullptr; } else { insertLengths = histVec(new std::vector<unsigned long long int>); } //setLookup(lookup, lookup_rc, readPhix); // there are any problems if(vm.count("read1-input")) { if (!vm.count("read2-input")) { throw std::runtime_error("must specify both read1 and read2 input files."); } else if (vm.count("read2-input") != vm.count("read1-input")) { throw std::runtime_error("must have same number of input files for read1 and read2"); } auto read1_files = vm["read1-input"].as<std::vector<std::string> >(); auto read2_files = vm["read2-input"].as<std::vector<std::string> >(); for(size_t i = 0; i < read1_files.size(); ++i) { bi::stream<bi::file_descriptor_source> is1{check_open_r(read1_files[i]), bi::close_handle}; bi::stream<bi::file_descriptor_source> is2{check_open_r(read2_files[i]), bi::close_handle}; InputReader<PairedEndRead, PairedEndReadFastqImpl> ifp(is1, is2); helper_overlapper(ifp, pe, se, counters, maxMismatch, minOverlap, insertLengths, stranded, minLength, checkLengths, adapterTrimming); } } if(vm.count("singleend-input")) { auto read_files = vm["singleend-input"].as<std::vector<std::string> >(); for (auto file : read_files) { bi::stream<bi::file_descriptor_source> sef{ check_open_r(file), bi::close_handle}; InputReader<SingleEndRead, SingleEndReadFastqImpl> ifs(sef); //JUST WRITE se read out - no way to overlap helper_overlapper(ifs, pe, se, counters, maxMismatch, minOverlap, insertLengths, stranded, minLength, checkLengths, adapterTrimming); } } if(vm.count("tab-input")) { auto read_files = vm["tab-input"].as<std::vector<std::string> > (); for (auto file : read_files) { bi::stream<bi::file_descriptor_source> tabin{ check_open_r(file), bi::close_handle}; InputReader<ReadBase, TabReadImpl> ift(tabin); helper_overlapper(ift, pe, se, counters, maxMismatch, minOverlap, insertLengths, stranded, minLength, checkLengths, adapterTrimming); } } if (vm.count("interleaved-input")) { auto read_files = vm["interleaved-input"].as<std::vector<std::string > >(); for (auto file : read_files) { bi::stream<bi::file_descriptor_source> inter{ check_open_r(file), bi::close_handle}; InputReader<PairedEndRead, InterReadImpl> ifp(inter); helper_overlapper(ifp, pe, se, counters, maxMismatch, minOverlap, insertLengths, stranded, minLength, checkLengths, adapterTrimming); } } if (std_in) { bi::stream<bi::file_descriptor_source> tabin {fileno(stdin), bi::close_handle}; InputReader<ReadBase, TabReadImpl> ift(tabin); helper_overlapper(ift, pe, se, counters, maxMismatch, minOverlap, insertLengths, stranded, minLength, checkLengths, adapterTrimming); } if (insertLengths) { std::ofstream histOutputFile(histFile); //0 is reserved for no overlap std::string stars; for (int i = 1; i < insertLengths->size(); ++i) { stars = ""; if ((*insertLengths)[i]) { stars = stars.insert(0, (*insertLengths)[i]/AST_COUNT, '*'); histOutputFile << i << '\t' << (*insertLengths)[i] << '\t' << stars << '\n'; } } stars = stars.insert(0, (*insertLengths)[0]/AST_COUNT, '*'); histOutputFile << "None" << '\t' << (*insertLengths)[0] << '\t' << stars << '\n'; histOutputFile.close(); } write_stats(statsFile, appendStats, counters, program_name); } catch(po::error& e) { std::cerr << "ERROR: " << e.what() << std::endl << std::endl; std::cerr << desc << std::endl; return ERROR_IN_COMMAND_LINE; } } catch(std::exception& e) { std::cerr << "\n\tUnhandled Exception: " << e.what() << std::endl; return ERROR_UNHANDLED_EXCEPTION; } return SUCCESS; } <|endoftext|>
<commit_before>#include "evas_common.h" #include "evas_engine.h" int evas_software_ddraw_init (HWND window, int depth, int fullscreen, Outbuf *buf) { DDSURFACEDESC surface_desc; DDPIXELFORMAT pixel_format; HRESULT res; int width; int height; if (!buf) return 0; buf->priv.dd.window = window; res = DirectDrawCreate(NULL, &buf->priv.dd.object, NULL); if (FAILED(res)) return 0; if (buf->priv.dd.fullscreen) { DDSCAPS caps; res = buf->priv.dd.object->SetCooperativeLevel(window, DDSCL_EXCLUSIVE | DDSCL_FULLSCREEN); if (FAILED(res)) goto release_object; width = GetSystemMetrics(SM_CXSCREEN); height = GetSystemMetrics(SM_CYSCREEN); ZeroMemory(&pixel_format, sizeof(pixel_format)); pixel_format.dwSize = sizeof(pixel_format); buf->priv.dd.surface_primary->GetPixelFormat(&pixel_format); if (pixel_format.dwRGBBitCount != depth) goto release_object; buf->priv.dd.depth = depth; res = buf->priv.dd.object->SetDisplayMode(width, height, depth); if (FAILED(res)) goto release_object; memset(&surface_desc, 0, sizeof(surface_desc)); surface_desc.dwSize = sizeof(surface_desc); surface_desc.dwFlags = DDSD_CAPS | DDSD_BACKBUFFERCOUNT; surface_desc.ddsCaps.dwCaps = DDSCAPS_PRIMARYSURFACE | DDSCAPS_FLIP | DDSCAPS_COMPLEX; surface_desc.dwBackBufferCount = 1; res = buf->priv.dd.object->CreateSurface(&surface_desc, &buf->priv.dd.surface_primary, NULL); if (FAILED(res)) goto release_object; caps.dwCaps = DDSCAPS_BACKBUFFER; res = buf->priv.dd.surface_primary->GetAttachedSurface(&caps, &buf->priv.dd.surface_back); if (FAILED(res)) goto release_surface_primary; } else { RECT rect; if (!GetClientRect(window, &rect)) goto release_object; width = rect.right - rect.left; height = rect.bottom - rect.top; res = buf->priv.dd.object->SetCooperativeLevel(window, DDSCL_NORMAL); if (FAILED(res)) goto release_object; res = buf->priv.dd.object->CreateClipper(0, &buf->priv.dd.clipper, NULL); if (FAILED(res)) goto release_object; res = buf->priv.dd.clipper->SetHWnd(0, window); if (FAILED(res)) goto release_clipper; memset(&surface_desc, 0, sizeof(surface_desc)); surface_desc.dwSize = sizeof(surface_desc); surface_desc.dwFlags = DDSD_CAPS; surface_desc.ddsCaps.dwCaps = DDSCAPS_PRIMARYSURFACE; res = buf->priv.dd.object->CreateSurface(&surface_desc, &buf->priv.dd.surface_primary, NULL); if (FAILED(res)) goto release_clipper; res = buf->priv.dd.surface_primary->SetClipper(buf->priv.dd.clipper); if (FAILED(res)) goto release_surface_primary; memset (&surface_desc, 0, sizeof(surface_desc)); surface_desc.dwSize = sizeof(surface_desc); surface_desc.dwFlags = DDSD_CAPS | DDSD_HEIGHT | DDSD_WIDTH; surface_desc.ddsCaps.dwCaps = DDSCAPS_OFFSCREENPLAIN; surface_desc.dwWidth = width; surface_desc.dwHeight = height; res = buf->priv.dd.object->CreateSurface(&surface_desc, &buf->priv.dd.surface_back, NULL); if (FAILED(res)) goto release_surface_primary; ZeroMemory(&pixel_format, sizeof(pixel_format)); pixel_format.dwSize = sizeof(pixel_format); buf->priv.dd.surface_primary->GetPixelFormat(&pixel_format); if (pixel_format.dwRGBBitCount != depth) goto release_surface_back; buf->priv.dd.depth = depth; } return 1; release_surface_back: buf->priv.dd.surface_back->Release(); release_surface_primary: buf->priv.dd.surface_primary->Release(); release_clipper: if (buf->priv.dd.fullscreen) buf->priv.dd.clipper->Release(); release_object: buf->priv.dd.object->Release(); return 0; } void evas_software_ddraw_shutdown(Outbuf *buf) { if (!buf) return; if (buf->priv.dd.fullscreen) if (buf->priv.dd.surface_back) buf->priv.dd.surface_back->Release(); if (buf->priv.dd.surface_primary) buf->priv.dd.surface_primary->Release(); if (buf->priv.dd.fullscreen) if (buf->priv.dd.clipper) buf->priv.dd.clipper->Release(); if (buf->priv.dd.object) buf->priv.dd.object->Release(); } int evas_software_ddraw_masks_get(Outbuf *buf) { DDPIXELFORMAT pixel_format; ZeroMemory(&pixel_format, sizeof(pixel_format)); pixel_format.dwSize = sizeof(pixel_format); if (FAILED(buf->priv.dd.surface_primary->GetPixelFormat(&pixel_format))) return 0; buf->priv.mask.r = pixel_format.dwRBitMask; buf->priv.mask.g = pixel_format.dwGBitMask; buf->priv.mask.b = pixel_format.dwBBitMask; return 1; } void * evas_software_ddraw_lock(Outbuf *buf, int *ddraw_width, int *ddraw_height, int *ddraw_pitch, int *ddraw_depth) { DDSURFACEDESC surface_desc; ZeroMemory(&surface_desc, sizeof(surface_desc)); surface_desc.dwSize = sizeof(surface_desc); if (FAILED(buf->priv.dd.surface_back->Lock(NULL, &surface_desc, DDLOCK_WAIT | DDLOCK_WRITEONLY | DDLOCK_SURFACEMEMORYPTR | DDLOCK_NOSYSLOCK, NULL))) return NULL; *ddraw_width = surface_desc.dwWidth; *ddraw_height = surface_desc.dwHeight; *ddraw_pitch = surface_desc.lPitch; *ddraw_depth = surface_desc.ddpfPixelFormat.dwRGBBitCount >> 3; return surface_desc.lpSurface; } void evas_software_ddraw_unlock_and_flip(Outbuf *buf) { RECT dst_rect; RECT src_rect; POINT p; if (FAILED(buf->priv.dd.surface_back->Unlock(NULL))) return; /* we figure out where on the primary surface our window lives */ p.x = 0; p.y = 0; ClientToScreen(buf->priv.dd.window, &p); GetClientRect(buf->priv.dd.window, &dst_rect); OffsetRect(&dst_rect, p.x, p.y); SetRect(&src_rect, 0, 0, buf->width, buf->height); /* nothing to do if the function fails, so we don't check the result */ buf->priv.dd.surface_primary->Blt(&dst_rect, buf->priv.dd.surface_back, &src_rect, DDBLT_WAIT, NULL); } void evas_software_ddraw_surface_resize(Outbuf *buf) { DDSURFACEDESC surface_desc; buf->priv.dd.surface_back->Release(); memset (&surface_desc, 0, sizeof (surface_desc)); surface_desc.dwSize = sizeof (surface_desc); /* FIXME: that code does not compile. Must know why */ #if 0 surface_desc.dwFlags = DDSD_HEIGHT | DDSD_WIDTH; surface_desc.dwWidth = width; surface_desc.dwHeight = height; buf->priv.dd.surface_back->SetSurfaceDesc(&surface_desc, NULL); #else surface_desc.dwFlags = DDSD_CAPS | DDSD_HEIGHT | DDSD_WIDTH; surface_desc.ddsCaps.dwCaps = DDSCAPS_OFFSCREENPLAIN; surface_desc.dwWidth = buf->width; surface_desc.dwHeight = buf->height; buf->priv.dd.object->CreateSurface(&surface_desc, &buf->priv.dd.surface_back, NULL); #endif } <commit_msg>release the clipper only it has been created, that is in windowed mode<commit_after>#include "evas_common.h" #include "evas_engine.h" int evas_software_ddraw_init (HWND window, int depth, int fullscreen, Outbuf *buf) { DDSURFACEDESC surface_desc; DDPIXELFORMAT pixel_format; HRESULT res; int width; int height; if (!buf) return 0; buf->priv.dd.window = window; res = DirectDrawCreate(NULL, &buf->priv.dd.object, NULL); if (FAILED(res)) return 0; if (buf->priv.dd.fullscreen) { DDSCAPS caps; res = buf->priv.dd.object->SetCooperativeLevel(window, DDSCL_EXCLUSIVE | DDSCL_FULLSCREEN); if (FAILED(res)) goto release_object; width = GetSystemMetrics(SM_CXSCREEN); height = GetSystemMetrics(SM_CYSCREEN); ZeroMemory(&pixel_format, sizeof(pixel_format)); pixel_format.dwSize = sizeof(pixel_format); buf->priv.dd.surface_primary->GetPixelFormat(&pixel_format); if (pixel_format.dwRGBBitCount != depth) goto release_object; buf->priv.dd.depth = depth; res = buf->priv.dd.object->SetDisplayMode(width, height, depth); if (FAILED(res)) goto release_object; memset(&surface_desc, 0, sizeof(surface_desc)); surface_desc.dwSize = sizeof(surface_desc); surface_desc.dwFlags = DDSD_CAPS | DDSD_BACKBUFFERCOUNT; surface_desc.ddsCaps.dwCaps = DDSCAPS_PRIMARYSURFACE | DDSCAPS_FLIP | DDSCAPS_COMPLEX; surface_desc.dwBackBufferCount = 1; res = buf->priv.dd.object->CreateSurface(&surface_desc, &buf->priv.dd.surface_primary, NULL); if (FAILED(res)) goto release_object; caps.dwCaps = DDSCAPS_BACKBUFFER; res = buf->priv.dd.surface_primary->GetAttachedSurface(&caps, &buf->priv.dd.surface_back); if (FAILED(res)) goto release_surface_primary; } else { RECT rect; if (!GetClientRect(window, &rect)) goto release_object; width = rect.right - rect.left; height = rect.bottom - rect.top; res = buf->priv.dd.object->SetCooperativeLevel(window, DDSCL_NORMAL); if (FAILED(res)) goto release_object; res = buf->priv.dd.object->CreateClipper(0, &buf->priv.dd.clipper, NULL); if (FAILED(res)) goto release_object; res = buf->priv.dd.clipper->SetHWnd(0, window); if (FAILED(res)) goto release_clipper; memset(&surface_desc, 0, sizeof(surface_desc)); surface_desc.dwSize = sizeof(surface_desc); surface_desc.dwFlags = DDSD_CAPS; surface_desc.ddsCaps.dwCaps = DDSCAPS_PRIMARYSURFACE; res = buf->priv.dd.object->CreateSurface(&surface_desc, &buf->priv.dd.surface_primary, NULL); if (FAILED(res)) goto release_clipper; res = buf->priv.dd.surface_primary->SetClipper(buf->priv.dd.clipper); if (FAILED(res)) goto release_surface_primary; memset (&surface_desc, 0, sizeof(surface_desc)); surface_desc.dwSize = sizeof(surface_desc); surface_desc.dwFlags = DDSD_CAPS | DDSD_HEIGHT | DDSD_WIDTH; surface_desc.ddsCaps.dwCaps = DDSCAPS_OFFSCREENPLAIN; surface_desc.dwWidth = width; surface_desc.dwHeight = height; res = buf->priv.dd.object->CreateSurface(&surface_desc, &buf->priv.dd.surface_back, NULL); if (FAILED(res)) goto release_surface_primary; ZeroMemory(&pixel_format, sizeof(pixel_format)); pixel_format.dwSize = sizeof(pixel_format); buf->priv.dd.surface_primary->GetPixelFormat(&pixel_format); if (pixel_format.dwRGBBitCount != depth) goto release_surface_back; buf->priv.dd.depth = depth; } return 1; release_surface_back: buf->priv.dd.surface_back->Release(); release_surface_primary: buf->priv.dd.surface_primary->Release(); release_clipper: if (!buf->priv.dd.fullscreen) buf->priv.dd.clipper->Release(); release_object: buf->priv.dd.object->Release(); return 0; } void evas_software_ddraw_shutdown(Outbuf *buf) { if (!buf) return; if (buf->priv.dd.fullscreen) if (buf->priv.dd.surface_back) buf->priv.dd.surface_back->Release(); if (buf->priv.dd.surface_primary) buf->priv.dd.surface_primary->Release(); if (!buf->priv.dd.fullscreen) if (buf->priv.dd.clipper) buf->priv.dd.clipper->Release(); if (buf->priv.dd.object) buf->priv.dd.object->Release(); } int evas_software_ddraw_masks_get(Outbuf *buf) { DDPIXELFORMAT pixel_format; ZeroMemory(&pixel_format, sizeof(pixel_format)); pixel_format.dwSize = sizeof(pixel_format); if (FAILED(buf->priv.dd.surface_primary->GetPixelFormat(&pixel_format))) return 0; buf->priv.mask.r = pixel_format.dwRBitMask; buf->priv.mask.g = pixel_format.dwGBitMask; buf->priv.mask.b = pixel_format.dwBBitMask; return 1; } void * evas_software_ddraw_lock(Outbuf *buf, int *ddraw_width, int *ddraw_height, int *ddraw_pitch, int *ddraw_depth) { DDSURFACEDESC surface_desc; ZeroMemory(&surface_desc, sizeof(surface_desc)); surface_desc.dwSize = sizeof(surface_desc); if (FAILED(buf->priv.dd.surface_back->Lock(NULL, &surface_desc, DDLOCK_WAIT | DDLOCK_WRITEONLY | DDLOCK_SURFACEMEMORYPTR | DDLOCK_NOSYSLOCK, NULL))) return NULL; *ddraw_width = surface_desc.dwWidth; *ddraw_height = surface_desc.dwHeight; *ddraw_pitch = surface_desc.lPitch; *ddraw_depth = surface_desc.ddpfPixelFormat.dwRGBBitCount >> 3; return surface_desc.lpSurface; } void evas_software_ddraw_unlock_and_flip(Outbuf *buf) { RECT dst_rect; RECT src_rect; POINT p; if (FAILED(buf->priv.dd.surface_back->Unlock(NULL))) return; /* we figure out where on the primary surface our window lives */ p.x = 0; p.y = 0; ClientToScreen(buf->priv.dd.window, &p); GetClientRect(buf->priv.dd.window, &dst_rect); OffsetRect(&dst_rect, p.x, p.y); SetRect(&src_rect, 0, 0, buf->width, buf->height); /* nothing to do if the function fails, so we don't check the result */ buf->priv.dd.surface_primary->Blt(&dst_rect, buf->priv.dd.surface_back, &src_rect, DDBLT_WAIT, NULL); } void evas_software_ddraw_surface_resize(Outbuf *buf) { DDSURFACEDESC surface_desc; buf->priv.dd.surface_back->Release(); memset (&surface_desc, 0, sizeof (surface_desc)); surface_desc.dwSize = sizeof (surface_desc); /* FIXME: that code does not compile. Must know why */ #if 0 surface_desc.dwFlags = DDSD_HEIGHT | DDSD_WIDTH; surface_desc.dwWidth = width; surface_desc.dwHeight = height; buf->priv.dd.surface_back->SetSurfaceDesc(&surface_desc, NULL); #else surface_desc.dwFlags = DDSD_CAPS | DDSD_HEIGHT | DDSD_WIDTH; surface_desc.ddsCaps.dwCaps = DDSCAPS_OFFSCREENPLAIN; surface_desc.dwWidth = buf->width; surface_desc.dwHeight = buf->height; buf->priv.dd.object->CreateSurface(&surface_desc, &buf->priv.dd.surface_back, NULL); #endif } <|endoftext|>
<commit_before>/* * Copyright 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ // Author: [email protected] (Ashish Gupta) #include "net/instaweb/rewriter/public/static_javascript_manager.h" #include <utility> #include "base/logging.h" #include "net/instaweb/htmlparse/public/doctype.h" #include "net/instaweb/htmlparse/public/html_element.h" #include "net/instaweb/htmlparse/public/html_name.h" #include "net/instaweb/htmlparse/public/html_node.h" #include "net/instaweb/http/public/meta_data.h" #include "net/instaweb/http/public/response_headers.h" #include "net/instaweb/rewriter/public/rewrite_driver.h" #include "net/instaweb/rewriter/public/rewrite_options.h" #include "net/instaweb/rewriter/public/server_context.h" #include "net/instaweb/rewriter/public/url_namer.h" #include "net/instaweb/util/public/hasher.h" #include "net/instaweb/util/public/message_handler.h" #include "net/instaweb/util/public/stl_util.h" #include "net/instaweb/util/public/string.h" #include "net/instaweb/util/public/string_util.h" namespace net_instaweb { extern const char* JS_add_instrumentation; extern const char* JS_add_instrumentation_opt; extern const char* JS_client_domain_rewriter; extern const char* JS_client_domain_rewriter_opt; extern const char* JS_critical_images_beacon; extern const char* JS_critical_images_beacon_opt; extern const char* JS_defer_iframe; extern const char* JS_defer_iframe_opt; extern const char* JS_delay_images; extern const char* JS_delay_images_opt; extern const char* JS_delay_images_inline; extern const char* JS_delay_images_inline_opt; extern const char* JS_js_defer; extern const char* JS_js_defer_opt; extern const char* JS_lazyload_images; extern const char* JS_lazyload_images_opt; extern const char* JS_deterministic; extern const char* JS_deterministic_opt; extern const char* JS_detect_reflow; extern const char* JS_detect_reflow_opt; extern const char* JS_local_storage_cache; extern const char* JS_local_storage_cache_opt; // The generated files(blink.js, js_defer.js) are named in "<hash>-<fileName>" // format. const char StaticJavascriptManager::kGStaticBase[] = "http://www.gstatic.com/psa/static/"; const char StaticJavascriptManager::kDefaultLibraryUrlPrefix[] = "/psajs/"; const char StaticJavascriptManager::kJsExtension[] = ".js"; struct StaticJavascriptManager::Asset { const char* file_name; const char* js_optimized; const char* js_debug; GoogleString js_opt_hash; GoogleString js_debug_hash; GoogleString opt_url; GoogleString debug_url; }; StaticJavascriptManager::StaticJavascriptManager( UrlNamer* url_namer, Hasher* hasher, MessageHandler* message_handler) : url_namer_(url_namer), hasher_(hasher), message_handler_(message_handler), serve_js_from_gstatic_(false), library_url_prefix_(kDefaultLibraryUrlPrefix) { InitializeJsStrings(); ResponseHeaders header; // TODO(ksimbili): Define a new constant kShortCacheTtlForMismatchedContentMs // in ServerContext for 5min. header.SetDateAndCaching(0, ResponseHeaders::kImplicitCacheTtlMs); cache_header_with_private_ttl_ = StrCat( header.Lookup1(HttpAttributes::kCacheControl), ",private"); header.Clear(); header.SetDateAndCaching(0, ServerContext::kGeneratedMaxAgeMs); cache_header_with_long_ttl_ = header.Lookup1(HttpAttributes::kCacheControl); } StaticJavascriptManager::~StaticJavascriptManager() { STLDeleteElements(&assets_); } const GoogleString& StaticJavascriptManager::GetJsUrl( const JsModule& module, const RewriteOptions* options) const { return options->Enabled(RewriteOptions::kDebug) ? assets_[module]->debug_url : assets_[module]->opt_url; } void StaticJavascriptManager::set_gstatic_hash(const JsModule& module, const GoogleString& hash) { if (serve_js_from_gstatic_) { CHECK(!hash.empty()); assets_[module]->opt_url = StrCat(kGStaticBase, hash, "-", assets_[module]->file_name, kJsExtension); } } void StaticJavascriptManager::InitializeJsStrings() { assets_.resize(kEndOfModules); for (std::vector<Asset*>::iterator it = assets_.begin(); it != assets_.end(); ++it) { *it = new Asset; } // Initialize file names. assets_[kAddInstrumentationJs]->file_name = "add_instrumentation"; assets_[kBlinkJs]->file_name = "blink"; assets_[kClientDomainRewriter]->file_name = "client_domain_rewriter"; assets_[kCriticalImagesBeaconJs]->file_name = "critical_images_beacon"; assets_[kDeferIframe]->file_name = "defer_iframe"; assets_[kDeferJs]->file_name = "js_defer"; assets_[kDelayImagesJs]->file_name = "delay_images"; assets_[kDelayImagesInlineJs]->file_name = "delay_images_inline"; assets_[kLazyloadImagesJs]->file_name = "lazyload_images"; assets_[kDetectReflowJs]->file_name = "detect_reflow"; assets_[kDeterministicJs]->file_name = "deterministic"; assets_[kLocalStorageCacheJs]->file_name = "local_storage_cache"; // Initialize compiled javascript strings-> assets_[kAddInstrumentationJs]->js_optimized = JS_add_instrumentation_opt; // Fetching the blink JS is not currently supported-> assets_[kBlinkJs]->js_optimized = "// Unsupported"; assets_[kClientDomainRewriter]->js_optimized = JS_client_domain_rewriter_opt; assets_[kCriticalImagesBeaconJs]->js_optimized = JS_critical_images_beacon_opt; assets_[kDeferIframe]->js_optimized = JS_defer_iframe_opt; assets_[kDeferJs]->js_optimized = JS_js_defer_opt; assets_[kDelayImagesJs]->js_optimized = JS_delay_images_opt; assets_[kDelayImagesInlineJs]->js_optimized = JS_delay_images_inline_opt; assets_[kLazyloadImagesJs]->js_optimized = JS_lazyload_images_opt; assets_[kDetectReflowJs]->js_optimized = JS_detect_reflow_opt; assets_[kDeterministicJs]->js_optimized = JS_deterministic_opt; assets_[kLocalStorageCacheJs]->js_optimized = JS_local_storage_cache_opt; // Initialize cleartext javascript strings-> assets_[kAddInstrumentationJs]->js_debug = JS_add_instrumentation; // Fetching the blink JS is not currently supported-> Add a comment in as the // unit test expects debug code to include comments-> assets_[kBlinkJs]->js_debug = "/* Unsupported */"; assets_[kClientDomainRewriter]->js_debug = JS_client_domain_rewriter; assets_[kCriticalImagesBeaconJs]->js_debug = JS_critical_images_beacon; assets_[kDeferIframe]->js_debug = JS_defer_iframe; assets_[kDeferJs]->js_debug = JS_js_defer; assets_[kDelayImagesJs]->js_debug = JS_delay_images; assets_[kDelayImagesInlineJs]->js_debug = JS_delay_images_inline; assets_[kLazyloadImagesJs]->js_debug = JS_lazyload_images; assets_[kDetectReflowJs]->js_debug = JS_detect_reflow; assets_[kDeterministicJs]->js_debug = JS_deterministic; assets_[kLocalStorageCacheJs]->js_debug = JS_local_storage_cache; for (std::vector<Asset*>::iterator it = assets_.begin(); it != assets_.end(); ++it) { Asset* asset = *it; asset->js_opt_hash = hasher_->Hash(asset->js_optimized); asset->js_debug_hash = hasher_->Hash(asset->js_debug); // Setup a map of file name to the corresponding index in assets_ to // allow easier lookup in GetJsSnippet. file_name_to_module_map_[asset->file_name] = static_cast<JsModule>(it - assets_.begin()); } InitializeJsUrls(); } void StaticJavascriptManager::InitializeJsUrls() { for (std::vector<Asset*>::iterator it = assets_.begin(); it != assets_.end(); ++it) { Asset* asset = *it; // Generated urls are in the format "<filename>.<md5>.js". asset->opt_url = StrCat(url_namer_->get_proxy_domain(), library_url_prefix_, asset->file_name, ".", asset->js_opt_hash, kJsExtension); // Generated debug urls are in the format "<fileName>_debug.<md5>.js". asset->debug_url = StrCat(url_namer_->get_proxy_domain(), library_url_prefix_, asset->file_name, "_debug.", asset->js_debug_hash, kJsExtension); } // Blink does not currently use the hash in the URL, so it is special cased // here. GoogleString blink_js_url = StrCat(url_namer_->get_proxy_domain(), library_url_prefix_, assets_[kBlinkJs]->file_name, kJsExtension); assets_[kBlinkJs]->debug_url = blink_js_url; assets_[kBlinkJs]->opt_url = blink_js_url; } const char* StaticJavascriptManager::GetJsSnippet( const JsModule& module, const RewriteOptions* options) const { CHECK(module != kEndOfModules); return options->Enabled(RewriteOptions::kDebug) ? assets_[module]->js_debug : assets_[module]->js_optimized; } void StaticJavascriptManager::AddJsToElement( StringPiece js, HtmlElement* script, RewriteDriver* driver) const { DCHECK(script->keyword() == HtmlName::kScript); // CDATA tags are required for inlined JS in XHTML pages to prevent // interpretation of certain characters (like &). In apache, something // downstream of mod_pagespeed could modify the content type of the response. // So CDATA tags are added conservatively if we are not sure that it is safe // to exclude them. GoogleString js_str; if (!(driver->server_context()->response_headers_finalized() && driver->MimeTypeXhtmlStatus() == RewriteDriver::kIsNotXhtml)) { StrAppend(&js_str, "//<![CDATA[\n", js, "\n//]]>"); js = js_str; } if (!driver->doctype().IsVersion5()) { driver->AddAttribute(script, HtmlName::kType, "text/javascript"); } HtmlCharactersNode* script_content = driver->NewCharactersNode(script, js); driver->AppendChild(script, script_content); } bool StaticJavascriptManager::GetJsSnippet(StringPiece file_name, StringPiece* content, StringPiece* cache_header) const { StringPieceVector names; SplitStringPieceToVector(file_name, ".", &names, true); // Expected file_name format is <name>[_debug].<HASH>.js // If file names doesn't contain hash in it, just return, because they may be // spurious request. if (names.size() != 3) { message_handler_->Message(kError, "Invalid url requested: %s.", file_name.as_string().c_str()); return false; } GoogleString plain_file_name; names[0].CopyToString(&plain_file_name); bool is_debug = false; if (StringPiece(plain_file_name).ends_with("_debug")) { is_debug = true; plain_file_name = plain_file_name.substr(0, plain_file_name.length() - strlen("_debug")); } FileNameToModuleMap::const_iterator p = file_name_to_module_map_.find(plain_file_name); if (p != file_name_to_module_map_.end()) { CHECK_GT(assets_.size(), p->second); Asset* asset = assets_[p->second]; *content = is_debug ? asset->js_debug : asset->js_optimized; if (cache_header) { StringPiece hash = is_debug ? asset->js_debug_hash : asset->js_opt_hash; if (hash == names[1]) { // compare hash *cache_header = cache_header_with_long_ttl_; } else { *cache_header = cache_header_with_private_ttl_; } } return true; } return false; } } // namespace net_instaweb <commit_msg>Fix build on lucid.<commit_after>/* * Copyright 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ // Author: [email protected] (Ashish Gupta) #include "net/instaweb/rewriter/public/static_javascript_manager.h" #include <utility> #include "base/logging.h" #include "net/instaweb/htmlparse/public/doctype.h" #include "net/instaweb/htmlparse/public/html_element.h" #include "net/instaweb/htmlparse/public/html_name.h" #include "net/instaweb/htmlparse/public/html_node.h" #include "net/instaweb/http/public/meta_data.h" #include "net/instaweb/http/public/response_headers.h" #include "net/instaweb/rewriter/public/rewrite_driver.h" #include "net/instaweb/rewriter/public/rewrite_options.h" #include "net/instaweb/rewriter/public/server_context.h" #include "net/instaweb/rewriter/public/url_namer.h" #include "net/instaweb/util/public/hasher.h" #include "net/instaweb/util/public/message_handler.h" #include "net/instaweb/util/public/stl_util.h" #include "net/instaweb/util/public/string.h" #include "net/instaweb/util/public/string_util.h" namespace net_instaweb { extern const char* JS_add_instrumentation; extern const char* JS_add_instrumentation_opt; extern const char* JS_client_domain_rewriter; extern const char* JS_client_domain_rewriter_opt; extern const char* JS_critical_images_beacon; extern const char* JS_critical_images_beacon_opt; extern const char* JS_defer_iframe; extern const char* JS_defer_iframe_opt; extern const char* JS_delay_images; extern const char* JS_delay_images_opt; extern const char* JS_delay_images_inline; extern const char* JS_delay_images_inline_opt; extern const char* JS_js_defer; extern const char* JS_js_defer_opt; extern const char* JS_lazyload_images; extern const char* JS_lazyload_images_opt; extern const char* JS_deterministic; extern const char* JS_deterministic_opt; extern const char* JS_detect_reflow; extern const char* JS_detect_reflow_opt; extern const char* JS_local_storage_cache; extern const char* JS_local_storage_cache_opt; // The generated files(blink.js, js_defer.js) are named in "<hash>-<fileName>" // format. const char StaticJavascriptManager::kGStaticBase[] = "http://www.gstatic.com/psa/static/"; const char StaticJavascriptManager::kDefaultLibraryUrlPrefix[] = "/psajs/"; const char StaticJavascriptManager::kJsExtension[] = ".js"; struct StaticJavascriptManager::Asset { const char* file_name; const char* js_optimized; const char* js_debug; GoogleString js_opt_hash; GoogleString js_debug_hash; GoogleString opt_url; GoogleString debug_url; }; StaticJavascriptManager::StaticJavascriptManager( UrlNamer* url_namer, Hasher* hasher, MessageHandler* message_handler) : url_namer_(url_namer), hasher_(hasher), message_handler_(message_handler), serve_js_from_gstatic_(false), library_url_prefix_(kDefaultLibraryUrlPrefix) { InitializeJsStrings(); ResponseHeaders header; // TODO(ksimbili): Define a new constant kShortCacheTtlForMismatchedContentMs // in ServerContext for 5min. header.SetDateAndCaching(0, ResponseHeaders::kImplicitCacheTtlMs); cache_header_with_private_ttl_ = StrCat( header.Lookup1(HttpAttributes::kCacheControl), ",private"); header.Clear(); header.SetDateAndCaching(0, ServerContext::kGeneratedMaxAgeMs); cache_header_with_long_ttl_ = header.Lookup1(HttpAttributes::kCacheControl); } StaticJavascriptManager::~StaticJavascriptManager() { STLDeleteElements(&assets_); } const GoogleString& StaticJavascriptManager::GetJsUrl( const JsModule& module, const RewriteOptions* options) const { return options->Enabled(RewriteOptions::kDebug) ? assets_[module]->debug_url : assets_[module]->opt_url; } void StaticJavascriptManager::set_gstatic_hash(const JsModule& module, const GoogleString& hash) { if (serve_js_from_gstatic_) { CHECK(!hash.empty()); assets_[module]->opt_url = StrCat(kGStaticBase, hash, "-", assets_[module]->file_name, kJsExtension); } } void StaticJavascriptManager::InitializeJsStrings() { assets_.resize(kEndOfModules); for (std::vector<Asset*>::iterator it = assets_.begin(); it != assets_.end(); ++it) { *it = new Asset; } // Initialize file names. assets_[kAddInstrumentationJs]->file_name = "add_instrumentation"; assets_[kBlinkJs]->file_name = "blink"; assets_[kClientDomainRewriter]->file_name = "client_domain_rewriter"; assets_[kCriticalImagesBeaconJs]->file_name = "critical_images_beacon"; assets_[kDeferIframe]->file_name = "defer_iframe"; assets_[kDeferJs]->file_name = "js_defer"; assets_[kDelayImagesJs]->file_name = "delay_images"; assets_[kDelayImagesInlineJs]->file_name = "delay_images_inline"; assets_[kLazyloadImagesJs]->file_name = "lazyload_images"; assets_[kDetectReflowJs]->file_name = "detect_reflow"; assets_[kDeterministicJs]->file_name = "deterministic"; assets_[kLocalStorageCacheJs]->file_name = "local_storage_cache"; // Initialize compiled javascript strings-> assets_[kAddInstrumentationJs]->js_optimized = JS_add_instrumentation_opt; // Fetching the blink JS is not currently supported-> assets_[kBlinkJs]->js_optimized = "// Unsupported"; assets_[kClientDomainRewriter]->js_optimized = JS_client_domain_rewriter_opt; assets_[kCriticalImagesBeaconJs]->js_optimized = JS_critical_images_beacon_opt; assets_[kDeferIframe]->js_optimized = JS_defer_iframe_opt; assets_[kDeferJs]->js_optimized = JS_js_defer_opt; assets_[kDelayImagesJs]->js_optimized = JS_delay_images_opt; assets_[kDelayImagesInlineJs]->js_optimized = JS_delay_images_inline_opt; assets_[kLazyloadImagesJs]->js_optimized = JS_lazyload_images_opt; assets_[kDetectReflowJs]->js_optimized = JS_detect_reflow_opt; assets_[kDeterministicJs]->js_optimized = JS_deterministic_opt; assets_[kLocalStorageCacheJs]->js_optimized = JS_local_storage_cache_opt; // Initialize cleartext javascript strings-> assets_[kAddInstrumentationJs]->js_debug = JS_add_instrumentation; // Fetching the blink JS is not currently supported-> Add a comment in as the // unit test expects debug code to include comments-> assets_[kBlinkJs]->js_debug = "/* Unsupported */"; assets_[kClientDomainRewriter]->js_debug = JS_client_domain_rewriter; assets_[kCriticalImagesBeaconJs]->js_debug = JS_critical_images_beacon; assets_[kDeferIframe]->js_debug = JS_defer_iframe; assets_[kDeferJs]->js_debug = JS_js_defer; assets_[kDelayImagesJs]->js_debug = JS_delay_images; assets_[kDelayImagesInlineJs]->js_debug = JS_delay_images_inline; assets_[kLazyloadImagesJs]->js_debug = JS_lazyload_images; assets_[kDetectReflowJs]->js_debug = JS_detect_reflow; assets_[kDeterministicJs]->js_debug = JS_deterministic; assets_[kLocalStorageCacheJs]->js_debug = JS_local_storage_cache; for (std::vector<Asset*>::iterator it = assets_.begin(); it != assets_.end(); ++it) { Asset* asset = *it; asset->js_opt_hash = hasher_->Hash(asset->js_optimized); asset->js_debug_hash = hasher_->Hash(asset->js_debug); // Setup a map of file name to the corresponding index in assets_ to // allow easier lookup in GetJsSnippet. file_name_to_module_map_[asset->file_name] = static_cast<JsModule>(it - assets_.begin()); } InitializeJsUrls(); } void StaticJavascriptManager::InitializeJsUrls() { for (std::vector<Asset*>::iterator it = assets_.begin(); it != assets_.end(); ++it) { Asset* asset = *it; // Generated urls are in the format "<filename>.<md5>.js". asset->opt_url = StrCat(url_namer_->get_proxy_domain(), library_url_prefix_, asset->file_name, ".", asset->js_opt_hash, kJsExtension); // Generated debug urls are in the format "<fileName>_debug.<md5>.js". asset->debug_url = StrCat(url_namer_->get_proxy_domain(), library_url_prefix_, asset->file_name, "_debug.", asset->js_debug_hash, kJsExtension); } // Blink does not currently use the hash in the URL, so it is special cased // here. GoogleString blink_js_url = StrCat(url_namer_->get_proxy_domain(), library_url_prefix_, assets_[kBlinkJs]->file_name, kJsExtension); assets_[kBlinkJs]->debug_url = blink_js_url; assets_[kBlinkJs]->opt_url = blink_js_url; } const char* StaticJavascriptManager::GetJsSnippet( const JsModule& module, const RewriteOptions* options) const { CHECK(module != kEndOfModules); return options->Enabled(RewriteOptions::kDebug) ? assets_[module]->js_debug : assets_[module]->js_optimized; } void StaticJavascriptManager::AddJsToElement( StringPiece js, HtmlElement* script, RewriteDriver* driver) const { DCHECK(script->keyword() == HtmlName::kScript); // CDATA tags are required for inlined JS in XHTML pages to prevent // interpretation of certain characters (like &). In apache, something // downstream of mod_pagespeed could modify the content type of the response. // So CDATA tags are added conservatively if we are not sure that it is safe // to exclude them. GoogleString js_str; if (!(driver->server_context()->response_headers_finalized() && driver->MimeTypeXhtmlStatus() == RewriteDriver::kIsNotXhtml)) { StrAppend(&js_str, "//<![CDATA[\n", js, "\n//]]>"); js = js_str; } if (!driver->doctype().IsVersion5()) { driver->AddAttribute(script, HtmlName::kType, "text/javascript"); } HtmlCharactersNode* script_content = driver->NewCharactersNode(script, js); driver->AppendChild(script, script_content); } bool StaticJavascriptManager::GetJsSnippet(StringPiece file_name, StringPiece* content, StringPiece* cache_header) const { StringPieceVector names; SplitStringPieceToVector(file_name, ".", &names, true); // Expected file_name format is <name>[_debug].<HASH>.js // If file names doesn't contain hash in it, just return, because they may be // spurious request. if (names.size() != 3) { message_handler_->Message(kError, "Invalid url requested: %s.", file_name.as_string().c_str()); return false; } GoogleString plain_file_name; names[0].CopyToString(&plain_file_name); bool is_debug = false; if (StringPiece(plain_file_name).ends_with("_debug")) { is_debug = true; plain_file_name = plain_file_name.substr(0, plain_file_name.length() - strlen("_debug")); } FileNameToModuleMap::const_iterator p = file_name_to_module_map_.find(plain_file_name); if (p != file_name_to_module_map_.end()) { CHECK_GT(assets_.size(), static_cast<size_t>(p->second)); Asset* asset = assets_[p->second]; *content = is_debug ? asset->js_debug : asset->js_optimized; if (cache_header) { StringPiece hash = is_debug ? asset->js_debug_hash : asset->js_opt_hash; if (hash == names[1]) { // compare hash *cache_header = cache_header_with_long_ttl_; } else { *cache_header = cache_header_with_private_ttl_; } } return true; } return false; } } // namespace net_instaweb <|endoftext|>
<commit_before>/* * specguiorder.cpp * StatusSpec project * * Copyright (c) 2014 thesupremecommander * BSD 2-Clause License * http://opensource.org/licenses/BSD-2-Clause * */ #include "specguiorder.h" SpecGUIOrder::SpecGUIOrder() { enabled = new ConVar("statusspec_specguiorder_enabled", "0", FCVAR_NONE, "enable ordering of spec GUI"); reverse_blu = new ConVar("statusspec_specguiorder_reverse_blu", "0", FCVAR_NONE, "reverse order for BLU players"); reverse_red = new ConVar("statusspec_specguiorder_reverse_red", "0", FCVAR_NONE, "reverse order for RED players"); specguiSettings = new KeyValues("Resource/UI/SpectatorTournament.res"); specguiSettings->LoadFromFile(Interfaces::pFileSystem, "resource/ui/spectatortournament.res", "mod"); } bool SpecGUIOrder::IsEnabled() { return enabled->GetBool(); } void SpecGUIOrder::InterceptMessage(vgui::VPANEL vguiPanel, KeyValues *params, vgui::VPANEL ifromPanel) { std::string originPanelName = g_pVGuiPanel->GetName(ifromPanel); if (originPanelName.substr(0, 11).compare("playerpanel") == 0 && strcmp(params->GetName(), "DialogVariables") == 0) { const char *playerName = params->GetString("playername", NULL); if (playerName) { for (int i = 0; i <= MAX_PLAYERS; i++) { Player player = i; if (!player) { continue; } if (strcmp(playerName, player.GetName()) == 0) { playerPanels[originPanelName] = player; break; } } } } } bool SpecGUIOrder::SetPosOverride(vgui::VPANEL vguiPanel, int &x, int &y) { std::string panelName = g_pVGuiPanel->GetName(vguiPanel); if (panelName.substr(0, 11).compare("playerpanel") == 0) { Player player = playerPanels[panelName]; if (!player) { return false; } TFTeam team = player.GetTeam(); if (team == TFTeam_Red) { int position; if (!reverse_red->GetBool()) { position = std::distance(redPlayers.begin(), std::find(redPlayers.begin(), redPlayers.end(), player)); } else { position = std::distance(redPlayers.rbegin(), std::find(redPlayers.rbegin(), redPlayers.rend(), player)); } int baseX = specguiSettings->FindKey("specgui")->GetInt("team2_player_base_offset_x"); int baseY = specguiSettings->FindKey("specgui")->GetInt("team2_player_base_y"); int deltaX = specguiSettings->FindKey("specgui")->GetInt("team2_player_delta_x"); int deltaY = specguiSettings->FindKey("specgui")->GetInt("team2_player_delta_y"); x = g_pVGuiSchemeManager->GetProportionalScaledValue(baseX + (position * deltaX)); y = g_pVGuiSchemeManager->GetProportionalScaledValue(baseY + (position * deltaY)); return true; } else if (team == TFTeam_Blue) { int position; if (!reverse_blu->GetBool()) { position = std::distance(bluPlayers.begin(), std::find(bluPlayers.begin(), bluPlayers.end(), player)); } else { position = std::distance(bluPlayers.rbegin(), std::find(bluPlayers.rbegin(), bluPlayers.rend(), player)); } int baseX = specguiSettings->FindKey("specgui")->GetInt("team1_player_base_offset_x"); int baseY = specguiSettings->FindKey("specgui")->GetInt("team1_player_base_y"); int deltaX = specguiSettings->FindKey("specgui")->GetInt("team1_player_delta_x"); int deltaY = specguiSettings->FindKey("specgui")->GetInt("team1_player_delta_y"); x = g_pVGuiSchemeManager->GetProportionalScaledValue(baseX + (position * deltaX)); y = g_pVGuiSchemeManager->GetProportionalScaledValue(baseY + (position * deltaY)); return true; } } return false; } void SpecGUIOrder::PreEntityUpdate() { bluPlayers.clear(); redPlayers.clear(); } void SpecGUIOrder::ProcessEntity(IClientEntity *entity) { Player player = entity; if (!player) { return; } TFTeam team = player.GetTeam(); if (team == TFTeam_Red) { redPlayers.push_back(player); } else if (team == TFTeam_Blue) { bluPlayers.push_back(player); } } void SpecGUIOrder::PostEntityUpdate() { bluPlayers.sort(); redPlayers.sort(); }<commit_msg>Fix an issue with small gaps in between players on the HUD.<commit_after>/* * specguiorder.cpp * StatusSpec project * * Copyright (c) 2014 thesupremecommander * BSD 2-Clause License * http://opensource.org/licenses/BSD-2-Clause * */ #include "specguiorder.h" SpecGUIOrder::SpecGUIOrder() { enabled = new ConVar("statusspec_specguiorder_enabled", "0", FCVAR_NONE, "enable ordering of spec GUI"); reverse_blu = new ConVar("statusspec_specguiorder_reverse_blu", "0", FCVAR_NONE, "reverse order for BLU players"); reverse_red = new ConVar("statusspec_specguiorder_reverse_red", "0", FCVAR_NONE, "reverse order for RED players"); specguiSettings = new KeyValues("Resource/UI/SpectatorTournament.res"); specguiSettings->LoadFromFile(Interfaces::pFileSystem, "resource/ui/spectatortournament.res", "mod"); } bool SpecGUIOrder::IsEnabled() { return enabled->GetBool(); } void SpecGUIOrder::InterceptMessage(vgui::VPANEL vguiPanel, KeyValues *params, vgui::VPANEL ifromPanel) { std::string originPanelName = g_pVGuiPanel->GetName(ifromPanel); if (originPanelName.substr(0, 11).compare("playerpanel") == 0 && strcmp(params->GetName(), "DialogVariables") == 0) { const char *playerName = params->GetString("playername", NULL); if (playerName) { for (int i = 0; i <= MAX_PLAYERS; i++) { Player player = i; if (!player) { continue; } if (strcmp(playerName, player.GetName()) == 0) { playerPanels[originPanelName] = player; break; } } } } } bool SpecGUIOrder::SetPosOverride(vgui::VPANEL vguiPanel, int &x, int &y) { std::string panelName = g_pVGuiPanel->GetName(vguiPanel); if (panelName.substr(0, 11).compare("playerpanel") == 0) { Player player = playerPanels[panelName]; if (!player) { return false; } TFTeam team = player.GetTeam(); if (team == TFTeam_Red) { int position; if (!reverse_red->GetBool()) { position = std::distance(redPlayers.begin(), std::find(redPlayers.begin(), redPlayers.end(), player)); } else { position = std::distance(redPlayers.rbegin(), std::find(redPlayers.rbegin(), redPlayers.rend(), player)); } int baseX = g_pVGuiSchemeManager->GetProportionalScaledValue(specguiSettings->FindKey("specgui")->GetInt("team2_player_base_offset_x")); int baseY = g_pVGuiSchemeManager->GetProportionalScaledValue(specguiSettings->FindKey("specgui")->GetInt("team2_player_base_y")); int deltaX = g_pVGuiSchemeManager->GetProportionalScaledValue(specguiSettings->FindKey("specgui")->GetInt("team2_player_delta_x")); int deltaY = g_pVGuiSchemeManager->GetProportionalScaledValue(specguiSettings->FindKey("specgui")->GetInt("team2_player_delta_y")); x = baseX + (position * deltaX); y = baseY + (position * deltaY); return true; } else if (team == TFTeam_Blue) { int position; if (!reverse_blu->GetBool()) { position = std::distance(bluPlayers.begin(), std::find(bluPlayers.begin(), bluPlayers.end(), player)); } else { position = std::distance(bluPlayers.rbegin(), std::find(bluPlayers.rbegin(), bluPlayers.rend(), player)); } int baseX = g_pVGuiSchemeManager->GetProportionalScaledValue(specguiSettings->FindKey("specgui")->GetInt("team1_player_base_offset_x")); int baseY = g_pVGuiSchemeManager->GetProportionalScaledValue(specguiSettings->FindKey("specgui")->GetInt("team1_player_base_y")); int deltaX = g_pVGuiSchemeManager->GetProportionalScaledValue(specguiSettings->FindKey("specgui")->GetInt("team1_player_delta_x")); int deltaY = g_pVGuiSchemeManager->GetProportionalScaledValue(specguiSettings->FindKey("specgui")->GetInt("team1_player_delta_y")); x = baseX + (position * deltaX); y = baseY + (position * deltaY); return true; } } return false; } void SpecGUIOrder::PreEntityUpdate() { bluPlayers.clear(); redPlayers.clear(); } void SpecGUIOrder::ProcessEntity(IClientEntity *entity) { Player player = entity; if (!player) { return; } TFTeam team = player.GetTeam(); if (team == TFTeam_Red) { redPlayers.push_back(player); } else if (team == TFTeam_Blue) { bluPlayers.push_back(player); } } void SpecGUIOrder::PostEntityUpdate() { bluPlayers.sort(); redPlayers.sort(); }<|endoftext|>
<commit_before>// Copyright 2014 MongoDB Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #pragma once #include <cstdint> #include <bsoncxx/stdx/optional.hpp> #include <mongocxx/write_type.hpp> #include <mongocxx/model/insert_one.hpp> #include <mongocxx/model/delete_one.hpp> #include <mongocxx/model/delete_many.hpp> #include <mongocxx/model/update_one.hpp> #include <mongocxx/model/update_many.hpp> #include <mongocxx/model/replace_one.hpp> #include <mongocxx/config/prelude.hpp> namespace mongocxx { MONGOCXX_INLINE_NAMESPACE_BEGIN namespace model { /// /// @todo document this class /// class MONGOCXX_API write { public: write(insert_one value); write(update_one value); write(update_many value); write(delete_one value); write(delete_many value); write(replace_one value); write(write&& rhs) noexcept; write& operator=(write&& rhs) noexcept; write(const write& rhs) = delete; write& operator=(const write& rhs) = delete; ~write(); write_type type() const; const insert_one& get_insert_one() const; const update_one& get_update_one() const; const update_many& get_update_many() const; const delete_one& get_delete_one() const; const delete_many& get_delete_many() const; const replace_one& get_replace_one() const; private: MONGOCXX_PRIVATE void destroy_member() noexcept; write_type _type; union { insert_one _insert_one; update_one _update_one; update_many _update_many; delete_one _delete_one; delete_many _delete_many; replace_one _replace_one; }; }; } // namespace model MONGOCXX_INLINE_NAMESPACE_END } // namespace mongocxx #include <mongocxx/config/postlude.hpp> <commit_msg>CXX-847 Document the model/write class<commit_after>// Copyright 2014 MongoDB Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #pragma once #include <cstdint> #include <bsoncxx/stdx/optional.hpp> #include <mongocxx/write_type.hpp> #include <mongocxx/model/insert_one.hpp> #include <mongocxx/model/delete_one.hpp> #include <mongocxx/model/delete_many.hpp> #include <mongocxx/model/update_one.hpp> #include <mongocxx/model/update_many.hpp> #include <mongocxx/model/replace_one.hpp> #include <mongocxx/config/prelude.hpp> namespace mongocxx { MONGOCXX_INLINE_NAMESPACE_BEGIN namespace model { /// /// Models a single write operation within a @bulk_write. /// class MONGOCXX_API write { public: /// /// Constructs a write from an @insert_one. /// write(insert_one value); /// /// Constructs a write from an @update_one. /// write(update_one value); /// /// Constructs a write from an @update_many. /// write(update_many value); /// /// Constructs a write from a @delete_one. /// write(delete_one value); /// /// Constructs a write from a @delete_many. /// write(delete_many value); /// /// Constructs a write from a @replace_one. /// write(replace_one value); /// /// Move constructs a write. /// write(write&& rhs) noexcept; /// /// Move assigns a write. /// write& operator=(write&& rhs) noexcept; write(const write& rhs) = delete; write& operator=(const write& rhs) = delete; /// /// Destroys a write. /// ~write(); /// /// Returns the current type of this write. You must call this /// method before calling any of the get methods below. /// write_type type() const; /// /// Accesses the write as an @insert_one. It is illegal to call /// this method if the return of @type (above) does not indicate /// that this object currently contains the applicable type. /// const insert_one& get_insert_one() const; /// /// Accesses the write as an @update_one. It is illegal to call /// this method if the return of @type (above) does not indicate /// that this object currently contains the applicable type. /// const update_one& get_update_one() const; /// /// Accesses the write as an @update_many. It is illegal to call /// this method if the return of @type (above) does not indicate /// that this object currently contains the applicable type. /// const update_many& get_update_many() const; /// /// Accesses the write as a @delete_one. It is illegal to call /// this method if the return of @type (above) does not indicate /// that this object currently contains the applicable type. /// const delete_one& get_delete_one() const; /// /// Accesses the write as a @delete_many. It is illegal to call /// this method if the return of @type (above) does not indicate /// that this object currently contains the applicable type. /// const delete_many& get_delete_many() const; /// /// Accesses the write as a @replace_one. It is illegal to call /// this method if the return of @type (above) does not indicate /// that this object currently contains the applicable type. /// const replace_one& get_replace_one() const; private: MONGOCXX_PRIVATE void destroy_member() noexcept; write_type _type; union { insert_one _insert_one; update_one _update_one; update_many _update_many; delete_one _delete_one; delete_many _delete_many; replace_one _replace_one; }; }; } // namespace model MONGOCXX_INLINE_NAMESPACE_END } // namespace mongocxx #include <mongocxx/config/postlude.hpp> <|endoftext|>
<commit_before>/************************************************************************************ ** * @copyright (c) 2013-2100, ChengDu Duyer Technology Co., LTD. All Right Reserved. * *************************************************************************************/ /** * @file g_network_client.cpp * @version * @brief * @author duye * @date 2014-09-30 * @note * * 1. 2014-09-30 duye Created this file * */ #include <g_network_client.h> namespace gcom { NetworkClient::NetworkClient() {} NetworkClient::NetworkClient(const IPPortPair& server_addr) : m_serverAddr(server_addr) , m_connectState(CLIENT_INIT) {} NetworkClient::~NetworkClient() {} const IPPortPair& NetworkClient::getServerAddr() const { return m_serverAddr; } const ClientConnectState& NetworkClient::getConnectState() const { return m_connectState; } GResult NetworkClient::addObserver(NetworkClientInterface* observer) { IS_YES_R(findObserver(observer)); m_observerList.push_back(observer); return G_YES; } GResult NetworkClient::removeObserver(NetworkClientInterface* observer) { m_observerList.remove(observer); return G_YES; } GResult NetworkClient::run() { return this->msgLoop(); } GResult NetworkClient::findObserver(NetworkClientInterface* observer) { ObserverList::const_iterator iter = m_observerList.begin(); for (; iter != m_observerList.end(); ++iter) { if (*iter == observer) { return G_YES; } } return G_NO; } } <commit_msg>Update g_network_client.cpp<commit_after>/************************************************************************************ ** * @copyright (c) 2013-2100, ChengDu Duyer Technology Co., LTD. All Right Reserved. * *************************************************************************************/ /** * @file g_network_client.cpp * @version * @brief * @author duye * @date 2014-09-30 * @note * * 1. 2014-09-30 duye Created this file * */ #include <g_network_client.h> namespace gcom { NetworkClient::NetworkClient() {} NetworkClient::NetworkClient(const IPPortPair& server_addr) : m_serverAddr(server_addr) , m_connectState(CLIENT_INIT) {} NetworkClient::~NetworkClient() {} const IPPortPair& NetworkClient::getServerAddr() const { return m_serverAddr; } const ClientConnectState& NetworkClient::getConnectState() const { return m_connectState; } GResult NetworkClient::addObserver(NetworkClientObserver* observer) { IS_YES_RX(findObserver(observer)); m_observerList.push_back(observer); return G_YES; } GResult NetworkClient::removeObserver(NetworkClientObserver* observer) { m_observerList.remove(observer); return G_YES; } void NetworkClient::setState(const ClientState& state) { m_state = state; } const ClientState& NetworkClient::state() const { return m_state; } GResult NetworkClient::run() { return this->msgLoop(); } GResult NetworkClient::findObserver(NetworkClientObserver* observer) { ObserverList::const_iterator iter = m_observerList.begin(); for (; iter != m_observerList.end(); ++iter) { if (*iter == observer) { return G_YES; } } return G_NO; } } <|endoftext|>
<commit_before>//--------------------------------------------------------- // Copyright 2018 Ontario Institute for Cancer Research // Written by Jared Simpson ([email protected]) //--------------------------------------------------------- // // nanopolish_vcf2fasta - write a new genome sequence // by introducing variants from a set of vcf files // #include <stdio.h> #include <stdlib.h> #include <string.h> #include <string> #include <vector> #include <map> #include <inttypes.h> #include <assert.h> #include <math.h> #include <sys/time.h> #include <algorithm> #include <sstream> #include <set> #include <omp.h> #include <getopt.h> #include <fast5.hpp> #include "htslib/faidx.h" #include "nanopolish_common.h" #include "nanopolish_variant.h" #include "nanopolish_eventalign.h" #include "nanopolish_haplotype.h" // // Getopt // #define SUBPROGRAM "vcf2fasta" static const char *VCF2FASTA_VERSION_MESSAGE = SUBPROGRAM " Version " PACKAGE_VERSION "\n" "Written by Jared Simpson.\n" "\n" "Copyright 2018 Ontario Institute for Cancer Research\n"; static const char *VCF2FASTA_USAGE_MESSAGE = "Usage: " PACKAGE_NAME " " SUBPROGRAM " -g draft.fa segment1.vcf segment2.vcf ...\n" "Write a new genome sequence by introducing variants from the input files\n" "\n" " -v, --verbose display verbose output\n" " --version display version\n" " --help display this help and exit\n" " -g, --genome=FILE the input genome is in FILE\n" "\nReport bugs to " PACKAGE_BUGREPORT "\n\n"; namespace opt { static unsigned int verbose; static std::vector<std::string> input_vcf_files; static std::string genome_file; } static const char* shortopts = "g:v"; enum { OPT_HELP = 1, OPT_VERSION }; static const struct option longopts[] = { { "verbose", no_argument, NULL, 'v' }, { "help", no_argument, NULL, OPT_HELP }, { "version", no_argument, NULL, OPT_VERSION }, { "genome", required_argument, NULL, 'g' }, { NULL, 0, NULL, 0 } }; void parse_vcf2fasta_options(int argc, char** argv) { bool die = false; for (char c; (c = getopt_long(argc, argv, shortopts, longopts, NULL)) != -1;) { std::istringstream arg(optarg != NULL ? optarg : ""); switch (c) { case '?': die = true; break; case 'v': opt::verbose++; break; case 'g': arg >> opt::genome_file; break; case OPT_HELP: std::cout << VCF2FASTA_USAGE_MESSAGE; exit(EXIT_SUCCESS); case OPT_VERSION: std::cout << VCF2FASTA_VERSION_MESSAGE; exit(EXIT_SUCCESS); } } if(opt::genome_file.empty()) { std::cerr << SUBPROGRAM ": -g/--genome file is required\n"; die = true; } if (argc - optind < 1) { std::cerr << SUBPROGRAM ": not enough arguments\n"; die = true; } if (die) { std::cout << "\n" << VCF2FASTA_USAGE_MESSAGE; exit(EXIT_FAILURE); } for(; optind < argc; ++optind) { opt::input_vcf_files.push_back(argv[optind]); } } int vcf2fasta_main(int argc, char** argv) { parse_vcf2fasta_options(argc, argv); // Read genome file faidx_t *fai = fai_load(opt::genome_file.c_str()); // Read VCF files and gather variants for each contig and the polishing window coordinates std::map<std::string, std::vector<Variant>> variants_by_contig; std::map<std::string, std::vector<std::pair<int, int>>> windows_by_contig; for(const auto& filename : opt::input_vcf_files) { std::string window_str; std::vector<Variant> out; std::ifstream infile(filename); std::string line; while(getline(infile, line)) { // parse header if(line[0] == '#') { // check for window coordinates if(line.find("nanopolish_window") != std::string::npos) { std::vector<std::string> fields = split(line, '='); assert(fields.size() == 2); window_str = fields[1]; } } else { Variant v(line); variants_by_contig[v.ref_name].push_back(v); } } if(window_str.empty()) { fprintf(stderr, "error: could not detect polishing window from input file %s\n", filename.c_str()); exit(EXIT_FAILURE); } std::string window_contig; int window_start, window_end; parse_region_string(window_str, window_contig, window_start, window_end); windows_by_contig[window_contig].push_back(std::make_pair(window_start, window_end)); } size_t n_contigs = faidx_nseq(fai); for(size_t contig_idx = 0; contig_idx < n_contigs; ++contig_idx) { std::string contig = faidx_iseq(fai, contig_idx); int contig_length = faidx_seq_len(fai, contig.c_str()); // Confirm that all windows on this contig have been polished bool window_check_ok = true; auto& windows = windows_by_contig[contig]; std::sort(windows.begin(), windows.end()); if(windows[0].first != 0) { fprintf(stderr, "error: first %d bases are not covered by a polished window for contig %s.\n", windows[0].first, contig.c_str()); window_check_ok = false; } for(size_t window_idx = 1; window_idx < windows.size(); ++window_idx) { int prev_start = windows[window_idx - 1].first; int prev_end = windows[window_idx - 1].second; int curr_start = windows[window_idx].first; int curr_end = windows[window_idx].second; if(curr_start > prev_end) { fprintf(stderr, "error: adjacent polishing windows do not overlap (%d-%d and %d-%d)\n", prev_start, prev_end, curr_start, curr_end); window_check_ok = false; } } int end_gap = contig_length - windows.back().second; if(end_gap > 500) { fprintf(stderr, "error: last %d bases are not covered by a polished window for contig %s.\n", end_gap, contig.c_str()); window_check_ok = false; } if(!window_check_ok) { fprintf(stderr, "error: one or more polishing windows are missing. Please check that all nanopolish variants --consensus jobs ran to completion\n"); exit(EXIT_FAILURE); } int length; char* seq = fai_fetch(fai, contig.c_str(), &length); if(length < 0) { fprintf(stderr, "error: could not fetch contig %s\n", contig.c_str()); exit(EXIT_FAILURE); } auto& variants = variants_by_contig[contig]; std::sort(variants.begin(), variants.end(), sortByPosition); // remove duplicate variants VariantKeyEqualityComp vkec; auto last = std::unique(variants.begin(), variants.end(), vkec); variants.erase(last, variants.end()); assert(variants.size() < (1 << 30)); uint32_t deleted_tag = 1 << 30; uint32_t variant_tag = 1 << 31; // make a vector holding either a literal character or an index to the variant that needs to be applied std::vector<uint32_t> consensus_record(length); for(size_t i = 0; i < length; ++i) { consensus_record[i] = seq[i]; } size_t num_skipped = 0; size_t num_subs = 0; size_t num_insertions = 0; size_t num_deletions = 0; // update the consensus record according to the variants for this contig size_t applied_variants = 0; for(size_t variant_idx = 0; variant_idx < variants.size(); ++variant_idx) { const Variant& v = variants[variant_idx]; // check if the variant record matches the reference sequence bool matches_ref = true; for(size_t i = 0; i < v.ref_seq.length(); ++i) { matches_ref = matches_ref && v.ref_seq[i] == consensus_record[v.ref_position + i]; } if(!matches_ref) { num_skipped += 1; continue; } // mark the first base of the reference sequence as a variant and set the index consensus_record[v.ref_position] = variant_tag | variant_idx; // mark the subsequent bases of the reference as deleted for(size_t i = 1; i < v.ref_seq.length(); ++i) { consensus_record[v.ref_position + i] = deleted_tag; } num_subs += v.ref_seq.length() == v.alt_seq.length(); num_insertions += v.ref_seq.length() < v.alt_seq.length(); num_deletions += v.ref_seq.length() > v.alt_seq.length(); } // write out the consensus record std::string out; out.reserve(length); for(size_t i = 0; i < length; ++i) { uint32_t r = consensus_record[i]; if(r & variant_tag) { out.append(variants[r & ~variant_tag].alt_seq); } else if(r & ~deleted_tag) { out.append(1, r); } else { assert(r & deleted_tag); } } fprintf(stderr, "[vcf2fasta] rewrote contig %s with %zu subs, %zu ins, %zu dels (%zu skipped)\n", contig.c_str(), num_subs, num_insertions, num_deletions, num_skipped); fprintf(stdout, ">%s\n%s\n", contig.c_str(), out.c_str()); free(seq); seq = NULL; } return 0; } <commit_msg>add option to skip the sanity checks<commit_after>//--------------------------------------------------------- // Copyright 2018 Ontario Institute for Cancer Research // Written by Jared Simpson ([email protected]) //--------------------------------------------------------- // // nanopolish_vcf2fasta - write a new genome sequence // by introducing variants from a set of vcf files // #include <stdio.h> #include <stdlib.h> #include <string.h> #include <string> #include <vector> #include <map> #include <inttypes.h> #include <assert.h> #include <math.h> #include <sys/time.h> #include <algorithm> #include <sstream> #include <set> #include <omp.h> #include <getopt.h> #include <fast5.hpp> #include "htslib/faidx.h" #include "nanopolish_common.h" #include "nanopolish_variant.h" #include "nanopolish_eventalign.h" #include "nanopolish_haplotype.h" // // Getopt // #define SUBPROGRAM "vcf2fasta" static const char *VCF2FASTA_VERSION_MESSAGE = SUBPROGRAM " Version " PACKAGE_VERSION "\n" "Written by Jared Simpson.\n" "\n" "Copyright 2018 Ontario Institute for Cancer Research\n"; static const char *VCF2FASTA_USAGE_MESSAGE = "Usage: " PACKAGE_NAME " " SUBPROGRAM " -g draft.fa segment1.vcf segment2.vcf ...\n" "Write a new genome sequence by introducing variants from the input files\n" "\n" " -v, --verbose display verbose output\n" " --version display version\n" " --help display this help and exit\n" " -g, --genome=FILE the input genome is in FILE\n" " --skip-checks skip the sanity checks\n" "\nReport bugs to " PACKAGE_BUGREPORT "\n\n"; namespace opt { static unsigned int verbose; static std::vector<std::string> input_vcf_files; static std::string genome_file; static bool skip_checks = false; } static const char* shortopts = "g:v"; enum { OPT_HELP = 1, OPT_VERSION, OPT_SKIP_CHECKS }; static const struct option longopts[] = { { "verbose", no_argument, NULL, 'v' }, { "help", no_argument, NULL, OPT_HELP }, { "version", no_argument, NULL, OPT_VERSION }, { "skip-checks", no_argument, NULL, OPT_SKIP_CHECKS }, { "genome", required_argument, NULL, 'g' }, { NULL, 0, NULL, 0 } }; void parse_vcf2fasta_options(int argc, char** argv) { bool die = false; for (char c; (c = getopt_long(argc, argv, shortopts, longopts, NULL)) != -1;) { std::istringstream arg(optarg != NULL ? optarg : ""); switch (c) { case '?': die = true; break; case 'v': opt::verbose++; break; case 'g': arg >> opt::genome_file; break; case OPT_SKIP_CHECKS: opt::skip_checks = true; break; case OPT_HELP: std::cout << VCF2FASTA_USAGE_MESSAGE; exit(EXIT_SUCCESS); case OPT_VERSION: std::cout << VCF2FASTA_VERSION_MESSAGE; exit(EXIT_SUCCESS); } } if(opt::genome_file.empty()) { std::cerr << SUBPROGRAM ": -g/--genome file is required\n"; die = true; } if (argc - optind < 1) { std::cerr << SUBPROGRAM ": not enough arguments\n"; die = true; } if (die) { std::cout << "\n" << VCF2FASTA_USAGE_MESSAGE; exit(EXIT_FAILURE); } for(; optind < argc; ++optind) { opt::input_vcf_files.push_back(argv[optind]); } } int vcf2fasta_main(int argc, char** argv) { parse_vcf2fasta_options(argc, argv); // Read genome file faidx_t *fai = fai_load(opt::genome_file.c_str()); // Read VCF files and gather variants for each contig and the polishing window coordinates std::map<std::string, std::vector<Variant>> variants_by_contig; std::map<std::string, std::vector<std::pair<int, int>>> windows_by_contig; for(const auto& filename : opt::input_vcf_files) { std::string window_str; std::vector<Variant> out; std::ifstream infile(filename); std::string line; while(getline(infile, line)) { // parse header if(line[0] == '#') { // check for window coordinates if(line.find("nanopolish_window") != std::string::npos) { std::vector<std::string> fields = split(line, '='); assert(fields.size() == 2); window_str = fields[1]; } } else { Variant v(line); variants_by_contig[v.ref_name].push_back(v); } } if(window_str.empty()) { fprintf(stderr, "error: could not detect polishing window from input file %s\n", filename.c_str()); exit(EXIT_FAILURE); } std::string window_contig; int window_start, window_end; parse_region_string(window_str, window_contig, window_start, window_end); windows_by_contig[window_contig].push_back(std::make_pair(window_start, window_end)); } size_t n_contigs = faidx_nseq(fai); for(size_t contig_idx = 0; contig_idx < n_contigs; ++contig_idx) { std::string contig = faidx_iseq(fai, contig_idx); int contig_length = faidx_seq_len(fai, contig.c_str()); // Confirm that all windows on this contig have been polished bool window_check_ok = true; auto& windows = windows_by_contig[contig]; std::sort(windows.begin(), windows.end()); for(size_t window_idx = 1; window_idx < windows.size(); ++window_idx) { int prev_start = windows[window_idx - 1].first; int prev_end = windows[window_idx - 1].second; int curr_start = windows[window_idx].first; int curr_end = windows[window_idx].second; if(!opt::skip_checks && curr_start > prev_end) { fprintf(stderr, "error: adjacent polishing windows do not overlap (%d-%d and %d-%d)\n", prev_start, prev_end, curr_start, curr_end); window_check_ok = false; } } // check the first and last windows of the contig were polished if(!opt::skip_checks) { if(windows[0].first != 0) { fprintf(stderr, "error: first %d bases are not covered by a polished window for contig %s.\n", windows[0].first, contig.c_str()); window_check_ok = false; } int end_gap = contig_length - windows.back().second; if(end_gap > 500) { fprintf(stderr, "error: last %d bases are not covered by a polished window for contig %s.\n", end_gap, contig.c_str()); window_check_ok = false; } } if(!window_check_ok) { fprintf(stderr, "error: one or more polishing windows are missing. Please check that all nanopolish variants --consensus jobs ran to completion\n"); exit(EXIT_FAILURE); } int length; char* seq = fai_fetch(fai, contig.c_str(), &length); if(length < 0) { fprintf(stderr, "error: could not fetch contig %s\n", contig.c_str()); exit(EXIT_FAILURE); } auto& variants = variants_by_contig[contig]; std::sort(variants.begin(), variants.end(), sortByPosition); // remove duplicate variants VariantKeyEqualityComp vkec; auto last = std::unique(variants.begin(), variants.end(), vkec); variants.erase(last, variants.end()); assert(variants.size() < (1 << 30)); uint32_t deleted_tag = 1 << 30; uint32_t variant_tag = 1 << 31; // make a vector holding either a literal character or an index to the variant that needs to be applied std::vector<uint32_t> consensus_record(length); for(size_t i = 0; i < length; ++i) { consensus_record[i] = seq[i]; } size_t num_skipped = 0; size_t num_subs = 0; size_t num_insertions = 0; size_t num_deletions = 0; // update the consensus record according to the variants for this contig size_t applied_variants = 0; for(size_t variant_idx = 0; variant_idx < variants.size(); ++variant_idx) { const Variant& v = variants[variant_idx]; // check if the variant record matches the reference sequence bool matches_ref = true; for(size_t i = 0; i < v.ref_seq.length(); ++i) { matches_ref = matches_ref && v.ref_seq[i] == consensus_record[v.ref_position + i]; } if(!matches_ref) { num_skipped += 1; continue; } // mark the first base of the reference sequence as a variant and set the index consensus_record[v.ref_position] = variant_tag | variant_idx; // mark the subsequent bases of the reference as deleted for(size_t i = 1; i < v.ref_seq.length(); ++i) { consensus_record[v.ref_position + i] = deleted_tag; } num_subs += v.ref_seq.length() == v.alt_seq.length(); num_insertions += v.ref_seq.length() < v.alt_seq.length(); num_deletions += v.ref_seq.length() > v.alt_seq.length(); } // write out the consensus record std::string out; out.reserve(length); for(size_t i = 0; i < length; ++i) { uint32_t r = consensus_record[i]; if(r & variant_tag) { out.append(variants[r & ~variant_tag].alt_seq); } else if(r & ~deleted_tag) { out.append(1, r); } else { assert(r & deleted_tag); } } fprintf(stderr, "[vcf2fasta] rewrote contig %s with %zu subs, %zu ins, %zu dels (%zu skipped)\n", contig.c_str(), num_subs, num_insertions, num_deletions, num_skipped); fprintf(stdout, ">%s\n%s\n", contig.c_str(), out.c_str()); free(seq); seq = NULL; } return 0; } <|endoftext|>
<commit_before>#ifndef __coldata2_hh__ #define __coldata2_hh__ #include <stdlib.h> #include "coldata1.hh" #ifndef NO_BINARY_OPERS #define oprsw(opr, other, conv) \ template<class Str> \ inline other operator opr (mysql_ColData<Str> x, other y) \ {return (conv)x opr y;} \ template<class Str> \ inline other operator opr (other x, mysql_ColData<Str> y) \ {return x opr (conv)y;} #define operator_binary(other, conv) \ oprsw(+, other, conv) \ oprsw(-, other, conv) \ oprsw(*, other, conv) \ oprsw(/, other, conv) #define operator_binary_int(other, conv) \ operator_binary(other, conv) \ oprsw(%, other, conv) \ oprsw(&, other, conv) \ oprsw(^, other, conv) \ oprsw(|, other, conv) \ oprsw(<<, other, conv) \ oprsw(>>, other, conv) operator_binary(float, double) operator_binary(double, double) operator_binary_int(char,long int) operator_binary_int(int, long int) operator_binary_int(short int, long int) operator_binary_int(long int, long int) operator_binary_int(unsigned char, unsigned long int) operator_binary_int(unsigned int, unsigned long int) operator_binary_int(unsigned short int, unsigned long int) operator_binary_int(unsigned long int, unsigned long int) operator_binary_int(longlong, longlong) operator_binary_int(ulonglong, ulonglong) #endif // NO_BINARY_OPERS #endif <commit_msg>Wrapped some uses of long long GCC type in ifdef so platforms that don't support it can avoid using it.<commit_after>#ifndef __coldata2_hh__ #define __coldata2_hh__ #include <stdlib.h> #include "coldata1.hh" #ifndef NO_BINARY_OPERS #define oprsw(opr, other, conv) \ template<class Str> \ inline other operator opr (mysql_ColData<Str> x, other y) \ {return (conv)x opr y;} \ template<class Str> \ inline other operator opr (other x, mysql_ColData<Str> y) \ {return x opr (conv)y;} #define operator_binary(other, conv) \ oprsw(+, other, conv) \ oprsw(-, other, conv) \ oprsw(*, other, conv) \ oprsw(/, other, conv) #define operator_binary_int(other, conv) \ operator_binary(other, conv) \ oprsw(%, other, conv) \ oprsw(&, other, conv) \ oprsw(^, other, conv) \ oprsw(|, other, conv) \ oprsw(<<, other, conv) \ oprsw(>>, other, conv) operator_binary(float, double) operator_binary(double, double) operator_binary_int(char,long int) operator_binary_int(int, long int) operator_binary_int(short int, long int) operator_binary_int(long int, long int) operator_binary_int(unsigned char, unsigned long int) operator_binary_int(unsigned int, unsigned long int) operator_binary_int(unsigned short int, unsigned long int) operator_binary_int(unsigned long int, unsigned long int) #if !defined(NO_LONG_LONGS) operator_binary_int(longlong, longlong) operator_binary_int(ulonglong, ulonglong) #endif #endif // NO_BINARY_OPERS #endif <|endoftext|>
<commit_before>/********************************************************************************* * * Inviwo - Interactive Visualization Workshop * * Copyright (c) 2016 Inviwo Foundation * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT 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. * *********************************************************************************/ #include <modules/base/processors/randommeshgenerator.h> namespace inviwo { // The Class Identifier has to be globally unique. Use a reverse DNS naming scheme const ProcessorInfo RandomMeshGenerator::processorInfo_{ "org.inviwo.RandomMeshGenerator", // Class identifier "Random Mesh Generator", // Display name "Undefined", // Category CodeState::Experimental, // Code state Tags::None, // Tags }; const ProcessorInfo RandomMeshGenerator::getProcessorInfo() const { return processorInfo_; } RandomMeshGenerator::RandomMeshGenerator() : Processor() , mesh_("mesh") , seed_("seed", "Seed", 0, 0, std::mt19937::max()) , rand_() , reseed_("reseed_", "Seed") , numberOfBoxes_("numberOf_", "Number of Boxes", 1, 0, 100) , numberOfSpheres_("numberOfSpheres_", "Number of Spheres", 1, 0, 100) , numberOfCylinders_("numberOfCylinders_", "Number of cylinders", 1, 0, 100) , numberOfCones_("numberOfCones_", "Number of Cones", 1, 0, 100) , numberOfToruses_("numberOfToruses", "Number of Toruses", 1, 0, 100) { addPort(mesh_); addProperty(numberOfBoxes_); addProperty(numberOfSpheres_); addProperty(numberOfCylinders_); addProperty(numberOfCones_); addProperty(numberOfToruses_); addProperty(seed_); addProperty(reseed_); reseed_.onChange([&]() { seed_.set(rand()); rand_.seed(static_cast<std::mt19937::result_type>(seed_.get())); }); } float RandomMeshGenerator::randD() { return dis_(rand_); } float RandomMeshGenerator::randD(const float min, const float max) { return min + randD() * (max - min); } inviwo::vec4 RandomMeshGenerator::randColor() { float r = randD(0.5, 1.0); float g = randD(0.5, 1.0); float b = randD(0.5, 1.0); return vec4(r, g, b, 1); } vec3 RandomMeshGenerator::randVec3(const float min, const float max) { float x = randD(min, max); float y = randD(min, max); float z = randD(min, max); return vec3(x, y, z); } void RandomMeshGenerator::process() { auto mesh = std::make_shared<BasicMesh>(); mesh_.setData(mesh); rand_.seed(static_cast<std::mt19937::result_type>(seed_.get())); for (int i = 0; i < numberOfBoxes_.get(); i++) { mat4 o = glm::rotate(mat4(1.0f), randD(0, 6.28f), vec3(1, 0, 0)); o = glm::rotate(o, randD(0, 6.28f), vec3(0, 1, 0)); o = glm::rotate(o, randD(0, 6.28f), vec3(0, 0, 1)); o = glm::translate(o, randVec3()); o = glm::scale(o, randVec3()); auto mesh2 = BasicMesh::cube(o, randColor()); mesh->append(mesh2.get()); } for (int i = 0; i < numberOfSpheres_.get(); i++) { auto center = randVec3(); auto color = randColor(); auto radius = randD(0.1f, 1.0f); BasicMesh::sphere(center, radius, color, mesh); } for (int i = 0; i < numberOfCylinders_.get(); i++) { auto start = randVec3(); auto end = randVec3(); auto color = randColor(); auto radius = randD(0.1f, 1.0f); auto mesh2 = BasicMesh::cylinder(start, end, color, radius); mesh->append(mesh2.get()); } for (int i = 0; i < numberOfCones_.get(); i++) { auto start = randVec3(); auto end = randVec3(); auto color = randColor(); auto radius = randD(0.1f, 1.0f); auto mesh2 = BasicMesh::cone(start, end, color, radius); mesh->append(mesh2.get()); } for (int i = 0; i < numberOfToruses_.get(); i++) { auto center = randVec3(); auto up = glm::normalize(randVec3()); auto r2 = randD(0.1, 0.5f); auto r1 = randD(0.1 + r2, 1.0f + r2); auto color = randColor(); auto mesh2 = BasicMesh::torus(center, up, r1, r2, ivec2(32, 8), color); mesh->append(mesh2.get()); } } } // namespace <commit_msg>Base: RandomMeshGenerator: Include Fix<commit_after>/********************************************************************************* * * Inviwo - Interactive Visualization Workshop * * Copyright (c) 2016 Inviwo Foundation * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT 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. * *********************************************************************************/ #include <modules/base/processors/randommeshgenerator.h> #include <inviwo/core/datastructures/geometry/basicmesh.h> namespace inviwo { // The Class Identifier has to be globally unique. Use a reverse DNS naming scheme const ProcessorInfo RandomMeshGenerator::processorInfo_{ "org.inviwo.RandomMeshGenerator", // Class identifier "Random Mesh Generator", // Display name "Undefined", // Category CodeState::Experimental, // Code state Tags::None, // Tags }; const ProcessorInfo RandomMeshGenerator::getProcessorInfo() const { return processorInfo_; } RandomMeshGenerator::RandomMeshGenerator() : Processor() , mesh_("mesh") , seed_("seed", "Seed", 0, 0, std::mt19937::max()) , rand_() , reseed_("reseed_", "Seed") , numberOfBoxes_("numberOf_", "Number of Boxes", 1, 0, 100) , numberOfSpheres_("numberOfSpheres_", "Number of Spheres", 1, 0, 100) , numberOfCylinders_("numberOfCylinders_", "Number of cylinders", 1, 0, 100) , numberOfCones_("numberOfCones_", "Number of Cones", 1, 0, 100) , numberOfToruses_("numberOfToruses", "Number of Toruses", 1, 0, 100) { addPort(mesh_); addProperty(numberOfBoxes_); addProperty(numberOfSpheres_); addProperty(numberOfCylinders_); addProperty(numberOfCones_); addProperty(numberOfToruses_); addProperty(seed_); addProperty(reseed_); reseed_.onChange([&]() { seed_.set(rand()); rand_.seed(static_cast<std::mt19937::result_type>(seed_.get())); }); } float RandomMeshGenerator::randD() { return dis_(rand_); } float RandomMeshGenerator::randD(const float min, const float max) { return min + randD() * (max - min); } inviwo::vec4 RandomMeshGenerator::randColor() { float r = randD(0.5, 1.0); float g = randD(0.5, 1.0); float b = randD(0.5, 1.0); return vec4(r, g, b, 1); } vec3 RandomMeshGenerator::randVec3(const float min, const float max) { float x = randD(min, max); float y = randD(min, max); float z = randD(min, max); return vec3(x, y, z); } void RandomMeshGenerator::process() { auto mesh = std::make_shared<BasicMesh>(); mesh_.setData(mesh); rand_.seed(static_cast<std::mt19937::result_type>(seed_.get())); for (int i = 0; i < numberOfBoxes_.get(); i++) { mat4 o = glm::rotate(mat4(1.0f), randD(0, 6.28f), vec3(1, 0, 0)); o = glm::rotate(o, randD(0, 6.28f), vec3(0, 1, 0)); o = glm::rotate(o, randD(0, 6.28f), vec3(0, 0, 1)); o = glm::translate(o, randVec3()); o = glm::scale(o, randVec3()); auto mesh2 = BasicMesh::cube(o, randColor()); mesh->append(mesh2.get()); } for (int i = 0; i < numberOfSpheres_.get(); i++) { auto center = randVec3(); auto color = randColor(); auto radius = randD(0.1f, 1.0f); BasicMesh::sphere(center, radius, color, mesh); } for (int i = 0; i < numberOfCylinders_.get(); i++) { auto start = randVec3(); auto end = randVec3(); auto color = randColor(); auto radius = randD(0.1f, 1.0f); auto mesh2 = BasicMesh::cylinder(start, end, color, radius); mesh->append(mesh2.get()); } for (int i = 0; i < numberOfCones_.get(); i++) { auto start = randVec3(); auto end = randVec3(); auto color = randColor(); auto radius = randD(0.1f, 1.0f); auto mesh2 = BasicMesh::cone(start, end, color, radius); mesh->append(mesh2.get()); } for (int i = 0; i < numberOfToruses_.get(); i++) { auto center = randVec3(); auto up = glm::normalize(randVec3()); auto r2 = randD(0.1, 0.5f); auto r1 = randD(0.1 + r2, 1.0f + r2); auto color = randColor(); auto mesh2 = BasicMesh::torus(center, up, r1, r2, ivec2(32, 8), color); mesh->append(mesh2.get()); } } } // namespace <|endoftext|>
<commit_before>// Copyright (c) 2006-2009 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "base/thread.h" #include "base/lazy_instance.h" #include "base/third_party/dynamic_annotations/dynamic_annotations.h" #include "base/thread_local.h" #include "base/waitable_event.h" namespace base { // This task is used to trigger the message loop to exit. class ThreadQuitTask : public Task { public: virtual void Run() { MessageLoop::current()->Quit(); Thread::SetThreadWasQuitProperly(true); } }; // Used to pass data to ThreadMain. This structure is allocated on the stack // from within StartWithOptions. struct Thread::StartupData { // We get away with a const reference here because of how we are allocated. const Thread::Options& options; // Used to synchronize thread startup. WaitableEvent event; explicit StartupData(const Options& opt) : options(opt), event(false, false) {} }; Thread::Thread(const char* name) : started_(false), stopping_(false), startup_data_(NULL), thread_(0), message_loop_(NULL), thread_id_(0), name_(name) { } Thread::~Thread() { Stop(); } namespace { // We use this thread-local variable to record whether or not a thread exited // because its Stop method was called. This allows us to catch cases where // MessageLoop::Quit() is called directly, which is unexpected when using a // Thread to setup and run a MessageLoop. base::LazyInstance<base::ThreadLocalBoolean> lazy_tls_bool( base::LINKER_INITIALIZED); } // namespace void Thread::SetThreadWasQuitProperly(bool flag) { lazy_tls_bool.Pointer()->Set(flag); } bool Thread::GetThreadWasQuitProperly() { bool quit_properly = true; #ifndef NDEBUG quit_properly = lazy_tls_bool.Pointer()->Get(); #endif return quit_properly; } bool Thread::Start() { return StartWithOptions(Options()); } bool Thread::StartWithOptions(const Options& options) { DCHECK(!message_loop_); SetThreadWasQuitProperly(false); StartupData startup_data(options); startup_data_ = &startup_data; if (!PlatformThread::Create(options.stack_size, this, &thread_)) { DLOG(ERROR) << "failed to create thread"; startup_data_ = NULL; return false; } // Wait for the thread to start and initialize message_loop_ startup_data.event.Wait(); // set it to NULL so we don't keep a pointer to some object on the stack. startup_data_ = NULL; started_ = true; DCHECK(message_loop_); return true; } void Thread::Stop() { if (!thread_was_started()) return; StopSoon(); // Wait for the thread to exit. // // TODO(darin): Unfortunately, we need to keep message_loop_ around until // the thread exits. Some consumers are abusing the API. Make them stop. // PlatformThread::Join(thread_); // The thread should NULL message_loop_ on exit. DCHECK(!message_loop_); // The thread no longer needs to be joined. started_ = false; stopping_ = false; } void Thread::StopSoon() { // We should only be called on the same thread that started us. // Reading thread_id_ without a lock can lead to a benign data race // with ThreadMain, so we annotate it to stay silent under ThreadSanitizer. DCHECK_NE(ANNOTATE_UNPROTECTED_READ(thread_id_), PlatformThread::CurrentId()); if (stopping_ || !message_loop_) return; stopping_ = true; message_loop_->PostTask(FROM_HERE, new ThreadQuitTask()); } #if defined(OS_WIN) #pragma warning (disable: 4748) #pragma optimize( "", off ) #endif void Thread::Run(MessageLoop* message_loop) { #if defined(OS_WIN) // Logging the thread name for debugging. // TODO(huanr): remove after done. // http://code.google.com/p/chromium/issues/detail?id=54307 char name[16]; strncpy(name, name_.c_str(), arraysize(name) - 1); name[arraysize(name) - 1] = '\0'; #endif message_loop->Run(); } #if defined(OS_WIN) #pragma optimize( "", on ) #pragma warning (default: 4748) #endif void Thread::ThreadMain() { { // The message loop for this thread. MessageLoop message_loop(startup_data_->options.message_loop_type); // Complete the initialization of our Thread object. thread_id_ = PlatformThread::CurrentId(); PlatformThread::SetName(name_.c_str()); ANNOTATE_THREAD_NAME(name_.c_str()); // Tell the name to race detector. message_loop.set_thread_name(name_); message_loop_ = &message_loop; message_loop_proxy_ = MessageLoopProxy::CreateForCurrentThread(); // Let the thread do extra initialization. // Let's do this before signaling we are started. Init(); startup_data_->event.Signal(); // startup_data_ can't be touched anymore since the starting thread is now // unlocked. Run(message_loop_); // Let the thread do extra cleanup. CleanUp(); // Assert that MessageLoop::Quit was called by ThreadQuitTask. DCHECK(GetThreadWasQuitProperly()); // We can't receive messages anymore. message_loop_ = NULL; message_loop_proxy_ = NULL; } CleanUpAfterMessageLoopDestruction(); thread_id_ = 0; } } // namespace base <commit_msg>Revert 58786 - Adding debugging info for thread name.<commit_after>// Copyright (c) 2006-2009 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "base/thread.h" #include "base/lazy_instance.h" #include "base/third_party/dynamic_annotations/dynamic_annotations.h" #include "base/thread_local.h" #include "base/waitable_event.h" namespace base { // This task is used to trigger the message loop to exit. class ThreadQuitTask : public Task { public: virtual void Run() { MessageLoop::current()->Quit(); Thread::SetThreadWasQuitProperly(true); } }; // Used to pass data to ThreadMain. This structure is allocated on the stack // from within StartWithOptions. struct Thread::StartupData { // We get away with a const reference here because of how we are allocated. const Thread::Options& options; // Used to synchronize thread startup. WaitableEvent event; explicit StartupData(const Options& opt) : options(opt), event(false, false) {} }; Thread::Thread(const char* name) : started_(false), stopping_(false), startup_data_(NULL), thread_(0), message_loop_(NULL), thread_id_(0), name_(name) { } Thread::~Thread() { Stop(); } namespace { // We use this thread-local variable to record whether or not a thread exited // because its Stop method was called. This allows us to catch cases where // MessageLoop::Quit() is called directly, which is unexpected when using a // Thread to setup and run a MessageLoop. base::LazyInstance<base::ThreadLocalBoolean> lazy_tls_bool( base::LINKER_INITIALIZED); } // namespace void Thread::SetThreadWasQuitProperly(bool flag) { lazy_tls_bool.Pointer()->Set(flag); } bool Thread::GetThreadWasQuitProperly() { bool quit_properly = true; #ifndef NDEBUG quit_properly = lazy_tls_bool.Pointer()->Get(); #endif return quit_properly; } bool Thread::Start() { return StartWithOptions(Options()); } bool Thread::StartWithOptions(const Options& options) { DCHECK(!message_loop_); SetThreadWasQuitProperly(false); StartupData startup_data(options); startup_data_ = &startup_data; if (!PlatformThread::Create(options.stack_size, this, &thread_)) { DLOG(ERROR) << "failed to create thread"; startup_data_ = NULL; return false; } // Wait for the thread to start and initialize message_loop_ startup_data.event.Wait(); // set it to NULL so we don't keep a pointer to some object on the stack. startup_data_ = NULL; started_ = true; DCHECK(message_loop_); return true; } void Thread::Stop() { if (!thread_was_started()) return; StopSoon(); // Wait for the thread to exit. // // TODO(darin): Unfortunately, we need to keep message_loop_ around until // the thread exits. Some consumers are abusing the API. Make them stop. // PlatformThread::Join(thread_); // The thread should NULL message_loop_ on exit. DCHECK(!message_loop_); // The thread no longer needs to be joined. started_ = false; stopping_ = false; } void Thread::StopSoon() { // We should only be called on the same thread that started us. // Reading thread_id_ without a lock can lead to a benign data race // with ThreadMain, so we annotate it to stay silent under ThreadSanitizer. DCHECK_NE(ANNOTATE_UNPROTECTED_READ(thread_id_), PlatformThread::CurrentId()); if (stopping_ || !message_loop_) return; stopping_ = true; message_loop_->PostTask(FROM_HERE, new ThreadQuitTask()); } void Thread::Run(MessageLoop* message_loop) { message_loop->Run(); } void Thread::ThreadMain() { { // The message loop for this thread. MessageLoop message_loop(startup_data_->options.message_loop_type); // Complete the initialization of our Thread object. thread_id_ = PlatformThread::CurrentId(); PlatformThread::SetName(name_.c_str()); ANNOTATE_THREAD_NAME(name_.c_str()); // Tell the name to race detector. message_loop.set_thread_name(name_); message_loop_ = &message_loop; message_loop_proxy_ = MessageLoopProxy::CreateForCurrentThread(); // Let the thread do extra initialization. // Let's do this before signaling we are started. Init(); startup_data_->event.Signal(); // startup_data_ can't be touched anymore since the starting thread is now // unlocked. Run(message_loop_); // Let the thread do extra cleanup. CleanUp(); // Assert that MessageLoop::Quit was called by ThreadQuitTask. DCHECK(GetThreadWasQuitProperly()); // We can't receive messages anymore. message_loop_ = NULL; message_loop_proxy_ = NULL; } CleanUpAfterMessageLoopDestruction(); thread_id_ = 0; } } // namespace base <|endoftext|>
<commit_before>/* * Copyright 2019 The Open GEE Contributors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "StateUpdater.h" #include "AssetVersionD.h" #include "common/notify.h" using namespace boost; using namespace std; // The depth_first_search function needs a way to map vertices to indexes. We // store a unique index inside each vertex; the code below provides a way for // boost to access them. These must be defined before including // depth_first_search.hpp. template <class Graph> class InNodeVertexIndexMap { public: typedef readable_property_map_tag category; typedef size_t value_type; typedef value_type reference; typedef typename Graph::vertex_descriptor key_type; InNodeVertexIndexMap(const Graph & graph) : graph(graph) {}; const Graph & graph; }; namespace boost { template<> struct property_map<StateUpdater::TreeType, vertex_index_t> { typedef InNodeVertexIndexMap<StateUpdater::TreeType> const_type; }; template<class Graph> InNodeVertexIndexMap<Graph> get(vertex_index_t, const Graph & graph) { return InNodeVertexIndexMap<Graph>(graph); } template<class Graph> typename InNodeVertexIndexMap<Graph>::value_type get( const InNodeVertexIndexMap<Graph> & map, typename InNodeVertexIndexMap<Graph>::key_type vertex) { return map.graph[vertex].index; } } #include <boost/graph/depth_first_search.hpp> // Builds the asset version tree containing the specified asset version. StateUpdater::TreeType::vertex_descriptor StateUpdater::BuildTree(const SharedString & ref) { VertexMap vertices; size_t index = 0; list<TreeType::vertex_descriptor> toFillIn, toFillInNext; // First create an empty vertex for the provided asset. Then fill it in, // which includes adding its connections to other assets. Every time we fill // in a node we will get new assets to add to the tree until all assets have // been added. This basically builds the tree using a breadth first search, // which allows us to keep memory usage (relatively) low by not forcing // assets to stay in the cache and limiting the size of the toFillIn and // toFillInNext lists. auto myVertex = AddEmptyVertex(ref, vertices, index, toFillIn); while (toFillIn.size() > 0) { for (auto vertex : toFillIn) { FillInVertex(vertex, vertices, index, toFillInNext); } toFillIn = std::move(toFillInNext); toFillInNext.clear(); } return myVertex; } // Creates an "empty" node for this asset if it has not already been added to // the tree. The node has a default state and doesn't include links to // inputs/children/etc. The vertex must be "filled in" by calling FillInVertex // before it can be used. StateUpdater::TreeType::vertex_descriptor StateUpdater::AddEmptyVertex( const SharedString & ref, VertexMap & vertices, size_t & index, list<TreeType::vertex_descriptor> & toFillIn) { auto myVertexIter = vertices.find(ref); if (myVertexIter == vertices.end()) { // I'm not in the graph yet, so make a new empty vertex and let the caller // know we need to load it with the correct information auto myVertex = add_vertex(tree); tree[myVertex] = {ref, AssetDefs::New, index}; ++index; vertices[ref] = myVertex; toFillIn.push_back(myVertex); return myVertex; } else { // I'm already in the graph, so just return my vertex descriptor. return myVertexIter->second; } } // "Fills in" an existing vertex with the state of an asset and its connections // to other assets. Adds any new nodes that need to be filled in to toFillIn. void StateUpdater::FillInVertex( TreeType::vertex_descriptor myVertex, VertexMap & vertices, size_t & index, list<TreeType::vertex_descriptor> & toFillIn) { SharedString name = tree[myVertex].name; notify(NFY_PROGRESS, "Loading '%s' for state update", name.toString().c_str()); AssetVersionD version(name); if (!version) { notify(NFY_WARN, "Could not load asset '%s' which is referenced by another asset.", name.toString().c_str()); // Set it to a bad state, but use a state that can be fixed by another // rebuild operation. tree[myVertex].state = AssetDefs::Blocked; return; } tree[myVertex].state = version->state; vector<SharedString> dependents; version->DependentChildren(dependents); for (const auto & dep : dependents) { auto depVertex = AddEmptyVertex(dep, vertices, index, toFillIn); AddEdge(myVertex, depVertex, {DEPENDENT}); } for (const auto & child : version->children) { auto childVertex = AddEmptyVertex(child, vertices, index, toFillIn); AddEdge(myVertex, childVertex, {CHILD}); } for (const auto & input : version->inputs) { auto inputVertex = AddEmptyVertex(input, vertices, index, toFillIn); AddEdge(myVertex, inputVertex, {INPUT}); } for (const auto & parent : version->parents) { auto parentVertex = AddEmptyVertex(parent, vertices, index, toFillIn); AddEdge(parentVertex, myVertex, {CHILD}); } for (const auto & listener : version->listeners) { auto listenerVertex = AddEmptyVertex(listener, vertices, index, toFillIn); AddEdge(listenerVertex, myVertex, {INPUT}); } } void StateUpdater::AddEdge( TreeType::vertex_descriptor from, TreeType::vertex_descriptor to, AssetEdge data) { auto edgeData = add_edge(from, to, tree); if (edgeData.second) { // This is a new edge tree[edgeData.first] = data; } else { // Check if this is both a dependent and a child DependencyType currentType = tree[edgeData.first].type; DependencyType newType = data.type; if ((currentType == DEPENDENT && newType == CHILD) || (currentType == CHILD && newType == DEPENDENT)) { tree[edgeData.first].type = DEPENDENT_AND_CHILD; } } } void StateUpdater::SetStateForRefAndDependents( const SharedString & ref, AssetDefs::State newState, function<bool(AssetDefs::State)> updateStatePredicate) { auto refVertex = BuildTree(ref); SetStateForVertexAndDependents(refVertex, newState, updateStatePredicate); } // Sets the state for the specified ref and recursively sets the state for // the ref's dependent children. void StateUpdater::SetStateForVertexAndDependents( TreeType::vertex_descriptor vertex, AssetDefs::State newState, function<bool(AssetDefs::State)> updateStatePredicate) { if (updateStatePredicate(tree[vertex].state)) { // Set the state. The OnStateChange handler will take care // of stopping any running tasks, etc // false -> don't send notifications about the new state because we // will change it soon. SetState(vertex, newState, false); // Now update the dependent children auto edgeIters = out_edges(vertex, tree); auto edgeBegin = edgeIters.first; auto edgeEnd = edgeIters.second; for (auto i = edgeBegin; i != edgeEnd; ++i) { if (IsDependent(tree[*i].type)) { SetStateForVertexAndDependents(target(*i, tree), newState, updateStatePredicate); } } } } void StateUpdater::SetState( TreeType::vertex_descriptor vertex, AssetDefs::State newState, bool sendNotifications) { SharedString name = tree[vertex].name; if (newState != tree[vertex].state) { MutableAssetVersionD version(name); notify(NFY_PROGRESS, "Setting state of '%s' to '%s'", name.toString().c_str(), ToString(newState).c_str()); if (version) { // Set the state. The OnStateChange handler will take care // of stopping any running tasks, etc. // This call does not propagate the state change to other assets. We will // take care of that inside the state updater. version->SetMyStateOnly(newState, sendNotifications); // Setting the state can trigger additional state changes, so get the new // state directly from the asset version. tree[vertex].state = version->state; } else { // This shoud never happen - we had to successfully load the asset // previously to get it into the tree. notify(NFY_WARN, "Could not load asset '%s' to set state.", name.toString().c_str()); } } } // Helper class to calculate the state of asset versions based on the states // of their inputs and children. It calculates states in depth-first order; // we use the finish_vertex function to ensure that we calculate the state // of an asset version after we've calculated the states of its inputs // and children. class StateUpdater::UpdateStateVisitor : public default_dfs_visitor { private: // Keep a pointer to the state updater StateUpdater * const updater; // Helper class for calculating state from inputs class InputStates { private: uint numinputs = 0; uint numgood = 0; uint numblocking = 0; uint numoffline = 0; public: void Add(AssetDefs::State inputState) { ++numinputs; if (inputState == AssetDefs::Succeeded) { ++numgood; } else if (inputState == AssetDefs::Offline) { ++numblocking; ++numoffline; } else if (inputState & (AssetDefs::Blocked | AssetDefs::Failed | AssetDefs::Canceled | AssetDefs::Bad)) { ++numblocking; } } void GetOutputs(AssetDefs::State & stateByInputs, bool & blockersAreOffline, uint32 & numWaitingFor) { if (numinputs == numgood) { stateByInputs = AssetDefs::Queued; } else if (numblocking) { stateByInputs = AssetDefs::Blocked; } else { stateByInputs = AssetDefs::Waiting; } blockersAreOffline = (numblocking == numoffline); if (stateByInputs == AssetDefs::Waiting) { numWaitingFor = (numinputs - numgood); } else { numWaitingFor = 0; } } }; // Helper class for calculating state from children class ChildStates { private: uint numkids = 0; uint numgood = 0; uint numblocking = 0; uint numinprog = 0; uint numfailed = 0; public: void Add(AssetDefs::State childState) { ++numkids; if (childState == AssetDefs::Succeeded) { ++numgood; } else if (childState == AssetDefs::Failed) { ++numfailed; } else if (childState == AssetDefs::InProgress) { ++numinprog; } else if (childState & (AssetDefs::Blocked | AssetDefs::Canceled | AssetDefs::Offline | AssetDefs::Bad)) { ++numblocking; } } void GetOutputs(AssetDefs::State & stateByChildren) { if (numkids == numgood) { stateByChildren = AssetDefs::Succeeded; } else if (numblocking || numfailed) { stateByChildren = AssetDefs::Blocked; } else if (numgood || numinprog) { stateByChildren = AssetDefs::InProgress; } else { stateByChildren = AssetDefs::Queued; } } }; // Loops through the inputs and children of an asset and calculates // everything the asset verion needs to know to figure out its state. This // data will be passed to the asset version so it can calculate its own // state. void CalculateStateParameters( StateUpdater::TreeType::vertex_descriptor vertex, const StateUpdater::TreeType & tree, AssetDefs::State &stateByInputs, AssetDefs::State &stateByChildren, bool & blockersAreOffline, uint32 & numWaitingFor) const { InputStates inputStates; ChildStates childStates; auto edgeIters = out_edges(vertex, tree); auto edgeBegin = edgeIters.first; auto edgeEnd = edgeIters.second; for (auto i = edgeBegin; i != edgeEnd; ++i) { StateUpdater::DependencyType type = tree[*i].type; StateUpdater::TreeType::vertex_descriptor dep = target(*i, tree); AssetDefs::State depState = tree[dep].state; switch(type) { case StateUpdater::INPUT: inputStates.Add(depState); break; case StateUpdater::CHILD: case StateUpdater::DEPENDENT_AND_CHILD: childStates.Add(depState); break; case StateUpdater::DEPENDENT: // Dependents that are not also children are not considered when // calculating state. break; } } inputStates.GetOutputs(stateByInputs, blockersAreOffline, numWaitingFor); childStates.GetOutputs(stateByChildren); } public: UpdateStateVisitor(StateUpdater * updater) : updater(updater) {}; // Update the state of an asset after we've updated the state of its // inputs and children. virtual void finish_vertex( StateUpdater::TreeType::vertex_descriptor vertex, const StateUpdater::TreeType & tree) const { SharedString name = tree[vertex].name; notify(NFY_PROGRESS, "Calculating state for '%s'", name.toString().c_str()); AssetVersionD version(name); if (!version) { // This shoud never happen - we had to successfully load the asset // previously to get it into the tree. notify(NFY_WARN, "Could not load asset '%s' to recalculate state.", name.toString().c_str()); return; } if (!version->NeedComputeState()) return; AssetDefs::State stateByInputs; AssetDefs::State stateByChildren; bool blockersAreOffline; uint32 numWaitingFor; CalculateStateParameters(vertex, tree, stateByInputs, stateByChildren, blockersAreOffline, numWaitingFor); AssetDefs::State newState = version->CalcStateByInputsAndChildren(stateByInputs, stateByChildren, blockersAreOffline, numWaitingFor); // Set the state and send notifications. updater->SetState(vertex, newState, true); } }; void StateUpdater::RecalculateAndSaveStates() { // Traverse the state tree, recalculate states, and update states as needed. // State is calculated for each vertex in the tree after state is calculated // for all of its child and input vertices. // Possible optimization: Many assets have significant overlap in their // inputs. It might save time if we could calculate the overlapping state // only once. depth_first_search(tree, visitor(UpdateStateVisitor(this))); } <commit_msg>Always use the correct version ref<commit_after>/* * Copyright 2019 The Open GEE Contributors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "StateUpdater.h" #include "AssetVersionD.h" #include "common/notify.h" using namespace boost; using namespace std; // The depth_first_search function needs a way to map vertices to indexes. We // store a unique index inside each vertex; the code below provides a way for // boost to access them. These must be defined before including // depth_first_search.hpp. template <class Graph> class InNodeVertexIndexMap { public: typedef readable_property_map_tag category; typedef size_t value_type; typedef value_type reference; typedef typename Graph::vertex_descriptor key_type; InNodeVertexIndexMap(const Graph & graph) : graph(graph) {}; const Graph & graph; }; namespace boost { template<> struct property_map<StateUpdater::TreeType, vertex_index_t> { typedef InNodeVertexIndexMap<StateUpdater::TreeType> const_type; }; template<class Graph> InNodeVertexIndexMap<Graph> get(vertex_index_t, const Graph & graph) { return InNodeVertexIndexMap<Graph>(graph); } template<class Graph> typename InNodeVertexIndexMap<Graph>::value_type get( const InNodeVertexIndexMap<Graph> & map, typename InNodeVertexIndexMap<Graph>::key_type vertex) { return map.graph[vertex].index; } } #include <boost/graph/depth_first_search.hpp> // Builds the asset version tree containing the specified asset version. StateUpdater::TreeType::vertex_descriptor StateUpdater::BuildTree(const SharedString & ref) { VertexMap vertices; size_t index = 0; list<TreeType::vertex_descriptor> toFillIn, toFillInNext; // First create an empty vertex for the provided asset. Then fill it in, // which includes adding its connections to other assets. Every time we fill // in a node we will get new assets to add to the tree until all assets have // been added. This basically builds the tree using a breadth first search, // which allows us to keep memory usage (relatively) low by not forcing // assets to stay in the cache and limiting the size of the toFillIn and // toFillInNext lists. auto myVertex = AddEmptyVertex(ref, vertices, index, toFillIn); while (toFillIn.size() > 0) { for (auto vertex : toFillIn) { FillInVertex(vertex, vertices, index, toFillInNext); } toFillIn = std::move(toFillInNext); toFillInNext.clear(); } return myVertex; } // Creates an "empty" node for this asset if it has not already been added to // the tree. The node has a default state and doesn't include links to // inputs/children/etc. The vertex must be "filled in" by calling FillInVertex // before it can be used. StateUpdater::TreeType::vertex_descriptor StateUpdater::AddEmptyVertex( const SharedString & ref, VertexMap & vertices, size_t & index, list<TreeType::vertex_descriptor> & toFillIn) { auto myVertexIter = vertices.find(ref); if (myVertexIter == vertices.end()) { // I'm not in the graph yet, so make a new empty vertex and let the caller // know we need to load it with the correct information auto myVertex = add_vertex(tree); tree[myVertex] = {ref, AssetDefs::New, index}; ++index; vertices[ref] = myVertex; toFillIn.push_back(myVertex); return myVertex; } else { // I'm already in the graph, so just return my vertex descriptor. return myVertexIter->second; } } // "Fills in" an existing vertex with the state of an asset and its connections // to other assets. Adds any new nodes that need to be filled in to toFillIn. void StateUpdater::FillInVertex( TreeType::vertex_descriptor myVertex, VertexMap & vertices, size_t & index, list<TreeType::vertex_descriptor> & toFillIn) { SharedString name = tree[myVertex].name; notify(NFY_PROGRESS, "Loading '%s' for state update", name.toString().c_str()); AssetVersionD version(name); if (!version) { notify(NFY_WARN, "Could not load asset '%s' which is referenced by another asset.", name.toString().c_str()); // Set it to a bad state, but use a state that can be fixed by another // rebuild operation. tree[myVertex].state = AssetDefs::Blocked; return; } tree[myVertex].state = version->state; // The ref passed in may be slightly different than the ref used in the storage // manager, so fix that here. if (name != version->GetRef()) { name = version->GetRef(); tree[myVertex].name = name; vertices[name] = myVertex; } vector<SharedString> dependents; version->DependentChildren(dependents); for (const auto & dep : dependents) { auto depVertex = AddEmptyVertex(dep, vertices, index, toFillIn); AddEdge(myVertex, depVertex, {DEPENDENT}); } for (const auto & child : version->children) { auto childVertex = AddEmptyVertex(child, vertices, index, toFillIn); AddEdge(myVertex, childVertex, {CHILD}); } for (const auto & input : version->inputs) { auto inputVertex = AddEmptyVertex(input, vertices, index, toFillIn); AddEdge(myVertex, inputVertex, {INPUT}); } for (const auto & parent : version->parents) { auto parentVertex = AddEmptyVertex(parent, vertices, index, toFillIn); AddEdge(parentVertex, myVertex, {CHILD}); } for (const auto & listener : version->listeners) { auto listenerVertex = AddEmptyVertex(listener, vertices, index, toFillIn); AddEdge(listenerVertex, myVertex, {INPUT}); } } void StateUpdater::AddEdge( TreeType::vertex_descriptor from, TreeType::vertex_descriptor to, AssetEdge data) { auto edgeData = add_edge(from, to, tree); if (edgeData.second) { // This is a new edge tree[edgeData.first] = data; } else { // Check if this is both a dependent and a child DependencyType currentType = tree[edgeData.first].type; DependencyType newType = data.type; if ((currentType == DEPENDENT && newType == CHILD) || (currentType == CHILD && newType == DEPENDENT)) { tree[edgeData.first].type = DEPENDENT_AND_CHILD; } } } void StateUpdater::SetStateForRefAndDependents( const SharedString & ref, AssetDefs::State newState, function<bool(AssetDefs::State)> updateStatePredicate) { SharedString verref = AssetVersionRef::Bind(ref); auto refVertex = BuildTree(verref); SetStateForVertexAndDependents(refVertex, newState, updateStatePredicate); } // Sets the state for the specified ref and recursively sets the state for // the ref's dependent children. void StateUpdater::SetStateForVertexAndDependents( TreeType::vertex_descriptor vertex, AssetDefs::State newState, function<bool(AssetDefs::State)> updateStatePredicate) { if (updateStatePredicate(tree[vertex].state)) { // Set the state. The OnStateChange handler will take care // of stopping any running tasks, etc // false -> don't send notifications about the new state because we // will change it soon. SetState(vertex, newState, false); // Now update the dependent children auto edgeIters = out_edges(vertex, tree); auto edgeBegin = edgeIters.first; auto edgeEnd = edgeIters.second; for (auto i = edgeBegin; i != edgeEnd; ++i) { if (IsDependent(tree[*i].type)) { SetStateForVertexAndDependents(target(*i, tree), newState, updateStatePredicate); } } } } void StateUpdater::SetState( TreeType::vertex_descriptor vertex, AssetDefs::State newState, bool sendNotifications) { SharedString name = tree[vertex].name; if (newState != tree[vertex].state) { MutableAssetVersionD version(name); notify(NFY_PROGRESS, "Setting state of '%s' to '%s'", name.toString().c_str(), ToString(newState).c_str()); if (version) { // Set the state. The OnStateChange handler will take care // of stopping any running tasks, etc. // This call does not propagate the state change to other assets. We will // take care of that inside the state updater. version->SetMyStateOnly(newState, sendNotifications); // Setting the state can trigger additional state changes, so get the new // state directly from the asset version. tree[vertex].state = version->state; } else { // This shoud never happen - we had to successfully load the asset // previously to get it into the tree. notify(NFY_WARN, "Could not load asset '%s' to set state.", name.toString().c_str()); } } } // Helper class to calculate the state of asset versions based on the states // of their inputs and children. It calculates states in depth-first order; // we use the finish_vertex function to ensure that we calculate the state // of an asset version after we've calculated the states of its inputs // and children. class StateUpdater::UpdateStateVisitor : public default_dfs_visitor { private: // Keep a pointer to the state updater StateUpdater * const updater; // Helper class for calculating state from inputs class InputStates { private: uint numinputs = 0; uint numgood = 0; uint numblocking = 0; uint numoffline = 0; public: void Add(AssetDefs::State inputState) { ++numinputs; if (inputState == AssetDefs::Succeeded) { ++numgood; } else if (inputState == AssetDefs::Offline) { ++numblocking; ++numoffline; } else if (inputState & (AssetDefs::Blocked | AssetDefs::Failed | AssetDefs::Canceled | AssetDefs::Bad)) { ++numblocking; } } void GetOutputs(AssetDefs::State & stateByInputs, bool & blockersAreOffline, uint32 & numWaitingFor) { if (numinputs == numgood) { stateByInputs = AssetDefs::Queued; } else if (numblocking) { stateByInputs = AssetDefs::Blocked; } else { stateByInputs = AssetDefs::Waiting; } blockersAreOffline = (numblocking == numoffline); if (stateByInputs == AssetDefs::Waiting) { numWaitingFor = (numinputs - numgood); } else { numWaitingFor = 0; } } }; // Helper class for calculating state from children class ChildStates { private: uint numkids = 0; uint numgood = 0; uint numblocking = 0; uint numinprog = 0; uint numfailed = 0; public: void Add(AssetDefs::State childState) { ++numkids; if (childState == AssetDefs::Succeeded) { ++numgood; } else if (childState == AssetDefs::Failed) { ++numfailed; } else if (childState == AssetDefs::InProgress) { ++numinprog; } else if (childState & (AssetDefs::Blocked | AssetDefs::Canceled | AssetDefs::Offline | AssetDefs::Bad)) { ++numblocking; } } void GetOutputs(AssetDefs::State & stateByChildren) { if (numkids == numgood) { stateByChildren = AssetDefs::Succeeded; } else if (numblocking || numfailed) { stateByChildren = AssetDefs::Blocked; } else if (numgood || numinprog) { stateByChildren = AssetDefs::InProgress; } else { stateByChildren = AssetDefs::Queued; } } }; // Loops through the inputs and children of an asset and calculates // everything the asset verion needs to know to figure out its state. This // data will be passed to the asset version so it can calculate its own // state. void CalculateStateParameters( StateUpdater::TreeType::vertex_descriptor vertex, const StateUpdater::TreeType & tree, AssetDefs::State &stateByInputs, AssetDefs::State &stateByChildren, bool & blockersAreOffline, uint32 & numWaitingFor) const { InputStates inputStates; ChildStates childStates; auto edgeIters = out_edges(vertex, tree); auto edgeBegin = edgeIters.first; auto edgeEnd = edgeIters.second; for (auto i = edgeBegin; i != edgeEnd; ++i) { StateUpdater::DependencyType type = tree[*i].type; StateUpdater::TreeType::vertex_descriptor dep = target(*i, tree); AssetDefs::State depState = tree[dep].state; switch(type) { case StateUpdater::INPUT: inputStates.Add(depState); break; case StateUpdater::CHILD: case StateUpdater::DEPENDENT_AND_CHILD: childStates.Add(depState); break; case StateUpdater::DEPENDENT: // Dependents that are not also children are not considered when // calculating state. break; } } inputStates.GetOutputs(stateByInputs, blockersAreOffline, numWaitingFor); childStates.GetOutputs(stateByChildren); } public: UpdateStateVisitor(StateUpdater * updater) : updater(updater) {}; // Update the state of an asset after we've updated the state of its // inputs and children. virtual void finish_vertex( StateUpdater::TreeType::vertex_descriptor vertex, const StateUpdater::TreeType & tree) const { SharedString name = tree[vertex].name; notify(NFY_PROGRESS, "Calculating state for '%s'", name.toString().c_str()); AssetVersionD version(name); if (!version) { // This shoud never happen - we had to successfully load the asset // previously to get it into the tree. notify(NFY_WARN, "Could not load asset '%s' to recalculate state.", name.toString().c_str()); return; } if (!version->NeedComputeState()) return; AssetDefs::State stateByInputs; AssetDefs::State stateByChildren; bool blockersAreOffline; uint32 numWaitingFor; CalculateStateParameters(vertex, tree, stateByInputs, stateByChildren, blockersAreOffline, numWaitingFor); AssetDefs::State newState = version->CalcStateByInputsAndChildren(stateByInputs, stateByChildren, blockersAreOffline, numWaitingFor); // Set the state and send notifications. updater->SetState(vertex, newState, true); } }; void StateUpdater::RecalculateAndSaveStates() { // Traverse the state tree, recalculate states, and update states as needed. // State is calculated for each vertex in the tree after state is calculated // for all of its child and input vertices. // Possible optimization: Many assets have significant overlap in their // inputs. It might save time if we could calculate the overlapping state // only once. depth_first_search(tree, visitor(UpdateStateVisitor(this))); } <|endoftext|>
<commit_before><commit_msg>fix typo<commit_after><|endoftext|>
<commit_before>// __BEGIN_LICENSE__ // Copyright (c) 2009-2012, United States Government as represented by the // Administrator of the National Aeronautics and Space Administration. All // rights reserved. // // The NGT platform is licensed under the Apache License, Version 2.0 (the // "License"); you may not use this file except in compliance with the // License. You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // __END_LICENSE__ // Wholesale copy from orthoproject.cc. Longer term, this needs to be dealt with properly. /// \file reconstruct_aux.cc /// #include <iostream> #include <string> #include <fstream> #include <vector> #include <vw/Camera.h> #include <vw/Cartography.h> #include <vw/Core.h> #include <vw/FileIO.h> #include <vw/Image.h> #include <vw/Math.h> #include <vw/Math/Functors.h> #include <vw/Photometry.h> using namespace std; using namespace vw::camera; using namespace vw::cartography; using namespace vw::math; using namespace vw::photometry; using namespace vw; #include <asp/Core/Macros.h> #include <asp/Core/Common.h> #include <asp/Sessions.h> #include <asp/IsisIO/DiskImageResourceIsis.h> #include <asp/IsisIO/IsisCameraModel.h> #include <asp/IsisIO/IsisAdjustCameraModel.h> #include <boost/tokenizer.hpp> namespace po = boost::program_options; namespace fs = boost::filesystem; using namespace std; struct Options : asp::BaseOptions { Options(){} std::string image_file, camera_model_file, stereo_session; }; int extractDRGFromCube(bool useDEMTiles, double metersPerPixel, std::string DEMTilesDir, std::string DEMFile, std::string cubeFile, std::string isis_adjust_file, std::string outputDrgFile, Vector3 & sunPosition, Vector3 & spacecraftPosition ){ // Extract the sun/spacecraft position from the cube. If, in // addition, the file isis_adjust_file is specified, extract // the adjusted spacecraft position from that file instead. Options opt; try { if ( !fs::exists(isis_adjust_file) ){ std::cout << "WARNING: The ISIS adjust file " << isis_adjust_file << " is missing, will extract the unadjusted spacecraft position from the cube file " << cubeFile << std::endl; isis_adjust_file = cubeFile; } opt.image_file = cubeFile; opt.camera_model_file = isis_adjust_file; // Create a fresh stereo session and query it for the camera models. asp::StereoSession::register_session_type("rmax", &asp::StereoSessionRmax::construct); #if defined(ASP_HAVE_PKG_ISISIO) && ASP_HAVE_PKG_ISISIO == 1 asp::StereoSession::register_session_type("isis", &asp::StereoSessionIsis::construct); opt.stereo_session = "isis"; // Okay, here's a total hack. We create a stereo session where both // of the imagers and images are the same, because we want to take // advantage of the stereo pipeline's ability to generate camera // models for various missions. Hence, we create two identical // camera models, but only one is used. The last empty strings // are dummy arguments. typedef boost::scoped_ptr<asp::StereoSession> SessionPtr; SessionPtr session( asp::StereoSession::create(opt.stereo_session) ); session->initialize(opt, opt.image_file, opt.image_file, opt.camera_model_file, opt.camera_model_file, "", "","","","" ); boost::shared_ptr<camera::CameraModel> camera_model; camera_model = session->camera_model(opt.image_file, opt.camera_model_file); spacecraftPosition = camera_model->camera_center(Vector2()); vw::camera::IsisCameraModel M(opt.image_file); sunPosition = M.sun_position(); std::cout << "sun and spacecraft positions are: " << sunPosition << ' ' << spacecraftPosition << std::endl; #else std::cout << "ERROR: The ISIS package is missing. Cannot extract " << "sun and spacecraft position from an ISIS cube file. " << std::endl; exit(1); #endif } ASP_STANDARD_CATCHES; return 0; } <commit_msg>Wipe no longer necessary albedo file<commit_after><|endoftext|>