text
stringlengths
54
60.6k
<commit_before>/* * datasetlabel.cpp * * Created on: 03.08.2014 * Author: Ralph Schurade */ #include "datasetlabel.h" #include "../models.h" #include "../../gui/gl/glfunctions.h" #include <QtOpenGL/QGLShaderProgram> DatasetLabel::DatasetLabel() : Dataset( QDir( "new label" ), Fn::DatasetType::LABEL ), m_handle0( GLFunctions::getPickIndex() ) { float x = Models::getGlobal( Fn::Property::G_SAGITTAL ).toFloat(); float y = Models::getGlobal( Fn::Property::G_CORONAL ).toFloat(); float z = Models::getGlobal( Fn::Property::G_AXIAL ).toFloat(); QVector3D h0( x, y, z ); m_properties["maingl"].createBool( Fn::Property::D_SHOW_PLANE_HANDLES, true, "general" ); m_properties["maingl"].createColor( Fn::Property::D_HANDLE_COLOR, QColor( 255, 0, 0 ), "general" ); m_properties["maingl"].createCharString( Fn::Property::D_COLORMAP_LABEL, "label", "general" ); m_properties["maingl"].createInt( Fn::Property::D_COLORMAP_TEXT_SIZE, 50, 1, 200, "general" ); m_properties["maingl"].createVector( Fn::Property::D_HANDLE_0, h0, "handles" ); PropertyGroup props2( m_properties["maingl"] ); m_properties.insert( "maingl2", props2 ); m_properties["maingl2"].createBool( Fn::Property::D_SHOW_PLANE_HANDLES, true, "general" ); m_properties["maingl2"].createColor( Fn::Property::D_HANDLE_COLOR, QColor( 255, 0, 0 ), "general" ); } DatasetLabel::~DatasetLabel() { } void DatasetLabel::draw( QMatrix4x4 pMatrix, QMatrix4x4 mvMatrix, int width, int height, int renderMode, QString target ) { if ( !properties( target ).get( Fn::Property::D_ACTIVE ).toBool() ) { return; } QVector3D h0 = m_properties["maingl"].get( Fn::Property::D_HANDLE_0 ).value<QVector3D>(); QColor color = m_properties["maingl"].get( Fn::Property::D_HANDLE_COLOR ).value<QColor>(); if ( m_properties["maingl"].get( Fn::Property::D_SHOW_PLANE_HANDLES ).toBool() ) { color.setAlpha( 254 ); GLFunctions::renderSphere( pMatrix, mvMatrix, h0.x(), h0.y(), h0.z(), 5, 5, 5, color, m_handle0, width, height, renderMode ); } QString text = m_properties["maingl"].get( Fn::Property::D_COLORMAP_LABEL ).toString(); int size = m_properties["maingl"].get( Fn::Property::D_COLORMAP_TEXT_SIZE ).toInt(); GLFunctions::renderLabel( pMatrix, mvMatrix, text, size, h0.x(), h0.y(), h0.z(), color, 1.0, width, height, renderMode ); } bool DatasetLabel::rightMouseDrag( int pickId, QVector3D dir, Qt::KeyboardModifiers modifiers, QString target ) { if ( pickId == m_handle0 ) { QVector3D h0 = m_properties["maingl"].get( Fn::Property::D_HANDLE_0 ).value<QVector3D>(); h0.setX( h0.x() + dir.x() ); h0.setY( h0.y() + dir.y() ); h0.setZ( h0.z() + dir.z() ); m_properties["maingl"].set( Fn::Property::D_HANDLE_0, h0 ); return true; } return false; } <commit_msg>added slider to change size of label handles<commit_after>/* * datasetlabel.cpp * * Created on: 03.08.2014 * Author: Ralph Schurade */ #include "datasetlabel.h" #include "../models.h" #include "../../gui/gl/glfunctions.h" #include <QtOpenGL/QGLShaderProgram> DatasetLabel::DatasetLabel() : Dataset( QDir( "new label" ), Fn::DatasetType::LABEL ), m_handle0( GLFunctions::getPickIndex() ) { float x = Models::getGlobal( Fn::Property::G_SAGITTAL ).toFloat(); float y = Models::getGlobal( Fn::Property::G_CORONAL ).toFloat(); float z = Models::getGlobal( Fn::Property::G_AXIAL ).toFloat(); QVector3D h0( x, y, z ); m_properties["maingl"].createBool( Fn::Property::D_SHOW_PLANE_HANDLES, true, "general" ); m_properties["maingl"].createColor( Fn::Property::D_HANDLE_COLOR, QColor( 255, 0, 0 ), "general" ); m_properties["maingl"].createCharString( Fn::Property::D_COLORMAP_LABEL, "label", "general" ); m_properties["maingl"].createInt( Fn::Property::D_COLORMAP_TEXT_SIZE, 50, 1, 200, "general" ); m_properties["maingl"].createVector( Fn::Property::D_HANDLE_0, h0, "handles" ); m_properties["maingl"].createFloat( Fn::Property::D_DX, 2.0, 0.0, 10.0, "handles" ); PropertyGroup props2( m_properties["maingl"] ); m_properties.insert( "maingl2", props2 ); m_properties["maingl2"].createBool( Fn::Property::D_SHOW_PLANE_HANDLES, true, "general" ); m_properties["maingl2"].createColor( Fn::Property::D_HANDLE_COLOR, QColor( 255, 0, 0 ), "general" ); } DatasetLabel::~DatasetLabel() { } void DatasetLabel::draw( QMatrix4x4 pMatrix, QMatrix4x4 mvMatrix, int width, int height, int renderMode, QString target ) { if ( !properties( target ).get( Fn::Property::D_ACTIVE ).toBool() ) { return; } QVector3D h0 = m_properties["maingl"].get( Fn::Property::D_HANDLE_0 ).value<QVector3D>(); QColor color = m_properties["maingl"].get( Fn::Property::D_HANDLE_COLOR ).value<QColor>(); if ( m_properties["maingl"].get( Fn::Property::D_SHOW_PLANE_HANDLES ).toBool() ) { color.setAlpha( 254 ); float dx = m_properties["maingl"].get( Fn::Property::D_DX ).toFloat(); GLFunctions::renderSphere( pMatrix, mvMatrix, h0.x(), h0.y(), h0.z(), dx, dx, dx, color, m_handle0, width, height, renderMode ); } QString text = m_properties["maingl"].get( Fn::Property::D_COLORMAP_LABEL ).toString(); int size = m_properties["maingl"].get( Fn::Property::D_COLORMAP_TEXT_SIZE ).toInt(); GLFunctions::renderLabel( pMatrix, mvMatrix, text, size, h0.x(), h0.y(), h0.z(), color, 1.0, width, height, renderMode ); } bool DatasetLabel::rightMouseDrag( int pickId, QVector3D dir, Qt::KeyboardModifiers modifiers, QString target ) { if ( pickId == m_handle0 ) { QVector3D h0 = m_properties["maingl"].get( Fn::Property::D_HANDLE_0 ).value<QVector3D>(); h0.setX( h0.x() + dir.x() ); h0.setY( h0.y() + dir.y() ); h0.setZ( h0.z() + dir.z() ); m_properties["maingl"].set( Fn::Property::D_HANDLE_0, h0 ); return true; } return false; } <|endoftext|>
<commit_before>/// /// @file S2_trivial.cpp /// @brief Calculate the contribution of the trivial special leaves /// in parallel using OpenMP. /// /// Copyright (C) 2014 Kim Walisch, <kim.walisch@gmail.com> /// /// This file is distributed under the BSD License. See the COPYING /// file in the top level directory. /// #include <PiTable.hpp> #include <primecount.hpp> #include <primecount-internal.hpp> #include <primesieve.hpp> #include <generate.hpp> #include <int128.hpp> #include <stdint.h> #include <algorithm> #include <iostream> #include <iomanip> #include <vector> #ifdef _OPENMP #include <omp.h> #endif using namespace std; using namespace primecount; namespace { namespace S2_trivial { template <typename T> T S2_trivial(T x, int64_t y, int64_t z, int64_t c, int threads) { int64_t thread_threshold = ipow(10, 7); threads = validate_threads(threads, y, thread_threshold); if (print_status()) { cout << endl; cout << "=== S2_trivial(x, y) ===" << endl; cout << "Computation of the trivial special leaves" << endl; } double time = get_wtime(); PiTable pi(y); int64_t pi_y = pi[y]; int64_t sqrtz = isqrt(z); int64_t prime_c = nth_prime(c); T S2_total = 0; // Find all trivial leaves: n = primes[b] * primes[l] // which satisfy phi(x / n), b - 1) = 1 #pragma omp parallel for num_threads(threads) reduction(+: S2_total) for (int64_t i = 0; i < threads; i++) { int64_t start = max(prime_c, sqrtz) + 1; int64_t thread_interval = ceil_div(y - start, threads); start += thread_interval * i; int64_t stop = min(start + thread_interval, y); primesieve::iterator iter(start - 1, stop); T prime; while ((prime = iter.next_prime()) < stop) { int64_t xn = (int64_t) max(x / (prime * prime), prime); S2_total += pi_y - pi[xn]; } } if (print_status()) print_result("S2_trivial", S2_total, time); return S2_total; } } // namespace S2_trivial } // namespace namespace primecount { int64_t S2_trivial(int64_t x, int64_t y, int64_t z, int64_t c, int threads) { return S2_trivial::S2_trivial(x, y, z, c, threads); } #ifdef HAVE_INT128_T int128_t S2_trivial(int128_t x, int64_t y, int64_t z, int64_t c, int threads) { return S2_trivial::S2_trivial(x, y, z, c, threads); } #endif } // namespace primecount <commit_msg>Refactoring<commit_after>/// /// @file S2_trivial.cpp /// @brief Calculate the contribution of the trivial special leaves /// in parallel using OpenMP. /// /// Copyright (C) 2015 Kim Walisch, <kim.walisch@gmail.com> /// /// This file is distributed under the BSD License. See the COPYING /// file in the top level directory. /// #include <PiTable.hpp> #include <primecount.hpp> #include <primecount-internal.hpp> #include <primesieve.hpp> #include <generate.hpp> #include <int128.hpp> #include <stdint.h> #include <algorithm> #include <iostream> #include <iomanip> #include <vector> #ifdef _OPENMP #include <omp.h> #endif using namespace std; using namespace primecount; namespace { namespace S2_trivial { template <typename T> T S2_trivial(T x, int64_t y, int64_t z, int64_t c, int threads) { int64_t thread_threshold = ipow(10, 7); threads = validate_threads(threads, y, thread_threshold); if (print_status()) { cout << endl; cout << "=== S2_trivial(x, y) ===" << endl; cout << "Computation of the trivial special leaves" << endl; } double time = get_wtime(); PiTable pi(y); int64_t pi_y = pi[y]; int64_t sqrtz = isqrt(z); int64_t prime_c = nth_prime(c); T s2_trivial = 0; // Find all trivial leaves: n = primes[b] * primes[l] // which satisfy phi(x / n), b - 1) = 1 #pragma omp parallel for num_threads(threads) reduction(+: s2_trivial) for (int64_t i = 0; i < threads; i++) { int64_t start = max(prime_c, sqrtz) + 1; int64_t thread_interval = ceil_div(y - start, threads); start += thread_interval * i; int64_t stop = min(start + thread_interval, y); primesieve::iterator iter(start - 1, stop); T prime; while ((prime = iter.next_prime()) < stop) { int64_t xn = (int64_t) max(x / (prime * prime), prime); s2_trivial += pi_y - pi[xn]; } } if (print_status()) print_result("S2_trivial", s2_trivial, time); return s2_trivial; } } // namespace S2_trivial } // namespace namespace primecount { int64_t S2_trivial(int64_t x, int64_t y, int64_t z, int64_t c, int threads) { return S2_trivial::S2_trivial(x, y, z, c, threads); } #ifdef HAVE_INT128_T int128_t S2_trivial(int128_t x, int64_t y, int64_t z, int64_t c, int threads) { return S2_trivial::S2_trivial(x, y, z, c, threads); } #endif } // namespace primecount <|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 "chrome/browser/sync/engine/auth_watcher.h" #include "base/file_util.h" #include "base/string_util.h" #include "chrome/browser/sync/engine/all_status.h" #include "chrome/browser/sync/engine/authenticator.h" #include "chrome/browser/sync/engine/net/gaia_authenticator.h" #include "chrome/browser/sync/engine/net/server_connection_manager.h" #include "chrome/browser/sync/notifier/listener/talk_mediator.h" #include "chrome/browser/sync/syncable/directory_manager.h" #include "chrome/browser/sync/syncable/syncable.h" #include "chrome/browser/sync/util/event_sys-inl.h" #include "chrome/browser/sync/util/user_settings.h" // How authentication happens: // // Kick Off: // The sync API looks to see if the user's name and // password are stored. If so, it calls authwatcher.Authenticate() with // them. Otherwise it fires an error event. // // On failed Gaia Auth: // The AuthWatcher attempts to use saved hashes to authenticate // locally, and on success opens the share. // On failure, fires an error event. // // On successful Gaia Auth: // AuthWatcher launches a thread to open the share and to get the // authentication token from the sync server. using std::pair; using std::string; using std::vector; namespace browser_sync { AuthWatcher::AuthWatcher(DirectoryManager* dirman, ServerConnectionManager* scm, AllStatus* allstatus, const string& user_agent, const string& service_id, const string& gaia_url, UserSettings* user_settings, GaiaAuthenticator* gaia_auth, TalkMediator* talk_mediator) : gaia_(gaia_auth), dirman_(dirman), scm_(scm), allstatus_(allstatus), status_(NOT_AUTHENTICATED), user_settings_(user_settings), talk_mediator_(talk_mediator), auth_backend_thread_("SyncEngine_AuthWatcherThread"), current_attempt_trigger_(AuthWatcherEvent::USER_INITIATED) { if (!auth_backend_thread_.Start()) NOTREACHED() << "Couldn't start SyncEngine_AuthWatcherThread"; gaia_->set_message_loop(message_loop()); connmgr_hookup_.reset( NewEventListenerHookup(scm->channel(), this, &AuthWatcher::HandleServerConnectionEvent)); AuthWatcherEvent done = { AuthWatcherEvent::AUTHWATCHER_DESTROYED }; channel_.reset(new Channel(done)); } void AuthWatcher::PersistCredentials() { DCHECK_EQ(MessageLoop::current(), message_loop()); GaiaAuthenticator::AuthResults results = gaia_->results(); // We just successfully signed in again, let's clear out any residual cached // login data from earlier sessions. ClearAuthenticationData(); user_settings_->StoreEmailForSignin(results.email, results.primary_email); user_settings_->RememberSigninType(results.email, results.signin); user_settings_->RememberSigninType(results.primary_email, results.signin); results.email = results.primary_email; gaia_->SetUsernamePassword(results.primary_email, results.password); if (!user_settings_->VerifyAgainstStoredHash(results.email, results.password)) user_settings_->StoreHashedPassword(results.email, results.password); if (PERSIST_TO_DISK == results.credentials_saved) { user_settings_->SetAuthTokenForService(results.email, SYNC_SERVICE_NAME, gaia_->auth_token()); } } const char kAuthWatcher[] = "AuthWatcher"; void AuthWatcher::AuthenticateWithToken(const std::string& gaia_email, const std::string& auth_token) { message_loop()->PostTask(FROM_HERE, NewRunnableMethod(this, &AuthWatcher::DoAuthenticateWithToken, gaia_email, auth_token)); } void AuthWatcher::DoAuthenticateWithToken(const std::string& gaia_email, const std::string& auth_token) { DCHECK_EQ(MessageLoop::current(), message_loop()); Authenticator auth(scm_, user_settings_); Authenticator::AuthenticationResult result = auth.AuthenticateToken(auth_token); AuthWatcherEvent event = {AuthWatcherEvent::ILLEGAL_VALUE , 0}; gaia_->SetUsername(gaia_email); gaia_->SetAuthToken(auth_token, SAVE_IN_MEMORY_ONLY); const bool was_authenticated = NOT_AUTHENTICATED != status_; switch (result) { case Authenticator::SUCCESS: { status_ = GAIA_AUTHENTICATED; const PathString& share_name = gaia_email; user_settings_->SwitchUser(gaia_email); // Set the authentication token for notifications talk_mediator_->SetAuthToken(gaia_email, auth_token); scm_->set_auth_token(auth_token); if (!was_authenticated) LoadDirectoryListAndOpen(share_name); NotifyAuthSucceeded(gaia_email); return; } case Authenticator::BAD_AUTH_TOKEN: event.what_happened = AuthWatcherEvent::SERVICE_AUTH_FAILED; break; case Authenticator::CORRUPT_SERVER_RESPONSE: case Authenticator::SERVICE_DOWN: event.what_happened = AuthWatcherEvent::SERVICE_CONNECTION_FAILED; break; case Authenticator::USER_NOT_ACTIVATED: event.what_happened = AuthWatcherEvent::SERVICE_USER_NOT_SIGNED_UP; break; default: LOG(FATAL) << "Illegal return from AuthenticateToken"; return; } // Always fall back to local authentication. if (was_authenticated || AuthenticateLocally(gaia_email)) { if (AuthWatcherEvent::SERVICE_CONNECTION_FAILED == event.what_happened) return; } DCHECK_NE(event.what_happened, AuthWatcherEvent::ILLEGAL_VALUE); NotifyListeners(&event); } bool AuthWatcher::AuthenticateLocally(string email) { DCHECK_EQ(MessageLoop::current(), message_loop()); user_settings_->GetEmailForSignin(&email); if (file_util::PathExists(FilePath(dirman_->GetSyncDataDatabasePath()))) { gaia_->SetUsername(email); status_ = LOCALLY_AUTHENTICATED; user_settings_->SwitchUser(email); const PathString& share_name = email; LoadDirectoryListAndOpen(share_name); NotifyAuthSucceeded(email); return true; } else { return false; } } bool AuthWatcher::AuthenticateLocally(string email, const string& password) { DCHECK_EQ(MessageLoop::current(), message_loop()); user_settings_->GetEmailForSignin(&email); return user_settings_->VerifyAgainstStoredHash(email, password) && AuthenticateLocally(email); } void AuthWatcher::ProcessGaiaAuthFailure() { DCHECK_EQ(MessageLoop::current(), message_loop()); GaiaAuthenticator::AuthResults results = gaia_->results(); if (LOCALLY_AUTHENTICATED == status_) { return; // nothing todo } else if (AuthenticateLocally(results.email, results.password)) { // We save the "Remember me" checkbox by putting a non-null auth // token into the last_user table. So if we're offline and the // user checks the box, insert a bogus auth token. if (PERSIST_TO_DISK == results.credentials_saved) { const string auth_token("bogus"); user_settings_->SetAuthTokenForService(results.email, SYNC_SERVICE_NAME, auth_token); } const bool unavailable = ConnectionUnavailable == results.auth_error || Unknown == results.auth_error || ServiceUnavailable == results.auth_error; if (unavailable) return; } AuthWatcherEvent myevent = { AuthWatcherEvent::GAIA_AUTH_FAILED, &results }; NotifyListeners(&myevent); } void AuthWatcher::DoAuthenticate(const AuthRequest& request) { DCHECK_EQ(MessageLoop::current(), message_loop()); AuthWatcherEvent event = { AuthWatcherEvent::AUTHENTICATION_ATTEMPT_START }; NotifyListeners(&event); current_attempt_trigger_ = request.trigger; SaveCredentials save = request.persist_creds_to_disk ? PERSIST_TO_DISK : SAVE_IN_MEMORY_ONLY; SignIn const signin = user_settings_-> RecallSigninType(request.email, GMAIL_SIGNIN); // We let the caller be lazy and try using the last captcha token seen by // the gaia authenticator if they haven't provided a token but have sent // a challenge response. Of course, if the captcha token is specified, // we use that one instead. std::string captcha_token(request.captcha_token); if (!request.captcha_value.empty() && captcha_token.empty()) captcha_token = gaia_->captcha_token(); if (!request.password.empty()) { bool authenticated = false; if (!captcha_token.empty()) { authenticated = gaia_->Authenticate(request.email, request.password, save, captcha_token, request.captcha_value, signin); } else { authenticated = gaia_->Authenticate(request.email, request.password, save, signin); } if (authenticated) { PersistCredentials(); DoAuthenticateWithToken(gaia_->email(), gaia_->auth_token()); } else { ProcessGaiaAuthFailure(); } } else if (!request.auth_token.empty()) { DoAuthenticateWithToken(request.email, request.auth_token); } else { LOG(ERROR) << "Attempt to authenticate with no credentials."; } } void AuthWatcher::NotifyAuthSucceeded(const string& email) { DCHECK_EQ(MessageLoop::current(), message_loop()); LOG(INFO) << "NotifyAuthSucceeded"; AuthWatcherEvent event = { AuthWatcherEvent::AUTH_SUCCEEDED }; event.user_email = email; NotifyListeners(&event); } void AuthWatcher::HandleServerConnectionEvent( const ServerConnectionEvent& event) { message_loop()->PostTask(FROM_HERE, NewRunnableMethod(this, &AuthWatcher::DoHandleServerConnectionEvent, event, scm_->auth_token())); } void AuthWatcher::DoHandleServerConnectionEvent( const ServerConnectionEvent& event, const std::string& auth_token_snapshot) { DCHECK_EQ(MessageLoop::current(), message_loop()); if (event.server_reachable && // If the auth_token at the time of the event differs from the current // one, we have authenticated since then and don't need to re-try. (auth_token_snapshot == gaia_->auth_token()) && (event.connection_code == HttpResponse::SYNC_AUTH_ERROR || status_ == LOCALLY_AUTHENTICATED)) { // We're either online or just got reconnected and want to try to // authenticate. If we've got a saved token this should just work. If not // the auth failure should trigger UI indications that we're not logged in. // METRIC: If we get a SYNC_AUTH_ERROR, our token expired. GaiaAuthenticator::AuthResults authresults = gaia_->results(); AuthRequest request = { authresults.email, authresults.password, authresults.auth_token, std::string(), std::string(), PERSIST_TO_DISK == authresults.credentials_saved, AuthWatcherEvent::EXPIRED_CREDENTIALS }; DoAuthenticate(request); } } bool AuthWatcher::LoadDirectoryListAndOpen(const PathString& login) { DCHECK_EQ(MessageLoop::current(), message_loop()); LOG(INFO) << "LoadDirectoryListAndOpen(" << login << ")"; bool initial_sync_ended = false; dirman_->Open(login); syncable::ScopedDirLookup dir(dirman_, login); if (dir.good() && dir->initial_sync_ended()) initial_sync_ended = true; LOG(INFO) << "LoadDirectoryListAndOpen returning " << initial_sync_ended; return initial_sync_ended; } AuthWatcher::~AuthWatcher() { auth_backend_thread_.Stop(); // The gaia authenticator takes a const MessageLoop* because it only uses it // to ensure all methods are invoked on the given loop. Once our thread has // stopped, the current message loop will be NULL, and no methods should be // invoked on |gaia_| after this point. We could set it to NULL, but // abstaining allows for even more sanity checking that nothing is invoked on // it from now on. } void AuthWatcher::Authenticate(const string& email, const string& password, const string& captcha_token, const string& captcha_value, bool persist_creds_to_disk) { LOG(INFO) << "AuthWatcher::Authenticate called"; string empty; AuthRequest request = { FormatAsEmailAddress(email), password, empty, captcha_token, captcha_value, persist_creds_to_disk, AuthWatcherEvent::USER_INITIATED }; message_loop()->PostTask(FROM_HERE, NewRunnableMethod(this, &AuthWatcher::DoAuthenticate, request)); } void AuthWatcher::ClearAuthenticationData() { scm_->set_auth_token(std::string()); user_settings_->ClearAllServiceTokens(); } string AuthWatcher::email() const { return gaia_->email(); } void AuthWatcher::NotifyListeners(AuthWatcherEvent* event) { event->trigger = current_attempt_trigger_; channel_->NotifyListeners(*event); } } // namespace browser_sync <commit_msg>Revert 31865 - This change is patched from http://codereview.chromium.org/276071 by randy.posynick@gmail.com<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 "chrome/browser/sync/engine/auth_watcher.h" #include "base/file_util.h" #include "base/string_util.h" #include "chrome/browser/sync/engine/all_status.h" #include "chrome/browser/sync/engine/authenticator.h" #include "chrome/browser/sync/engine/net/gaia_authenticator.h" #include "chrome/browser/sync/engine/net/server_connection_manager.h" #include "chrome/browser/sync/notifier/listener/talk_mediator.h" #include "chrome/browser/sync/syncable/directory_manager.h" #include "chrome/browser/sync/syncable/syncable.h" #include "chrome/browser/sync/util/event_sys-inl.h" #include "chrome/browser/sync/util/user_settings.h" // How authentication happens: // // Kick Off: // The sync API looks to see if the user's name and // password are stored. If so, it calls authwatcher.Authenticate() with // them. Otherwise it fires an error event. // // On failed Gaia Auth: // The AuthWatcher attempts to use saved hashes to authenticate // locally, and on success opens the share. // On failure, fires an error event. // // On successful Gaia Auth: // AuthWatcher launches a thread to open the share and to get the // authentication token from the sync server. using std::pair; using std::string; using std::vector; namespace browser_sync { AuthWatcher::AuthWatcher(DirectoryManager* dirman, ServerConnectionManager* scm, AllStatus* allstatus, const string& user_agent, const string& service_id, const string& gaia_url, UserSettings* user_settings, GaiaAuthenticator* gaia_auth, TalkMediator* talk_mediator) : gaia_(gaia_auth), dirman_(dirman), scm_(scm), allstatus_(allstatus), status_(NOT_AUTHENTICATED), user_settings_(user_settings), talk_mediator_(talk_mediator), auth_backend_thread_("SyncEngine_AuthWatcherThread"), current_attempt_trigger_(AuthWatcherEvent::USER_INITIATED) { if (!auth_backend_thread_.Start()) NOTREACHED() << "Couldn't start SyncEngine_AuthWatcherThread"; gaia_->set_message_loop(message_loop()); connmgr_hookup_.reset( NewEventListenerHookup(scm->channel(), this, &AuthWatcher::HandleServerConnectionEvent)); AuthWatcherEvent done = { AuthWatcherEvent::AUTHWATCHER_DESTROYED }; channel_.reset(new Channel(done)); } void AuthWatcher::PersistCredentials() { DCHECK_EQ(MessageLoop::current(), message_loop()); GaiaAuthenticator::AuthResults results = gaia_->results(); // We just successfully signed in again, let's clear out any residual cached // login data from earlier sessions. ClearAuthenticationData(); user_settings_->StoreEmailForSignin(results.email, results.primary_email); user_settings_->RememberSigninType(results.email, results.signin); user_settings_->RememberSigninType(results.primary_email, results.signin); results.email = results.primary_email; gaia_->SetUsernamePassword(results.primary_email, results.password); if (!user_settings_->VerifyAgainstStoredHash(results.email, results.password)) user_settings_->StoreHashedPassword(results.email, results.password); if (PERSIST_TO_DISK == results.credentials_saved) { user_settings_->SetAuthTokenForService(results.email, SYNC_SERVICE_NAME, gaia_->auth_token()); } } const char kAuthWatcher[] = "AuthWatcher"; void AuthWatcher::AuthenticateWithToken(const std::string& gaia_email, const std::string& auth_token) { message_loop()->PostTask(FROM_HERE, NewRunnableMethod(this, &AuthWatcher::DoAuthenticateWithToken, gaia_email, auth_token)); } void AuthWatcher::DoAuthenticateWithToken(const std::string& gaia_email, const std::string& auth_token) { DCHECK_EQ(MessageLoop::current(), message_loop()); Authenticator auth(scm_, user_settings_); Authenticator::AuthenticationResult result = auth.AuthenticateToken(auth_token); string email = gaia_email; if (auth.display_email() && *auth.display_email()) { email = auth.display_email(); LOG(INFO) << "Auth returned email " << email << " for gaia email " << gaia_email; } AuthWatcherEvent event = {AuthWatcherEvent::ILLEGAL_VALUE , 0}; gaia_->SetUsername(email); gaia_->SetAuthToken(auth_token, SAVE_IN_MEMORY_ONLY); const bool was_authenticated = NOT_AUTHENTICATED != status_; switch (result) { case Authenticator::SUCCESS: { status_ = GAIA_AUTHENTICATED; const PathString& share_name = email; user_settings_->SwitchUser(email); // Set the authentication token for notifications talk_mediator_->SetAuthToken(email, auth_token); scm_->set_auth_token(auth_token); if (!was_authenticated) LoadDirectoryListAndOpen(share_name); NotifyAuthSucceeded(email); return; } case Authenticator::BAD_AUTH_TOKEN: event.what_happened = AuthWatcherEvent::SERVICE_AUTH_FAILED; break; case Authenticator::CORRUPT_SERVER_RESPONSE: case Authenticator::SERVICE_DOWN: event.what_happened = AuthWatcherEvent::SERVICE_CONNECTION_FAILED; break; case Authenticator::USER_NOT_ACTIVATED: event.what_happened = AuthWatcherEvent::SERVICE_USER_NOT_SIGNED_UP; break; default: LOG(FATAL) << "Illegal return from AuthenticateToken"; return; } // Always fall back to local authentication. if (was_authenticated || AuthenticateLocally(email)) { if (AuthWatcherEvent::SERVICE_CONNECTION_FAILED == event.what_happened) return; } DCHECK_NE(event.what_happened, AuthWatcherEvent::ILLEGAL_VALUE); NotifyListeners(&event); } bool AuthWatcher::AuthenticateLocally(string email) { DCHECK_EQ(MessageLoop::current(), message_loop()); user_settings_->GetEmailForSignin(&email); if (file_util::PathExists(FilePath(dirman_->GetSyncDataDatabasePath()))) { gaia_->SetUsername(email); status_ = LOCALLY_AUTHENTICATED; user_settings_->SwitchUser(email); const PathString& share_name = email; LoadDirectoryListAndOpen(share_name); NotifyAuthSucceeded(email); return true; } else { return false; } } bool AuthWatcher::AuthenticateLocally(string email, const string& password) { DCHECK_EQ(MessageLoop::current(), message_loop()); user_settings_->GetEmailForSignin(&email); return user_settings_->VerifyAgainstStoredHash(email, password) && AuthenticateLocally(email); } void AuthWatcher::ProcessGaiaAuthFailure() { DCHECK_EQ(MessageLoop::current(), message_loop()); GaiaAuthenticator::AuthResults results = gaia_->results(); if (LOCALLY_AUTHENTICATED == status_) { return; // nothing todo } else if (AuthenticateLocally(results.email, results.password)) { // We save the "Remember me" checkbox by putting a non-null auth // token into the last_user table. So if we're offline and the // user checks the box, insert a bogus auth token. if (PERSIST_TO_DISK == results.credentials_saved) { const string auth_token("bogus"); user_settings_->SetAuthTokenForService(results.email, SYNC_SERVICE_NAME, auth_token); } const bool unavailable = ConnectionUnavailable == results.auth_error || Unknown == results.auth_error || ServiceUnavailable == results.auth_error; if (unavailable) return; } AuthWatcherEvent myevent = { AuthWatcherEvent::GAIA_AUTH_FAILED, &results }; NotifyListeners(&myevent); } void AuthWatcher::DoAuthenticate(const AuthRequest& request) { DCHECK_EQ(MessageLoop::current(), message_loop()); AuthWatcherEvent event = { AuthWatcherEvent::AUTHENTICATION_ATTEMPT_START }; NotifyListeners(&event); current_attempt_trigger_ = request.trigger; SaveCredentials save = request.persist_creds_to_disk ? PERSIST_TO_DISK : SAVE_IN_MEMORY_ONLY; SignIn const signin = user_settings_-> RecallSigninType(request.email, GMAIL_SIGNIN); // We let the caller be lazy and try using the last captcha token seen by // the gaia authenticator if they haven't provided a token but have sent // a challenge response. Of course, if the captcha token is specified, // we use that one instead. std::string captcha_token(request.captcha_token); if (!request.captcha_value.empty() && captcha_token.empty()) captcha_token = gaia_->captcha_token(); if (!request.password.empty()) { bool authenticated = false; if (!captcha_token.empty()) { authenticated = gaia_->Authenticate(request.email, request.password, save, captcha_token, request.captcha_value, signin); } else { authenticated = gaia_->Authenticate(request.email, request.password, save, signin); } if (authenticated) { PersistCredentials(); DoAuthenticateWithToken(gaia_->email(), gaia_->auth_token()); } else { ProcessGaiaAuthFailure(); } } else if (!request.auth_token.empty()) { DoAuthenticateWithToken(request.email, request.auth_token); } else { LOG(ERROR) << "Attempt to authenticate with no credentials."; } } void AuthWatcher::NotifyAuthSucceeded(const string& email) { DCHECK_EQ(MessageLoop::current(), message_loop()); LOG(INFO) << "NotifyAuthSucceeded"; AuthWatcherEvent event = { AuthWatcherEvent::AUTH_SUCCEEDED }; event.user_email = email; NotifyListeners(&event); } void AuthWatcher::HandleServerConnectionEvent( const ServerConnectionEvent& event) { message_loop()->PostTask(FROM_HERE, NewRunnableMethod(this, &AuthWatcher::DoHandleServerConnectionEvent, event, scm_->auth_token())); } void AuthWatcher::DoHandleServerConnectionEvent( const ServerConnectionEvent& event, const std::string& auth_token_snapshot) { DCHECK_EQ(MessageLoop::current(), message_loop()); if (event.server_reachable && // If the auth_token at the time of the event differs from the current // one, we have authenticated since then and don't need to re-try. (auth_token_snapshot == gaia_->auth_token()) && (event.connection_code == HttpResponse::SYNC_AUTH_ERROR || status_ == LOCALLY_AUTHENTICATED)) { // We're either online or just got reconnected and want to try to // authenticate. If we've got a saved token this should just work. If not // the auth failure should trigger UI indications that we're not logged in. // METRIC: If we get a SYNC_AUTH_ERROR, our token expired. GaiaAuthenticator::AuthResults authresults = gaia_->results(); AuthRequest request = { authresults.email, authresults.password, authresults.auth_token, std::string(), std::string(), PERSIST_TO_DISK == authresults.credentials_saved, AuthWatcherEvent::EXPIRED_CREDENTIALS }; DoAuthenticate(request); } } bool AuthWatcher::LoadDirectoryListAndOpen(const PathString& login) { DCHECK_EQ(MessageLoop::current(), message_loop()); LOG(INFO) << "LoadDirectoryListAndOpen(" << login << ")"; bool initial_sync_ended = false; dirman_->Open(login); syncable::ScopedDirLookup dir(dirman_, login); if (dir.good() && dir->initial_sync_ended()) initial_sync_ended = true; LOG(INFO) << "LoadDirectoryListAndOpen returning " << initial_sync_ended; return initial_sync_ended; } AuthWatcher::~AuthWatcher() { auth_backend_thread_.Stop(); // The gaia authenticator takes a const MessageLoop* because it only uses it // to ensure all methods are invoked on the given loop. Once our thread has // stopped, the current message loop will be NULL, and no methods should be // invoked on |gaia_| after this point. We could set it to NULL, but // abstaining allows for even more sanity checking that nothing is invoked on // it from now on. } void AuthWatcher::Authenticate(const string& email, const string& password, const string& captcha_token, const string& captcha_value, bool persist_creds_to_disk) { LOG(INFO) << "AuthWatcher::Authenticate called"; string empty; AuthRequest request = { FormatAsEmailAddress(email), password, empty, captcha_token, captcha_value, persist_creds_to_disk, AuthWatcherEvent::USER_INITIATED }; message_loop()->PostTask(FROM_HERE, NewRunnableMethod(this, &AuthWatcher::DoAuthenticate, request)); } void AuthWatcher::ClearAuthenticationData() { scm_->set_auth_token(std::string()); user_settings_->ClearAllServiceTokens(); } string AuthWatcher::email() const { return gaia_->email(); } void AuthWatcher::NotifyListeners(AuthWatcherEvent* event) { event->trigger = current_attempt_trigger_; channel_->NotifyListeners(*event); } } // namespace browser_sync <|endoftext|>
<commit_before><commit_msg>Temporarily disable the thumbnail store unittests due to leaks.<commit_after><|endoftext|>
<commit_before>// Copyright (c) 2011 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/ui/gtk/status_bubble_gtk.h" #include <gtk/gtk.h> #include <algorithm> #include "app/text_elider.h" #include "base/i18n/rtl.h" #include "base/message_loop.h" #include "base/utf_string_conversions.h" #include "chrome/browser/ui/gtk/gtk_theme_provider.h" #include "chrome/browser/ui/gtk/gtk_util.h" #include "chrome/browser/ui/gtk/rounded_window.h" #include "chrome/browser/ui/gtk/slide_animator_gtk.h" #include "chrome/common/notification_service.h" #include "ui/base/animation/slide_animation.h" namespace { // Inner padding between the border and the text label. const int kInternalTopBottomPadding = 1; const int kInternalLeftRightPadding = 2; // The radius of the edges of our bubble. const int kCornerSize = 3; // Milliseconds before we hide the status bubble widget when you mouseout. const int kHideDelay = 250; // How close the mouse can get to the infobubble before it starts sliding // off-screen. const int kMousePadding = 20; } // namespace StatusBubbleGtk::StatusBubbleGtk(Profile* profile) : theme_provider_(GtkThemeProvider::GetFrom(profile)), padding_(NULL), label_(NULL), flip_horizontally_(false), y_offset_(0), download_shelf_is_visible_(false), last_mouse_location_(0, 0), last_mouse_left_content_(false), ignore_next_left_content_(false) { InitWidgets(); theme_provider_->InitThemesFor(this); registrar_.Add(this, NotificationType::BROWSER_THEME_CHANGED, NotificationService::AllSources()); } StatusBubbleGtk::~StatusBubbleGtk() { container_.Destroy(); } void StatusBubbleGtk::SetStatus(const string16& status_text_wide) { std::string status_text = UTF16ToUTF8(status_text_wide); if (status_text_ == status_text) return; status_text_ = status_text; if (!status_text_.empty()) SetStatusTextTo(status_text_); else if (!url_text_.empty()) SetStatusTextTo(url_text_); else SetStatusTextTo(std::string()); } void StatusBubbleGtk::SetURL(const GURL& url, const string16& languages) { url_ = url; languages_ = languages; // If we want to clear a displayed URL but there is a status still to // display, display that status instead. if (url.is_empty() && !status_text_.empty()) { url_text_ = std::string(); SetStatusTextTo(status_text_); return; } SetStatusTextToURL(); } void StatusBubbleGtk::SetStatusTextToURL() { GtkWidget* parent = gtk_widget_get_parent(container_.get()); // It appears that parent can be NULL (probably only during shutdown). if (!parent || !GTK_WIDGET_REALIZED(parent)) return; int desired_width = parent->allocation.width; if (!expanded()) { expand_timer_.Stop(); expand_timer_.Start(base::TimeDelta::FromMilliseconds(kExpandHoverDelay), this, &StatusBubbleGtk::ExpandURL); // When not expanded, we limit the size to one third the browser's // width. desired_width /= 3; } // TODO(tc): We don't actually use gfx::Font as the font in the status // bubble. We should extend gfx::ElideUrl to take some sort of pango font. url_text_ = UTF16ToUTF8(gfx::ElideUrl(url_, gfx::Font(), desired_width, UTF16ToWideHack(languages_))); SetStatusTextTo(url_text_); } void StatusBubbleGtk::Show() { // If we were going to hide, stop. hide_timer_.Stop(); gtk_widget_show_all(container_.get()); if (container_->window) gdk_window_raise(container_->window); } void StatusBubbleGtk::Hide() { // If we were going to expand the bubble, stop. expand_timer_.Stop(); expand_animation_.reset(); gtk_widget_hide_all(container_.get()); } void StatusBubbleGtk::SetStatusTextTo(const std::string& status_utf8) { if (status_utf8.empty()) { hide_timer_.Stop(); hide_timer_.Start(base::TimeDelta::FromMilliseconds(kHideDelay), this, &StatusBubbleGtk::Hide); } else { gtk_label_set_text(GTK_LABEL(label_), status_utf8.c_str()); GtkRequisition req; gtk_widget_size_request(label_, &req); desired_width_ = req.width; UpdateLabelSizeRequest(); if (!last_mouse_left_content_) { // Show the padding and label to update our requisition and then // re-process the last mouse event -- if the label was empty before or the // text changed, our size will have changed and we may need to move // ourselves away from the pointer now. gtk_widget_show_all(padding_); MouseMoved(last_mouse_location_, false); } Show(); } } void StatusBubbleGtk::MouseMoved( const gfx::Point& location, bool left_content) { if (left_content && ignore_next_left_content_) { ignore_next_left_content_ = false; return; } last_mouse_location_ = location; last_mouse_left_content_ = left_content; if (!GTK_WIDGET_REALIZED(container_.get())) return; GtkWidget* parent = gtk_widget_get_parent(container_.get()); if (!parent || !GTK_WIDGET_REALIZED(parent)) return; int old_y_offset = y_offset_; bool old_flip_horizontally = flip_horizontally_; if (left_content) { SetFlipHorizontally(false); y_offset_ = 0; } else { GtkWidget* toplevel = gtk_widget_get_toplevel(container_.get()); if (!toplevel || !GTK_WIDGET_REALIZED(toplevel)) return; bool ltr = !base::i18n::IsRTL(); GtkRequisition requisition; gtk_widget_size_request(container_.get(), &requisition); // Get our base position (that is, not including the current offset) // relative to the origin of the root window. gint toplevel_x = 0, toplevel_y = 0; gdk_window_get_position(toplevel->window, &toplevel_x, &toplevel_y); gfx::Rect parent_rect = gtk_util::GetWidgetRectRelativeToToplevel(parent); gfx::Rect bubble_rect( toplevel_x + parent_rect.x() + (ltr ? 0 : parent->allocation.width - requisition.width), toplevel_y + parent_rect.y() + parent->allocation.height - requisition.height, requisition.width, requisition.height); int left_threshold = bubble_rect.x() - bubble_rect.height() - kMousePadding; int right_threshold = bubble_rect.right() + bubble_rect.height() + kMousePadding; int top_threshold = bubble_rect.y() - kMousePadding; if (((ltr && location.x() < right_threshold) || (!ltr && location.x() > left_threshold)) && location.y() > top_threshold) { if (download_shelf_is_visible_) { SetFlipHorizontally(true); y_offset_ = 0; } else { SetFlipHorizontally(false); int distance = std::max(ltr ? location.x() - right_threshold : left_threshold - location.x(), top_threshold - location.y()); y_offset_ = std::min(-1 * distance, requisition.height); } } else { SetFlipHorizontally(false); y_offset_ = 0; } } if (y_offset_ != old_y_offset || flip_horizontally_ != old_flip_horizontally) gtk_widget_queue_resize_no_redraw(parent); } void StatusBubbleGtk::UpdateDownloadShelfVisibility(bool visible) { download_shelf_is_visible_ = visible; } void StatusBubbleGtk::Observe(NotificationType type, const NotificationSource& source, const NotificationDetails& details) { if (type == NotificationType::BROWSER_THEME_CHANGED) { UserChangedTheme(); } } void StatusBubbleGtk::InitWidgets() { bool ltr = !base::i18n::IsRTL(); label_ = gtk_label_new(NULL); padding_ = gtk_alignment_new(0, 0, 1, 1); gtk_alignment_set_padding(GTK_ALIGNMENT(padding_), kInternalTopBottomPadding, kInternalTopBottomPadding, kInternalLeftRightPadding + (ltr ? 0 : kCornerSize), kInternalLeftRightPadding + (ltr ? kCornerSize : 0)); gtk_container_add(GTK_CONTAINER(padding_), label_); container_.Own(gtk_event_box_new()); gtk_util::ActAsRoundedWindow( container_.get(), gtk_util::kGdkWhite, kCornerSize, gtk_util::ROUNDED_TOP_RIGHT, gtk_util::BORDER_TOP | gtk_util::BORDER_RIGHT); gtk_widget_set_name(container_.get(), "status-bubble"); gtk_container_add(GTK_CONTAINER(container_.get()), padding_); // We need to listen for mouse motion events, since a fast-moving pointer may // enter our window without us getting any motion events on the browser near // enough for us to run away. gtk_widget_add_events(container_.get(), GDK_POINTER_MOTION_MASK | GDK_ENTER_NOTIFY_MASK); g_signal_connect(container_.get(), "motion-notify-event", G_CALLBACK(HandleMotionNotifyThunk), this); g_signal_connect(container_.get(), "enter-notify-event", G_CALLBACK(HandleEnterNotifyThunk), this); UserChangedTheme(); } void StatusBubbleGtk::UserChangedTheme() { if (theme_provider_->UseGtkTheme()) { gtk_widget_modify_fg(label_, GTK_STATE_NORMAL, NULL); gtk_widget_modify_bg(container_.get(), GTK_STATE_NORMAL, NULL); } else { // TODO(erg): This is the closest to "text that will look good on a // toolbar" that I can find. Maybe in later iterations of the theme system, // there will be a better color to pick. GdkColor bookmark_text = theme_provider_->GetGdkColor(BrowserThemeProvider::COLOR_BOOKMARK_TEXT); gtk_widget_modify_fg(label_, GTK_STATE_NORMAL, &bookmark_text); GdkColor toolbar_color = theme_provider_->GetGdkColor(BrowserThemeProvider::COLOR_TOOLBAR); gtk_widget_modify_bg(container_.get(), GTK_STATE_NORMAL, &toolbar_color); } gtk_util::SetRoundedWindowBorderColor(container_.get(), theme_provider_->GetBorderColor()); } void StatusBubbleGtk::SetFlipHorizontally(bool flip_horizontally) { if (flip_horizontally == flip_horizontally_) return; flip_horizontally_ = flip_horizontally; bool ltr = !base::i18n::IsRTL(); bool on_left = (ltr && !flip_horizontally) || (!ltr && flip_horizontally); gtk_alignment_set_padding(GTK_ALIGNMENT(padding_), kInternalTopBottomPadding, kInternalTopBottomPadding, kInternalLeftRightPadding + (on_left ? 0 : kCornerSize), kInternalLeftRightPadding + (on_left ? kCornerSize : 0)); // The rounded window code flips these arguments if we're RTL. gtk_util::SetRoundedWindowEdgesAndBorders( container_.get(), kCornerSize, flip_horizontally ? gtk_util::ROUNDED_TOP_LEFT : gtk_util::ROUNDED_TOP_RIGHT, gtk_util::BORDER_TOP | (flip_horizontally ? gtk_util::BORDER_LEFT : gtk_util::BORDER_RIGHT)); gtk_widget_queue_draw(container_.get()); } void StatusBubbleGtk::ExpandURL() { start_width_ = label_->allocation.width; expand_animation_.reset(new ui::SlideAnimation(this)); expand_animation_->SetTweenType(ui::Tween::LINEAR); expand_animation_->Show(); SetStatusTextToURL(); } void StatusBubbleGtk::UpdateLabelSizeRequest() { if (!expanded() || !expand_animation_->is_animating()) { gtk_widget_set_size_request(label_, -1, -1); return; } int new_width = start_width_ + (desired_width_ - start_width_) * expand_animation_->GetCurrentValue(); gtk_widget_set_size_request(label_, new_width, -1); } // See http://crbug.com/68897 for why we have to handle this event. gboolean StatusBubbleGtk::HandleEnterNotify(GtkWidget* sender, GdkEventCrossing* event) { ignore_next_left_content_ = true; MouseMoved(gfx::Point(event->x_root, event->y_root), false); return FALSE; } gboolean StatusBubbleGtk::HandleMotionNotify(GtkWidget* sender, GdkEventMotion* event) { MouseMoved(gfx::Point(event->x_root, event->y_root), false); return FALSE; } void StatusBubbleGtk::AnimationEnded(const ui::Animation* animation) { UpdateLabelSizeRequest(); } void StatusBubbleGtk::AnimationProgressed(const ui::Animation* animation) { UpdateLabelSizeRequest(); } <commit_msg>[gtk] Don't show empty status bubble in kiosk mode.<commit_after>// Copyright (c) 2011 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/ui/gtk/status_bubble_gtk.h" #include <gtk/gtk.h> #include <algorithm> #include "app/text_elider.h" #include "base/i18n/rtl.h" #include "base/message_loop.h" #include "base/utf_string_conversions.h" #include "chrome/browser/ui/gtk/gtk_theme_provider.h" #include "chrome/browser/ui/gtk/gtk_util.h" #include "chrome/browser/ui/gtk/rounded_window.h" #include "chrome/browser/ui/gtk/slide_animator_gtk.h" #include "chrome/common/notification_service.h" #include "ui/base/animation/slide_animation.h" namespace { // Inner padding between the border and the text label. const int kInternalTopBottomPadding = 1; const int kInternalLeftRightPadding = 2; // The radius of the edges of our bubble. const int kCornerSize = 3; // Milliseconds before we hide the status bubble widget when you mouseout. const int kHideDelay = 250; // How close the mouse can get to the infobubble before it starts sliding // off-screen. const int kMousePadding = 20; } // namespace StatusBubbleGtk::StatusBubbleGtk(Profile* profile) : theme_provider_(GtkThemeProvider::GetFrom(profile)), padding_(NULL), label_(NULL), flip_horizontally_(false), y_offset_(0), download_shelf_is_visible_(false), last_mouse_location_(0, 0), last_mouse_left_content_(false), ignore_next_left_content_(false) { InitWidgets(); theme_provider_->InitThemesFor(this); registrar_.Add(this, NotificationType::BROWSER_THEME_CHANGED, NotificationService::AllSources()); } StatusBubbleGtk::~StatusBubbleGtk() { container_.Destroy(); } void StatusBubbleGtk::SetStatus(const string16& status_text_wide) { std::string status_text = UTF16ToUTF8(status_text_wide); if (status_text_ == status_text) return; status_text_ = status_text; if (!status_text_.empty()) SetStatusTextTo(status_text_); else if (!url_text_.empty()) SetStatusTextTo(url_text_); else SetStatusTextTo(std::string()); } void StatusBubbleGtk::SetURL(const GURL& url, const string16& languages) { url_ = url; languages_ = languages; // If we want to clear a displayed URL but there is a status still to // display, display that status instead. if (url.is_empty() && !status_text_.empty()) { url_text_ = std::string(); SetStatusTextTo(status_text_); return; } SetStatusTextToURL(); } void StatusBubbleGtk::SetStatusTextToURL() { GtkWidget* parent = gtk_widget_get_parent(container_.get()); // It appears that parent can be NULL (probably only during shutdown). if (!parent || !GTK_WIDGET_REALIZED(parent)) return; int desired_width = parent->allocation.width; if (!expanded()) { expand_timer_.Stop(); expand_timer_.Start(base::TimeDelta::FromMilliseconds(kExpandHoverDelay), this, &StatusBubbleGtk::ExpandURL); // When not expanded, we limit the size to one third the browser's // width. desired_width /= 3; } // TODO(tc): We don't actually use gfx::Font as the font in the status // bubble. We should extend gfx::ElideUrl to take some sort of pango font. url_text_ = UTF16ToUTF8(gfx::ElideUrl(url_, gfx::Font(), desired_width, UTF16ToWideHack(languages_))); SetStatusTextTo(url_text_); } void StatusBubbleGtk::Show() { // If we were going to hide, stop. hide_timer_.Stop(); gtk_widget_show_all(container_.get()); if (container_->window) gdk_window_raise(container_->window); } void StatusBubbleGtk::Hide() { // If we were going to expand the bubble, stop. expand_timer_.Stop(); expand_animation_.reset(); gtk_widget_hide_all(container_.get()); } void StatusBubbleGtk::SetStatusTextTo(const std::string& status_utf8) { if (status_utf8.empty()) { hide_timer_.Stop(); hide_timer_.Start(base::TimeDelta::FromMilliseconds(kHideDelay), this, &StatusBubbleGtk::Hide); } else { gtk_label_set_text(GTK_LABEL(label_), status_utf8.c_str()); GtkRequisition req; gtk_widget_size_request(label_, &req); desired_width_ = req.width; UpdateLabelSizeRequest(); if (!last_mouse_left_content_) { // Show the padding and label to update our requisition and then // re-process the last mouse event -- if the label was empty before or the // text changed, our size will have changed and we may need to move // ourselves away from the pointer now. gtk_widget_show_all(padding_); MouseMoved(last_mouse_location_, false); } Show(); } } void StatusBubbleGtk::MouseMoved( const gfx::Point& location, bool left_content) { if (left_content && ignore_next_left_content_) { ignore_next_left_content_ = false; return; } last_mouse_location_ = location; last_mouse_left_content_ = left_content; if (!GTK_WIDGET_REALIZED(container_.get())) return; GtkWidget* parent = gtk_widget_get_parent(container_.get()); if (!parent || !GTK_WIDGET_REALIZED(parent)) return; int old_y_offset = y_offset_; bool old_flip_horizontally = flip_horizontally_; if (left_content) { SetFlipHorizontally(false); y_offset_ = 0; } else { GtkWidget* toplevel = gtk_widget_get_toplevel(container_.get()); if (!toplevel || !GTK_WIDGET_REALIZED(toplevel)) return; bool ltr = !base::i18n::IsRTL(); GtkRequisition requisition; gtk_widget_size_request(container_.get(), &requisition); // Get our base position (that is, not including the current offset) // relative to the origin of the root window. gint toplevel_x = 0, toplevel_y = 0; gdk_window_get_position(toplevel->window, &toplevel_x, &toplevel_y); gfx::Rect parent_rect = gtk_util::GetWidgetRectRelativeToToplevel(parent); gfx::Rect bubble_rect( toplevel_x + parent_rect.x() + (ltr ? 0 : parent->allocation.width - requisition.width), toplevel_y + parent_rect.y() + parent->allocation.height - requisition.height, requisition.width, requisition.height); int left_threshold = bubble_rect.x() - bubble_rect.height() - kMousePadding; int right_threshold = bubble_rect.right() + bubble_rect.height() + kMousePadding; int top_threshold = bubble_rect.y() - kMousePadding; if (((ltr && location.x() < right_threshold) || (!ltr && location.x() > left_threshold)) && location.y() > top_threshold) { if (download_shelf_is_visible_) { SetFlipHorizontally(true); y_offset_ = 0; } else { SetFlipHorizontally(false); int distance = std::max(ltr ? location.x() - right_threshold : left_threshold - location.x(), top_threshold - location.y()); y_offset_ = std::min(-1 * distance, requisition.height); } } else { SetFlipHorizontally(false); y_offset_ = 0; } } if (y_offset_ != old_y_offset || flip_horizontally_ != old_flip_horizontally) gtk_widget_queue_resize_no_redraw(parent); } void StatusBubbleGtk::UpdateDownloadShelfVisibility(bool visible) { download_shelf_is_visible_ = visible; } void StatusBubbleGtk::Observe(NotificationType type, const NotificationSource& source, const NotificationDetails& details) { if (type == NotificationType::BROWSER_THEME_CHANGED) { UserChangedTheme(); } } void StatusBubbleGtk::InitWidgets() { bool ltr = !base::i18n::IsRTL(); label_ = gtk_label_new(NULL); padding_ = gtk_alignment_new(0, 0, 1, 1); gtk_alignment_set_padding(GTK_ALIGNMENT(padding_), kInternalTopBottomPadding, kInternalTopBottomPadding, kInternalLeftRightPadding + (ltr ? 0 : kCornerSize), kInternalLeftRightPadding + (ltr ? kCornerSize : 0)); gtk_container_add(GTK_CONTAINER(padding_), label_); container_.Own(gtk_event_box_new()); gtk_widget_set_no_show_all(container_.get(), TRUE); gtk_util::ActAsRoundedWindow( container_.get(), gtk_util::kGdkWhite, kCornerSize, gtk_util::ROUNDED_TOP_RIGHT, gtk_util::BORDER_TOP | gtk_util::BORDER_RIGHT); gtk_widget_set_name(container_.get(), "status-bubble"); gtk_container_add(GTK_CONTAINER(container_.get()), padding_); // We need to listen for mouse motion events, since a fast-moving pointer may // enter our window without us getting any motion events on the browser near // enough for us to run away. gtk_widget_add_events(container_.get(), GDK_POINTER_MOTION_MASK | GDK_ENTER_NOTIFY_MASK); g_signal_connect(container_.get(), "motion-notify-event", G_CALLBACK(HandleMotionNotifyThunk), this); g_signal_connect(container_.get(), "enter-notify-event", G_CALLBACK(HandleEnterNotifyThunk), this); UserChangedTheme(); } void StatusBubbleGtk::UserChangedTheme() { if (theme_provider_->UseGtkTheme()) { gtk_widget_modify_fg(label_, GTK_STATE_NORMAL, NULL); gtk_widget_modify_bg(container_.get(), GTK_STATE_NORMAL, NULL); } else { // TODO(erg): This is the closest to "text that will look good on a // toolbar" that I can find. Maybe in later iterations of the theme system, // there will be a better color to pick. GdkColor bookmark_text = theme_provider_->GetGdkColor(BrowserThemeProvider::COLOR_BOOKMARK_TEXT); gtk_widget_modify_fg(label_, GTK_STATE_NORMAL, &bookmark_text); GdkColor toolbar_color = theme_provider_->GetGdkColor(BrowserThemeProvider::COLOR_TOOLBAR); gtk_widget_modify_bg(container_.get(), GTK_STATE_NORMAL, &toolbar_color); } gtk_util::SetRoundedWindowBorderColor(container_.get(), theme_provider_->GetBorderColor()); } void StatusBubbleGtk::SetFlipHorizontally(bool flip_horizontally) { if (flip_horizontally == flip_horizontally_) return; flip_horizontally_ = flip_horizontally; bool ltr = !base::i18n::IsRTL(); bool on_left = (ltr && !flip_horizontally) || (!ltr && flip_horizontally); gtk_alignment_set_padding(GTK_ALIGNMENT(padding_), kInternalTopBottomPadding, kInternalTopBottomPadding, kInternalLeftRightPadding + (on_left ? 0 : kCornerSize), kInternalLeftRightPadding + (on_left ? kCornerSize : 0)); // The rounded window code flips these arguments if we're RTL. gtk_util::SetRoundedWindowEdgesAndBorders( container_.get(), kCornerSize, flip_horizontally ? gtk_util::ROUNDED_TOP_LEFT : gtk_util::ROUNDED_TOP_RIGHT, gtk_util::BORDER_TOP | (flip_horizontally ? gtk_util::BORDER_LEFT : gtk_util::BORDER_RIGHT)); gtk_widget_queue_draw(container_.get()); } void StatusBubbleGtk::ExpandURL() { start_width_ = label_->allocation.width; expand_animation_.reset(new ui::SlideAnimation(this)); expand_animation_->SetTweenType(ui::Tween::LINEAR); expand_animation_->Show(); SetStatusTextToURL(); } void StatusBubbleGtk::UpdateLabelSizeRequest() { if (!expanded() || !expand_animation_->is_animating()) { gtk_widget_set_size_request(label_, -1, -1); return; } int new_width = start_width_ + (desired_width_ - start_width_) * expand_animation_->GetCurrentValue(); gtk_widget_set_size_request(label_, new_width, -1); } // See http://crbug.com/68897 for why we have to handle this event. gboolean StatusBubbleGtk::HandleEnterNotify(GtkWidget* sender, GdkEventCrossing* event) { ignore_next_left_content_ = true; MouseMoved(gfx::Point(event->x_root, event->y_root), false); return FALSE; } gboolean StatusBubbleGtk::HandleMotionNotify(GtkWidget* sender, GdkEventMotion* event) { MouseMoved(gfx::Point(event->x_root, event->y_root), false); return FALSE; } void StatusBubbleGtk::AnimationEnded(const ui::Animation* animation) { UpdateLabelSizeRequest(); } void StatusBubbleGtk::AnimationProgressed(const ui::Animation* animation) { UpdateLabelSizeRequest(); } <|endoftext|>
<commit_before>#include "ffmpeg_video_source.h" extern "C" { #include <libavutil/imgutils.h> } namespace gg { VideoSourceFFmpeg::VideoSourceFFmpeg() { // nop } VideoSourceFFmpeg::VideoSourceFFmpeg(std::string source_path, enum ColourSpace colour_space, bool use_refcount) : IVideoSource(colour_space) , _source_path(source_path) , _avformat_context(nullptr) , _avstream_idx(-1) , _use_refcount(use_refcount) , _avcodec_context(nullptr) , _avframe(nullptr) , _avframe_converted(nullptr) , _sws_context(nullptr) , _daemon(nullptr) { int ret = 0; std::string error_msg = ""; av_register_all(); ret = avformat_open_input(&_avformat_context, _source_path.c_str(), nullptr, nullptr); if (ret < 0) { error_msg.append("Could not open video source ") .append(_source_path) .append(get_ffmpeg_error_desc(ret)); throw VideoSourceError(error_msg); } ret = avformat_find_stream_info(_avformat_context, nullptr); if (ret < 0) { error_msg.append("Could not find stream information") .append(get_ffmpeg_error_desc(ret)); throw VideoSourceError(error_msg); } ret = open_codec_context(&_avstream_idx, _avformat_context, AVMEDIA_TYPE_VIDEO, error_msg); if (ret < 0) { error_msg.append(get_ffmpeg_error_desc(ret)); throw VideoSourceError(error_msg); } _avcodec_context = _avformat_context->streams[_avstream_idx]->codec; /* allocate image where the decoded image will be put */ if (_avformat_context->streams[_avstream_idx] == nullptr) throw VideoSourceError("Could not find video stream in source"); _avframe = av_frame_alloc(); if (_avframe == nullptr) throw VideoSourceError("Could not allocate frame"); /* initialize packet, set data to NULL, let the demuxer fill it */ av_init_packet(&_avpacket); _avpacket.data = nullptr; _avpacket.size = 0; AVPixelFormat target_avpixel_format; int sws_flags = 0; switch(_colour) { case BGRA: target_avpixel_format = AV_PIX_FMT_BGRA; break; case I420: target_avpixel_format = AV_PIX_FMT_YUV420P; break; case UYVY: target_avpixel_format = AV_PIX_FMT_UYVY422; break; default: throw VideoSourceError("Target colour space not supported"); } if (_avcodec_context->pix_fmt != target_avpixel_format) { _avframe_converted = av_frame_alloc(); if (_avframe_converted == nullptr) throw VideoSourceError("Could not allocate conversion frame"); _avframe_converted->format = target_avpixel_format; _avframe_converted->width = _avcodec_context->width; _avframe_converted->height = _avcodec_context->height; int pixel_depth; switch(target_avpixel_format) { case AV_PIX_FMT_BGRA: pixel_depth = 32; // bits-per-pixel break; case AV_PIX_FMT_YUV420P: pixel_depth = 12; // bits-per-pixel break; case AV_PIX_FMT_UYVY422: pixel_depth = 16; // bits-per-pixel break; default: throw VideoSourceError("Colour space not supported"); } ret = av_frame_get_buffer(_avframe_converted, pixel_depth); if (ret < 0) { error_msg.append("Could not allocate conversion buffer") .append(get_ffmpeg_error_desc(ret)); throw VideoSourceError(error_msg); } _sws_context = sws_getContext( _avcodec_context->width, _avcodec_context->height, _avcodec_context->pix_fmt, _avcodec_context->width, _avcodec_context->height, target_avpixel_format, sws_flags, nullptr, nullptr, nullptr); if (_sws_context == nullptr) throw VideoSourceError("Could not allocate Sws context"); } ret = av_image_alloc(_data_buffer, _data_buffer_linesizes, _avcodec_context->width, _avcodec_context->height, target_avpixel_format, 1); if (ret < 0) { error_msg.append("Could not allocate raw video buffer") .append(get_ffmpeg_error_desc(ret)); throw VideoSourceError(error_msg); } _data_buffer_length = ret; _daemon = new gg::BroadcastDaemon(this); _daemon->start(get_frame_rate()); } VideoSourceFFmpeg::~VideoSourceFFmpeg() { delete _daemon; if (_sws_context != nullptr) sws_freeContext(_sws_context); avcodec_close(_avcodec_context); avformat_close_input(&_avformat_context); av_frame_free(&_avframe); if (_avframe_converted != nullptr) av_frame_free(&_avframe_converted); av_free(_data_buffer[0]); _data_buffer_length = 0; } bool VideoSourceFFmpeg::get_frame_dimensions(int & width, int & height) { if (_avcodec_context->width > 0 and _avcodec_context->height > 0) { width = _avcodec_context->width; height = _avcodec_context->height; return true; } else return false; } bool VideoSourceFFmpeg::get_frame(VideoFrame & frame) { if (av_read_frame(_avformat_context, &_avpacket) < 0) return false; int ret = 0, got_frame; bool success = true; AVPacket orig_pkt = _avpacket; do { ret = decode_packet(&got_frame, 0); if (ret < 0) { success = false; break; } _avpacket.data += ret; _avpacket.size -= ret; } while (_avpacket.size > 0); av_packet_unref(&orig_pkt); // need to convert pixel format? AVFrame * avframe_ptr = nullptr; if (_sws_context != nullptr) { ret = sws_scale(_sws_context, _avframe->data, _avframe->linesize, 0, _avcodec_context->height, _avframe_converted->data, _avframe_converted->linesize ); if (ret <= 0) success = false; avframe_ptr = _avframe_converted; } else { avframe_ptr = _avframe; } /* copy decoded frame to destination buffer: * this is required since rawvideo expects non aligned data */ av_image_copy(_data_buffer, _data_buffer_linesizes, const_cast<const uint8_t **>(avframe_ptr->data), avframe_ptr->linesize, static_cast<AVPixelFormat>(avframe_ptr->format), _avcodec_context->width, _avcodec_context->height); if (not success) return false; frame.init_from_specs(_data_buffer[0], _data_buffer_length, _avcodec_context->width, _avcodec_context->height); return true; } double VideoSourceFFmpeg::get_frame_rate() { int num = _avformat_context->streams[_avstream_idx]->avg_frame_rate.num; int den = _avformat_context->streams[_avstream_idx]->avg_frame_rate.den; if (num == 0) return 0.0; return static_cast<double>(num) / den; } void VideoSourceFFmpeg::set_sub_frame(int x, int y, int width, int height) { // TODO } void VideoSourceFFmpeg::get_full_frame() { // TODO } int VideoSourceFFmpeg::open_codec_context( int * stream_idx, AVFormatContext * fmt_ctx, enum AVMediaType type, std::string & error_msg) { int ret, stream_index; AVStream * st; AVCodecContext * dec_ctx = nullptr; AVCodec * dec = nullptr; AVDictionary * opts = nullptr; ret = av_find_best_stream(fmt_ctx, type, -1, -1, nullptr, 0); if (ret < 0) { error_msg.append("Could not find ") .append(av_get_media_type_string(type)) .append(" stream in source ") .append(_source_path); return ret; } else { stream_index = ret; st = fmt_ctx->streams[stream_index]; /* find decoder for the stream */ dec_ctx = st->codec; dec = avcodec_find_decoder(dec_ctx->codec_id); if (!dec) { error_msg.append("Failed to find ") .append(av_get_media_type_string(type)) .append(" codec"); return AVERROR(EINVAL); } /* Init the decoders, with or without reference counting */ av_dict_set(&opts, "refcounted_frames", _use_refcount ? "1" : "0", 0); if ((ret = avcodec_open2(dec_ctx, dec, &opts)) < 0) { error_msg.append("Failed to open ") .append(av_get_media_type_string(type)) .append(" codec"); return ret; } *stream_idx = stream_index; } return 0; } int VideoSourceFFmpeg::decode_packet(int * got_frame, int cached) { int ret = 0; int decoded = 0; *got_frame = 0; if (_avpacket.stream_index == _avstream_idx) { /* decode video frame */ ret = avcodec_decode_video2(_avcodec_context, _avframe, got_frame, &_avpacket); if (ret < 0) return ret; if (*got_frame) { if (_avframe->width != _avcodec_context->width or _avframe->height != _avcodec_context->height or _avframe->format != _avcodec_context->pix_fmt) return -1; decoded = ret; } } /* If we use frame reference counting, we own the data and need * to de-reference it when we don't use it anymore */ if (*got_frame and _use_refcount) av_frame_unref(_avframe); return decoded; } std::string VideoSourceFFmpeg::get_ffmpeg_error_desc(int ffmpeg_error_code) { const size_t FFMPEG_ERR_MSG_SIZE = 2048; char ffmpeg_err_msg[FFMPEG_ERR_MSG_SIZE]; std::string ffmpeg_error_desc = ""; if (av_strerror(ffmpeg_error_code, ffmpeg_err_msg, FFMPEG_ERR_MSG_SIZE) == 0) ffmpeg_error_desc.append(" (FFmpeg error description: ") .append(std::string(ffmpeg_err_msg)) .append(")"); else ffmpeg_error_desc.append(" (No specific error description" " could be obtained from FFmpeg)"); return ffmpeg_error_desc; } } <commit_msg>Issue #74: fixed illogical order of checking stream allocated<commit_after>#include "ffmpeg_video_source.h" extern "C" { #include <libavutil/imgutils.h> } namespace gg { VideoSourceFFmpeg::VideoSourceFFmpeg() { // nop } VideoSourceFFmpeg::VideoSourceFFmpeg(std::string source_path, enum ColourSpace colour_space, bool use_refcount) : IVideoSource(colour_space) , _source_path(source_path) , _avformat_context(nullptr) , _avstream_idx(-1) , _use_refcount(use_refcount) , _avcodec_context(nullptr) , _avframe(nullptr) , _avframe_converted(nullptr) , _sws_context(nullptr) , _daemon(nullptr) { int ret = 0; std::string error_msg = ""; av_register_all(); ret = avformat_open_input(&_avformat_context, _source_path.c_str(), nullptr, nullptr); if (ret < 0) { error_msg.append("Could not open video source ") .append(_source_path) .append(get_ffmpeg_error_desc(ret)); throw VideoSourceError(error_msg); } ret = avformat_find_stream_info(_avformat_context, nullptr); if (ret < 0) { error_msg.append("Could not find stream information") .append(get_ffmpeg_error_desc(ret)); throw VideoSourceError(error_msg); } ret = open_codec_context(&_avstream_idx, _avformat_context, AVMEDIA_TYPE_VIDEO, error_msg); if (ret < 0) { error_msg.append(get_ffmpeg_error_desc(ret)); throw VideoSourceError(error_msg); } if (_avformat_context->streams[_avstream_idx] == nullptr) throw VideoSourceError("Could not find video stream in source"); _avcodec_context = _avformat_context->streams[_avstream_idx]->codec; /* allocate image where the decoded image will be put */ _avframe = av_frame_alloc(); if (_avframe == nullptr) throw VideoSourceError("Could not allocate frame"); /* initialize packet, set data to NULL, let the demuxer fill it */ av_init_packet(&_avpacket); _avpacket.data = nullptr; _avpacket.size = 0; AVPixelFormat target_avpixel_format; int sws_flags = 0; switch(_colour) { case BGRA: target_avpixel_format = AV_PIX_FMT_BGRA; break; case I420: target_avpixel_format = AV_PIX_FMT_YUV420P; break; case UYVY: target_avpixel_format = AV_PIX_FMT_UYVY422; break; default: throw VideoSourceError("Target colour space not supported"); } if (_avcodec_context->pix_fmt != target_avpixel_format) { _avframe_converted = av_frame_alloc(); if (_avframe_converted == nullptr) throw VideoSourceError("Could not allocate conversion frame"); _avframe_converted->format = target_avpixel_format; _avframe_converted->width = _avcodec_context->width; _avframe_converted->height = _avcodec_context->height; int pixel_depth; switch(target_avpixel_format) { case AV_PIX_FMT_BGRA: pixel_depth = 32; // bits-per-pixel break; case AV_PIX_FMT_YUV420P: pixel_depth = 12; // bits-per-pixel break; case AV_PIX_FMT_UYVY422: pixel_depth = 16; // bits-per-pixel break; default: throw VideoSourceError("Colour space not supported"); } ret = av_frame_get_buffer(_avframe_converted, pixel_depth); if (ret < 0) { error_msg.append("Could not allocate conversion buffer") .append(get_ffmpeg_error_desc(ret)); throw VideoSourceError(error_msg); } _sws_context = sws_getContext( _avcodec_context->width, _avcodec_context->height, _avcodec_context->pix_fmt, _avcodec_context->width, _avcodec_context->height, target_avpixel_format, sws_flags, nullptr, nullptr, nullptr); if (_sws_context == nullptr) throw VideoSourceError("Could not allocate Sws context"); } ret = av_image_alloc(_data_buffer, _data_buffer_linesizes, _avcodec_context->width, _avcodec_context->height, target_avpixel_format, 1); if (ret < 0) { error_msg.append("Could not allocate raw video buffer") .append(get_ffmpeg_error_desc(ret)); throw VideoSourceError(error_msg); } _data_buffer_length = ret; _daemon = new gg::BroadcastDaemon(this); _daemon->start(get_frame_rate()); } VideoSourceFFmpeg::~VideoSourceFFmpeg() { delete _daemon; if (_sws_context != nullptr) sws_freeContext(_sws_context); avcodec_close(_avcodec_context); avformat_close_input(&_avformat_context); av_frame_free(&_avframe); if (_avframe_converted != nullptr) av_frame_free(&_avframe_converted); av_free(_data_buffer[0]); _data_buffer_length = 0; } bool VideoSourceFFmpeg::get_frame_dimensions(int & width, int & height) { if (_avcodec_context->width > 0 and _avcodec_context->height > 0) { width = _avcodec_context->width; height = _avcodec_context->height; return true; } else return false; } bool VideoSourceFFmpeg::get_frame(VideoFrame & frame) { if (av_read_frame(_avformat_context, &_avpacket) < 0) return false; int ret = 0, got_frame; bool success = true; AVPacket orig_pkt = _avpacket; do { ret = decode_packet(&got_frame, 0); if (ret < 0) { success = false; break; } _avpacket.data += ret; _avpacket.size -= ret; } while (_avpacket.size > 0); av_packet_unref(&orig_pkt); // need to convert pixel format? AVFrame * avframe_ptr = nullptr; if (_sws_context != nullptr) { ret = sws_scale(_sws_context, _avframe->data, _avframe->linesize, 0, _avcodec_context->height, _avframe_converted->data, _avframe_converted->linesize ); if (ret <= 0) success = false; avframe_ptr = _avframe_converted; } else { avframe_ptr = _avframe; } /* copy decoded frame to destination buffer: * this is required since rawvideo expects non aligned data */ av_image_copy(_data_buffer, _data_buffer_linesizes, const_cast<const uint8_t **>(avframe_ptr->data), avframe_ptr->linesize, static_cast<AVPixelFormat>(avframe_ptr->format), _avcodec_context->width, _avcodec_context->height); if (not success) return false; frame.init_from_specs(_data_buffer[0], _data_buffer_length, _avcodec_context->width, _avcodec_context->height); return true; } double VideoSourceFFmpeg::get_frame_rate() { int num = _avformat_context->streams[_avstream_idx]->avg_frame_rate.num; int den = _avformat_context->streams[_avstream_idx]->avg_frame_rate.den; if (num == 0) return 0.0; return static_cast<double>(num) / den; } void VideoSourceFFmpeg::set_sub_frame(int x, int y, int width, int height) { // TODO } void VideoSourceFFmpeg::get_full_frame() { // TODO } int VideoSourceFFmpeg::open_codec_context( int * stream_idx, AVFormatContext * fmt_ctx, enum AVMediaType type, std::string & error_msg) { int ret, stream_index; AVStream * st; AVCodecContext * dec_ctx = nullptr; AVCodec * dec = nullptr; AVDictionary * opts = nullptr; ret = av_find_best_stream(fmt_ctx, type, -1, -1, nullptr, 0); if (ret < 0) { error_msg.append("Could not find ") .append(av_get_media_type_string(type)) .append(" stream in source ") .append(_source_path); return ret; } else { stream_index = ret; st = fmt_ctx->streams[stream_index]; /* find decoder for the stream */ dec_ctx = st->codec; dec = avcodec_find_decoder(dec_ctx->codec_id); if (!dec) { error_msg.append("Failed to find ") .append(av_get_media_type_string(type)) .append(" codec"); return AVERROR(EINVAL); } /* Init the decoders, with or without reference counting */ av_dict_set(&opts, "refcounted_frames", _use_refcount ? "1" : "0", 0); if ((ret = avcodec_open2(dec_ctx, dec, &opts)) < 0) { error_msg.append("Failed to open ") .append(av_get_media_type_string(type)) .append(" codec"); return ret; } *stream_idx = stream_index; } return 0; } int VideoSourceFFmpeg::decode_packet(int * got_frame, int cached) { int ret = 0; int decoded = 0; *got_frame = 0; if (_avpacket.stream_index == _avstream_idx) { /* decode video frame */ ret = avcodec_decode_video2(_avcodec_context, _avframe, got_frame, &_avpacket); if (ret < 0) return ret; if (*got_frame) { if (_avframe->width != _avcodec_context->width or _avframe->height != _avcodec_context->height or _avframe->format != _avcodec_context->pix_fmt) return -1; decoded = ret; } } /* If we use frame reference counting, we own the data and need * to de-reference it when we don't use it anymore */ if (*got_frame and _use_refcount) av_frame_unref(_avframe); return decoded; } std::string VideoSourceFFmpeg::get_ffmpeg_error_desc(int ffmpeg_error_code) { const size_t FFMPEG_ERR_MSG_SIZE = 2048; char ffmpeg_err_msg[FFMPEG_ERR_MSG_SIZE]; std::string ffmpeg_error_desc = ""; if (av_strerror(ffmpeg_error_code, ffmpeg_err_msg, FFMPEG_ERR_MSG_SIZE) == 0) ffmpeg_error_desc.append(" (FFmpeg error description: ") .append(std::string(ffmpeg_err_msg)) .append(")"); else ffmpeg_error_desc.append(" (No specific error description" " could be obtained from FFmpeg)"); return ffmpeg_error_desc; } } <|endoftext|>
<commit_before>/***************************************************************************** * Media Library ***************************************************************************** * Copyright (C) 2015 Hugo Beauzée-Luyssen, Videolabs * * Authors: Hugo Beauzée-Luyssen<hugo@beauzee.fr> * * 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 Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA. *****************************************************************************/ #if HAVE_CONFIG_H # include "config.h" #endif #include "Directory.h" #include "utils/Charsets.h" #include "utils/Filename.h" #include "factory/IFileSystem.h" #include "File.h" #include "logging/Logger.h" #include <sys/types.h> #include <sys/stat.h> #include <windows.h> #include <winapifamily.h> namespace medialibrary { namespace fs { Directory::Directory( const std::string& mrl , factory::IFileSystem& fsFactory ) : CommonDirectory( fsFactory ) , m_mrl( mrl ) { } const std::string& Directory::mrl() const { return m_mrl; } void Directory::read() const { const auto path = toAbsolute( utils::file::toLocalPath( m_mrl ) ); #if WINAPI_FAMILY_PARTITION (WINAPI_PARTITION_DESKTOP) WIN32_FIND_DATA f; auto pattern = path + '*'; auto wpattern = charset::ToWide( pattern.c_str() ); auto h = FindFirstFile( wpattern.get(), &f ); if ( h == INVALID_HANDLE_VALUE ) { LOG_ERROR( "Failed to browse ", path ); throw std::system_error( GetLastError(), std::generic_category(), "Failed to browse through directory" ); } do { auto file = charset::FromWide( f.cFileName ); if ( file[0] == '.' ) continue; auto fullpath = path + file.get(); if ( ( f.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY ) != 0 ) m_dirs.emplace_back( m_fsFactory.createDirectory( utils::file::toUri( fullpath ) ) ); else m_files.emplace_back( std::make_shared<File>( fullpath ) ); } while ( FindNextFile( h, &f ) != 0 ); FindClose( h ); #else // We must remove the trailing / // https://msdn.microsoft.com/en-us/library/windows/desktop/aa363858(v=vs.85).aspx // «Do not use a trailing backslash (\), which indicates the root directory of a drive» assert( *path.rbegin() == '\\' ); auto tmpPath = path.substr( 0, path.length() - 1 ); auto wpath = charset::ToWide( tmpPath.c_str() ); CREATEFILE2_EXTENDED_PARAMETERS params{}; params.dwFileFlags = FILE_FLAG_BACKUP_SEMANTICS; auto handle = CreateFile2( wpath.get(), GENERIC_READ, FILE_SHARE_READ, OPEN_EXISTING, &params ); if ( handle == INVALID_HANDLE_VALUE ) { LOG_ERROR( "Failed to open directory ", path ); throw std::system_error( GetLastError(), std::generic_category(), "Failed to open directory" ); } std::unique_ptr<typename std::remove_pointer<HANDLE>::type, decltype(&CloseHandle)> handlePtr( handle, &CloseHandle ); // Allocating a 32 bytes buffer to contain the file name. If more is required, we'll allocate size_t buffSize = sizeof( FILE_FULL_DIR_INFO ) + 32; std::unique_ptr<FILE_FULL_DIR_INFO, void(*)(FILE_FULL_DIR_INFO*)> dirInfo( reinterpret_cast<FILE_FULL_DIR_INFO*>( malloc( buffSize ) ), [](FILE_FULL_DIR_INFO* ptr) { free( ptr ); } ); if ( dirInfo == nullptr ) throw std::bad_alloc(); while ( true ) { auto h = GetFileInformationByHandleEx( handle, FileFullDirectoryInfo, dirInfo.get(), buffSize ); if ( h == 0 ) { auto error = GetLastError(); if ( error == ERROR_FILE_NOT_FOUND ) break; else if ( error == ERROR_MORE_DATA ) { buffSize *= 2; dirInfo.reset( reinterpret_cast<FILE_FULL_DIR_INFO*>( malloc( buffSize ) ) ); if ( dirInfo == nullptr ) throw std::bad_alloc(); continue; } LOG_ERROR( "Failed to browse ", path, ". GetLastError(): ", GetLastError() ); throw std::system_error( GetLastError(), std::generic_category(), "Failed to browse through directory" ); } auto file = charset::FromWide( dirInfo->FileName ); if ( file[0] == '.' && strcasecmp( file.get(), ".nomedia" ) ) continue; auto path = path + file.get(); if ( ( dirInfo->FileAttributes & FILE_ATTRIBUTE_DIRECTORY ) != 0 ) m_dirs.emplace_back( m_fsFactory.createDirectory( utils::file::toMrl( path ) ) ); else m_files.emplace_back( std::make_shared<File>( path ) ); } #endif } std::string Directory::toAbsolute( const std::string& path ) { TCHAR buff[MAX_PATH]; auto wpath = charset::ToWide( path.c_str() ); if ( GetFullPathName( wpath.get(), MAX_PATH, buff, nullptr ) == 0 ) { LOG_ERROR( "Failed to convert ", path, " to absolute path" ); throw std::system_error( GetLastError(), std::generic_category(), "Failed to convert to absolute path" ); } auto upath = charset::FromWide( buff ); return std::string( upath.get() ); } } } <commit_msg>win32: Directory: Fix build<commit_after>/***************************************************************************** * Media Library ***************************************************************************** * Copyright (C) 2015 Hugo Beauzée-Luyssen, Videolabs * * Authors: Hugo Beauzée-Luyssen<hugo@beauzee.fr> * * 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 Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA. *****************************************************************************/ #if HAVE_CONFIG_H # include "config.h" #endif #include "Directory.h" #include "utils/Charsets.h" #include "utils/Filename.h" #include "factory/IFileSystem.h" #include "File.h" #include "logging/Logger.h" #include <sys/types.h> #include <sys/stat.h> #include <windows.h> #include <winapifamily.h> namespace medialibrary { namespace fs { Directory::Directory( const std::string& mrl , factory::IFileSystem& fsFactory ) : CommonDirectory( fsFactory ) , m_mrl( mrl ) { } const std::string& Directory::mrl() const { return m_mrl; } void Directory::read() const { const auto path = toAbsolute( utils::file::toLocalPath( m_mrl ) ); #if WINAPI_FAMILY_PARTITION (WINAPI_PARTITION_DESKTOP) WIN32_FIND_DATA f; auto pattern = path + '*'; auto wpattern = charset::ToWide( pattern.c_str() ); auto h = FindFirstFile( wpattern.get(), &f ); if ( h == INVALID_HANDLE_VALUE ) { LOG_ERROR( "Failed to browse ", path ); throw std::system_error( GetLastError(), std::generic_category(), "Failed to browse through directory" ); } do { auto file = charset::FromWide( f.cFileName ); if ( file[0] == '.' ) continue; auto fullpath = path + file.get(); if ( ( f.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY ) != 0 ) m_dirs.emplace_back( m_fsFactory.createDirectory( utils::file::toMrl( fullpath ) ) ); else m_files.emplace_back( std::make_shared<File>( fullpath ) ); } while ( FindNextFile( h, &f ) != 0 ); FindClose( h ); #else // We must remove the trailing / // https://msdn.microsoft.com/en-us/library/windows/desktop/aa363858(v=vs.85).aspx // «Do not use a trailing backslash (\), which indicates the root directory of a drive» assert( *path.rbegin() == '\\' ); auto tmpPath = path.substr( 0, path.length() - 1 ); auto wpath = charset::ToWide( tmpPath.c_str() ); CREATEFILE2_EXTENDED_PARAMETERS params{}; params.dwFileFlags = FILE_FLAG_BACKUP_SEMANTICS; auto handle = CreateFile2( wpath.get(), GENERIC_READ, FILE_SHARE_READ, OPEN_EXISTING, &params ); if ( handle == INVALID_HANDLE_VALUE ) { LOG_ERROR( "Failed to open directory ", path ); throw std::system_error( GetLastError(), std::generic_category(), "Failed to open directory" ); } std::unique_ptr<typename std::remove_pointer<HANDLE>::type, decltype(&CloseHandle)> handlePtr( handle, &CloseHandle ); // Allocating a 32 bytes buffer to contain the file name. If more is required, we'll allocate size_t buffSize = sizeof( FILE_FULL_DIR_INFO ) + 32; std::unique_ptr<FILE_FULL_DIR_INFO, void(*)(FILE_FULL_DIR_INFO*)> dirInfo( reinterpret_cast<FILE_FULL_DIR_INFO*>( malloc( buffSize ) ), [](FILE_FULL_DIR_INFO* ptr) { free( ptr ); } ); if ( dirInfo == nullptr ) throw std::bad_alloc(); while ( true ) { auto h = GetFileInformationByHandleEx( handle, FileFullDirectoryInfo, dirInfo.get(), buffSize ); if ( h == 0 ) { auto error = GetLastError(); if ( error == ERROR_FILE_NOT_FOUND ) break; else if ( error == ERROR_MORE_DATA ) { buffSize *= 2; dirInfo.reset( reinterpret_cast<FILE_FULL_DIR_INFO*>( malloc( buffSize ) ) ); if ( dirInfo == nullptr ) throw std::bad_alloc(); continue; } LOG_ERROR( "Failed to browse ", path, ". GetLastError(): ", GetLastError() ); throw std::system_error( GetLastError(), std::generic_category(), "Failed to browse through directory" ); } auto file = charset::FromWide( dirInfo->FileName ); if ( file[0] == '.' && strcasecmp( file.get(), ".nomedia" ) ) continue; auto path = path + file.get(); if ( ( dirInfo->FileAttributes & FILE_ATTRIBUTE_DIRECTORY ) != 0 ) m_dirs.emplace_back( m_fsFactory.createDirectory( utils::file::toMrl( path ) ) ); else m_files.emplace_back( std::make_shared<File>( path ) ); } #endif } std::string Directory::toAbsolute( const std::string& path ) { TCHAR buff[MAX_PATH]; auto wpath = charset::ToWide( path.c_str() ); if ( GetFullPathName( wpath.get(), MAX_PATH, buff, nullptr ) == 0 ) { LOG_ERROR( "Failed to convert ", path, " to absolute path" ); throw std::system_error( GetLastError(), std::generic_category(), "Failed to convert to absolute path" ); } auto upath = charset::FromWide( buff ); return std::string( upath.get() ); } } } <|endoftext|>
<commit_before>/* * Copyright (c) 2018 Airbus Defence and Space and RISC Software GmbH * * 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 "CCPACSSkinSegment.h" #include <TopoDS_Face.hxx> #include <TopoDS_Edge.hxx> #include <BRep_Tool.hxx> #include <BRepExtrema_ExtCC.hxx> #include <TopExp.hxx> #include <BRepTools.hxx> #include <Bnd_Box.hxx> #include <BRepBndLib.hxx> #include <TopTools_IndexedMapOfShape.hxx> #include <Geom_Surface.hxx> #include "generated/CPACSSkinSegments.h" #include "CCPACSFrame.h" #include "CCPACSFuselageStringer.h" #include "CTiglError.h" #include "CCPACSFuselage.h" #include "CTiglUIDManager.h" #include "CNamedShape.h" #include "tiglcommonfunctions.h" namespace tigl { CCPACSSkinSegment::CCPACSSkinSegment(CCPACSSkinSegments* parent, CTiglUIDManager* uidMgr) : generated::CPACSSkinSegment(parent, uidMgr) { } void CCPACSSkinSegment::Invalidate() { m_borderCache = boost::none; } bool CCPACSSkinSegment::Contains(const TopoDS_Face& face) { double u_min = 0., u_max = 0., v_min = 0., v_max = 0.; BRepTools::UVBounds(face, u_min, u_max, v_min, v_max); Handle(Geom_Surface) testSurf = BRep_Tool::Surface(face); gp_Pnt point = testSurf->Value(u_min + ((u_max - u_min) / 2), v_min + ((v_max - v_min) / 2)); return Contains(point); } bool CCPACSSkinSegment::Contains(const TopoDS_Edge& edge) { double u_min = 0., u_max = 0.; Handle(Geom_Curve) curve = BRep_Tool::Curve(edge, u_min, u_max); gp_Pnt point = curve->Value(u_min + ((u_max - u_min) / 2)); return Contains(point); } bool CCPACSSkinSegment::Contains(const gp_Pnt& point) { if (!m_borderCache) UpdateBorders(); const double angleLower = Radians(45.); const double angleUpper = Radians(89.); const BorderCache& c = m_borderCache.value(); if (gp_Ax1(c.sFrame_sStringer.Location(), gp_Vec(c.sFrame_sStringer.Location(), point)).Angle(c.sFrame_sStringer) >= angleLower) return false; if (gp_Ax1(c.sFrame_eStringer.Location(), gp_Vec(c.sFrame_eStringer.Location(), point)).Angle(c.sFrame_eStringer) >= angleLower) return false; if (gp_Ax1(c.eFrame_sStringer.Location(), gp_Vec(c.eFrame_sStringer.Location(), point)).Angle(c.eFrame_sStringer) >= angleLower) return false; if (gp_Ax1(c.eFrame_eStringer.Location(), gp_Vec(c.eFrame_eStringer.Location(), point)).Angle(c.eFrame_eStringer) >= angleLower) return false; const gp_Pnt p1 = (c.sFrame_sStringer.Location().XYZ() + c.eFrame_sStringer.Location().XYZ()) / 2; const gp_Pnt p2 = (c.eFrame_sStringer.Location().XYZ() + c.eFrame_eStringer.Location().XYZ()) / 2; const gp_Pnt p3 = (c.eFrame_eStringer.Location().XYZ() + c.sFrame_eStringer.Location().XYZ()) / 2; const gp_Pnt p4 = (c.sFrame_eStringer.Location().XYZ() + c.sFrame_sStringer.Location().XYZ()) / 2; const gp_Pnt p5 = (c.sFrame_sStringer.Location().XYZ() + c.eFrame_eStringer.Location().XYZ()) / 2; Bnd_Box boundingBox; BRepBndLib::Add(m_parent->GetParent()->GetParent()->GetParent()->GetLoft()->Shape(), boundingBox); const double yMid = (boundingBox.CornerMax().Y() + boundingBox.CornerMin().Y()) / 2; const gp_Pnt p6(p5.X(), yMid, p5.Z()); const gp_Ax1 ref1(p1, gp_Vec(p1, p3)); const gp_Ax1 ref2(p2, gp_Vec(p2, p4)); const gp_Ax1 ref3(p3, gp_Vec(p3, p1)); const gp_Ax1 ref4(p4, gp_Vec(p4, p2)); const gp_Ax1 ref5(p6, gp_Vec(p6, p5)); if (gp_Ax1(p1, gp_Vec(p1, point)).Angle(ref1) >= angleUpper) return false; if (gp_Ax1(p2, gp_Vec(p2, point)).Angle(ref2) >= angleUpper) return false; if (gp_Ax1(p3, gp_Vec(p3, point)).Angle(ref3) >= angleUpper) return false; if (gp_Ax1(p4, gp_Vec(p4, point)).Angle(ref4) >= angleUpper) return false; double maxAngle = 0; maxAngle = std::max(maxAngle, gp_Ax1(p6, gp_Vec(p6, c.sFrame_sStringer.Location())).Angle(ref5)); maxAngle = std::max(maxAngle, gp_Ax1(p6, gp_Vec(p6, c.eFrame_sStringer.Location())).Angle(ref5)); maxAngle = std::max(maxAngle, gp_Ax1(p6, gp_Vec(p6, c.sFrame_eStringer.Location())).Angle(ref5)); maxAngle = std::max(maxAngle, gp_Ax1(p6, gp_Vec(p6, c.eFrame_eStringer.Location())).Angle(ref5)); return gp_Ax1(p6, gp_Vec(p6, point)).Angle(ref5) < maxAngle; } void CCPACSSkinSegment::UpdateBorders() { try { CCPACSFrame& sFrame = m_uidMgr->ResolveObject<CCPACSFrame>(m_startFrameUID); CCPACSFrame& eFrame = m_uidMgr->ResolveObject<CCPACSFrame>(m_endFrameUID); CCPACSFuselageStringer& sStringer = m_uidMgr->ResolveObject<CCPACSFuselageStringer>(m_startStringerUID); CCPACSFuselageStringer& eStringer = m_uidMgr->ResolveObject<CCPACSFuselageStringer>(m_endStringerUID.value()); m_borderCache = BorderCache(); BorderCache& c = *m_borderCache; // get the intersection points between stringer and frames UpdateBorder(c.sFrame_sStringer, sFrame.GetGeometry(true), sStringer.GetGeometry(true)); UpdateBorder(c.sFrame_eStringer, sFrame.GetGeometry(true), eStringer.GetGeometry(true)); UpdateBorder(c.eFrame_sStringer, eFrame.GetGeometry(true), sStringer.GetGeometry(true)); UpdateBorder(c.eFrame_eStringer, eFrame.GetGeometry(true), eStringer.GetGeometry(true)); // generate directions to the opposite intersection point c.sFrame_sStringer.SetDirection(gp_Vec(c.sFrame_sStringer.Location(), c.eFrame_eStringer.Location())); c.sFrame_eStringer.SetDirection(gp_Vec(c.sFrame_eStringer.Location(), c.eFrame_sStringer.Location())); c.eFrame_sStringer.SetDirection(gp_Vec(c.eFrame_sStringer.Location(), c.sFrame_eStringer.Location())); c.eFrame_eStringer.SetDirection(gp_Vec(c.eFrame_eStringer.Location(), c.sFrame_sStringer.Location())); } catch (...) { m_borderCache = boost::none; } } void CCPACSSkinSegment::UpdateBorder(gp_Ax1& b, TopoDS_Shape s1, TopoDS_Shape s2) { b.SetLocation(GetIntersectionPoint(s1, s2)); } gp_Pnt CCPACSSkinSegment::GetIntersectionPoint(TopoDS_Shape s1, TopoDS_Shape s2) const { TopTools_IndexedMapOfShape edgeMap1; edgeMap1.Clear(); TopExp::MapShapes(s1, TopAbs_EDGE, edgeMap1); TopTools_IndexedMapOfShape edgeMap2; edgeMap2.Clear(); TopExp::MapShapes(s2, TopAbs_EDGE, edgeMap2); for (int i = 1; i <= edgeMap1.Extent(); i++) { for (int j = 1; j <= edgeMap2.Extent(); j++) { BRepExtrema_ExtCC pG(TopoDS::Edge(edgeMap1(i)), TopoDS::Edge(edgeMap2(j))); if (pG.NbExt() == 1) { return pG.PointOnE1(1); } } } throw CTiglError("No intersection between frame and stringer"); } } // namespace tigl <commit_msg>made usage of fuselage loft more clear<commit_after>/* * Copyright (c) 2018 Airbus Defence and Space and RISC Software GmbH * * 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 "CCPACSSkinSegment.h" #include <TopoDS_Face.hxx> #include <TopoDS_Edge.hxx> #include <BRep_Tool.hxx> #include <BRepExtrema_ExtCC.hxx> #include <TopExp.hxx> #include <BRepTools.hxx> #include <Bnd_Box.hxx> #include <BRepBndLib.hxx> #include <TopTools_IndexedMapOfShape.hxx> #include <Geom_Surface.hxx> #include "generated/CPACSSkinSegments.h" #include "CCPACSFrame.h" #include "CCPACSFuselageStringer.h" #include "CTiglError.h" #include "CCPACSFuselage.h" #include "CTiglUIDManager.h" #include "CNamedShape.h" #include "tiglcommonfunctions.h" namespace tigl { CCPACSSkinSegment::CCPACSSkinSegment(CCPACSSkinSegments* parent, CTiglUIDManager* uidMgr) : generated::CPACSSkinSegment(parent, uidMgr) { } void CCPACSSkinSegment::Invalidate() { m_borderCache = boost::none; } bool CCPACSSkinSegment::Contains(const TopoDS_Face& face) { double u_min = 0., u_max = 0., v_min = 0., v_max = 0.; BRepTools::UVBounds(face, u_min, u_max, v_min, v_max); Handle(Geom_Surface) testSurf = BRep_Tool::Surface(face); gp_Pnt point = testSurf->Value(u_min + ((u_max - u_min) / 2), v_min + ((v_max - v_min) / 2)); return Contains(point); } bool CCPACSSkinSegment::Contains(const TopoDS_Edge& edge) { double u_min = 0., u_max = 0.; Handle(Geom_Curve) curve = BRep_Tool::Curve(edge, u_min, u_max); gp_Pnt point = curve->Value(u_min + ((u_max - u_min) / 2)); return Contains(point); } bool CCPACSSkinSegment::Contains(const gp_Pnt& point) { if (!m_borderCache) UpdateBorders(); const double angleLower = Radians(45.); const double angleUpper = Radians(89.); const BorderCache& c = m_borderCache.value(); if (gp_Ax1(c.sFrame_sStringer.Location(), gp_Vec(c.sFrame_sStringer.Location(), point)).Angle(c.sFrame_sStringer) >= angleLower) return false; if (gp_Ax1(c.sFrame_eStringer.Location(), gp_Vec(c.sFrame_eStringer.Location(), point)).Angle(c.sFrame_eStringer) >= angleLower) return false; if (gp_Ax1(c.eFrame_sStringer.Location(), gp_Vec(c.eFrame_sStringer.Location(), point)).Angle(c.eFrame_sStringer) >= angleLower) return false; if (gp_Ax1(c.eFrame_eStringer.Location(), gp_Vec(c.eFrame_eStringer.Location(), point)).Angle(c.eFrame_eStringer) >= angleLower) return false; const gp_Pnt p1 = (c.sFrame_sStringer.Location().XYZ() + c.eFrame_sStringer.Location().XYZ()) / 2; const gp_Pnt p2 = (c.eFrame_sStringer.Location().XYZ() + c.eFrame_eStringer.Location().XYZ()) / 2; const gp_Pnt p3 = (c.eFrame_eStringer.Location().XYZ() + c.sFrame_eStringer.Location().XYZ()) / 2; const gp_Pnt p4 = (c.sFrame_eStringer.Location().XYZ() + c.sFrame_sStringer.Location().XYZ()) / 2; const gp_Pnt p5 = (c.sFrame_sStringer.Location().XYZ() + c.eFrame_eStringer.Location().XYZ()) / 2; const TopoDS_Shape fuselageLoft = m_parent->GetParent()->GetParent()->GetParent()->GetLoft()->Shape(); Bnd_Box boundingBox; BRepBndLib::Add(fuselageLoft, boundingBox); const double yMid = (boundingBox.CornerMax().Y() + boundingBox.CornerMin().Y()) / 2; const gp_Pnt p6(p5.X(), yMid, p5.Z()); const gp_Ax1 ref1(p1, gp_Vec(p1, p3)); const gp_Ax1 ref2(p2, gp_Vec(p2, p4)); const gp_Ax1 ref3(p3, gp_Vec(p3, p1)); const gp_Ax1 ref4(p4, gp_Vec(p4, p2)); const gp_Ax1 ref5(p6, gp_Vec(p6, p5)); if (gp_Ax1(p1, gp_Vec(p1, point)).Angle(ref1) >= angleUpper) return false; if (gp_Ax1(p2, gp_Vec(p2, point)).Angle(ref2) >= angleUpper) return false; if (gp_Ax1(p3, gp_Vec(p3, point)).Angle(ref3) >= angleUpper) return false; if (gp_Ax1(p4, gp_Vec(p4, point)).Angle(ref4) >= angleUpper) return false; double maxAngle = 0; maxAngle = std::max(maxAngle, gp_Ax1(p6, gp_Vec(p6, c.sFrame_sStringer.Location())).Angle(ref5)); maxAngle = std::max(maxAngle, gp_Ax1(p6, gp_Vec(p6, c.eFrame_sStringer.Location())).Angle(ref5)); maxAngle = std::max(maxAngle, gp_Ax1(p6, gp_Vec(p6, c.sFrame_eStringer.Location())).Angle(ref5)); maxAngle = std::max(maxAngle, gp_Ax1(p6, gp_Vec(p6, c.eFrame_eStringer.Location())).Angle(ref5)); return gp_Ax1(p6, gp_Vec(p6, point)).Angle(ref5) < maxAngle; } void CCPACSSkinSegment::UpdateBorders() { try { CCPACSFrame& sFrame = m_uidMgr->ResolveObject<CCPACSFrame>(m_startFrameUID); CCPACSFrame& eFrame = m_uidMgr->ResolveObject<CCPACSFrame>(m_endFrameUID); CCPACSFuselageStringer& sStringer = m_uidMgr->ResolveObject<CCPACSFuselageStringer>(m_startStringerUID); CCPACSFuselageStringer& eStringer = m_uidMgr->ResolveObject<CCPACSFuselageStringer>(m_endStringerUID.value()); m_borderCache = BorderCache(); BorderCache& c = *m_borderCache; // get the intersection points between stringer and frames UpdateBorder(c.sFrame_sStringer, sFrame.GetGeometry(true), sStringer.GetGeometry(true)); UpdateBorder(c.sFrame_eStringer, sFrame.GetGeometry(true), eStringer.GetGeometry(true)); UpdateBorder(c.eFrame_sStringer, eFrame.GetGeometry(true), sStringer.GetGeometry(true)); UpdateBorder(c.eFrame_eStringer, eFrame.GetGeometry(true), eStringer.GetGeometry(true)); // generate directions to the opposite intersection point c.sFrame_sStringer.SetDirection(gp_Vec(c.sFrame_sStringer.Location(), c.eFrame_eStringer.Location())); c.sFrame_eStringer.SetDirection(gp_Vec(c.sFrame_eStringer.Location(), c.eFrame_sStringer.Location())); c.eFrame_sStringer.SetDirection(gp_Vec(c.eFrame_sStringer.Location(), c.sFrame_eStringer.Location())); c.eFrame_eStringer.SetDirection(gp_Vec(c.eFrame_eStringer.Location(), c.sFrame_sStringer.Location())); } catch (...) { m_borderCache = boost::none; } } void CCPACSSkinSegment::UpdateBorder(gp_Ax1& b, TopoDS_Shape s1, TopoDS_Shape s2) { b.SetLocation(GetIntersectionPoint(s1, s2)); } gp_Pnt CCPACSSkinSegment::GetIntersectionPoint(TopoDS_Shape s1, TopoDS_Shape s2) const { TopTools_IndexedMapOfShape edgeMap1; edgeMap1.Clear(); TopExp::MapShapes(s1, TopAbs_EDGE, edgeMap1); TopTools_IndexedMapOfShape edgeMap2; edgeMap2.Clear(); TopExp::MapShapes(s2, TopAbs_EDGE, edgeMap2); for (int i = 1; i <= edgeMap1.Extent(); i++) { for (int j = 1; j <= edgeMap2.Extent(); j++) { BRepExtrema_ExtCC pG(TopoDS::Edge(edgeMap1(i)), TopoDS::Edge(edgeMap2(j))); if (pG.NbExt() == 1) { return pG.PointOnE1(1); } } } throw CTiglError("No intersection between frame and stringer"); } } // namespace tigl <|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 "base/file_path.h" #include "content/test/layout_browsertest.h" class IndexedDBLayoutTest : public InProcessBrowserLayoutTest { public: IndexedDBLayoutTest() : InProcessBrowserLayoutTest( FilePath(), FilePath().AppendASCII("storage").AppendASCII("indexeddb")) { } virtual void SetUpInProcessBrowserTestFixture() OVERRIDE { InProcessBrowserLayoutTest::SetUpInProcessBrowserTestFixture(); AddResourceForLayoutTest( FilePath().AppendASCII("fast").AppendASCII("js"), FilePath().AppendASCII("resources")); } void RunLayoutTests(const char* file_names[]) { for (size_t i = 0; file_names[i]; i++) RunLayoutTest(file_names[i]); } }; namespace { static const char* kBasicTests[] = { "basics.html", "basics-shared-workers.html", "basics-workers.html", "database-basics.html", "factory-basics.html", "index-basics.html", "objectstore-basics.html", NULL }; static const char* kComplexTests[] = { "prefetch-bugfix-108071.html", "pending-version-change-stuck-works-with-terminate.html", NULL }; static const char* kIndexTests[] = { "deleteIndex.html", "index-count.html", "index-cursor.html", // Locally takes ~6s compared to <1 for the others. "index-get-key-argument-required.html", "index-multientry.html", "index-population.html", "index-unique.html", NULL }; static const char* kKeyTests[] = { "key-generator.html", "keypath-basics.html", "keypath-edges.html", "keypath-fetch-key.html", "keyrange.html", "keyrange-required-arguments.html", "key-sort-order-across-types.html", "key-sort-order-date.html", "key-type-array.html", "key-type-infinity.html", "invalid-keys.html", NULL }; static const char* kTransactionTests[] = { // "transaction-abort.html", // Flaky, http://crbug.com/83226 "transaction-abort-with-js-recursion-cross-frame.html", "transaction-abort-with-js-recursion.html", "transaction-abort-workers.html", "transaction-after-close.html", "transaction-and-objectstore-calls.html", "transaction-basics.html", "transaction-crash-on-abort.html", "transaction-event-propagation.html", "transaction-read-only.html", "transaction-rollback.html", "transaction-storeNames-required.html", NULL }; static const char* kRegressionTests[] = { "dont-commit-on-blocked.html", NULL }; } IN_PROC_BROWSER_TEST_F(IndexedDBLayoutTest, BasicTests) { RunLayoutTests(kBasicTests); } IN_PROC_BROWSER_TEST_F(IndexedDBLayoutTest, ComplexTests) { RunLayoutTests(kComplexTests); } // Frequently times out, sometimes due to webkit assertion failure. // http://crbug.com/120924 IN_PROC_BROWSER_TEST_F(IndexedDBLayoutTest, FAILS_IndexBasicsWorkersTest) { RunLayoutTest("deleteIndex.html"); RunLayoutTest("index-basics-workers.html"); } IN_PROC_BROWSER_TEST_F(IndexedDBLayoutTest, IndexTests) { RunLayoutTests(kIndexTests); } IN_PROC_BROWSER_TEST_F(IndexedDBLayoutTest, KeyTests) { RunLayoutTests(kKeyTests); } IN_PROC_BROWSER_TEST_F(IndexedDBLayoutTest, TransactionTests) { RunLayoutTests(kTransactionTests); } IN_PROC_BROWSER_TEST_F(IndexedDBLayoutTest, RegressionTests) { RunLayoutTests(kRegressionTests); } <commit_msg>Disable some flaky IndexedDB browser tests.<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 "base/file_path.h" #include "content/test/layout_browsertest.h" class IndexedDBLayoutTest : public InProcessBrowserLayoutTest { public: IndexedDBLayoutTest() : InProcessBrowserLayoutTest( FilePath(), FilePath().AppendASCII("storage").AppendASCII("indexeddb")) { } virtual void SetUpInProcessBrowserTestFixture() OVERRIDE { InProcessBrowserLayoutTest::SetUpInProcessBrowserTestFixture(); AddResourceForLayoutTest( FilePath().AppendASCII("fast").AppendASCII("js"), FilePath().AppendASCII("resources")); } void RunLayoutTests(const char* file_names[]) { for (size_t i = 0; file_names[i]; i++) RunLayoutTest(file_names[i]); } }; namespace { static const char* kBasicTests[] = { "basics.html", "basics-shared-workers.html", "basics-workers.html", "database-basics.html", "factory-basics.html", "index-basics.html", "objectstore-basics.html", NULL }; static const char* kComplexTests[] = { "prefetch-bugfix-108071.html", // Flaky: http://crbug.com/123685 // "pending-version-change-stuck-works-with-terminate.html", NULL }; static const char* kIndexTests[] = { "deleteIndex.html", // Flaky: http://crbug.com/123685 // "index-basics-workers.html", "index-count.html", "index-cursor.html", // Locally takes ~6s compared to <1 for the others. "index-get-key-argument-required.html", "index-multientry.html", "index-population.html", "index-unique.html", NULL }; static const char* kKeyTests[] = { "key-generator.html", "keypath-basics.html", "keypath-edges.html", "keypath-fetch-key.html", "keyrange.html", "keyrange-required-arguments.html", "key-sort-order-across-types.html", "key-sort-order-date.html", "key-type-array.html", "key-type-infinity.html", "invalid-keys.html", NULL }; static const char* kTransactionTests[] = { // "transaction-abort.html", // Flaky, http://crbug.com/83226 "transaction-abort-with-js-recursion-cross-frame.html", "transaction-abort-with-js-recursion.html", "transaction-abort-workers.html", "transaction-after-close.html", "transaction-and-objectstore-calls.html", "transaction-basics.html", "transaction-crash-on-abort.html", "transaction-event-propagation.html", "transaction-read-only.html", "transaction-rollback.html", "transaction-storeNames-required.html", NULL }; static const char* kRegressionTests[] = { "dont-commit-on-blocked.html", NULL }; } IN_PROC_BROWSER_TEST_F(IndexedDBLayoutTest, BasicTests) { RunLayoutTests(kBasicTests); } IN_PROC_BROWSER_TEST_F(IndexedDBLayoutTest, ComplexTests) { RunLayoutTests(kComplexTests); } IN_PROC_BROWSER_TEST_F(IndexedDBLayoutTest, IndexTests) { RunLayoutTests(kIndexTests); } IN_PROC_BROWSER_TEST_F(IndexedDBLayoutTest, KeyTests) { RunLayoutTests(kKeyTests); } IN_PROC_BROWSER_TEST_F(IndexedDBLayoutTest, TransactionTests) { RunLayoutTests(kTransactionTests); } IN_PROC_BROWSER_TEST_F(IndexedDBLayoutTest, RegressionTests) { RunLayoutTests(kRegressionTests); } <|endoftext|>
<commit_before>/* * PhraseTableMemory.cpp * * Created on: 28 Oct 2015 * Author: hieu */ #include <cassert> #include <boost/foreach.hpp> #include "PhraseTableMemory.h" #include "../Phrase.h" #include "../TargetPhrase.h" #include "../System.h" #include "../Scores.h" #include "../InputPaths.h" #include "../legacy/InputFileStream.h" using namespace std; PhraseTableMemory::Node::Node() {} PhraseTableMemory::Node::~Node() { } void PhraseTableMemory::Node::AddRule(PhraseImpl &source, TargetPhrase *target) { AddRule(source, target, 0); } PhraseTableMemory::Node &PhraseTableMemory::Node::AddRule(PhraseImpl &source, TargetPhrase *target, size_t pos) { if (pos == source.GetSize()) { TargetPhrases *tp = m_targetPhrases.get(); if (tp == NULL) { tp = new TargetPhrases(); m_targetPhrases.reset(tp); } tp->AddTargetPhrase(*target); return *this; } else { const Word &word = source[pos]; Node &child = m_children[word]; return child.AddRule(source, target, pos + 1); } } TargetPhrases::shared_const_ptr PhraseTableMemory::Node::Find(const Phrase &source, size_t pos) const { assert(source.GetSize()); if (pos == source.GetSize()) { return m_targetPhrases; } else { const Word &word = source[pos]; //cerr << "word=" << word << endl; Children::const_iterator iter = m_children.find(word); if (iter == m_children.end()) { return TargetPhrases::shared_const_ptr(); } else { const Node &child = iter->second; return child.Find(source, pos + 1); } } } void PhraseTableMemory::Node::SortAndPrune(size_t tableLimit) { BOOST_FOREACH(Children::value_type &val, m_children) { Node &child = val.second; child.SortAndPrune(tableLimit); } // prune target phrases in this node TargetPhrases *tps = m_targetPhrases.get(); if (tps) { tps->SortAndPrune(tableLimit); } } //////////////////////////////////////////////////////////////////////// PhraseTableMemory::PhraseTableMemory(size_t startInd, const std::string &line) :PhraseTable(startInd, line) { ReadParameters(); } PhraseTableMemory::~PhraseTableMemory() { // TODO Auto-generated destructor stub } void PhraseTableMemory::Load(System &system) { FactorCollection &vocab = system.vocab; MemPool tmpPool; vector<string> toks; size_t lineNum = 0; InputFileStream strme(m_path); string line; while (getline(strme, line)) { if (++lineNum % 10000) { cerr << lineNum << " "; } toks.clear(); TokenizeMultiCharSeparator(toks, line, "|||"); assert(toks.size() >= 3); //cerr << "line=" << line << endl; PhraseImpl *source = PhraseImpl::CreateFromString(tmpPool, vocab, toks[0]); //cerr << "created soure" << endl; TargetPhrase *target = TargetPhrase::CreateFromString(system.systemPool, system, toks[1]); //cerr << "created target" << endl; target->GetScores().CreateFromString(toks[2], *this, system, true); //cerr << "created scores" << endl; MemPool tmpPool; system.featureFunctions.EvaluateInIsolation(tmpPool, system, *source, *target); m_root.AddRule(*source, target); } m_root.SortAndPrune(m_tableLimit); } TargetPhrases::shared_const_ptr PhraseTableMemory::Lookup(const Manager &mgr, InputPath &inputPath) const { const SubPhrase &phrase = inputPath.subPhrase; TargetPhrases::shared_const_ptr tps = m_root.Find(phrase); return tps; } <commit_msg>timer<commit_after>/* * PhraseTableMemory.cpp * * Created on: 28 Oct 2015 * Author: hieu */ #include <cassert> #include <boost/foreach.hpp> #include "PhraseTableMemory.h" #include "../Phrase.h" #include "../TargetPhrase.h" #include "../System.h" #include "../Scores.h" #include "../InputPaths.h" #include "../legacy/InputFileStream.h" using namespace std; PhraseTableMemory::Node::Node() {} PhraseTableMemory::Node::~Node() { } void PhraseTableMemory::Node::AddRule(PhraseImpl &source, TargetPhrase *target) { AddRule(source, target, 0); } PhraseTableMemory::Node &PhraseTableMemory::Node::AddRule(PhraseImpl &source, TargetPhrase *target, size_t pos) { if (pos == source.GetSize()) { TargetPhrases *tp = m_targetPhrases.get(); if (tp == NULL) { tp = new TargetPhrases(); m_targetPhrases.reset(tp); } tp->AddTargetPhrase(*target); return *this; } else { const Word &word = source[pos]; Node &child = m_children[word]; return child.AddRule(source, target, pos + 1); } } TargetPhrases::shared_const_ptr PhraseTableMemory::Node::Find(const Phrase &source, size_t pos) const { assert(source.GetSize()); if (pos == source.GetSize()) { return m_targetPhrases; } else { const Word &word = source[pos]; //cerr << "word=" << word << endl; Children::const_iterator iter = m_children.find(word); if (iter == m_children.end()) { return TargetPhrases::shared_const_ptr(); } else { const Node &child = iter->second; return child.Find(source, pos + 1); } } } void PhraseTableMemory::Node::SortAndPrune(size_t tableLimit) { BOOST_FOREACH(Children::value_type &val, m_children) { Node &child = val.second; child.SortAndPrune(tableLimit); } // prune target phrases in this node TargetPhrases *tps = m_targetPhrases.get(); if (tps) { tps->SortAndPrune(tableLimit); } } //////////////////////////////////////////////////////////////////////// PhraseTableMemory::PhraseTableMemory(size_t startInd, const std::string &line) :PhraseTable(startInd, line) { ReadParameters(); } PhraseTableMemory::~PhraseTableMemory() { // TODO Auto-generated destructor stub } void PhraseTableMemory::Load(System &system) { FactorCollection &vocab = system.vocab; MemPool tmpPool; vector<string> toks; size_t lineNum = 0; InputFileStream strme(m_path); string line; while (getline(strme, line)) { if (++lineNum % 100000) { cerr << lineNum << " "; } toks.clear(); TokenizeMultiCharSeparator(toks, line, "|||"); assert(toks.size() >= 3); //cerr << "line=" << line << endl; PhraseImpl *source = PhraseImpl::CreateFromString(tmpPool, vocab, toks[0]); //cerr << "created soure" << endl; TargetPhrase *target = TargetPhrase::CreateFromString(system.systemPool, system, toks[1]); //cerr << "created target" << endl; target->GetScores().CreateFromString(toks[2], *this, system, true); //cerr << "created scores" << endl; MemPool tmpPool; system.featureFunctions.EvaluateInIsolation(tmpPool, system, *source, *target); m_root.AddRule(*source, target); } m_root.SortAndPrune(m_tableLimit); } TargetPhrases::shared_const_ptr PhraseTableMemory::Lookup(const Manager &mgr, InputPath &inputPath) const { const SubPhrase &phrase = inputPath.subPhrase; TargetPhrases::shared_const_ptr tps = m_root.Find(phrase); return tps; } <|endoftext|>
<commit_before>/*========================================================================= * * Copyright NumFOCUS * * 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 * * https://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. * *=========================================================================*/ /*========================================================================= * * Portions of this file are subject to the VTK Toolkit Version 3 copyright. * * Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen * * For complete copyright, license and disclaimer of warranty information * please refer to the NOTICE file at the top of the ITK source tree. * *=========================================================================*/ #include "itkCommand.h" #include <algorithm> #include <memory> // For unique_ptr. #include "itkSingleton.h" namespace itk { /** * Initialize static member that controls warning display. */ itkGetGlobalValueMacro(Object, bool, GlobalWarningDisplay, true); bool * Object::m_GlobalWarningDisplay; namespace { class ITKCommon_HIDDEN Observer { public: Observer(Command * c, const EventObject * event, unsigned long tag) : m_Command(c) , m_Event(event) , m_Tag(tag) {} Command::Pointer m_Command; std::unique_ptr<const EventObject> m_Event; unsigned long m_Tag; }; } // namespace class ITKCommon_HIDDEN Object::SubjectImplementation { public: SubjectImplementation() { m_Count = 0; } ~SubjectImplementation() = default; unsigned long AddObserver(const EventObject & event, Command * cmd); void RemoveObserver(unsigned long tag); void RemoveAllObservers(); void InvokeEvent(const EventObject & event, Object * self); void InvokeEvent(const EventObject & event, const Object * self); Command * GetCommand(unsigned long tag); bool HasObserver(const EventObject & event) const; bool PrintObservers(std::ostream & os, Indent indent) const; bool m_ListModified{ false }; protected: // RAII of ListModified state to ensure exception safety struct SaveRestoreListModified { // save the list modified flag, and reset to false SaveRestoreListModified(SubjectImplementation * s) : m_Subject(s) , m_Save(s->m_ListModified) { m_Subject->m_ListModified = false; } // restore modify flag, and propagate if modified ~SaveRestoreListModified() { m_Subject->m_ListModified = m_Save || m_Subject->m_ListModified; } SubjectImplementation * m_Subject; bool m_Save; }; template <typename TObject> void InvokeEventRecursion(const EventObject & event, TObject * self, std::list<Observer>::reverse_iterator & i); private: std::list<Observer> m_Observers; unsigned long m_Count; }; unsigned long Object::SubjectImplementation::AddObserver(const EventObject & event, Command * cmd) { const unsigned long tag{ m_Count }; m_Observers.emplace_back(cmd, event.MakeObject(), tag); ++m_Count; return tag; } void Object::SubjectImplementation::RemoveObserver(unsigned long tag) { for (auto i = m_Observers.begin(); i != m_Observers.end(); ++i) { if (i->m_Tag == tag) { m_Observers.erase(i); m_ListModified = true; return; } } } void Object::SubjectImplementation::RemoveAllObservers() { m_Observers.clear(); m_ListModified = true; } void Object::SubjectImplementation::InvokeEvent(const EventObject & event, Object * self) { // While an event is being invoked, it's possible to remove // observers, or another event to be invoked. All methods which // remove observers mark the list as modified with the // m_ListModified flag. The modified flag is save to the stack and // marked false before recursively saving the current list. SaveRestoreListModified save(this); auto i = m_Observers.rbegin(); InvokeEventRecursion(event, self, i); } void Object::SubjectImplementation::InvokeEvent(const EventObject & event, const Object * self) { SaveRestoreListModified save(this); auto i = m_Observers.rbegin(); InvokeEventRecursion(event, self, i); } template <typename TObject> void Object::SubjectImplementation::InvokeEventRecursion(const EventObject & event, TObject * self, std::list<Observer>::reverse_iterator & i) { // This method recursively visits the list of observers in reverse // order so that on the last recursion the first observer can be // executed. Each iteration saves the list element on the // stack. Each observer's execution could potentially modify the // observer list, by placing the entire list on the stack we save the // list when the event is first invoked. If observers are removed // during execution, then the current list is search for the current // observer save on the stack. while (i != m_Observers.rend()) { // save observer const Observer & o = *i; // Save its tag, before the observer could /possibly/ be removed. const unsigned long tag{ o.m_Tag }; if (o.m_Event->CheckEvent(&event)) { InvokeEventRecursion(event, self, ++i); const auto hasSameTag = [tag](const Observer & observer) { return observer.m_Tag == tag; }; if (!m_ListModified || std::any_of(m_Observers.begin(), m_Observers.end(), hasSameTag)) { o.m_Command->Execute(self, event); } return; } ++i; } return; } Command * Object::SubjectImplementation::GetCommand(unsigned long tag) { for (auto & observer : m_Observers) { if (observer.m_Tag == tag) { return observer.m_Command; } } return nullptr; } bool Object::SubjectImplementation::HasObserver(const EventObject & event) const { for (const auto & observer : m_Observers) { const EventObject * e = observer.m_Event.get(); if (e->CheckEvent(&event)) { return true; } } return false; } bool Object::SubjectImplementation::PrintObservers(std::ostream & os, Indent indent) const { if (m_Observers.empty()) { return false; } for (const auto & observer : m_Observers) { const EventObject * e = observer.m_Event.get(); const Command * c = observer.m_Command; os << indent << e->GetEventName() << "(" << c->GetNameOfClass(); if (!c->GetObjectName().empty()) { os << " \"" << c->GetObjectName() << "\""; } os << ")\n"; } return true; } Object::Pointer Object::New() { Pointer smartPtr; Object * rawPtr = itk::ObjectFactory<Object>::Create(); if (rawPtr == nullptr) { rawPtr = new Object; } smartPtr = rawPtr; rawPtr->UnRegister(); return smartPtr; } LightObject::Pointer Object::CreateAnother() const { return Object::New().GetPointer(); } /** * Turn debugging output on. */ void Object::DebugOn() const { m_Debug = true; } /** * Turn debugging output off. */ void Object::DebugOff() const { m_Debug = false; } /** * Get the value of the debug flag. */ bool Object::GetDebug() const { return m_Debug; } /** * Set the value of the debug flag. A non-zero value turns debugging on. */ void Object::SetDebug(bool debugFlag) const { m_Debug = debugFlag; } /** * Return the modification for this object. */ ModifiedTimeType Object::GetMTime() const { return m_MTime.GetMTime(); } /** * Return the modification for this object. */ const TimeStamp & Object::GetTimeStamp() const { return m_MTime; } /** Set the time stamp of this object. To be used very carefully !!!. * Most mortals will never need to call this method. */ void Object::SetTimeStamp(const TimeStamp & timeStamp) { this->m_MTime = timeStamp; } /** * Make sure this object's modified time is greater than all others. */ void Object::Modified() const { m_MTime.Modified(); InvokeEvent(ModifiedEvent()); } /** * Increase the reference count (mark as used by another object). */ void Object::Register() const { itkDebugMacro(<< "Registered, " << "ReferenceCount = " << (m_ReferenceCount + 1)); // call the parent Superclass::Register(); } /** * Decrease the reference count (release by another object). */ void Object::UnRegister() const noexcept { // call the parent itkDebugMacro(<< "UnRegistered, " << "ReferenceCount = " << (m_ReferenceCount - 1)); if ((m_ReferenceCount - 1) <= 0) { /** * If there is a delete method, invoke it. */ try { this->InvokeEvent(DeleteEvent()); } catch (...) { // The macro is not use to avoid a memory allocation, and reduce // potential exceptions. // itkWarningMacro("Exception occurred in DeleteEvent Observer!"); try { if (GetGlobalWarningDisplay()) { itk::OutputWindowDisplayWarningText("WARNING: Exception occurred in DeleteEvent Observer!"); } } catch (...) { // ignore exception in warning display } } } Superclass::UnRegister(); } /** * Sets the reference count (use with care) */ void Object::SetReferenceCount(int ref) { itkDebugMacro(<< "Reference Count set to " << ref); // ReferenceCount in now unlocked. We may have a race condition to // to delete the object. if (ref <= 0) { /** * If there is a delete method, invoke it. */ try { this->InvokeEvent(DeleteEvent()); } catch (...) { itkWarningMacro("Exception occurred in DeleteEvent Observer!"); } } Superclass::SetReferenceCount(ref); } /** * Set the value of the global debug output control flag. */ void Object::SetGlobalWarningDisplay(bool val) { itkInitGlobalsMacro(GlobalWarningDisplay); *m_GlobalWarningDisplay = val; } /** * Get the value of the global debug output control flag. */ bool Object::GetGlobalWarningDisplay() { return *Object::GetGlobalWarningDisplayPointer(); } unsigned long Object::AddObserver(const EventObject & event, Command * cmd) { if (!this->m_SubjectImplementation) { this->m_SubjectImplementation = std::make_unique<SubjectImplementation>(); } return this->m_SubjectImplementation->AddObserver(event, cmd); } unsigned long Object::AddObserver(const EventObject & event, Command * cmd) const { if (!this->m_SubjectImplementation) { auto * me = const_cast<Self *>(this); me->m_SubjectImplementation = std::make_unique<SubjectImplementation>(); } return this->m_SubjectImplementation->AddObserver(event, cmd); } unsigned long Object::AddObserver(const EventObject & event, std::function<void(const EventObject &)> function) const { auto cmd = FunctionCommand::New(); cmd->SetCallback(std::move(function)); return this->AddObserver(event, cmd); } Command * Object::GetCommand(unsigned long tag) { if (this->m_SubjectImplementation) { return this->m_SubjectImplementation->GetCommand(tag); } return nullptr; } void Object::RemoveObserver(unsigned long tag) { if (this->m_SubjectImplementation) { this->m_SubjectImplementation->RemoveObserver(tag); } } void Object::RemoveAllObservers() { if (this->m_SubjectImplementation) { this->m_SubjectImplementation->RemoveAllObservers(); } } void Object::InvokeEvent(const EventObject & event) { if (this->m_SubjectImplementation) { this->m_SubjectImplementation->InvokeEvent(event, this); } } void Object::InvokeEvent(const EventObject & event) const { if (this->m_SubjectImplementation) { this->m_SubjectImplementation->InvokeEvent(event, this); } } bool Object::HasObserver(const EventObject & event) const { if (this->m_SubjectImplementation) { return this->m_SubjectImplementation->HasObserver(event); } return false; } bool Object::PrintObservers(std::ostream & os, Indent indent) const { if (this->m_SubjectImplementation) { return this->m_SubjectImplementation->PrintObservers(os, indent); } return false; } /** * Create an object with Debug turned off and modified time initialized * to the most recently modified object. */ Object::Object() : LightObject() , m_ObjectName() { this->Modified(); } Object::~Object() { itkDebugMacro(<< "Destructing!"); } /** * Chaining method to print an object's instance variables, as well as * its superclasses. */ void Object::PrintSelf(std::ostream & os, Indent indent) const { Superclass::PrintSelf(os, indent); os << indent << "Modified Time: " << this->GetMTime() << std::endl; os << indent << "Debug: " << (m_Debug ? "On\n" : "Off\n"); os << indent << "Object Name: " << this->GetObjectName() << std::endl; os << indent << "Observers: \n"; if (!this->PrintObservers(os, indent.GetNextIndent())) { os << indent.GetNextIndent() << "none\n"; } } MetaDataDictionary & Object::GetMetaDataDictionary() { if (m_MetaDataDictionary == nullptr) { m_MetaDataDictionary = std::make_unique<MetaDataDictionary>(); } return *m_MetaDataDictionary; } const MetaDataDictionary & Object::GetMetaDataDictionary() const { if (m_MetaDataDictionary == nullptr) { m_MetaDataDictionary = std::make_unique<MetaDataDictionary>(); } return *m_MetaDataDictionary; } void Object::SetMetaDataDictionary(const MetaDataDictionary & rhs) { if (m_MetaDataDictionary == nullptr) { m_MetaDataDictionary = std::make_unique<MetaDataDictionary>(rhs); return; } *m_MetaDataDictionary = rhs; } void Object::SetMetaDataDictionary(MetaDataDictionary && rrhs) { if (m_MetaDataDictionary == nullptr) { m_MetaDataDictionary = std::make_unique<MetaDataDictionary>(std::move(rrhs)); return; } *m_MetaDataDictionary = std::move(rrhs); } } // end namespace itk <commit_msg>STYLE: Make protected `Object::SubjectImplementation` members private<commit_after>/*========================================================================= * * Copyright NumFOCUS * * 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 * * https://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. * *=========================================================================*/ /*========================================================================= * * Portions of this file are subject to the VTK Toolkit Version 3 copyright. * * Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen * * For complete copyright, license and disclaimer of warranty information * please refer to the NOTICE file at the top of the ITK source tree. * *=========================================================================*/ #include "itkCommand.h" #include <algorithm> #include <memory> // For unique_ptr. #include "itkSingleton.h" namespace itk { /** * Initialize static member that controls warning display. */ itkGetGlobalValueMacro(Object, bool, GlobalWarningDisplay, true); bool * Object::m_GlobalWarningDisplay; namespace { class ITKCommon_HIDDEN Observer { public: Observer(Command * c, const EventObject * event, unsigned long tag) : m_Command(c) , m_Event(event) , m_Tag(tag) {} Command::Pointer m_Command; std::unique_ptr<const EventObject> m_Event; unsigned long m_Tag; }; } // namespace class ITKCommon_HIDDEN Object::SubjectImplementation { public: SubjectImplementation() { m_Count = 0; } ~SubjectImplementation() = default; unsigned long AddObserver(const EventObject & event, Command * cmd); void RemoveObserver(unsigned long tag); void RemoveAllObservers(); void InvokeEvent(const EventObject & event, Object * self); void InvokeEvent(const EventObject & event, const Object * self); Command * GetCommand(unsigned long tag); bool HasObserver(const EventObject & event) const; bool PrintObservers(std::ostream & os, Indent indent) const; bool m_ListModified{ false }; private: // RAII of ListModified state to ensure exception safety struct SaveRestoreListModified { // save the list modified flag, and reset to false SaveRestoreListModified(SubjectImplementation * s) : m_Subject(s) , m_Save(s->m_ListModified) { m_Subject->m_ListModified = false; } // restore modify flag, and propagate if modified ~SaveRestoreListModified() { m_Subject->m_ListModified = m_Save || m_Subject->m_ListModified; } SubjectImplementation * m_Subject; bool m_Save; }; template <typename TObject> void InvokeEventRecursion(const EventObject & event, TObject * self, std::list<Observer>::reverse_iterator & i); std::list<Observer> m_Observers; unsigned long m_Count; }; unsigned long Object::SubjectImplementation::AddObserver(const EventObject & event, Command * cmd) { const unsigned long tag{ m_Count }; m_Observers.emplace_back(cmd, event.MakeObject(), tag); ++m_Count; return tag; } void Object::SubjectImplementation::RemoveObserver(unsigned long tag) { for (auto i = m_Observers.begin(); i != m_Observers.end(); ++i) { if (i->m_Tag == tag) { m_Observers.erase(i); m_ListModified = true; return; } } } void Object::SubjectImplementation::RemoveAllObservers() { m_Observers.clear(); m_ListModified = true; } void Object::SubjectImplementation::InvokeEvent(const EventObject & event, Object * self) { // While an event is being invoked, it's possible to remove // observers, or another event to be invoked. All methods which // remove observers mark the list as modified with the // m_ListModified flag. The modified flag is save to the stack and // marked false before recursively saving the current list. SaveRestoreListModified save(this); auto i = m_Observers.rbegin(); InvokeEventRecursion(event, self, i); } void Object::SubjectImplementation::InvokeEvent(const EventObject & event, const Object * self) { SaveRestoreListModified save(this); auto i = m_Observers.rbegin(); InvokeEventRecursion(event, self, i); } template <typename TObject> void Object::SubjectImplementation::InvokeEventRecursion(const EventObject & event, TObject * self, std::list<Observer>::reverse_iterator & i) { // This method recursively visits the list of observers in reverse // order so that on the last recursion the first observer can be // executed. Each iteration saves the list element on the // stack. Each observer's execution could potentially modify the // observer list, by placing the entire list on the stack we save the // list when the event is first invoked. If observers are removed // during execution, then the current list is search for the current // observer save on the stack. while (i != m_Observers.rend()) { // save observer const Observer & o = *i; // Save its tag, before the observer could /possibly/ be removed. const unsigned long tag{ o.m_Tag }; if (o.m_Event->CheckEvent(&event)) { InvokeEventRecursion(event, self, ++i); const auto hasSameTag = [tag](const Observer & observer) { return observer.m_Tag == tag; }; if (!m_ListModified || std::any_of(m_Observers.begin(), m_Observers.end(), hasSameTag)) { o.m_Command->Execute(self, event); } return; } ++i; } return; } Command * Object::SubjectImplementation::GetCommand(unsigned long tag) { for (auto & observer : m_Observers) { if (observer.m_Tag == tag) { return observer.m_Command; } } return nullptr; } bool Object::SubjectImplementation::HasObserver(const EventObject & event) const { for (const auto & observer : m_Observers) { const EventObject * e = observer.m_Event.get(); if (e->CheckEvent(&event)) { return true; } } return false; } bool Object::SubjectImplementation::PrintObservers(std::ostream & os, Indent indent) const { if (m_Observers.empty()) { return false; } for (const auto & observer : m_Observers) { const EventObject * e = observer.m_Event.get(); const Command * c = observer.m_Command; os << indent << e->GetEventName() << "(" << c->GetNameOfClass(); if (!c->GetObjectName().empty()) { os << " \"" << c->GetObjectName() << "\""; } os << ")\n"; } return true; } Object::Pointer Object::New() { Pointer smartPtr; Object * rawPtr = itk::ObjectFactory<Object>::Create(); if (rawPtr == nullptr) { rawPtr = new Object; } smartPtr = rawPtr; rawPtr->UnRegister(); return smartPtr; } LightObject::Pointer Object::CreateAnother() const { return Object::New().GetPointer(); } /** * Turn debugging output on. */ void Object::DebugOn() const { m_Debug = true; } /** * Turn debugging output off. */ void Object::DebugOff() const { m_Debug = false; } /** * Get the value of the debug flag. */ bool Object::GetDebug() const { return m_Debug; } /** * Set the value of the debug flag. A non-zero value turns debugging on. */ void Object::SetDebug(bool debugFlag) const { m_Debug = debugFlag; } /** * Return the modification for this object. */ ModifiedTimeType Object::GetMTime() const { return m_MTime.GetMTime(); } /** * Return the modification for this object. */ const TimeStamp & Object::GetTimeStamp() const { return m_MTime; } /** Set the time stamp of this object. To be used very carefully !!!. * Most mortals will never need to call this method. */ void Object::SetTimeStamp(const TimeStamp & timeStamp) { this->m_MTime = timeStamp; } /** * Make sure this object's modified time is greater than all others. */ void Object::Modified() const { m_MTime.Modified(); InvokeEvent(ModifiedEvent()); } /** * Increase the reference count (mark as used by another object). */ void Object::Register() const { itkDebugMacro(<< "Registered, " << "ReferenceCount = " << (m_ReferenceCount + 1)); // call the parent Superclass::Register(); } /** * Decrease the reference count (release by another object). */ void Object::UnRegister() const noexcept { // call the parent itkDebugMacro(<< "UnRegistered, " << "ReferenceCount = " << (m_ReferenceCount - 1)); if ((m_ReferenceCount - 1) <= 0) { /** * If there is a delete method, invoke it. */ try { this->InvokeEvent(DeleteEvent()); } catch (...) { // The macro is not use to avoid a memory allocation, and reduce // potential exceptions. // itkWarningMacro("Exception occurred in DeleteEvent Observer!"); try { if (GetGlobalWarningDisplay()) { itk::OutputWindowDisplayWarningText("WARNING: Exception occurred in DeleteEvent Observer!"); } } catch (...) { // ignore exception in warning display } } } Superclass::UnRegister(); } /** * Sets the reference count (use with care) */ void Object::SetReferenceCount(int ref) { itkDebugMacro(<< "Reference Count set to " << ref); // ReferenceCount in now unlocked. We may have a race condition to // to delete the object. if (ref <= 0) { /** * If there is a delete method, invoke it. */ try { this->InvokeEvent(DeleteEvent()); } catch (...) { itkWarningMacro("Exception occurred in DeleteEvent Observer!"); } } Superclass::SetReferenceCount(ref); } /** * Set the value of the global debug output control flag. */ void Object::SetGlobalWarningDisplay(bool val) { itkInitGlobalsMacro(GlobalWarningDisplay); *m_GlobalWarningDisplay = val; } /** * Get the value of the global debug output control flag. */ bool Object::GetGlobalWarningDisplay() { return *Object::GetGlobalWarningDisplayPointer(); } unsigned long Object::AddObserver(const EventObject & event, Command * cmd) { if (!this->m_SubjectImplementation) { this->m_SubjectImplementation = std::make_unique<SubjectImplementation>(); } return this->m_SubjectImplementation->AddObserver(event, cmd); } unsigned long Object::AddObserver(const EventObject & event, Command * cmd) const { if (!this->m_SubjectImplementation) { auto * me = const_cast<Self *>(this); me->m_SubjectImplementation = std::make_unique<SubjectImplementation>(); } return this->m_SubjectImplementation->AddObserver(event, cmd); } unsigned long Object::AddObserver(const EventObject & event, std::function<void(const EventObject &)> function) const { auto cmd = FunctionCommand::New(); cmd->SetCallback(std::move(function)); return this->AddObserver(event, cmd); } Command * Object::GetCommand(unsigned long tag) { if (this->m_SubjectImplementation) { return this->m_SubjectImplementation->GetCommand(tag); } return nullptr; } void Object::RemoveObserver(unsigned long tag) { if (this->m_SubjectImplementation) { this->m_SubjectImplementation->RemoveObserver(tag); } } void Object::RemoveAllObservers() { if (this->m_SubjectImplementation) { this->m_SubjectImplementation->RemoveAllObservers(); } } void Object::InvokeEvent(const EventObject & event) { if (this->m_SubjectImplementation) { this->m_SubjectImplementation->InvokeEvent(event, this); } } void Object::InvokeEvent(const EventObject & event) const { if (this->m_SubjectImplementation) { this->m_SubjectImplementation->InvokeEvent(event, this); } } bool Object::HasObserver(const EventObject & event) const { if (this->m_SubjectImplementation) { return this->m_SubjectImplementation->HasObserver(event); } return false; } bool Object::PrintObservers(std::ostream & os, Indent indent) const { if (this->m_SubjectImplementation) { return this->m_SubjectImplementation->PrintObservers(os, indent); } return false; } /** * Create an object with Debug turned off and modified time initialized * to the most recently modified object. */ Object::Object() : LightObject() , m_ObjectName() { this->Modified(); } Object::~Object() { itkDebugMacro(<< "Destructing!"); } /** * Chaining method to print an object's instance variables, as well as * its superclasses. */ void Object::PrintSelf(std::ostream & os, Indent indent) const { Superclass::PrintSelf(os, indent); os << indent << "Modified Time: " << this->GetMTime() << std::endl; os << indent << "Debug: " << (m_Debug ? "On\n" : "Off\n"); os << indent << "Object Name: " << this->GetObjectName() << std::endl; os << indent << "Observers: \n"; if (!this->PrintObservers(os, indent.GetNextIndent())) { os << indent.GetNextIndent() << "none\n"; } } MetaDataDictionary & Object::GetMetaDataDictionary() { if (m_MetaDataDictionary == nullptr) { m_MetaDataDictionary = std::make_unique<MetaDataDictionary>(); } return *m_MetaDataDictionary; } const MetaDataDictionary & Object::GetMetaDataDictionary() const { if (m_MetaDataDictionary == nullptr) { m_MetaDataDictionary = std::make_unique<MetaDataDictionary>(); } return *m_MetaDataDictionary; } void Object::SetMetaDataDictionary(const MetaDataDictionary & rhs) { if (m_MetaDataDictionary == nullptr) { m_MetaDataDictionary = std::make_unique<MetaDataDictionary>(rhs); return; } *m_MetaDataDictionary = rhs; } void Object::SetMetaDataDictionary(MetaDataDictionary && rrhs) { if (m_MetaDataDictionary == nullptr) { m_MetaDataDictionary = std::make_unique<MetaDataDictionary>(std::move(rrhs)); return; } *m_MetaDataDictionary = std::move(rrhs); } } // end namespace itk <|endoftext|>
<commit_before>/* * Copyright 2015 Cloudius Systems * */ #include <yaml-cpp/yaml.h> #include <boost/program_options.hpp> #include <unordered_map> #include <regex> #include "config.hh" #include "core/file.hh" #include "core/reactor.hh" #include "core/shared_ptr.hh" #include "core/fstream.hh" #include "core/do_with.hh" #include "log.hh" static logging::logger logger("config"); db::config::config() : // Initialize members to defaults. #define _mk_init(name, type, deflt, status, desc, ...) \ name(deflt), _make_config_values(_mk_init) _dummy(0) {} namespace bpo = boost::program_options; // Special "validator" for boost::program_options to allow reading options // into an unordered_map<string, string> (we have in config.hh a bunch of // those). This validator allows the parameter of each option to look like // 'key=value'. It also allows multiple occurrences of this option to add // multiple entries into the map. "String" can be any time which can be // converted from std::string, e.g., sstring. template<typename String> static void validate(boost::any& out, const std::vector<std::string>& in, std::unordered_map<String, String>*, int) { if (out.empty()) { out = boost::any(std::unordered_map<String, String>()); } auto* p = boost::any_cast<std::unordered_map<String, String>>(&out); for (const auto& s : in) { auto i = s.find_first_of('='); if (i == std::string::npos) { throw boost::program_options::invalid_option_value(s); } (*p)[String(s.substr(0, i))] = String(s.substr(i+1)); } } namespace YAML { /* * Add converters as needed here... */ template<> struct convert<sstring> { static Node encode(sstring rhs) { auto p = rhs.c_str(); return convert<const char *>::encode(p); } static bool decode(const Node& node, sstring& rhs) { std::string tmp; if (!convert<std::string>::decode(node, tmp)) { return false; } rhs = tmp; return true; } }; template <> struct convert<db::config::string_list> { static Node encode(const db::config::string_list& rhs) { Node node(NodeType::Sequence); for (auto& s : rhs) { node.push_back(convert<sstring>::encode(s)); } return node; } static bool decode(const Node& node, db::config::string_list& rhs) { if (!node.IsSequence()) { return false; } rhs.clear(); for (auto& n : node) { sstring tmp; if (!convert<sstring>::decode(n,tmp)) { return false; } rhs.push_back(tmp); } return true; } }; template<typename K, typename V> struct convert<std::unordered_map<K, V>> { static Node encode(const std::unordered_map<K, V>& rhs) { Node node(NodeType::Map); for(typename std::map<K, V>::const_iterator it=rhs.begin();it!=rhs.end();++it) node.force_insert(it->first, it->second); return node; } static bool decode(const Node& node, std::unordered_map<K, V>& rhs) { if (!node.IsMap()) { return false; } rhs.clear(); for (auto& n : node) { rhs[n.first.as<K>()] = n.second.as<V>(); } return true; } }; template<> struct convert<db::config::seed_provider_type> { static Node encode(const db::config::seed_provider_type& rhs) { throw std::runtime_error("should not reach"); } static bool decode(const Node& node, db::config::seed_provider_type& rhs) { if (!node.IsSequence()) { return false; } rhs = db::config::seed_provider_type(); for (auto& n : node) { if (!n.IsMap()) { continue; } for (auto& n2 : n) { if (n2.first.as<sstring>() == "class_name") { rhs.class_name = n2.second.as<sstring>(); } if (n2.first.as<sstring>() == "parameters") { auto v = n2.second.as<std::vector<db::config::string_map>>(); if (!v.empty()) { rhs.parameters = v.front(); } } } } return true; } }; } template<typename... Args> std::basic_ostream<Args...> & operator<<(std::basic_ostream<Args...> & os, const db::config::string_map & map) { int n = 0; for (auto& e : map) { if (n > 0) { os << ":"; } os << e.first << "=" << e.second; } return os; } template<typename... Args> std::basic_istream<Args...> & operator>>(std::basic_istream<Args...> & is, db::config::string_map & map) { std::string str; is >> str; std::regex colon(":"); std::sregex_token_iterator s(str.begin(), str.end(), colon, -1); std::sregex_token_iterator e; while (s != e) { sstring p = std::string(*s++); auto i = p.find('='); auto k = p.substr(0, i); auto v = i == sstring::npos ? sstring() : p.substr(i + 1, p.size()); map.emplace(std::make_pair(k, v)); }; return is; } /* * Helper type to do compile time exclusion of Unused/invalid options from * command line. * * Only opts marked "used" should get a boost::opt * */ template<typename T, db::config::value_status S> struct do_value_opt; template<typename T> struct do_value_opt<T, db::config::value_status::Used> { template<typename Func> void operator()(Func&& func, const char* name, const T& dflt, T * dst, db::config::config_source & src, const char* desc) const { func(name, dflt, dst, src, desc); } }; template<> struct do_value_opt<db::config::seed_provider_type, db::config::value_status::Used> { using seed_provider_type = db::config::seed_provider_type; template<typename Func> void operator()(Func&& func, const char* name, const seed_provider_type& dflt, seed_provider_type * dst, db::config::config_source & src, const char* desc) const { func((sstring(name) + "_class_name").c_str(), dflt.class_name, &dst->class_name, src, desc); func((sstring(name) + "_parameters").c_str(), dflt.parameters, &dst->parameters, src, desc); } }; template<typename T> struct do_value_opt<T, db::config::value_status::Unused> { template<typename... Args> void operator()(Args&&... args) const {} }; template<typename T> struct do_value_opt<T, db::config::value_status::Invalid> { template<typename... Args> void operator()(Args&&... args) const {} }; bpo::options_description db::config::get_options_description() { bpo::options_description opts("Urchin options"); auto init = opts.add_options(); add_options(init); return std::move(opts); } /* * Our own bpo::typed_valye. * Only difference is that we _don't_ apply defaults (they are already applied) * Needed to make aliases work properly. */ template<class T, class charT = char> class typed_value_ex : public bpo::typed_value<T, charT> { public: typedef bpo::typed_value<T, charT> _Super; typed_value_ex(T* store_to) : _Super(store_to) {} bool apply_default(boost::any& value_store) const override { return false; } }; template<class T> inline typed_value_ex<T>* value_ex(T* v) { typed_value_ex<T>* r = new typed_value_ex<T>(v); return r; } template<class T> inline typed_value_ex<std::vector<T>>* value_ex(std::vector<T>* v) { auto r = new typed_value_ex<std::vector<T>>(v); r->multitoken(); return r; } bpo::options_description_easy_init& db::config::add_options(bpo::options_description_easy_init& init) { auto opt_add = [&init](const char* name, const auto& dflt, auto* dst, auto& src, const char* desc) mutable { sstring tmp(name); std::replace(tmp.begin(), tmp.end(), '_', '-'); init(tmp.c_str(), value_ex(dst)->default_value(dflt)->notifier([&src](auto) mutable { src = config_source::CommandLine; }) , desc); }; // Add all used opts as command line opts #define _add_boost_opt(name, type, deflt, status, desc, ...) \ do_value_opt<type, value_status::status>()(opt_add, #name, type( deflt ), &name._value, name._source, desc); _make_config_values(_add_boost_opt) auto alias_add = [&init](const char* name, auto& dst, const char* desc) mutable { init(name, value_ex(&dst._value)->notifier([&dst](auto& v) mutable { dst._source = config_source::CommandLine; }) , desc); }; // Handle "old" syntax with "aliases" alias_add("datadir", data_file_directories, "alias for 'data-file-directories'"); alias_add("thrift-port", rpc_port, "alias for 'rpc-port'"); alias_add("cql-port", native_transport_port, "alias for 'native-transport-port'"); return init; } // Virtual dispatch to convert yaml->data type. struct handle_yaml { virtual ~handle_yaml() {}; virtual void operator()(const YAML::Node&) = 0; virtual db::config::value_status status() const = 0; virtual db::config::config_source source() const = 0; }; template<typename T, db::config::value_status S> struct handle_yaml_impl : public handle_yaml { typedef db::config::value<T, S> value_type; handle_yaml_impl(value_type& v, db::config::config_source& src) : _dst(v), _src(src) {} void operator()(const YAML::Node& node) override { _dst(node.as<T>()); _src = db::config::config_source::SettingsFile; } db::config::value_status status() const override { return _dst.status(); } db::config::config_source source() const override { return _src; } value_type& _dst; db::config::config_source& _src; }; void db::config::read_from_yaml(const sstring& yaml) { read_from_yaml(yaml.c_str()); } void db::config::read_from_yaml(const char* yaml) { std::unordered_map<sstring, std::unique_ptr<handle_yaml>> values; #define _add_yaml_opt(name, type, deflt, status, desc, ...) \ values.emplace(#name, std::make_unique<handle_yaml_impl<type, value_status::status>>(name, name._source)); _make_config_values(_add_yaml_opt) /* * Note: this is not very "half-fault" tolerant. I.e. there could be * yaml syntax errors that origin handles and still sets the options * where as we don't... * There are no exhaustive attempts at converting, we rely on syntax of * file mapping to the data type... */ auto doc = YAML::Load(yaml); for (auto node : doc) { auto label = node.first.as<sstring>(); auto i = values.find(label); if (i == values.end()) { logger.warn("Unknown option {} ignored.", label); continue; } if (i->second->source() > config_source::SettingsFile) { logger.debug("Option {} already set by commandline. ignored.", label); continue; } switch (i->second->status()) { case value_status::Invalid: logger.warn("Option {} is not applicable. Ignoring.", label); continue; case value_status::Unused: logger.debug("Option {} is not (yet) used.", label); break; default: break; } if (node.second.IsNull()) { logger.debug("Option {}, empty value. Skipping.", label); continue; } // Still, a syntax error is an error warning, not a fail try { (*i->second)(node.second); } catch (...) { logger.error("Option {}, exception while converting value.", label); } } } future<> db::config::read_from_file(file f) { return f.size().then([this, f](size_t s) { return do_with(make_file_input_stream(f), [this, s](input_stream<char>& in) { return in.read_exactly(s).then([this](temporary_buffer<char> buf) { read_from_yaml(sstring(buf.begin(), buf.end())); }); }); }); } future<> db::config::read_from_file(const sstring& filename) { return engine().open_file_dma(filename, open_flags::ro).then([this](file f) { return read_from_file(std::move(f)); }); } <commit_msg>config.cc : add logging of unset attributes<commit_after>/* * Copyright 2015 Cloudius Systems * */ #include <yaml-cpp/yaml.h> #include <boost/program_options.hpp> #include <unordered_map> #include <regex> #include "config.hh" #include "core/file.hh" #include "core/reactor.hh" #include "core/shared_ptr.hh" #include "core/fstream.hh" #include "core/do_with.hh" #include "log.hh" static logging::logger logger("config"); db::config::config() : // Initialize members to defaults. #define _mk_init(name, type, deflt, status, desc, ...) \ name(deflt), _make_config_values(_mk_init) _dummy(0) {} namespace bpo = boost::program_options; // Special "validator" for boost::program_options to allow reading options // into an unordered_map<string, string> (we have in config.hh a bunch of // those). This validator allows the parameter of each option to look like // 'key=value'. It also allows multiple occurrences of this option to add // multiple entries into the map. "String" can be any time which can be // converted from std::string, e.g., sstring. template<typename String> static void validate(boost::any& out, const std::vector<std::string>& in, std::unordered_map<String, String>*, int) { if (out.empty()) { out = boost::any(std::unordered_map<String, String>()); } auto* p = boost::any_cast<std::unordered_map<String, String>>(&out); for (const auto& s : in) { auto i = s.find_first_of('='); if (i == std::string::npos) { throw boost::program_options::invalid_option_value(s); } (*p)[String(s.substr(0, i))] = String(s.substr(i+1)); } } namespace YAML { /* * Add converters as needed here... */ template<> struct convert<sstring> { static Node encode(sstring rhs) { auto p = rhs.c_str(); return convert<const char *>::encode(p); } static bool decode(const Node& node, sstring& rhs) { std::string tmp; if (!convert<std::string>::decode(node, tmp)) { return false; } rhs = tmp; return true; } }; template <> struct convert<db::config::string_list> { static Node encode(const db::config::string_list& rhs) { Node node(NodeType::Sequence); for (auto& s : rhs) { node.push_back(convert<sstring>::encode(s)); } return node; } static bool decode(const Node& node, db::config::string_list& rhs) { if (!node.IsSequence()) { return false; } rhs.clear(); for (auto& n : node) { sstring tmp; if (!convert<sstring>::decode(n,tmp)) { return false; } rhs.push_back(tmp); } return true; } }; template<typename K, typename V> struct convert<std::unordered_map<K, V>> { static Node encode(const std::unordered_map<K, V>& rhs) { Node node(NodeType::Map); for(typename std::map<K, V>::const_iterator it=rhs.begin();it!=rhs.end();++it) node.force_insert(it->first, it->second); return node; } static bool decode(const Node& node, std::unordered_map<K, V>& rhs) { if (!node.IsMap()) { return false; } rhs.clear(); for (auto& n : node) { rhs[n.first.as<K>()] = n.second.as<V>(); } return true; } }; template<> struct convert<db::config::seed_provider_type> { static Node encode(const db::config::seed_provider_type& rhs) { throw std::runtime_error("should not reach"); } static bool decode(const Node& node, db::config::seed_provider_type& rhs) { if (!node.IsSequence()) { return false; } rhs = db::config::seed_provider_type(); for (auto& n : node) { if (!n.IsMap()) { continue; } for (auto& n2 : n) { if (n2.first.as<sstring>() == "class_name") { rhs.class_name = n2.second.as<sstring>(); } if (n2.first.as<sstring>() == "parameters") { auto v = n2.second.as<std::vector<db::config::string_map>>(); if (!v.empty()) { rhs.parameters = v.front(); } } } } return true; } }; } template<typename... Args> std::basic_ostream<Args...> & operator<<(std::basic_ostream<Args...> & os, const db::config::string_map & map) { int n = 0; for (auto& e : map) { if (n > 0) { os << ":"; } os << e.first << "=" << e.second; } return os; } template<typename... Args> std::basic_istream<Args...> & operator>>(std::basic_istream<Args...> & is, db::config::string_map & map) { std::string str; is >> str; std::regex colon(":"); std::sregex_token_iterator s(str.begin(), str.end(), colon, -1); std::sregex_token_iterator e; while (s != e) { sstring p = std::string(*s++); auto i = p.find('='); auto k = p.substr(0, i); auto v = i == sstring::npos ? sstring() : p.substr(i + 1, p.size()); map.emplace(std::make_pair(k, v)); }; return is; } /* * Helper type to do compile time exclusion of Unused/invalid options from * command line. * * Only opts marked "used" should get a boost::opt * */ template<typename T, db::config::value_status S> struct do_value_opt; template<typename T> struct do_value_opt<T, db::config::value_status::Used> { template<typename Func> void operator()(Func&& func, const char* name, const T& dflt, T * dst, db::config::config_source & src, const char* desc) const { func(name, dflt, dst, src, desc); } }; template<> struct do_value_opt<db::config::seed_provider_type, db::config::value_status::Used> { using seed_provider_type = db::config::seed_provider_type; template<typename Func> void operator()(Func&& func, const char* name, const seed_provider_type& dflt, seed_provider_type * dst, db::config::config_source & src, const char* desc) const { func((sstring(name) + "_class_name").c_str(), dflt.class_name, &dst->class_name, src, desc); func((sstring(name) + "_parameters").c_str(), dflt.parameters, &dst->parameters, src, desc); } }; template<typename T> struct do_value_opt<T, db::config::value_status::Unused> { template<typename... Args> void operator()(Args&&... args) const {} }; template<typename T> struct do_value_opt<T, db::config::value_status::Invalid> { template<typename... Args> void operator()(Args&&... args) const {} }; bpo::options_description db::config::get_options_description() { bpo::options_description opts("Urchin options"); auto init = opts.add_options(); add_options(init); return std::move(opts); } /* * Our own bpo::typed_valye. * Only difference is that we _don't_ apply defaults (they are already applied) * Needed to make aliases work properly. */ template<class T, class charT = char> class typed_value_ex : public bpo::typed_value<T, charT> { public: typedef bpo::typed_value<T, charT> _Super; typed_value_ex(T* store_to) : _Super(store_to) {} bool apply_default(boost::any& value_store) const override { return false; } }; template<class T> inline typed_value_ex<T>* value_ex(T* v) { typed_value_ex<T>* r = new typed_value_ex<T>(v); return r; } template<class T> inline typed_value_ex<std::vector<T>>* value_ex(std::vector<T>* v) { auto r = new typed_value_ex<std::vector<T>>(v); r->multitoken(); return r; } bpo::options_description_easy_init& db::config::add_options(bpo::options_description_easy_init& init) { auto opt_add = [&init](const char* name, const auto& dflt, auto* dst, auto& src, const char* desc) mutable { sstring tmp(name); std::replace(tmp.begin(), tmp.end(), '_', '-'); init(tmp.c_str(), value_ex(dst)->default_value(dflt)->notifier([&src](auto) mutable { src = config_source::CommandLine; }) , desc); }; // Add all used opts as command line opts #define _add_boost_opt(name, type, deflt, status, desc, ...) \ do_value_opt<type, value_status::status>()(opt_add, #name, type( deflt ), &name._value, name._source, desc); _make_config_values(_add_boost_opt) auto alias_add = [&init](const char* name, auto& dst, const char* desc) mutable { init(name, value_ex(&dst._value)->notifier([&dst](auto& v) mutable { dst._source = config_source::CommandLine; }) , desc); }; // Handle "old" syntax with "aliases" alias_add("datadir", data_file_directories, "alias for 'data-file-directories'"); alias_add("thrift-port", rpc_port, "alias for 'rpc-port'"); alias_add("cql-port", native_transport_port, "alias for 'native-transport-port'"); return init; } // Virtual dispatch to convert yaml->data type. struct handle_yaml { virtual ~handle_yaml() {}; virtual void operator()(const YAML::Node&) = 0; virtual db::config::value_status status() const = 0; virtual db::config::config_source source() const = 0; }; template<typename T, db::config::value_status S> struct handle_yaml_impl : public handle_yaml { typedef db::config::value<T, S> value_type; handle_yaml_impl(value_type& v, db::config::config_source& src) : _dst(v), _src(src) {} void operator()(const YAML::Node& node) override { _dst(node.as<T>()); _src = db::config::config_source::SettingsFile; } db::config::value_status status() const override { return _dst.status(); } db::config::config_source source() const override { return _src; } value_type& _dst; db::config::config_source& _src; }; void db::config::read_from_yaml(const sstring& yaml) { read_from_yaml(yaml.c_str()); } void db::config::read_from_yaml(const char* yaml) { std::unordered_map<sstring, std::unique_ptr<handle_yaml>> values; #define _add_yaml_opt(name, type, deflt, status, desc, ...) \ values.emplace(#name, std::make_unique<handle_yaml_impl<type, value_status::status>>(name, name._source)); _make_config_values(_add_yaml_opt) /* * Note: this is not very "half-fault" tolerant. I.e. there could be * yaml syntax errors that origin handles and still sets the options * where as we don't... * There are no exhaustive attempts at converting, we rely on syntax of * file mapping to the data type... */ auto doc = YAML::Load(yaml); for (auto node : doc) { auto label = node.first.as<sstring>(); auto i = values.find(label); if (i == values.end()) { logger.warn("Unknown option {} ignored.", label); continue; } if (i->second->source() > config_source::SettingsFile) { logger.debug("Option {} already set by commandline. ignored.", label); continue; } switch (i->second->status()) { case value_status::Invalid: logger.warn("Option {} is not applicable. Ignoring.", label); continue; case value_status::Unused: logger.debug("Option {} is not (yet) used.", label); break; default: break; } if (node.second.IsNull()) { logger.debug("Option {}, empty value. Skipping.", label); continue; } // Still, a syntax error is an error warning, not a fail try { (*i->second)(node.second); } catch (...) { logger.error("Option {}, exception while converting value.", label); } } for (auto& p : values) { if (p.second->status() > value_status::Used) { continue; } if (p.second->source() > config_source::None) { continue; } logger.debug("Option {} not set", p.first); } } future<> db::config::read_from_file(file f) { return f.size().then([this, f](size_t s) { return do_with(make_file_input_stream(f), [this, s](input_stream<char>& in) { return in.read_exactly(s).then([this](temporary_buffer<char> buf) { read_from_yaml(sstring(buf.begin(), buf.end())); }); }); }); } future<> db::config::read_from_file(const sstring& filename) { return engine().open_file_dma(filename, open_flags::ro).then([this](file f) { return read_from_file(std::move(f)); }); } <|endoftext|>
<commit_before>// Copyright (c) 2009 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "app/l10n_util.h" #include "base/command_line.h" #include "chrome/browser/browser.h" #include "chrome/browser/debugger/devtools_client_host.h" #include "chrome/browser/debugger/devtools_manager.h" #include "chrome/browser/debugger/devtools_window.h" #include "chrome/browser/profile.h" #include "chrome/browser/tab_contents/tab_contents.h" #include "chrome/browser/tab_contents/tab_contents_view.h" #include "chrome/common/chrome_switches.h" #include "chrome/common/pref_names.h" #include "chrome/common/pref_service.h" #include "chrome/common/render_messages.h" #include "chrome/common/url_constants.h" #include "grit/generated_resources.h" DevToolsWindow::DevToolsWindow(Profile* profile) : TabStripModelObserver(), inspected_tab_closing_(false) { static bool g_prefs_registered = false; if (!g_prefs_registered) { std::wstring window_pref(prefs::kBrowserWindowPlacement); window_pref.append(L"_"); window_pref.append(L"DevToolsApp"); PrefService* prefs = g_browser_process->local_state(); prefs->RegisterDictionaryPref(window_pref.c_str()); g_prefs_registered = true; } browser_.reset(Browser::CreateForApp(L"DevToolsApp", profile, false)); GURL contents(std::string(chrome::kChromeUIDevToolsURL) + "devtools.html"); browser_->AddTabWithURL(contents, GURL(), PageTransition::START_PAGE, true, -1, false, NULL); tab_contents_ = browser_->GetSelectedTabContents(); browser_->tabstrip_model()->AddObserver(this); } DevToolsWindow::~DevToolsWindow() { } void DevToolsWindow::Show() { browser_->window()->Show(); tab_contents_->view()->SetInitialFocus(); } DevToolsWindow* DevToolsWindow::AsDevToolsWindow() { return this; } RenderViewHost* DevToolsWindow::GetRenderViewHost() const { return tab_contents_->render_view_host(); } void DevToolsWindow::InspectedTabClosing() { inspected_tab_closing_ = true; browser_->CloseAllTabs(); } void DevToolsWindow::SendMessageToClient(const IPC::Message& message) { RenderViewHost* target_host = tab_contents_->render_view_host(); IPC::Message* m = new IPC::Message(message); m->set_routing_id(target_host->routing_id()); target_host->Send(m); } void DevToolsWindow::TabClosingAt(TabContents* contents, int index) { if (!inspected_tab_closing_ && contents == tab_contents_) { // Notify manager that this DevToolsClientHost no longer exists. NotifyCloseListener(); } if (browser_->tabstrip_model()->empty()) { // We are removing the last tab. Delete browser along with the // tabstrip_model and its listeners. delete this; } } <commit_msg>DevTools: Provide nice initial location/size for the devtools window.<commit_after>// Copyright (c) 2009 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "app/l10n_util.h" #include "base/command_line.h" #include "chrome/browser/browser.h" #include "chrome/browser/debugger/devtools_client_host.h" #include "chrome/browser/debugger/devtools_manager.h" #include "chrome/browser/debugger/devtools_window.h" #include "chrome/browser/profile.h" #include "chrome/browser/tab_contents/tab_contents.h" #include "chrome/browser/tab_contents/tab_contents_view.h" #include "chrome/common/chrome_switches.h" #include "chrome/common/pref_names.h" #include "chrome/common/pref_service.h" #include "chrome/common/render_messages.h" #include "chrome/common/url_constants.h" #include "grit/generated_resources.h" DevToolsWindow::DevToolsWindow(Profile* profile) : TabStripModelObserver(), inspected_tab_closing_(false) { static std::wstring g_wp_key = L""; if (g_wp_key.empty()) { // TODO(pfeldman): Make browser's getter for this key static. g_wp_key.append(prefs::kBrowserWindowPlacement); g_wp_key.append(L"_"); g_wp_key.append(L"DevToolsApp"); PrefService* prefs = g_browser_process->local_state(); prefs->RegisterDictionaryPref(g_wp_key.c_str()); const DictionaryValue* wp_pref = prefs->GetDictionary(g_wp_key.c_str()); if (!wp_pref) { DictionaryValue* defaults = prefs->GetMutableDictionary( g_wp_key.c_str()); defaults->SetInteger(L"left", 100); defaults->SetInteger(L"top", 100); defaults->SetInteger(L"right", 740); defaults->SetInteger(L"bottom", 740); defaults->SetBoolean(L"maximized", false); defaults->SetBoolean(L"always_on_top", false); } } browser_.reset(Browser::CreateForApp(L"DevToolsApp", profile, false)); GURL contents(std::string(chrome::kChromeUIDevToolsURL) + "devtools.html"); browser_->AddTabWithURL(contents, GURL(), PageTransition::START_PAGE, true, -1, false, NULL); tab_contents_ = browser_->GetSelectedTabContents(); browser_->tabstrip_model()->AddObserver(this); } DevToolsWindow::~DevToolsWindow() { } void DevToolsWindow::Show() { browser_->window()->Show(); tab_contents_->view()->SetInitialFocus(); } DevToolsWindow* DevToolsWindow::AsDevToolsWindow() { return this; } RenderViewHost* DevToolsWindow::GetRenderViewHost() const { return tab_contents_->render_view_host(); } void DevToolsWindow::InspectedTabClosing() { inspected_tab_closing_ = true; browser_->CloseAllTabs(); } void DevToolsWindow::SendMessageToClient(const IPC::Message& message) { RenderViewHost* target_host = tab_contents_->render_view_host(); IPC::Message* m = new IPC::Message(message); m->set_routing_id(target_host->routing_id()); target_host->Send(m); } void DevToolsWindow::TabClosingAt(TabContents* contents, int index) { if (!inspected_tab_closing_ && contents == tab_contents_) { // Notify manager that this DevToolsClientHost no longer exists. NotifyCloseListener(); } if (browser_->tabstrip_model()->empty()) { // We are removing the last tab. Delete browser along with the // tabstrip_model and its listeners. delete this; } } <|endoftext|>
<commit_before>/* * Copyright 2014 David Moreno Montero <dmoreno@coralbits.com> * * 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 <string> #include <vector> #include <boost/concept_check.hpp> #include "underscore.hpp" namespace underscore{ class string; typedef ::underscore::underscore<std::vector<string>> string_list; typedef std::vector<string> std_string_list; class string{ std::string _str; public: string(std::string &&str) : _str(std::move(str)){}; string(const std::string &str) : _str(str){}; string(const char *str) : _str(str){}; template<typename T> string(const T &v) : _str(std::to_string(v)){}; string() : _str(){}; string_list split(const char &sep=',', bool insert_empty_elements=false) const { std_string_list v; std::string el; std::string::const_iterator I=_str.begin(), endI=_str.end(); std::string::const_iterator p; do{ p=std::find(I, endI, sep); el=std::string(I, p); if (insert_empty_elements || !el.empty()) v.push_back(std::move(el)); I=p+1; }while(p!=endI); return string_list(std::move(v)); } string_list split(const std::string &sep, bool insert_empty_elements=false) const { std_string_list v; std::string el; auto I=_str.begin(), endI=_str.end(), sepBegin=sep.begin(), sepEnd=sep.end(); std::string::const_iterator p; do{ p=std::search(I, endI, sepBegin, sepEnd); el=std::string(I, p); if (insert_empty_elements || !el.empty()) v.push_back(el); I=p+sep.size(); }while(p!=endI); return string_list(std::move(v)); } string lower() const{ std::string ret; ret.reserve(_str.size()); for (auto c: _str) ret.push_back(::tolower(c)); return string(std::move(ret)); }; string upper() const{ std::string ret; ret.reserve(_str.size()); for (auto c: _str) ret.push_back(::toupper(c)); return string(std::move(ret)); }; bool startswith(const std::string &starting) const { if (_str.size()<starting.size()) return false; return (_str.substr(0,starting.size())==starting); } bool endswith(const std::string &ending) const { if (_str.size()<ending.size()) return false; return (_str.substr(_str.size()-ending.size())==ending); } bool contains(const std::string &substr) const { return _str.find(substr)!=std::string::npos; } string replace(const std::string &orig, const std::string &replace_with){ std::string ret=_str; size_t pos = 0; size_t orig_length = orig.length(); size_t replace_with_length = replace_with.length(); while((pos = ret.find(orig, pos)) != std::string::npos) { ret.replace(pos, orig_length, replace_with); pos += replace_with_length; } return ret; } /** * @short Removes all spaces, new lines and tabs from begining and end. */ string strip() const{ auto begin=_str.find_first_not_of(" \n\t"); auto end=_str.find_last_not_of(" \n\t"); return slice(begin, end+1); } operator std::string() const{ return _str; } size_t size() const { return _str.size(); } size_t length() const{ return size(); } bool empty() const{ return _str.empty(); } string slice(ssize_t start, ssize_t end) const{ ssize_t s=size(); if (end<0) end=s+end+1; if (end<0) return std::string(); if (end>s) end=s; if (start<0) start=s+start; if (start<0) start=0; if (start>s) return std::string(); if (start==0 && end==s) return *this; return _str.substr(start, end-start); } string format(std::initializer_list<string> &&str_list){ auto ulist=string_list(str_list); // std::cout<<"as ulist "<<ulist.join(", ")<<std::endl; return format(ulist); } class invalid_format : public std::exception{ public: const char *what() const throw(){ return "Invalid string format"; }; }; class invalid_format_require_more_arguments : public invalid_format{ public: const char *what() const throw(){ return "Invalid string format, requires more arguments."; }; }; class invalid_format_too_many_arguments : public invalid_format{ public: const char *what() const throw(){ return "Invalid string format, it has too many arguments."; }; }; string format(const string_list &sl){ std::string ret; auto res=size() + sl.reduce<size_t>([](const string &str, size_t s){ return s+str.size(); }, 0); // std::cout<<"reserve "<<res<<std::endl; ret.reserve(res); int n=0; auto sl_size=sl.size(); for (auto &part: split("{}", true)){ ret+=part; if (n<sl_size){ ret+=sl[n]; } else if (n>sl_size){ throw invalid_format_require_more_arguments(); } // else is just enought aguments, so ok. n++; // std::cout<<"format "<<ret<<std::endl; } if (n<=sl_size){ throw invalid_format_too_many_arguments(); } return ret; } long to_long() const { size_t n; long l=stol(_str, &n); if (n!=_str.size()) throw std::invalid_argument(_str); return l; } double to_double() const { size_t n; double f=stod(_str, &n); if (n!=_str.size()) throw std::invalid_argument(_str); return f; } float to_float() const { size_t n; float f=stof(_str, &n); if (n!=_str.size()) throw std::invalid_argument(_str); return f; } friend std::ostream& operator <<(std::ostream &output, const string &str) { output << "" << str._str; return output; } }; inline string _(std::string &&s){ return string(std::move(s)); } inline string _(const char *s){ return string(std::string(s)); } };<commit_msg>Compilation fixes.<commit_after>/* * Copyright 2014 David Moreno Montero <dmoreno@coralbits.com> * * 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 <string> #include <vector> #include <boost/concept_check.hpp> #include "underscore.hpp" namespace underscore{ class string; typedef ::underscore::underscore<std::vector<string>> string_list; typedef std::vector<string> std_string_list; class string{ std::string _str; public: string(std::string &&str) : _str(std::move(str)){}; string(const std::string &str) : _str(str){}; string(const char *str) : _str(str){}; template<typename T> string(const T &v) : _str(std::to_string(v)){}; string() : _str(){}; string_list split(const char &sep=',', bool insert_empty_elements=false) const { std_string_list v; std::string el; std::string::const_iterator I=_str.begin(), endI=_str.end(); std::string::const_iterator p; do{ p=std::find(I, endI, sep); el=std::string(I, p); if (insert_empty_elements || !el.empty()) v.push_back(std::move(el)); I=p+1; }while(p!=endI); return string_list(std::move(v)); } string_list split(const std::string &sep, bool insert_empty_elements=false) const { std_string_list v; std::string el; auto I=_str.begin(), endI=_str.end(), sepBegin=sep.begin(), sepEnd=sep.end(); std::string::const_iterator p; do{ p=std::search(I, endI, sepBegin, sepEnd); el=std::string(I, p); if (insert_empty_elements || !el.empty()) v.push_back(el); I=p+sep.size(); }while(p!=endI); return string_list(std::move(v)); } string lower() const{ std::string ret; ret.reserve(_str.size()); for (auto c: _str) ret.push_back(::tolower(c)); return string(std::move(ret)); }; string upper() const{ std::string ret; ret.reserve(_str.size()); for (auto c: _str) ret.push_back(::toupper(c)); return string(std::move(ret)); }; bool startswith(const std::string &starting) const { if (_str.size()<starting.size()) return false; return (_str.substr(0,starting.size())==starting); } bool endswith(const std::string &ending) const { if (_str.size()<ending.size()) return false; return (_str.substr(_str.size()-ending.size())==ending); } bool contains(const std::string &substr) const { return _str.find(substr)!=std::string::npos; } string replace(const std::string &orig, const std::string &replace_with){ std::string ret=_str; size_t pos = 0; size_t orig_length = orig.length(); size_t replace_with_length = replace_with.length(); while((pos = ret.find(orig, pos)) != std::string::npos) { ret.replace(pos, orig_length, replace_with); pos += replace_with_length; } return ret; } /** * @short Removes all spaces, new lines and tabs from begining and end. */ string strip() const{ auto begin=_str.find_first_not_of(" \n\t"); auto end=_str.find_last_not_of(" \n\t"); return slice(begin, end+1); } operator std::string() const{ return _str; } size_t size() const { return _str.size(); } size_t length() const{ return size(); } bool empty() const{ return _str.empty(); } string slice(ssize_t start, ssize_t end) const{ ssize_t s=size(); if (end<0) end=s+end+1; if (end<0) return std::string(); if (end-s>0) end=s; if (start<0) start=s+start; if (start<0) start=0; if (start>s) return std::string(); if (start==0 && end==s) return *this; return _str.substr(start, end-start); } string format(std::initializer_list<string> &&str_list){ auto ulist=string_list(str_list); // std::cout<<"as ulist "<<ulist.join(", ")<<std::endl; return format(ulist); } class invalid_format : public std::exception{ public: const char *what() const throw(){ return "Invalid string format"; }; }; class invalid_format_require_more_arguments : public invalid_format{ public: const char *what() const throw(){ return "Invalid string format, requires more arguments."; }; }; class invalid_format_too_many_arguments : public invalid_format{ public: const char *what() const throw(){ return "Invalid string format, it has too many arguments."; }; }; string format(const string_list &sl){ std::string ret; auto res=size() + sl.reduce<size_t>([](const string &str, size_t s){ return s+str.size(); }, 0); // std::cout<<"reserve "<<res<<std::endl; ret.reserve(res); signed long n=0; signed long sl_size=sl.size(); for (auto &part: split("{}", true)){ ret+=part; if (n<sl_size){ ret+=sl[n]; } else if (n>sl_size){ throw invalid_format_require_more_arguments(); } // else is just enought aguments, so ok. n++; // std::cout<<"format "<<ret<<std::endl; } if (n<=sl_size){ throw invalid_format_too_many_arguments(); } return ret; } long to_long() const { size_t n; long l=stol(_str, &n); if (n!=_str.size()) throw std::invalid_argument(_str); return l; } double to_double() const { size_t n; double f=stod(_str, &n); if (n!=_str.size()) throw std::invalid_argument(_str); return f; } float to_float() const { size_t n; float f=stof(_str, &n); if (n!=_str.size()) throw std::invalid_argument(_str); return f; } friend std::ostream& operator <<(std::ostream &output, const string &str) { output << "" << str._str; return output; } }; inline string _(std::string &&s){ return string(std::move(s)); } inline string _(const char *s){ return string(std::string(s)); } };<|endoftext|>
<commit_before>//===-- sanitizer_tls_get_addr.cc -----------------------------------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // Handle the __tls_get_addr call. // //===----------------------------------------------------------------------===// #include "sanitizer_tls_get_addr.h" #include "sanitizer_flags.h" #include "sanitizer_platform_interceptors.h" namespace __sanitizer { #if SANITIZER_INTERCEPT_TLS_GET_ADDR // The actual parameter that comes to __tls_get_addr // is a pointer to a struct with two words in it: struct TlsGetAddrParam { uptr dso_id; uptr offset; }; // Glibc starting from 2.19 allocates tls using __signal_safe_memalign, // which has such header. struct Glibc_2_19_tls_header { uptr size; uptr start; }; // This must be static TLS __attribute__((tls_model("initial-exec"))) static __thread DTLS dtls; // Make sure we properly destroy the DTLS objects: // this counter should never get too large. static atomic_uintptr_t number_of_live_dtls; static const uptr kDestroyedThread = -1; static inline void DTLS_Deallocate(DTLS::DTV *dtv, uptr size) { if (!size) return; VPrintf(2, "__tls_get_addr: DTLS_Deallocate %p %zd\n", dtv, size); UnmapOrDie(dtv, size * sizeof(DTLS::DTV)); atomic_fetch_sub(&number_of_live_dtls, 1, memory_order_relaxed); } static inline void DTLS_Resize(uptr new_size) { if (dtls.dtv_size >= new_size) return; new_size = RoundUpToPowerOfTwo(new_size); new_size = Max(new_size, 4096UL / sizeof(DTLS::DTV)); DTLS::DTV *new_dtv = (DTLS::DTV *)MmapOrDie(new_size * sizeof(DTLS::DTV), "DTLS_Resize"); uptr num_live_dtls = atomic_fetch_add(&number_of_live_dtls, 1, memory_order_relaxed); VPrintf(2, "__tls_get_addr: DTLS_Resize %p %zd\n", &dtls, num_live_dtls); CHECK_LT(num_live_dtls, 1 << 20); uptr old_dtv_size = dtls.dtv_size; DTLS::DTV *old_dtv = dtls.dtv; if (old_dtv_size) internal_memcpy(new_dtv, dtls.dtv, dtls.dtv_size * sizeof(DTLS::DTV)); dtls.dtv = new_dtv; dtls.dtv_size = new_size; if (old_dtv_size) DTLS_Deallocate(old_dtv, old_dtv_size); } void DTLS_Destroy() { if (!common_flags()->intercept_tls_get_addr) return; VPrintf(2, "__tls_get_addr: DTLS_Destroy %p %zd\n", &dtls, dtls.dtv_size); uptr s = dtls.dtv_size; dtls.dtv_size = kDestroyedThread; // Do this before unmap for AS-safety. DTLS_Deallocate(dtls.dtv, s); } DTLS::DTV *DTLS_on_tls_get_addr(void *arg_void, void *res) { if (!common_flags()->intercept_tls_get_addr) return 0; TlsGetAddrParam *arg = reinterpret_cast<TlsGetAddrParam *>(arg_void); uptr dso_id = arg->dso_id; if (dtls.dtv_size == kDestroyedThread) return 0; DTLS_Resize(dso_id + 1); if (dtls.dtv[dso_id].beg) return 0; uptr tls_size = 0; uptr tls_beg = reinterpret_cast<uptr>(res) - arg->offset; VPrintf(2, "__tls_get_addr: %p {%p,%p} => %p; tls_beg: %p; sp: %p " "num_live_dtls %zd\n", arg, arg->dso_id, arg->offset, res, tls_beg, &tls_beg, atomic_load(&number_of_live_dtls, memory_order_relaxed)); if (dtls.last_memalign_ptr == tls_beg) { tls_size = dtls.last_memalign_size; VPrintf(2, "__tls_get_addr: glibc <=2.18 suspected; tls={%p,%p}\n", tls_beg, tls_size); } else if ((tls_beg % 4096) == sizeof(Glibc_2_19_tls_header)) { // We may want to check gnu_get_libc_version(). Glibc_2_19_tls_header *header = (Glibc_2_19_tls_header *)tls_beg - 1; tls_size = header->size; tls_beg = header->start; VPrintf(2, "__tls_get_addr: glibc >=2.19 suspected; tls={%p %p}\n", tls_beg, tls_size); } else { VPrintf(2, "__tls_get_addr: Can't guess glibc version\n"); // This may happen inside the DTOR of main thread, so just ignore it. tls_size = 0; } dtls.dtv[dso_id].beg = tls_beg; dtls.dtv[dso_id].size = tls_size; return dtls.dtv + dso_id; } void DTLS_on_libc_memalign(void *ptr, uptr size) { if (!common_flags()->intercept_tls_get_addr) return; VPrintf(2, "DTLS_on_libc_memalign: %p %p\n", ptr, size); dtls.last_memalign_ptr = reinterpret_cast<uptr>(ptr); dtls.last_memalign_size = size; } DTLS *DTLS_Get() { return &dtls; } #else void DTLS_on_libc_memalign(void *ptr, uptr size) {} void DTLS_on_tls_get_addr(void *arg, void *res) {} DTLS *DTLS_Get() { return 0; } void DTLS_Destroy() {} #endif // SANITIZER_INTERCEPT_TLS_GET_ADDR } // namespace __sanitizer <commit_msg>[sanitizer] Fix build on platforms where dtls support is disabled.<commit_after>//===-- sanitizer_tls_get_addr.cc -----------------------------------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // Handle the __tls_get_addr call. // //===----------------------------------------------------------------------===// #include "sanitizer_tls_get_addr.h" #include "sanitizer_flags.h" #include "sanitizer_platform_interceptors.h" namespace __sanitizer { #if SANITIZER_INTERCEPT_TLS_GET_ADDR // The actual parameter that comes to __tls_get_addr // is a pointer to a struct with two words in it: struct TlsGetAddrParam { uptr dso_id; uptr offset; }; // Glibc starting from 2.19 allocates tls using __signal_safe_memalign, // which has such header. struct Glibc_2_19_tls_header { uptr size; uptr start; }; // This must be static TLS __attribute__((tls_model("initial-exec"))) static __thread DTLS dtls; // Make sure we properly destroy the DTLS objects: // this counter should never get too large. static atomic_uintptr_t number_of_live_dtls; static const uptr kDestroyedThread = -1; static inline void DTLS_Deallocate(DTLS::DTV *dtv, uptr size) { if (!size) return; VPrintf(2, "__tls_get_addr: DTLS_Deallocate %p %zd\n", dtv, size); UnmapOrDie(dtv, size * sizeof(DTLS::DTV)); atomic_fetch_sub(&number_of_live_dtls, 1, memory_order_relaxed); } static inline void DTLS_Resize(uptr new_size) { if (dtls.dtv_size >= new_size) return; new_size = RoundUpToPowerOfTwo(new_size); new_size = Max(new_size, 4096UL / sizeof(DTLS::DTV)); DTLS::DTV *new_dtv = (DTLS::DTV *)MmapOrDie(new_size * sizeof(DTLS::DTV), "DTLS_Resize"); uptr num_live_dtls = atomic_fetch_add(&number_of_live_dtls, 1, memory_order_relaxed); VPrintf(2, "__tls_get_addr: DTLS_Resize %p %zd\n", &dtls, num_live_dtls); CHECK_LT(num_live_dtls, 1 << 20); uptr old_dtv_size = dtls.dtv_size; DTLS::DTV *old_dtv = dtls.dtv; if (old_dtv_size) internal_memcpy(new_dtv, dtls.dtv, dtls.dtv_size * sizeof(DTLS::DTV)); dtls.dtv = new_dtv; dtls.dtv_size = new_size; if (old_dtv_size) DTLS_Deallocate(old_dtv, old_dtv_size); } void DTLS_Destroy() { if (!common_flags()->intercept_tls_get_addr) return; VPrintf(2, "__tls_get_addr: DTLS_Destroy %p %zd\n", &dtls, dtls.dtv_size); uptr s = dtls.dtv_size; dtls.dtv_size = kDestroyedThread; // Do this before unmap for AS-safety. DTLS_Deallocate(dtls.dtv, s); } DTLS::DTV *DTLS_on_tls_get_addr(void *arg_void, void *res) { if (!common_flags()->intercept_tls_get_addr) return 0; TlsGetAddrParam *arg = reinterpret_cast<TlsGetAddrParam *>(arg_void); uptr dso_id = arg->dso_id; if (dtls.dtv_size == kDestroyedThread) return 0; DTLS_Resize(dso_id + 1); if (dtls.dtv[dso_id].beg) return 0; uptr tls_size = 0; uptr tls_beg = reinterpret_cast<uptr>(res) - arg->offset; VPrintf(2, "__tls_get_addr: %p {%p,%p} => %p; tls_beg: %p; sp: %p " "num_live_dtls %zd\n", arg, arg->dso_id, arg->offset, res, tls_beg, &tls_beg, atomic_load(&number_of_live_dtls, memory_order_relaxed)); if (dtls.last_memalign_ptr == tls_beg) { tls_size = dtls.last_memalign_size; VPrintf(2, "__tls_get_addr: glibc <=2.18 suspected; tls={%p,%p}\n", tls_beg, tls_size); } else if ((tls_beg % 4096) == sizeof(Glibc_2_19_tls_header)) { // We may want to check gnu_get_libc_version(). Glibc_2_19_tls_header *header = (Glibc_2_19_tls_header *)tls_beg - 1; tls_size = header->size; tls_beg = header->start; VPrintf(2, "__tls_get_addr: glibc >=2.19 suspected; tls={%p %p}\n", tls_beg, tls_size); } else { VPrintf(2, "__tls_get_addr: Can't guess glibc version\n"); // This may happen inside the DTOR of main thread, so just ignore it. tls_size = 0; } dtls.dtv[dso_id].beg = tls_beg; dtls.dtv[dso_id].size = tls_size; return dtls.dtv + dso_id; } void DTLS_on_libc_memalign(void *ptr, uptr size) { if (!common_flags()->intercept_tls_get_addr) return; VPrintf(2, "DTLS_on_libc_memalign: %p %p\n", ptr, size); dtls.last_memalign_ptr = reinterpret_cast<uptr>(ptr); dtls.last_memalign_size = size; } DTLS *DTLS_Get() { return &dtls; } #else void DTLS_on_libc_memalign(void *ptr, uptr size) {} DTLS::DTV *DTLS_on_tls_get_addr(void *arg, void *res) { return 0; } DTLS *DTLS_Get() { return 0; } void DTLS_Destroy() {} #endif // SANITIZER_INTERCEPT_TLS_GET_ADDR } // namespace __sanitizer <|endoftext|>
<commit_before>// This file is part of the pd::ssl library. // Copyright (C) 2011-2014, Eugene Mamchits <mamchits@yandex-team.ru>. // Copyright (C) 2011-2014, YANDEX LLC. // This library may be distributed under the terms of the GNU LGPL 2.1. // See the file ‘COPYING’ or ‘http://www.gnu.org/licenses/lgpl-2.1.html’. #include "ssl.H" #include "log.I" #include <pd/bq/bq_cont.H> #include <pd/base/exception.H> #include <pd/base/string_file.H> #include <pthread.h> #include <openssl/crypto.h> #include <openssl/ssl.h> #include <openssl/engine.h> namespace pd { namespace { struct mgr_t { static unsigned types; static pthread_rwlock_t *locks; static void lock_func(int mode, int type, const char *, int) { if((unsigned)type > types) return; pthread_rwlock_t *lock = &locks[type]; if(mode & CRYPTO_LOCK) { if(mode & CRYPTO_READ) pthread_rwlock_rdlock(lock); else pthread_rwlock_wrlock(lock); } else pthread_rwlock_unlock(lock); } static unsigned long id_func(void) { return (unsigned long)bq_cont_current ?: (unsigned long)pthread_self(); } inline mgr_t() throw() { SSL_library_init(); SSL_load_error_strings(); ENGINE_load_builtin_engines(); OpenSSL_add_all_algorithms(); types = CRYPTO_num_locks(); locks = (pthread_rwlock_t *)malloc(types * sizeof(pthread_rwlock_t)); for(unsigned i = 0; i < types; ++i) pthread_rwlock_init(&locks[i], NULL); CRYPTO_set_locking_callback(&lock_func); CRYPTO_set_id_callback(&id_func); } inline ~mgr_t() throw() { CRYPTO_set_id_callback(NULL); CRYPTO_set_locking_callback(NULL); for(unsigned i = 0; i < types; ++i) pthread_rwlock_destroy(&locks[i]); free(locks); locks = NULL; types = 0; } }; unsigned mgr_t::types = 0; pthread_rwlock_t *mgr_t::locks = NULL; static mgr_t const mgr; class bio_t { BIO *val; public: inline bio_t(string_t const &buf) : val(BIO_new_mem_buf((void *)buf.ptr(), buf.size())) { if(!val) { log_openssl_error(log::error); throw exception_log_t(log::error, "BIO_new_mem_buf"); } } inline ~bio_t() throw() { BIO_free(val); } inline operator BIO *() { return val; } }; } // namespace ssl_auth_t::ssl_auth_t( string_t const &key_fname, string_t const &cert_fname ) : key(), cert() { if(key_fname) key = string_file(key_fname.str()); if(cert_fname) cert = string_file(cert_fname.str()); } ssl_auth_t::~ssl_auth_t() throw() { } ssl_ctx_t::ssl_ctx_t( mode_t _mode, ssl_auth_t const *auth, string_t const &ciphers ) : internal(NULL) { SSL_CTX *ctx = SSL_CTX_new( _mode == client ? SSLv23_client_method() : SSLv23_server_method() ); if(!ctx) { log_openssl_error(log::error); throw exception_log_t(log::error, "SSL_CTX_new"); } if(auth) { try { if(auth->cert) { bio_t cert_bio(auth->cert); X509 *x = PEM_read_bio_X509_AUX(cert_bio, NULL, NULL, NULL); if(!x) { log_openssl_error(log::error); throw exception_log_t(log::error, "cert, PEM_read_bio_X509"); } if(SSL_CTX_use_certificate(ctx, x) <= 0) { log_openssl_error(log::error); throw exception_log_t(log::error, "SSL_CTX_use_certificate"); } X509_free(x); while(!BIO_eof(cert_bio)) { x = PEM_read_bio_X509(cert_bio, NULL, NULL, NULL); if(!x) { log_openssl_error(log::error); throw exception_log_t(log::error, "cert_chain, PEM_read_bio_X509"); } if(SSL_CTX_add_extra_chain_cert(ctx, x) <= 0) { X509_free(x); log_openssl_error(log::error); throw exception_log_t(log::error, "SSL_CTX_add_extra_chain_cert"); } // X509_free(x); // ???? } } if(auth->key) { bio_t key_bio(auth->key); EVP_PKEY *pkey = PEM_read_bio_PrivateKey(key_bio, NULL, NULL, NULL); if(!pkey) { log_openssl_error(log::error); throw exception_log_t(log::error, "PEM_read_bio_PrivateKey"); } if(SSL_CTX_use_PrivateKey(ctx, pkey) <= 0) { log_openssl_error(log::error); throw exception_log_t(log::error, "SSL_CTX_use_PrivateKey"); } EVP_PKEY_free(pkey); } if(_mode == server) { SSL_CTX_set_options(ctx, SSL_OP_CIPHER_SERVER_PREFERENCE); SSL_CTX_set_options(ctx, SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS); SSL_CTX_set_options(ctx, SSL_OP_TLS_ROLLBACK_BUG); SSL_CTX_set_options(ctx, SSL_OP_NO_SSLv2); if(ciphers) { MKCSTR(_ciphers, ciphers); if(SSL_CTX_set_cipher_list(ctx, _ciphers) <= 0) { log_openssl_error(log::error); throw exception_log_t(log::error, "SSL_CTX_set_cipher_list"); } } /* SSL_CTX_set_session_cache_mode(ctx, ...); SSL_CTX_set_timeout(ctx, ...); */ } /* SSL_CTX_set_default_verify_paths(ctx); SSL_CTX_load_verify_locations(ctx, NULL, "/etc/ssl/certs"); SSL_CTX_set_verify(ctx, SSL_VERIFY_NONE, NULL); */ } catch(...) { SSL_CTX_free(ctx); throw; } } internal = ctx; } ssl_ctx_t::~ssl_ctx_t() throw() { SSL_CTX_free((SSL_CTX *)internal); } } // namespace pd <commit_msg>SSL_CTX_set_cipher_list should be called outside of if(auth) {..} block, because that block is executed in client-authenticated TLS handshake only and ciphers list could be limited by client in basic TLS handshake too.<commit_after>// This file is part of the pd::ssl library. // Copyright (C) 2011-2014, Eugene Mamchits <mamchits@yandex-team.ru>. // Copyright (C) 2011-2014, YANDEX LLC. // This library may be distributed under the terms of the GNU LGPL 2.1. // See the file ‘COPYING’ or ‘http://www.gnu.org/licenses/lgpl-2.1.html’. #include "ssl.H" #include "log.I" #include <pd/bq/bq_cont.H> #include <pd/base/exception.H> #include <pd/base/string_file.H> #include <pthread.h> #include <openssl/crypto.h> #include <openssl/ssl.h> #include <openssl/engine.h> namespace pd { namespace { struct mgr_t { static unsigned types; static pthread_rwlock_t *locks; static void lock_func(int mode, int type, const char *, int) { if((unsigned)type > types) return; pthread_rwlock_t *lock = &locks[type]; if(mode & CRYPTO_LOCK) { if(mode & CRYPTO_READ) pthread_rwlock_rdlock(lock); else pthread_rwlock_wrlock(lock); } else pthread_rwlock_unlock(lock); } static unsigned long id_func(void) { return (unsigned long)bq_cont_current ?: (unsigned long)pthread_self(); } inline mgr_t() throw() { SSL_library_init(); SSL_load_error_strings(); ENGINE_load_builtin_engines(); OpenSSL_add_all_algorithms(); types = CRYPTO_num_locks(); locks = (pthread_rwlock_t *)malloc(types * sizeof(pthread_rwlock_t)); for(unsigned i = 0; i < types; ++i) pthread_rwlock_init(&locks[i], NULL); CRYPTO_set_locking_callback(&lock_func); CRYPTO_set_id_callback(&id_func); } inline ~mgr_t() throw() { CRYPTO_set_id_callback(NULL); CRYPTO_set_locking_callback(NULL); for(unsigned i = 0; i < types; ++i) pthread_rwlock_destroy(&locks[i]); free(locks); locks = NULL; types = 0; } }; unsigned mgr_t::types = 0; pthread_rwlock_t *mgr_t::locks = NULL; static mgr_t const mgr; class bio_t { BIO *val; public: inline bio_t(string_t const &buf) : val(BIO_new_mem_buf((void *)buf.ptr(), buf.size())) { if(!val) { log_openssl_error(log::error); throw exception_log_t(log::error, "BIO_new_mem_buf"); } } inline ~bio_t() throw() { BIO_free(val); } inline operator BIO *() { return val; } }; } // namespace ssl_auth_t::ssl_auth_t( string_t const &key_fname, string_t const &cert_fname ) : key(), cert() { if(key_fname) key = string_file(key_fname.str()); if(cert_fname) cert = string_file(cert_fname.str()); } ssl_auth_t::~ssl_auth_t() throw() { } ssl_ctx_t::ssl_ctx_t( mode_t _mode, ssl_auth_t const *auth, string_t const &ciphers ) : internal(NULL) { SSL_CTX *ctx = SSL_CTX_new( _mode == client ? SSLv23_client_method() : SSLv23_server_method() ); if(!ctx) { log_openssl_error(log::error); throw exception_log_t(log::error, "SSL_CTX_new"); } if(auth) { try { if(auth->cert) { bio_t cert_bio(auth->cert); X509 *x = PEM_read_bio_X509_AUX(cert_bio, NULL, NULL, NULL); if(!x) { log_openssl_error(log::error); throw exception_log_t(log::error, "cert, PEM_read_bio_X509"); } if(SSL_CTX_use_certificate(ctx, x) <= 0) { log_openssl_error(log::error); throw exception_log_t(log::error, "SSL_CTX_use_certificate"); } X509_free(x); while(!BIO_eof(cert_bio)) { x = PEM_read_bio_X509(cert_bio, NULL, NULL, NULL); if(!x) { log_openssl_error(log::error); throw exception_log_t(log::error, "cert_chain, PEM_read_bio_X509"); } if(SSL_CTX_add_extra_chain_cert(ctx, x) <= 0) { X509_free(x); log_openssl_error(log::error); throw exception_log_t(log::error, "SSL_CTX_add_extra_chain_cert"); } // X509_free(x); // ???? } } if(auth->key) { bio_t key_bio(auth->key); EVP_PKEY *pkey = PEM_read_bio_PrivateKey(key_bio, NULL, NULL, NULL); if(!pkey) { log_openssl_error(log::error); throw exception_log_t(log::error, "PEM_read_bio_PrivateKey"); } if(SSL_CTX_use_PrivateKey(ctx, pkey) <= 0) { log_openssl_error(log::error); throw exception_log_t(log::error, "SSL_CTX_use_PrivateKey"); } EVP_PKEY_free(pkey); } if(_mode == server) { SSL_CTX_set_options(ctx, SSL_OP_CIPHER_SERVER_PREFERENCE); SSL_CTX_set_options(ctx, SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS); SSL_CTX_set_options(ctx, SSL_OP_TLS_ROLLBACK_BUG); SSL_CTX_set_options(ctx, SSL_OP_NO_SSLv2); /* SSL_CTX_set_session_cache_mode(ctx, ...); SSL_CTX_set_timeout(ctx, ...); */ } /* SSL_CTX_set_default_verify_paths(ctx); SSL_CTX_load_verify_locations(ctx, NULL, "/etc/ssl/certs"); SSL_CTX_set_verify(ctx, SSL_VERIFY_NONE, NULL); */ } catch(...) { SSL_CTX_free(ctx); throw; } } if(ciphers) { MKCSTR(_ciphers, ciphers); if(SSL_CTX_set_cipher_list(ctx, _ciphers) <= 0) { log_openssl_error(log::error); throw exception_log_t(log::error, "SSL_CTX_set_cipher_list"); } } internal = ctx; } ssl_ctx_t::~ssl_ctx_t() throw() { SSL_CTX_free((SSL_CTX *)internal); } } // namespace pd <|endoftext|>
<commit_before>/** * @file lda_gibbs.cpp */ #include "topics/lda_gibbs.h" namespace topics { lda_gibbs::lda_gibbs( std::vector<Document> & docs, size_t num_topics, double alpha, double beta ) : tokenizer_{ 1, NgramTokenizer::Word }, docs_{ docs }, alpha_{ alpha }, beta_{ beta }, num_topics_{ num_topics }, rng_{ std::random_device{}() } { for( auto & d : docs_ ) tokenizer_.tokenize( d ); num_words_ = tokenizer_.getNumTerms(); } void lda_gibbs::run( size_t num_iters, double convergence /* = 1e-6 */ ) { std::cerr << "Running LDA inference..." << std::endl; initialize(); double likelihood = corpus_likelihood(); for( size_t i = 0; i < num_iters; ++i ) { std::cerr << "Remaining iterations: " << (num_iters - i) << " "; perform_iteration(); double likelihood_update = corpus_likelihood(); double ratio = std::fabs( ( likelihood - likelihood_update ) / likelihood ); likelihood = likelihood_update; std::cerr << "\tCorpus log likelihood: " << likelihood << " \r"; if( ratio <= convergence ) { std::cerr << "\nFound convergence after " << i << " iterations!\n"; break; } } std::cerr << "\nFinished maximum iterations, or found convergence!\n"; } void lda_gibbs::save_doc_topic_distributions( const std::string & filename ) const { std::ofstream file{ filename }; for( size_t i = 0; i < docs_.size(); ++i ) { file << docs_[i].getName() << "\t"; for( size_t j = 0; j < num_topics_; ++j ) { double prob = compute_doc_topic_probability( i, j ); if( prob > 0 ) file << j << ":" << prob << "\t"; } file << "\n"; } } void lda_gibbs::save_topic_term_distributions( const std::string & filename ) const { std::ofstream file{ filename }; for( size_t j = 0; j < num_topics_; ++j ) { file << j << "\t"; for( const auto & pair : tokenizer_.getTermIDMapping() ) { TermID term = pair.first; double prob = compute_term_topic_probability( term, j ); if( prob > 0 ) file << term << ":" << prob << "\t"; } file << "\n"; } } void lda_gibbs::save_term_mapping( const std::string & filename ) const { tokenizer_.saveTermIDMapping( filename ); } void lda_gibbs::save( const std::string & prefix ) const { save_doc_topic_distributions( prefix + ".theta" ); save_topic_term_distributions( prefix + ".phi" ); save_term_mapping( prefix + ".terms" ); } size_t lda_gibbs::sample_topic( TermID term, size_t doc ) { std::vector<double> weights( num_topics_ ); for( size_t j = 0; j < weights.size(); ++j ) weights[ j ] = compute_probability( term, doc, j ); std::discrete_distribution<> dist( weights.begin(), weights.end() ); return dist( rng_ ); } double lda_gibbs::compute_probability( TermID term, size_t doc, size_t topic ) const { return compute_term_topic_probability( term, topic ) * compute_doc_topic_probability( doc, topic ); } double lda_gibbs::compute_term_topic_probability( TermID term, size_t topic ) const { return ( count_term( term, topic ) + beta_ ) / ( count_topic( topic ) + num_words_ * beta_ ); } double lda_gibbs::compute_doc_topic_probability( size_t doc, size_t topic ) const { return ( count_doc( doc, topic ) + alpha_ ) / ( count_doc( doc ) + num_topics_ * alpha_ ); } double lda_gibbs::count_term( TermID term, size_t topic ) const { auto it = topic_term_count_.find( topic ); if( it == topic_term_count_.end() ) return 0; auto iit = it->second.find( term ); if( iit == it->second.end() ) return 0; return iit->second; } double lda_gibbs::count_topic( size_t topic ) const { auto it = topic_count_.find( topic ); if( it == topic_count_.end() ) return 0; return it->second; } double lda_gibbs::count_doc( size_t doc, size_t topic ) const { auto it = doc_topic_count_.find( doc ); if( it == doc_topic_count_.end() ) return 0; auto iit = it->second.find( topic ); if( iit == it->second.end() ) return 0; return iit->second; } double lda_gibbs::count_doc( size_t doc ) const { return docs_[ doc ].getLength(); } void lda_gibbs::initialize() { std::cerr << "Initializing topic assignments..." << std::endl; perform_iteration( true ); } void lda_gibbs::perform_iteration( bool init /* = false */ ) { for( size_t i = 0; i < docs_.size(); ++i ) { size_t n = 0; // term number within document---constructed // so that each occurrence of the same term // can still be assigned a different topic for( const auto & freq : docs_[i].getFrequencies() ) { for( size_t j = 0; j < freq.second; ++j ) { size_t old_topic = doc_word_topic_[ i ][ n ]; // don't include current topic assignment in // probability calculation if( !init ) decrease_counts( old_topic, freq.first, i ); // sample a new topic assignment size_t topic = sample_topic( freq.first, i ); doc_word_topic_[ i ][ n ] = topic; // increase counts increase_counts( topic, freq.first, i ); n += 1; } } } } void lda_gibbs::decrease_counts( size_t topic, TermID term, size_t doc ) { // decrease topic_term_count_ for the given assignment auto & tt_count = topic_term_count_.at( topic ).at( term ); if( tt_count == 1 ) topic_term_count_.at( topic ).erase( term ); else tt_count -= 1; // decrease doc_topic_count_ for the given assignment auto & dt_count = doc_topic_count_.at( doc ).at( topic ); if( dt_count == 1 ) doc_topic_count_.at( doc ).erase( topic ); else dt_count -= 1; // decrease topic count auto & tc = topic_count_.at( topic ); if( tc == 1 ) topic_count_.erase( topic ); else tc -= 1; } void lda_gibbs::increase_counts( size_t topic, TermID term, size_t doc ) { topic_term_count_[ topic ][ term ] += 1; doc_topic_count_[ doc ][ topic ] += 1; topic_count_[ topic ] += 1; } double lda_gibbs::corpus_likelihood() const { double likelihood = num_topics_ * std::lgamma( num_words_ * beta_ ); for( size_t j = 0; j < num_topics_; ++j ) { for( const auto & doc : docs_ ) { for( const auto & freq : doc.getFrequencies() ) { likelihood += freq.second * std::lgamma( count_term( freq.first, j ) + beta_ ); } } likelihood -= std::lgamma( count_topic( j ) + num_words_ * beta_ ); } return likelihood; } } <commit_msg>Improve progress output for lda_gibbs.<commit_after>/** * @file lda_gibbs.cpp */ #include "topics/lda_gibbs.h" #include "util/common.h" namespace topics { lda_gibbs::lda_gibbs( std::vector<Document> & docs, size_t num_topics, double alpha, double beta ) : tokenizer_{ 1, NgramTokenizer::Word }, docs_{ docs }, alpha_{ alpha }, beta_{ beta }, num_topics_{ num_topics }, rng_{ std::random_device{}() } { for( size_t i = 0; i < docs_.size(); ++i ) { Common::show_progress( i, docs_.size(), 10, "Tokenizing documents: " ); tokenizer_.tokenize( docs_[i] ); } std::cerr << '\n'; num_words_ = tokenizer_.getNumTerms(); } void lda_gibbs::run( size_t num_iters, double convergence /* = 1e-6 */ ) { std::cerr << "Running LDA inference...\n"; initialize(); double likelihood = corpus_likelihood(); for( size_t i = 0; i < num_iters; ++i ) { std::cerr << "Iteration " << i + 1 << "/" << num_iters << ":\r"; perform_iteration(); double likelihood_update = corpus_likelihood(); double ratio = std::fabs( ( likelihood - likelihood_update ) / likelihood ); likelihood = likelihood_update; std::cerr << "\t\t\t\t\t\tlog likelihood: " << likelihood << " \r"; if( ratio <= convergence ) { std::cerr << "\nFound convergence after " << i + 1 << " iterations!\n"; break; } } std::cerr << "\nFinished maximum iterations, or found convergence!\n"; } void lda_gibbs::save_doc_topic_distributions( const std::string & filename ) const { std::ofstream file{ filename }; for( size_t i = 0; i < docs_.size(); ++i ) { file << docs_[i].getName() << "\t"; for( size_t j = 0; j < num_topics_; ++j ) { double prob = compute_doc_topic_probability( i, j ); if( prob > 0 ) file << j << ":" << prob << "\t"; } file << "\n"; } } void lda_gibbs::save_topic_term_distributions( const std::string & filename ) const { std::ofstream file{ filename }; for( size_t j = 0; j < num_topics_; ++j ) { file << j << "\t"; for( const auto & pair : tokenizer_.getTermIDMapping() ) { TermID term = pair.first; double prob = compute_term_topic_probability( term, j ); if( prob > 0 ) file << term << ":" << prob << "\t"; } file << "\n"; } } void lda_gibbs::save_term_mapping( const std::string & filename ) const { tokenizer_.saveTermIDMapping( filename ); } void lda_gibbs::save( const std::string & prefix ) const { save_doc_topic_distributions( prefix + ".theta" ); save_topic_term_distributions( prefix + ".phi" ); save_term_mapping( prefix + ".terms" ); } size_t lda_gibbs::sample_topic( TermID term, size_t doc ) { std::vector<double> weights( num_topics_ ); for( size_t j = 0; j < weights.size(); ++j ) weights[ j ] = compute_probability( term, doc, j ); std::discrete_distribution<> dist( weights.begin(), weights.end() ); return dist( rng_ ); } double lda_gibbs::compute_probability( TermID term, size_t doc, size_t topic ) const { return compute_term_topic_probability( term, topic ) * compute_doc_topic_probability( doc, topic ); } double lda_gibbs::compute_term_topic_probability( TermID term, size_t topic ) const { return ( count_term( term, topic ) + beta_ ) / ( count_topic( topic ) + num_words_ * beta_ ); } double lda_gibbs::compute_doc_topic_probability( size_t doc, size_t topic ) const { return ( count_doc( doc, topic ) + alpha_ ) / ( count_doc( doc ) + num_topics_ * alpha_ ); } double lda_gibbs::count_term( TermID term, size_t topic ) const { auto it = topic_term_count_.find( topic ); if( it == topic_term_count_.end() ) return 0; auto iit = it->second.find( term ); if( iit == it->second.end() ) return 0; return iit->second; } double lda_gibbs::count_topic( size_t topic ) const { auto it = topic_count_.find( topic ); if( it == topic_count_.end() ) return 0; return it->second; } double lda_gibbs::count_doc( size_t doc, size_t topic ) const { auto it = doc_topic_count_.find( doc ); if( it == doc_topic_count_.end() ) return 0; auto iit = it->second.find( topic ); if( iit == it->second.end() ) return 0; return iit->second; } double lda_gibbs::count_doc( size_t doc ) const { return docs_[ doc ].getLength(); } void lda_gibbs::initialize() { std::cerr << "Initialization:\r"; perform_iteration( true ); } void lda_gibbs::perform_iteration( bool init /* = false */ ) { for( size_t i = 0; i < docs_.size(); ++i ) { Common::show_progress( i, docs_.size(), 10, "\t\t\t" ); size_t n = 0; // term number within document---constructed // so that each occurrence of the same term // can still be assigned a different topic for( const auto & freq : docs_[i].getFrequencies() ) { for( size_t j = 0; j < freq.second; ++j ) { size_t old_topic = doc_word_topic_[ i ][ n ]; // don't include current topic assignment in // probability calculation if( !init ) decrease_counts( old_topic, freq.first, i ); // sample a new topic assignment size_t topic = sample_topic( freq.first, i ); doc_word_topic_[ i ][ n ] = topic; // increase counts increase_counts( topic, freq.first, i ); n += 1; } } } } void lda_gibbs::decrease_counts( size_t topic, TermID term, size_t doc ) { // decrease topic_term_count_ for the given assignment auto & tt_count = topic_term_count_.at( topic ).at( term ); if( tt_count == 1 ) topic_term_count_.at( topic ).erase( term ); else tt_count -= 1; // decrease doc_topic_count_ for the given assignment auto & dt_count = doc_topic_count_.at( doc ).at( topic ); if( dt_count == 1 ) doc_topic_count_.at( doc ).erase( topic ); else dt_count -= 1; // decrease topic count auto & tc = topic_count_.at( topic ); if( tc == 1 ) topic_count_.erase( topic ); else tc -= 1; } void lda_gibbs::increase_counts( size_t topic, TermID term, size_t doc ) { topic_term_count_[ topic ][ term ] += 1; doc_topic_count_[ doc ][ topic ] += 1; topic_count_[ topic ] += 1; } double lda_gibbs::corpus_likelihood() const { double likelihood = num_topics_ * std::lgamma( num_words_ * beta_ ); for( size_t j = 0; j < num_topics_; ++j ) { for( const auto & doc : docs_ ) { for( const auto & freq : doc.getFrequencies() ) { likelihood += freq.second * std::lgamma( count_term( freq.first, j ) + beta_ ); } } likelihood -= std::lgamma( count_topic( j ) + num_words_ * beta_ ); } return likelihood; } } <|endoftext|>
<commit_before>/* This file is part of Groho, a simulator for inter-planetary travel and warfare. Copyright (c) 2017-2018 by Kaushik Ghose. Some rights reserved, see LICENSE This file contains some common functions used in parsing scenario files */ #pragma once #include <fstream> #include <iterator> #include <optional> #include <sstream> #include <string> #include <vector> // For file modification time #include <sys/stat.h> #include <sys/types.h> #ifndef WIN32 #include <unistd.h> #endif #ifdef WIN32 #define stat _stat #endif #include "vector.hpp" #define LOGURU_WITH_STREAMS 1 #include "loguru.hpp" namespace sim { const double T0 = 2451545.0; const double S_PER_DAY = 86400.0; inline double jd2s(double jd) { return (jd - T0) * S_PER_DAY; } struct KeyValue { std::string key, value; }; const std::string wspace = " \t\n\r\f\v"; inline std::string trim_whitespace(std::string line) { line.erase(0, line.find_first_not_of(wspace)); line.erase(line.find_last_not_of(wspace) + 1); return line; } inline std::string trim_comments(std::string line) { return line.erase(std::min(line.find_first_of(';'), line.size())); } inline bool line_continued(std::string line) { return line.back() == '\\'; } // An iterator in disguise // Trims leading/trailing whitespace and joins continued lines struct ScenarioFile { static std::optional<ScenarioFile> open(std::string fname) { ScenarioFile sf; sf.cfile = std::ifstream(fname); if (!sf.cfile) { return {}; } sf.line_no = 0; sf.continued_line = ""; return sf; } std::optional<std::string> next() { std::string line; continued_line = ""; while (std::getline(cfile, line)) { line_no++; line = trim_whitespace(trim_comments(line)); if (line.size() == 0) continue; if (line_continued(line)) { line.pop_back(); continued_line += line; continue; } else { return continued_line + line; } } if (continued_line.size()) { return continued_line; } else { return {}; } } std::ifstream cfile; int line_no = 0; std::string continued_line; }; inline std::optional<KeyValue> get_key_value(std::string line) { KeyValue kv; size_t n0 = line.find_first_of('='); if (n0 > line.size()) { return {}; } kv.key = trim_whitespace(line.substr(0, n0 - 1)); kv.value = trim_whitespace(line.substr(n0 + 1)); return kv; } inline std::vector<std::string> split(std::string line) { std::istringstream iss(line); return std::vector<std::string>( std::istream_iterator<std::string>(iss), std::istream_iterator<std::string>()); } inline Vector stoV(std::string v) { std::vector<std::string> tokens = split(v); if (tokens.size() < 3) { LOG_S(ERROR) << "Vector needs three components: Got " << v; return {}; } Vector out{ stof(tokens[0]), stof(tokens[1]), stof(tokens[2]) }; return out; } inline bool could_be_a_number(std::string token) { return !token.empty() && (token.find_first_not_of("-.0123456789") == std::string::npos); } inline time_t file_modification_time(std::string fname) { struct stat result; if (stat(fname.c_str(), &result) == 0) { return result.st_mtime; } else { return 0; } } // Given a list of files, give us the time of latest change among them all inline time_t file_modification_time(std::vector<std::string> fnames) { time_t fmod_time = 0; for (auto& fn : fnames) { time_t fn_ft = file_modification_time(fn); if (fn_ft > fmod_time) { fmod_time = fn_ft; } } return fmod_time; } }<commit_msg>bugfix: Fix OBO error in parser<commit_after>/* This file is part of Groho, a simulator for inter-planetary travel and warfare. Copyright (c) 2017-2018 by Kaushik Ghose. Some rights reserved, see LICENSE This file contains some common functions used in parsing scenario files */ #pragma once #include <fstream> #include <iterator> #include <optional> #include <sstream> #include <string> #include <vector> // For file modification time #include <sys/stat.h> #include <sys/types.h> #ifndef WIN32 #include <unistd.h> #endif #ifdef WIN32 #define stat _stat #endif #include "vector.hpp" #define LOGURU_WITH_STREAMS 1 #include "loguru.hpp" namespace sim { const double T0 = 2451545.0; const double S_PER_DAY = 86400.0; inline double jd2s(double jd) { return (jd - T0) * S_PER_DAY; } struct KeyValue { std::string key, value; }; const std::string wspace = " \t\n\r\f\v"; inline std::string trim_whitespace(std::string line) { line.erase(0, line.find_first_not_of(wspace)); line.erase(line.find_last_not_of(wspace) + 1); return line; } inline std::string trim_comments(std::string line) { return line.erase(std::min(line.find_first_of(';'), line.size())); } inline bool line_continued(std::string line) { return line.back() == '\\'; } // An iterator in disguise // Trims leading/trailing whitespace and joins continued lines struct ScenarioFile { static std::optional<ScenarioFile> open(std::string fname) { ScenarioFile sf; sf.cfile = std::ifstream(fname); if (!sf.cfile) { return {}; } sf.line_no = 0; sf.continued_line = ""; return sf; } std::optional<std::string> next() { std::string line; continued_line = ""; while (std::getline(cfile, line)) { line_no++; line = trim_whitespace(trim_comments(line)); if (line.size() == 0) continue; if (line_continued(line)) { line.pop_back(); continued_line += line; continue; } else { return continued_line + line; } } if (continued_line.size()) { return continued_line; } else { return {}; } } std::ifstream cfile; int line_no = 0; std::string continued_line; }; inline std::optional<KeyValue> parse_key_value_pair(std::string line, std::string sep) { KeyValue kv; size_t n0 = line.find_first_of(sep); if (n0 > line.size()) { return {}; } kv.key = trim_whitespace(line.substr(0, n0)); kv.value = trim_whitespace(line.substr(n0 + 1)); return kv; } // parse name = boo! inline std::optional<KeyValue> get_key_value(std::string line) { return parse_key_value_pair(line, "="); } // parse id:-23 inline std::optional<KeyValue> get_named_parameter(std::string token) { return parse_key_value_pair(token, ":"); } inline std::vector<std::string> split(std::string line) { std::istringstream iss(line); return std::vector<std::string>( std::istream_iterator<std::string>(iss), std::istream_iterator<std::string>()); } inline Vector stoV(std::string v) { std::vector<std::string> tokens = split(v); if (tokens.size() < 3) { LOG_S(ERROR) << "Vector needs three components: Got " << v; return {}; } Vector out{ stof(tokens[0]), stof(tokens[1]), stof(tokens[2]) }; return out; } inline bool could_be_a_number(std::string token) { return !token.empty() && (token.find_first_not_of("-.0123456789") == std::string::npos); } inline time_t file_modification_time(std::string fname) { struct stat result; if (stat(fname.c_str(), &result) == 0) { return result.st_mtime; } else { return 0; } } // Given a list of files, give us the time of latest change among them all inline time_t file_modification_time(std::vector<std::string> fnames) { time_t fmod_time = 0; for (auto& fn : fnames) { time_t fn_ft = file_modification_time(fn); if (fn_ft > fmod_time) { fmod_time = fn_ft; } } return fmod_time; } }<|endoftext|>
<commit_before>#include <map> #include <stdio.h> #include <string.h> #include <assert.h> #include <stdlib.h> #include <unistd.h> #include "boxer.h" #include "stage.h" #ifdef __ANDROID__ #include "jni.h" #include <android/log.h> #endif extern int32_t _BOXER_FILES_SIZE; extern char* _BOXER_FILES[]; int32_t cachedArgc = 0; char argvStorage[1024]; char* cachedArgv[64]; namespace boxer { enum error: int32_t { SUCCESS, FAILURE }; stage* gStage = NULL; std::map<int32_t, uint8_t*> gResourceMap; int32_t getArgc() { return cachedArgc; } char** getArgv() { return cachedArgv; } const uint8_t* getResource(int32_t id) { auto found = gResourceMap.find(id); return found == gResourceMap.end() ? NULL: gResourceMap.find(id)->second; } void setStage(int32_t id) { if(gStage != NULL) { gStage->~stage(); free(gStage); } gStage = (stage*)malloc(sizeof(stage)); gStage->init(id); } int32_t blockResource(int32_t id, int32_t x, int32_t y) { int32_t code = FAILURE; if(gStage == NULL || (x > gStage->getWidth()) || (y > gStage->getHeight())) return code; const boxer::bmpStat* stat = (const boxer::bmpStat*)boxer::getResource(id); assert(stat != NULL); assert(stat->colorPlanes == 1); assert(stat->compression == 3); //BI_BITFIELDS if((x+stat->width) <= gStage->getWidth() && (y+stat->height) <= gStage->getHeight()) { gStage->draw(boxer::getResource(id), x, y); code = SUCCESS; } return code; } void showStage() { if(gStage != NULL) { gStage->show(); } } struct _BUILDER { ~_BUILDER() { int32_t count = 0; char buffer[PATH_MAX]; while(count < _BOXER_FILES_SIZE) { free(gResourceMap.find(count++)->second); } if(gStage != NULL) { gStage->~stage(); free(gStage); } } }; static _BUILDER resourceBuilder; } void preload(const char* path) { int32_t count = 0; char buffer[PATH_MAX]; while(count < _BOXER_FILES_SIZE) { memset(buffer, '\0', PATH_MAX); memcpy(buffer, path, strlen(path)); strcat(buffer, _BOXER_FILES[count]); FILE* temp = fopen(buffer, "r"); if(temp) { fseek(temp, 0, SEEK_END); int32_t size = ftell(temp); rewind(temp); uint8_t* binary = (uint8_t*)malloc(size); size_t read = fread(binary, 1, size, temp); assert(read == size); boxer::gResourceMap.insert(std::pair<int32_t, uint8_t*>(count, binary)); fclose(temp); } count++; } } int32_t main(int32_t argc, char** argv) { cachedArgc = argc; char* storagePointer = argvStorage; while(argc--) { cachedArgv[argc] = storagePointer; int32_t length = strlen(argv[argc]); strcat(storagePointer, argv[argc]); storagePointer+=(length+1); } char buffer[PATH_MAX]; memset(buffer, '\0', PATH_MAX); char* finalSlash = strrchr(cachedArgv[0], '/'); memcpy(buffer, cachedArgv[0], (finalSlash - cachedArgv[0]) + 1); preload(buffer); boxerMain(); return 0; } #ifdef __ANDROID__ JavaVM* jVM = NULL; char androidData[PATH_MAX]; JNIEXPORT jint JNICALL JNI_OnLoad(JavaVM* vm, void* reserved) { jVM = vm; JNIEnv* env; if(vm->GetEnv((void**)&env, JNI_VERSION_1_6) != JNI_OK) { return -1; } return JNI_VERSION_1_6; } extern "C" JNIEXPORT void JNICALL Java_org_starlo_boxer_BoxerEngine_preload(JNIEnv* env, jobject obj, jstring pathString) { const char* path = env->GetStringUTFChars(pathString, NULL); preload(path); env->ReleaseStringUTFChars(pathString, path); memset(androidData, '\0', PATH_MAX); memcpy(androidData, path, strlen(path)); } extern "C" JNIEXPORT void JNICALL Java_org_starlo_boxer_BoxerEngine_boxerMain(JNIEnv* env, jobject obj) { boxerMain(); } #endif <commit_msg>Fix issue with save file path<commit_after>#include <map> #include <stdio.h> #include <string.h> #include <assert.h> #include <stdlib.h> #include <unistd.h> #include "boxer.h" #include "stage.h" #ifdef __ANDROID__ #include "jni.h" #include <android/log.h> #endif extern int32_t _BOXER_FILES_SIZE; extern char* _BOXER_FILES[]; int32_t cachedArgc = 0; char argvStorage[1024]; char* cachedArgv[64]; namespace boxer { enum error: int32_t { SUCCESS, FAILURE }; stage* gStage = NULL; std::map<int32_t, uint8_t*> gResourceMap; int32_t getArgc() { return cachedArgc; } char** getArgv() { return cachedArgv; } const uint8_t* getResource(int32_t id) { auto found = gResourceMap.find(id); return found == gResourceMap.end() ? NULL: gResourceMap.find(id)->second; } void setStage(int32_t id) { if(gStage != NULL) { gStage->~stage(); free(gStage); } gStage = (stage*)malloc(sizeof(stage)); gStage->init(id); } int32_t blockResource(int32_t id, int32_t x, int32_t y) { int32_t code = FAILURE; if(gStage == NULL || (x > gStage->getWidth()) || (y > gStage->getHeight())) return code; const boxer::bmpStat* stat = (const boxer::bmpStat*)boxer::getResource(id); assert(stat != NULL); assert(stat->colorPlanes == 1); assert(stat->compression == 3); //BI_BITFIELDS if((x+stat->width) <= gStage->getWidth() && (y+stat->height) <= gStage->getHeight()) { gStage->draw(boxer::getResource(id), x, y); code = SUCCESS; } return code; } void showStage() { if(gStage != NULL) { gStage->show(); } } struct _BUILDER { ~_BUILDER() { int32_t count = 0; char buffer[PATH_MAX]; while(count < _BOXER_FILES_SIZE) { free(gResourceMap.find(count++)->second); } if(gStage != NULL) { gStage->~stage(); free(gStage); } } }; static _BUILDER resourceBuilder; } void preload(const char* path) { int32_t count = 0; char buffer[PATH_MAX]; while(count < _BOXER_FILES_SIZE) { memset(buffer, '\0', PATH_MAX); memcpy(buffer, path, strlen(path)); strcat(buffer, _BOXER_FILES[count]); FILE* temp = fopen(buffer, "r"); if(temp) { fseek(temp, 0, SEEK_END); int32_t size = ftell(temp); rewind(temp); uint8_t* binary = (uint8_t*)malloc(size); size_t read = fread(binary, 1, size, temp); assert(read == size); boxer::gResourceMap.insert(std::pair<int32_t, uint8_t*>(count, binary)); fclose(temp); } count++; } } int32_t main(int32_t argc, char** argv) { cachedArgc = argc; char* storagePointer = argvStorage; while(argc--) { cachedArgv[argc] = storagePointer; int32_t length = strlen(argv[argc]); strcat(storagePointer, argv[argc]); storagePointer+=(length+1); } char buffer[PATH_MAX]; memset(buffer, '\0', PATH_MAX); char* finalSlash = strrchr(cachedArgv[0], '/'); memcpy(buffer, cachedArgv[0], (finalSlash - cachedArgv[0]) + 1); preload(buffer); boxerMain(); return 0; } #ifdef __ANDROID__ JavaVM* jVM = NULL; char androidData[PATH_MAX]; JNIEXPORT jint JNICALL JNI_OnLoad(JavaVM* vm, void* reserved) { jVM = vm; JNIEnv* env; if(vm->GetEnv((void**)&env, JNI_VERSION_1_6) != JNI_OK) { return -1; } return JNI_VERSION_1_6; } extern "C" JNIEXPORT void JNICALL Java_org_starlo_boxer_BoxerEngine_preload(JNIEnv* env, jobject obj, jstring pathString) { const char* path = env->GetStringUTFChars(pathString, NULL); preload(path); memset(androidData, '\0', PATH_MAX); char* finalSlash = strrchr(path, '/'); memcpy(androidData, path, (finalSlash - path) + 1); env->ReleaseStringUTFChars(pathString, path); } extern "C" JNIEXPORT void JNICALL Java_org_starlo_boxer_BoxerEngine_boxerMain(JNIEnv* env, jobject obj) { boxerMain(); } #endif <|endoftext|>
<commit_before>/** * This file is part of the "libfnord" project * Copyright (c) 2015 Paul Asmuth * * FnordMetric is free software: you can redistribute it and/or modify it under * the terms of the GNU General Public License v3.0. 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 <stx/stdtypes.h> #include <stx/logging.h> #include <stx/io/fileutil.h> #include <stx/io/mmappedfile.h> #include <stx/protobuf/msg.h> #include <stx/wallclock.h> #include <tsdb/CSTableIndex.h> #include <tsdb/CSTableIndexBuildState.pb.h> #include <tsdb/RecordSet.h> #include <stx/protobuf/MessageDecoder.h> #include <cstable/CSTableBuilder.h> using namespace stx; namespace tsdb { CSTableIndex::CSTableIndex(PartitionMap* pmap) : queue_([] ( const Pair<uint64_t, RefPtr<Partition>>& a, const Pair<uint64_t, RefPtr<Partition>>& b) { return a.first < b.first; }), running_(false) { pmap->subscribeToPartitionChanges([this] ( RefPtr<tsdb::PartitionChangeNotification> change) { enqueuePartition(change->partition); }); start(); } CSTableIndex::~CSTableIndex() { stop(); } Option<RefPtr<VFSFile>> CSTableIndex::fetchCSTable( const String& tsdb_namespace, const String& table, const SHA1Hash& partition) const { auto filepath = fetchCSTableFilename(tsdb_namespace, table, partition); if (filepath.isEmpty()) { return None<RefPtr<VFSFile>>(); } else { return Some<RefPtr<VFSFile>>( new io::MmappedFile(File::openFile(filepath.get(), File::O_READ))); } } Option<String> CSTableIndex::fetchCSTableFilename( const String& tsdb_namespace, const String& table, const SHA1Hash& partition) const { RAISE(kNotImplementedError); //auto filepath = FileUtil::joinPaths( // db_path_, // StringUtil::format( // "$0/$1/$2/_cstable", // tsdb_namespace, // SHA1::compute(table).toString(), // partition.toString())); //if (FileUtil::exists(filepath)) { // return Some(filepath); //} else { // return None<String>(); //} } bool CSTableIndex::needsUpdate( RefPtr<PartitionSnapshot> snap) const { String tbl_uuid((char*) snap->uuid().data(), snap->uuid().size()); auto metapath = FileUtil::joinPaths(snap->base_path, "_cstable_state"); //auto metapath_tmp = metapath + "." + Random::singleton()->hex128(); if (FileUtil::exists(metapath)) { auto metadata = msg::decode<CSTableIndexBuildState>( FileUtil::read(metapath)); if (metadata.uuid() == tbl_uuid && metadata.offset() >= snap->nrecs) { return false; } } return true; } void CSTableIndex::buildCSTable(RefPtr<Partition> partition) { auto table = partition->getTable(); if (table->storage() == tsdb::TBL_STORAGE_STATIC) { return; } auto t0 = WallClock::unixMicros(); auto snap = partition->getSnapshot(); if (!needsUpdate(snap)) { return; } logDebug( "tsdb", "Building CSTable index for partition $0/$1/$2", snap->state.tsdb_namespace(), table->name(), snap->key.toString()); auto filepath = FileUtil::joinPaths(snap->base_path, "_cstable"); auto filepath_tmp = filepath + "." + Random::singleton()->hex128(); auto schema = table->schema(); { cstable::CSTableBuilder cstable(schema.get()); auto reader = partition->getReader(); reader->fetchRecords([&schema, &cstable] (const Buffer& record) { msg::MessageObject obj; msg::MessageDecoder::decode(record.data(), record.size(), *schema, &obj); cstable.addRecord(obj); }); cstable.write(filepath_tmp); } auto metapath = FileUtil::joinPaths(snap->base_path, "_cstable_state"); auto metapath_tmp = metapath + "." + Random::singleton()->hex128(); { auto metafile = File::openFile( metapath_tmp, File::O_CREATE | File::O_WRITE); CSTableIndexBuildState metadata; metadata.set_offset(snap->nrecs); metadata.set_uuid(snap->uuid().data(), snap->uuid().size()); auto buf = msg::encode(metadata); metafile.write(buf->data(), buf->size()); } FileUtil::mv(filepath_tmp, filepath); FileUtil::mv(metapath_tmp, metapath); auto t1 = WallClock::unixMicros(); logDebug( "tsdb", "Commiting CSTable index for partition $0/$1/$2, building took $3s", snap->state.tsdb_namespace(), table->name(), snap->key.toString(), (double) (t1 - t0) / 1000000.0f); } void CSTableIndex::enqueuePartition(RefPtr<Partition> partition) { std::unique_lock<std::mutex> lk(mutex_); enqueuePartitionWithLock(partition); } void CSTableIndex::enqueuePartitionWithLock(RefPtr<Partition> partition) { auto interval = partition->getTable()->cstableBuildInterval(); auto uuid = partition->uuid(); if (waitset_.count(uuid) > 0) { return; } queue_.emplace( WallClock::unixMicros() + interval.microseconds(), partition); waitset_.emplace(uuid); cv_.notify_all(); } void CSTableIndex::start() { running_ = true; for (int i = 0; i < 4; ++i) { threads_.emplace_back(std::bind(&CSTableIndex::work, this)); } } void CSTableIndex::stop() { if (!running_) { return; } running_ = false; cv_.notify_all(); for (auto& t : threads_) { t.join(); } } void CSTableIndex::work() { std::unique_lock<std::mutex> lk(mutex_); while (running_) { if (queue_.size() == 0) { cv_.wait(lk); } if (queue_.size() == 0) { continue; } auto now = WallClock::unixMicros(); if (now < queue_.begin()->first) { cv_.wait_for( lk, std::chrono::microseconds(queue_.begin()->first - now)); continue; } auto partition = queue_.begin()->second; queue_.erase(queue_.begin()); bool success = true; { lk.unlock(); try { buildCSTable(partition); } catch (const StandardException& e) { logError("tsdb", e, "CSTableIndex error"); success = false; } lk.lock(); } if (success) { waitset_.erase(partition->uuid()); if (needsUpdate(partition->getSnapshot())) { enqueuePartitionWithLock(partition); } } else { auto delay = 30 * kMicrosPerSecond; // FIXPAUL increasing delay.. queue_.emplace(now + delay, partition); } } } } // namespace tsdb <commit_msg>run single index build thread<commit_after>/** * This file is part of the "libfnord" project * Copyright (c) 2015 Paul Asmuth * * FnordMetric is free software: you can redistribute it and/or modify it under * the terms of the GNU General Public License v3.0. 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 <stx/stdtypes.h> #include <stx/logging.h> #include <stx/io/fileutil.h> #include <stx/io/mmappedfile.h> #include <stx/protobuf/msg.h> #include <stx/wallclock.h> #include <tsdb/CSTableIndex.h> #include <tsdb/CSTableIndexBuildState.pb.h> #include <tsdb/RecordSet.h> #include <stx/protobuf/MessageDecoder.h> #include <cstable/CSTableBuilder.h> using namespace stx; namespace tsdb { CSTableIndex::CSTableIndex(PartitionMap* pmap) : queue_([] ( const Pair<uint64_t, RefPtr<Partition>>& a, const Pair<uint64_t, RefPtr<Partition>>& b) { return a.first < b.first; }), running_(false) { pmap->subscribeToPartitionChanges([this] ( RefPtr<tsdb::PartitionChangeNotification> change) { enqueuePartition(change->partition); }); start(); } CSTableIndex::~CSTableIndex() { stop(); } Option<RefPtr<VFSFile>> CSTableIndex::fetchCSTable( const String& tsdb_namespace, const String& table, const SHA1Hash& partition) const { auto filepath = fetchCSTableFilename(tsdb_namespace, table, partition); if (filepath.isEmpty()) { return None<RefPtr<VFSFile>>(); } else { return Some<RefPtr<VFSFile>>( new io::MmappedFile(File::openFile(filepath.get(), File::O_READ))); } } Option<String> CSTableIndex::fetchCSTableFilename( const String& tsdb_namespace, const String& table, const SHA1Hash& partition) const { RAISE(kNotImplementedError); //auto filepath = FileUtil::joinPaths( // db_path_, // StringUtil::format( // "$0/$1/$2/_cstable", // tsdb_namespace, // SHA1::compute(table).toString(), // partition.toString())); //if (FileUtil::exists(filepath)) { // return Some(filepath); //} else { // return None<String>(); //} } bool CSTableIndex::needsUpdate( RefPtr<PartitionSnapshot> snap) const { String tbl_uuid((char*) snap->uuid().data(), snap->uuid().size()); auto metapath = FileUtil::joinPaths(snap->base_path, "_cstable_state"); //auto metapath_tmp = metapath + "." + Random::singleton()->hex128(); if (FileUtil::exists(metapath)) { auto metadata = msg::decode<CSTableIndexBuildState>( FileUtil::read(metapath)); if (metadata.uuid() == tbl_uuid && metadata.offset() >= snap->nrecs) { return false; } } return true; } void CSTableIndex::buildCSTable(RefPtr<Partition> partition) { auto table = partition->getTable(); if (table->storage() == tsdb::TBL_STORAGE_STATIC) { return; } auto t0 = WallClock::unixMicros(); auto snap = partition->getSnapshot(); if (!needsUpdate(snap)) { return; } logDebug( "tsdb", "Building CSTable index for partition $0/$1/$2", snap->state.tsdb_namespace(), table->name(), snap->key.toString()); auto filepath = FileUtil::joinPaths(snap->base_path, "_cstable"); auto filepath_tmp = filepath + "." + Random::singleton()->hex128(); auto schema = table->schema(); { cstable::CSTableBuilder cstable(schema.get()); auto reader = partition->getReader(); reader->fetchRecords([&schema, &cstable] (const Buffer& record) { msg::MessageObject obj; msg::MessageDecoder::decode(record.data(), record.size(), *schema, &obj); cstable.addRecord(obj); }); cstable.write(filepath_tmp); } auto metapath = FileUtil::joinPaths(snap->base_path, "_cstable_state"); auto metapath_tmp = metapath + "." + Random::singleton()->hex128(); { auto metafile = File::openFile( metapath_tmp, File::O_CREATE | File::O_WRITE); CSTableIndexBuildState metadata; metadata.set_offset(snap->nrecs); metadata.set_uuid(snap->uuid().data(), snap->uuid().size()); auto buf = msg::encode(metadata); metafile.write(buf->data(), buf->size()); } FileUtil::mv(filepath_tmp, filepath); FileUtil::mv(metapath_tmp, metapath); auto t1 = WallClock::unixMicros(); logDebug( "tsdb", "Commiting CSTable index for partition $0/$1/$2, building took $3s", snap->state.tsdb_namespace(), table->name(), snap->key.toString(), (double) (t1 - t0) / 1000000.0f); } void CSTableIndex::enqueuePartition(RefPtr<Partition> partition) { std::unique_lock<std::mutex> lk(mutex_); enqueuePartitionWithLock(partition); } void CSTableIndex::enqueuePartitionWithLock(RefPtr<Partition> partition) { auto interval = partition->getTable()->cstableBuildInterval(); auto uuid = partition->uuid(); if (waitset_.count(uuid) > 0) { return; } queue_.emplace( WallClock::unixMicros() + interval.microseconds(), partition); waitset_.emplace(uuid); cv_.notify_all(); } void CSTableIndex::start() { running_ = true; for (int i = 0; i < 1; ++i) { threads_.emplace_back(std::bind(&CSTableIndex::work, this)); } } void CSTableIndex::stop() { if (!running_) { return; } running_ = false; cv_.notify_all(); for (auto& t : threads_) { t.join(); } } void CSTableIndex::work() { std::unique_lock<std::mutex> lk(mutex_); while (running_) { if (queue_.size() == 0) { cv_.wait(lk); } if (queue_.size() == 0) { continue; } auto now = WallClock::unixMicros(); if (now < queue_.begin()->first) { cv_.wait_for( lk, std::chrono::microseconds(queue_.begin()->first - now)); continue; } auto partition = queue_.begin()->second; queue_.erase(queue_.begin()); bool success = true; { lk.unlock(); try { buildCSTable(partition); } catch (const StandardException& e) { logError("tsdb", e, "CSTableIndex error"); success = false; } lk.lock(); } if (success) { waitset_.erase(partition->uuid()); if (needsUpdate(partition->getSnapshot())) { enqueuePartitionWithLock(partition); } } else { auto delay = 30 * kMicrosPerSecond; // FIXPAUL increasing delay.. queue_.emplace(now + delay, partition); } } } } // namespace tsdb <|endoftext|>
<commit_before>/**************************************************************************** * * (c) 2009-2016 QGROUNDCONTROL PROJECT <http://www.qgroundcontrol.org> * * QGroundControl is licensed according to the terms in the file * COPYING.md in the root of the source code directory. * ****************************************************************************/ #include "QGCUASFileView.h" #include "FileManager.h" #include "QGCQFileDialog.h" #include "UAS.h" #include <QFileDialog> #include <QDir> #include <QDebug> QGCUASFileView::QGCUASFileView(QWidget *parent, Vehicle* vehicle) : QWidget(parent) , _manager(vehicle->uas()->getFileManager()) , _currentCommand(commandNone) { _ui.setupUi(this); if (vehicle->px4Firmware()) { _ui.progressBar->reset(); // Connect UI signals connect(_ui.listFilesButton, &QPushButton::clicked, this, &QGCUASFileView::_refreshTree); connect(_ui.downloadButton, &QPushButton::clicked, this, &QGCUASFileView::_downloadFile); connect(_ui.uploadButton, &QPushButton::clicked, this, &QGCUASFileView::_uploadFile); connect(_ui.treeWidget, &QTreeWidget::currentItemChanged, this, &QGCUASFileView::_currentItemChanged); // Connect signals from FileManager connect(_manager, &FileManager::commandProgress, this, &QGCUASFileView::_commandProgress); connect(_manager, &FileManager::commandComplete, this, &QGCUASFileView::_commandComplete); connect(_manager, &FileManager::commandError, this, &QGCUASFileView::_commandError); connect(_manager, &FileManager::listEntry, this, &QGCUASFileView::_listEntryReceived); } else { _setAllButtonsEnabled(false); _ui.statusText->setText(QStringLiteral("Onboard Files not supported by this Vehicle")); } } /// @brief Downloads the file currently selected in the tree view void QGCUASFileView::_downloadFile(void) { if (_currentCommand != commandNone) { qWarning() << QString("Download attempted while another command was in progress: _currentCommand(%1)").arg(_currentCommand); return; } _ui.statusText->clear(); QString downloadToHere = QGCQFileDialog::getExistingDirectory(this, "Download Directory", QDir::homePath(), QGCQFileDialog::ShowDirsOnly | QGCQFileDialog::DontResolveSymlinks); // And now download to this location QString path; QString downloadFilename; QTreeWidgetItem* item = _ui.treeWidget->currentItem(); if (item && item->type() == _typeFile) { do { QString name = item->text(0).split("\t")[0]; // Strip off file sizes // If this is the file name and not a directory keep track of the download file name if (downloadFilename.isEmpty()) { downloadFilename = name; } path.prepend("/" + name); item = item->parent(); } while (item); _setAllButtonsEnabled(false); _currentCommand = commandDownload; _ui.statusText->setText(QString("Downloading: %1").arg(downloadFilename)); _manager->streamPath(path, QDir(downloadToHere)); } } /// @brief uploads a file into the currently selected directory the tree view void QGCUASFileView::_uploadFile(void) { if (_currentCommand != commandNone) { qWarning() << QString("Upload attempted while another command was in progress: _currentCommand(%1)").arg(_currentCommand); return; } _ui.statusText->clear(); // get and check directory from list view QTreeWidgetItem* item = _ui.treeWidget->currentItem(); if (item && item->type() != _typeDir) { return; } // Find complete path for upload directory QString path; do { QString name = item->text(0).split("\t")[0]; // Strip off file sizes path.prepend("/" + name); item = item->parent(); } while (item); QString uploadFromHere = QGCQFileDialog::getOpenFileName(this, "Upload File", QDir::homePath()); _ui.statusText->setText(QString("Uploading: %1").arg(uploadFromHere)); qDebug() << "Upload: " << uploadFromHere << "to path" << path; _setAllButtonsEnabled(false); _currentCommand = commandUpload; _manager->uploadPath(path, uploadFromHere); } /// @brief Called to update the progress of the download. /// @param value Progress bar value void QGCUASFileView::_commandProgress(int value) { _ui.progressBar->setValue(value); } /// @brief Called when an error occurs during a download. /// @param msg Error message void QGCUASFileView::_commandError(const QString& msg) { _setAllButtonsEnabled(true); _currentCommand = commandNone; _ui.statusText->setText(QString("Error: %1").arg(msg)); } /// @brief Refreshes the directory list tree. void QGCUASFileView::_refreshTree(void) { if (_currentCommand != commandNone) { qWarning() << QString("List attempted while another command was in progress: _currentCommand(%1)").arg(_currentCommand); return; } _ui.treeWidget->clear(); _ui.statusText->clear(); _walkIndexStack.clear(); _walkItemStack.clear(); _walkIndexStack.append(0); _walkItemStack.append(_ui.treeWidget->invisibleRootItem()); _setAllButtonsEnabled(false); _currentCommand = commandList; _requestDirectoryList("/"); } /// @brief Adds the specified directory entry to the tree view. void QGCUASFileView::_listEntryReceived(const QString& entry) { if (_currentCommand != commandList) { qWarning() << QString("List entry received while no list command in progress: _currentCommand(%1)").arg(_currentCommand); return; } int type; if (entry.startsWith("F")) { type = _typeFile; } else if (entry.startsWith("D")) { type = _typeDir; if (entry == "D." || entry == "D..") { return; } } else { Q_ASSERT(false); return; // Silence maybe-unitialized on type } QTreeWidgetItem* item; item = new QTreeWidgetItem(_walkItemStack.last(), type); Q_CHECK_PTR(item); item->setText(0, entry.right(entry.size() - 1)); } /// @brief Called when a command completes successfully void QGCUASFileView::_commandComplete(void) { QString statusText; if (_currentCommand == commandDownload) { _currentCommand = commandNone; _setAllButtonsEnabled(true); statusText = "Download complete"; } else if (_currentCommand == commandDownload) { _currentCommand = commandNone; _setAllButtonsEnabled(true); statusText = "Upload complete"; } else if (_currentCommand == commandList) { _listComplete(); } _ui.statusText->setText(statusText); _ui.progressBar->reset(); } void QGCUASFileView::_listComplete(void) { // Walk the current items, traversing down into directories Again: int walkIndex = _walkIndexStack.last(); QTreeWidgetItem* parentItem = _walkItemStack.last(); QTreeWidgetItem* childItem = parentItem->child(walkIndex); // Loop until we hit a directory while (childItem && childItem->type() != _typeDir) { // Move to next index at current level _walkIndexStack.last() = ++walkIndex; childItem = parentItem->child(walkIndex); } if (childItem) { // Process this item QString text = childItem->text(0); // Move to the next item for processing at this level _walkIndexStack.last() = ++walkIndex; // Push this new directory on the stack _walkItemStack.append(childItem); _walkIndexStack.append(0); // Ask for the directory list QString dir; for (int i=1; i<_walkItemStack.count(); i++) { QTreeWidgetItem* item = _walkItemStack[i]; dir.append("/" + item->text(0)); } _requestDirectoryList(dir); } else { // We have run out of items at the this level, pop the stack and keep going at that level _walkIndexStack.removeLast(); _walkItemStack.removeLast(); if (_walkIndexStack.count() != 0) { goto Again; } else { _setAllButtonsEnabled(true); _currentCommand = commandNone; } } } void QGCUASFileView::_currentItemChanged(QTreeWidgetItem* current, QTreeWidgetItem* previous) { Q_UNUSED(previous); _ui.downloadButton->setEnabled(current ? (current->type() == _typeFile) : false); _ui.uploadButton->setEnabled(current ? (current->type() == _typeDir) : false); } void QGCUASFileView::_requestDirectoryList(const QString& dir) { _manager->listDirectory(dir); } void QGCUASFileView::_setAllButtonsEnabled(bool enabled) { _ui.treeWidget->setEnabled(enabled); _ui.downloadButton->setEnabled(enabled); _ui.listFilesButton->setEnabled(enabled); _ui.uploadButton->setEnabled(enabled); if (enabled) { _currentItemChanged(_ui.treeWidget->currentItem(), NULL); } } <commit_msg>QGCUASFileView.cc: fix upload complete<commit_after>/**************************************************************************** * * (c) 2009-2016 QGROUNDCONTROL PROJECT <http://www.qgroundcontrol.org> * * QGroundControl is licensed according to the terms in the file * COPYING.md in the root of the source code directory. * ****************************************************************************/ #include "QGCUASFileView.h" #include "FileManager.h" #include "QGCQFileDialog.h" #include "UAS.h" #include <QFileDialog> #include <QDir> #include <QDebug> QGCUASFileView::QGCUASFileView(QWidget *parent, Vehicle* vehicle) : QWidget(parent) , _manager(vehicle->uas()->getFileManager()) , _currentCommand(commandNone) { _ui.setupUi(this); if (vehicle->px4Firmware()) { _ui.progressBar->reset(); // Connect UI signals connect(_ui.listFilesButton, &QPushButton::clicked, this, &QGCUASFileView::_refreshTree); connect(_ui.downloadButton, &QPushButton::clicked, this, &QGCUASFileView::_downloadFile); connect(_ui.uploadButton, &QPushButton::clicked, this, &QGCUASFileView::_uploadFile); connect(_ui.treeWidget, &QTreeWidget::currentItemChanged, this, &QGCUASFileView::_currentItemChanged); // Connect signals from FileManager connect(_manager, &FileManager::commandProgress, this, &QGCUASFileView::_commandProgress); connect(_manager, &FileManager::commandComplete, this, &QGCUASFileView::_commandComplete); connect(_manager, &FileManager::commandError, this, &QGCUASFileView::_commandError); connect(_manager, &FileManager::listEntry, this, &QGCUASFileView::_listEntryReceived); } else { _setAllButtonsEnabled(false); _ui.statusText->setText(QStringLiteral("Onboard Files not supported by this Vehicle")); } } /// @brief Downloads the file currently selected in the tree view void QGCUASFileView::_downloadFile(void) { if (_currentCommand != commandNone) { qWarning() << QString("Download attempted while another command was in progress: _currentCommand(%1)").arg(_currentCommand); return; } _ui.statusText->clear(); QString downloadToHere = QGCQFileDialog::getExistingDirectory(this, "Download Directory", QDir::homePath(), QGCQFileDialog::ShowDirsOnly | QGCQFileDialog::DontResolveSymlinks); // And now download to this location QString path; QString downloadFilename; QTreeWidgetItem* item = _ui.treeWidget->currentItem(); if (item && item->type() == _typeFile) { do { QString name = item->text(0).split("\t")[0]; // Strip off file sizes // If this is the file name and not a directory keep track of the download file name if (downloadFilename.isEmpty()) { downloadFilename = name; } path.prepend("/" + name); item = item->parent(); } while (item); _setAllButtonsEnabled(false); _currentCommand = commandDownload; _ui.statusText->setText(QString("Downloading: %1").arg(downloadFilename)); _manager->streamPath(path, QDir(downloadToHere)); } } /// @brief uploads a file into the currently selected directory the tree view void QGCUASFileView::_uploadFile(void) { if (_currentCommand != commandNone) { qWarning() << QString("Upload attempted while another command was in progress: _currentCommand(%1)").arg(_currentCommand); return; } _ui.statusText->clear(); // get and check directory from list view QTreeWidgetItem* item = _ui.treeWidget->currentItem(); if (item && item->type() != _typeDir) { return; } // Find complete path for upload directory QString path; do { QString name = item->text(0).split("\t")[0]; // Strip off file sizes path.prepend("/" + name); item = item->parent(); } while (item); QString uploadFromHere = QGCQFileDialog::getOpenFileName(this, "Upload File", QDir::homePath()); _ui.statusText->setText(QString("Uploading: %1").arg(uploadFromHere)); qDebug() << "Upload: " << uploadFromHere << "to path" << path; _setAllButtonsEnabled(false); _currentCommand = commandUpload; _manager->uploadPath(path, uploadFromHere); } /// @brief Called to update the progress of the download. /// @param value Progress bar value void QGCUASFileView::_commandProgress(int value) { _ui.progressBar->setValue(value); } /// @brief Called when an error occurs during a download. /// @param msg Error message void QGCUASFileView::_commandError(const QString& msg) { _setAllButtonsEnabled(true); _currentCommand = commandNone; _ui.statusText->setText(QString("Error: %1").arg(msg)); } /// @brief Refreshes the directory list tree. void QGCUASFileView::_refreshTree(void) { if (_currentCommand != commandNone) { qWarning() << QString("List attempted while another command was in progress: _currentCommand(%1)").arg(_currentCommand); return; } _ui.treeWidget->clear(); _ui.statusText->clear(); _walkIndexStack.clear(); _walkItemStack.clear(); _walkIndexStack.append(0); _walkItemStack.append(_ui.treeWidget->invisibleRootItem()); _setAllButtonsEnabled(false); _currentCommand = commandList; _requestDirectoryList("/"); } /// @brief Adds the specified directory entry to the tree view. void QGCUASFileView::_listEntryReceived(const QString& entry) { if (_currentCommand != commandList) { qWarning() << QString("List entry received while no list command in progress: _currentCommand(%1)").arg(_currentCommand); return; } int type; if (entry.startsWith("F")) { type = _typeFile; } else if (entry.startsWith("D")) { type = _typeDir; if (entry == "D." || entry == "D..") { return; } } else { Q_ASSERT(false); return; // Silence maybe-unitialized on type } QTreeWidgetItem* item; item = new QTreeWidgetItem(_walkItemStack.last(), type); Q_CHECK_PTR(item); item->setText(0, entry.right(entry.size() - 1)); } /// @brief Called when a command completes successfully void QGCUASFileView::_commandComplete(void) { QString statusText; if (_currentCommand == commandDownload) { _currentCommand = commandNone; _setAllButtonsEnabled(true); statusText = "Download complete"; } else if (_currentCommand == commandUpload) { _currentCommand = commandNone; _setAllButtonsEnabled(true); statusText = "Upload complete"; } else if (_currentCommand == commandList) { _listComplete(); } _ui.statusText->setText(statusText); _ui.progressBar->reset(); } void QGCUASFileView::_listComplete(void) { // Walk the current items, traversing down into directories Again: int walkIndex = _walkIndexStack.last(); QTreeWidgetItem* parentItem = _walkItemStack.last(); QTreeWidgetItem* childItem = parentItem->child(walkIndex); // Loop until we hit a directory while (childItem && childItem->type() != _typeDir) { // Move to next index at current level _walkIndexStack.last() = ++walkIndex; childItem = parentItem->child(walkIndex); } if (childItem) { // Process this item QString text = childItem->text(0); // Move to the next item for processing at this level _walkIndexStack.last() = ++walkIndex; // Push this new directory on the stack _walkItemStack.append(childItem); _walkIndexStack.append(0); // Ask for the directory list QString dir; for (int i=1; i<_walkItemStack.count(); i++) { QTreeWidgetItem* item = _walkItemStack[i]; dir.append("/" + item->text(0)); } _requestDirectoryList(dir); } else { // We have run out of items at the this level, pop the stack and keep going at that level _walkIndexStack.removeLast(); _walkItemStack.removeLast(); if (_walkIndexStack.count() != 0) { goto Again; } else { _setAllButtonsEnabled(true); _currentCommand = commandNone; } } } void QGCUASFileView::_currentItemChanged(QTreeWidgetItem* current, QTreeWidgetItem* previous) { Q_UNUSED(previous); _ui.downloadButton->setEnabled(current ? (current->type() == _typeFile) : false); _ui.uploadButton->setEnabled(current ? (current->type() == _typeDir) : false); } void QGCUASFileView::_requestDirectoryList(const QString& dir) { _manager->listDirectory(dir); } void QGCUASFileView::_setAllButtonsEnabled(bool enabled) { _ui.treeWidget->setEnabled(enabled); _ui.downloadButton->setEnabled(enabled); _ui.listFilesButton->setEnabled(enabled); _ui.uploadButton->setEnabled(enabled); if (enabled) { _currentItemChanged(_ui.treeWidget->currentItem(), NULL); } } <|endoftext|>
<commit_before>// Module: Log4CPLUS // File: loglevel.cxx // Created: 6/2001 // Author: Tad E. Smith // // // Copyright 2001-2014 Tad E. Smith // // 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 <log4cplus/loglevel.h> #include <log4cplus/helpers/loglog.h> #include <log4cplus/helpers/stringhelper.h> #include <log4cplus/internal/internal.h> #include <algorithm> namespace log4cplus { namespace { // The strings here are not simple tstring constants to allow using these // strings and log4cplus itself in client code during static variables // initialization. If they are simple tstring constants then, due to undefined // order of initialization between translation units, they might be // uninitialized before they are used by the client code. One possible solution // to this is to use compiler specific attributes and/or pragmas to influence // initialization order/priority. Another solution is using function local // static variables, which are initialized on first use. We choose this // implementation because it is more portable than compiler specific means. #define DEF_LL_STRING(_logLevel) \ static tstring const & _logLevel ## _STRING () \ { \ static tstring const str (LOG4CPLUS_TEXT (#_logLevel)); \ return str; \ } DEF_LL_STRING (OFF) DEF_LL_STRING (FATAL) DEF_LL_STRING (ERROR) DEF_LL_STRING (WARN) DEF_LL_STRING (INFO) DEF_LL_STRING (DEBUG) DEF_LL_STRING (TRACE) DEF_LL_STRING (ALL) DEF_LL_STRING (NOTSET) DEF_LL_STRING (UNKNOWN) #undef DEF_LL_STRING static tstring const & defaultLogLevelToStringMethod(LogLevel ll) { switch(ll) { case OFF_LOG_LEVEL: return OFF_STRING(); case FATAL_LOG_LEVEL: return FATAL_STRING(); case ERROR_LOG_LEVEL: return ERROR_STRING(); case WARN_LOG_LEVEL: return WARN_STRING(); case INFO_LOG_LEVEL: return INFO_STRING(); case DEBUG_LOG_LEVEL: return DEBUG_STRING(); case TRACE_LOG_LEVEL: return TRACE_STRING(); //case ALL_LOG_LEVEL: return ALL_STRING(); case NOT_SET_LOG_LEVEL: return NOTSET_STRING(); }; return internal::empty_str; } static LogLevel defaultStringToLogLevelMethod(const tstring& s) { // Since C++11, accessing str[0] is always safe as it returns '\0' for // empty string. switch (s[0]) { #define DEF_LLMATCH(_chr, _logLevel) \ case _chr: if (s == _logLevel ## _STRING ()) \ return _logLevel ## _LOG_LEVEL; break; DEF_LLMATCH ('O', OFF); DEF_LLMATCH ('F', FATAL); DEF_LLMATCH ('E', ERROR); DEF_LLMATCH ('W', WARN); DEF_LLMATCH ('I', INFO); DEF_LLMATCH ('D', DEBUG); DEF_LLMATCH ('T', TRACE); DEF_LLMATCH ('A', ALL); #undef DEF_LLMATCH } return NOT_SET_LOG_LEVEL; } } // namespace void initializeLogLevelStrings () { OFF_STRING(); FATAL_STRING(); ERROR_STRING(); WARN_STRING(); INFO_STRING(); DEBUG_STRING(); TRACE_STRING(); ALL_STRING(); NOTSET_STRING(); } ////////////////////////////////////////////////////////////////////////////// // LogLevelManager ctors and dtor ////////////////////////////////////////////////////////////////////////////// LogLevelManager::LogLevelManager() { toStringMethods.emplace_back (defaultLogLevelToStringMethod); fromStringMethods.push_back (defaultStringToLogLevelMethod); } LogLevelManager::~LogLevelManager() { } ////////////////////////////////////////////////////////////////////////////// // LogLevelManager public methods ////////////////////////////////////////////////////////////////////////////// tstring const & LogLevelManager::toString(LogLevel ll) const { tstring const * ret; for (LogLevelToStringMethodRec const & rec : toStringMethods) { if (rec.use_1_0) { // Use TLS to store the result to allow us to return // a reference. tstring & ll_str = internal::get_ptd ()->ll_str; ll_str = rec.func_1_0 (ll); ret = &ll_str; } else ret = &rec.func (ll); if (! ret->empty ()) return *ret; } return UNKNOWN_STRING(); } LogLevel LogLevelManager::fromString(const tstring& arg) const { tstring const s = helpers::toUpper(arg); for (auto func : fromStringMethods) { LogLevel ret = func (s); if (ret != NOT_SET_LOG_LEVEL) return ret; } helpers::getLogLog ().error ( LOG4CPLUS_TEXT ("Unrecognized log level: ") + arg); return NOT_SET_LOG_LEVEL; } void LogLevelManager::pushToStringMethod(LogLevelToStringMethod newToString) { toStringMethods.emplace_back (newToString); } void LogLevelManager::pushToStringMethod(LogLevelToStringMethod_1_0 newToString) { toStringMethods.emplace_back (newToString); } void LogLevelManager::pushFromStringMethod(StringToLogLevelMethod newFromString) { fromStringMethods.push_back (newFromString); } // // // LogLevelManager::LogLevelToStringMethodRec::LogLevelToStringMethodRec () { } LogLevelManager::LogLevelToStringMethodRec::LogLevelToStringMethodRec ( LogLevelToStringMethod f) : func {f} , use_1_0 {false} { } LogLevelManager::LogLevelToStringMethodRec::LogLevelToStringMethodRec ( LogLevelToStringMethod_1_0 f) : func_1_0 {f} , use_1_0 {true} { } } // namespace log4cplus <commit_msg>loglevel.cxx: Insert to/from string/log level conversion functions to the beginning of vector to favour user defined log levels and conversion functions.<commit_after>// Module: Log4CPLUS // File: loglevel.cxx // Created: 6/2001 // Author: Tad E. Smith // // // Copyright 2001-2014 Tad E. Smith // // 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 <log4cplus/loglevel.h> #include <log4cplus/helpers/loglog.h> #include <log4cplus/helpers/stringhelper.h> #include <log4cplus/internal/internal.h> #include <algorithm> namespace log4cplus { namespace { // The strings here are not simple tstring constants to allow using these // strings and log4cplus itself in client code during static variables // initialization. If they are simple tstring constants then, due to undefined // order of initialization between translation units, they might be // uninitialized before they are used by the client code. One possible solution // to this is to use compiler specific attributes and/or pragmas to influence // initialization order/priority. Another solution is using function local // static variables, which are initialized on first use. We choose this // implementation because it is more portable than compiler specific means. #define DEF_LL_STRING(_logLevel) \ static tstring const & _logLevel ## _STRING () \ { \ static tstring const str (LOG4CPLUS_TEXT (#_logLevel)); \ return str; \ } DEF_LL_STRING (OFF) DEF_LL_STRING (FATAL) DEF_LL_STRING (ERROR) DEF_LL_STRING (WARN) DEF_LL_STRING (INFO) DEF_LL_STRING (DEBUG) DEF_LL_STRING (TRACE) DEF_LL_STRING (ALL) DEF_LL_STRING (NOTSET) DEF_LL_STRING (UNKNOWN) #undef DEF_LL_STRING static tstring const & defaultLogLevelToStringMethod(LogLevel ll) { switch(ll) { case OFF_LOG_LEVEL: return OFF_STRING(); case FATAL_LOG_LEVEL: return FATAL_STRING(); case ERROR_LOG_LEVEL: return ERROR_STRING(); case WARN_LOG_LEVEL: return WARN_STRING(); case INFO_LOG_LEVEL: return INFO_STRING(); case DEBUG_LOG_LEVEL: return DEBUG_STRING(); case TRACE_LOG_LEVEL: return TRACE_STRING(); //case ALL_LOG_LEVEL: return ALL_STRING(); case NOT_SET_LOG_LEVEL: return NOTSET_STRING(); }; return internal::empty_str; } static LogLevel defaultStringToLogLevelMethod(const tstring& s) { // Since C++11, accessing str[0] is always safe as it returns '\0' for // empty string. switch (s[0]) { #define DEF_LLMATCH(_chr, _logLevel) \ case _chr: if (s == _logLevel ## _STRING ()) \ return _logLevel ## _LOG_LEVEL; break; DEF_LLMATCH ('O', OFF); DEF_LLMATCH ('F', FATAL); DEF_LLMATCH ('E', ERROR); DEF_LLMATCH ('W', WARN); DEF_LLMATCH ('I', INFO); DEF_LLMATCH ('D', DEBUG); DEF_LLMATCH ('T', TRACE); DEF_LLMATCH ('A', ALL); #undef DEF_LLMATCH } return NOT_SET_LOG_LEVEL; } } // namespace void initializeLogLevelStrings () { OFF_STRING(); FATAL_STRING(); ERROR_STRING(); WARN_STRING(); INFO_STRING(); DEBUG_STRING(); TRACE_STRING(); ALL_STRING(); NOTSET_STRING(); } ////////////////////////////////////////////////////////////////////////////// // LogLevelManager ctors and dtor ////////////////////////////////////////////////////////////////////////////// LogLevelManager::LogLevelManager() { pushToStringMethod (defaultLogLevelToStringMethod); pushFromStringMethod (defaultStringToLogLevelMethod); } LogLevelManager::~LogLevelManager() { } ////////////////////////////////////////////////////////////////////////////// // LogLevelManager public methods ////////////////////////////////////////////////////////////////////////////// tstring const & LogLevelManager::toString(LogLevel ll) const { tstring const * ret; for (LogLevelToStringMethodRec const & rec : toStringMethods) { if (rec.use_1_0) { // Use TLS to store the result to allow us to return // a reference. tstring & ll_str = internal::get_ptd ()->ll_str; ll_str = rec.func_1_0 (ll); ret = &ll_str; } else ret = &rec.func (ll); if (! ret->empty ()) return *ret; } return UNKNOWN_STRING(); } LogLevel LogLevelManager::fromString(const tstring& arg) const { tstring const s = helpers::toUpper(arg); for (auto func : fromStringMethods) { LogLevel ret = func (s); if (ret != NOT_SET_LOG_LEVEL) return ret; } helpers::getLogLog ().error ( LOG4CPLUS_TEXT ("Unrecognized log level: ") + arg); return NOT_SET_LOG_LEVEL; } void LogLevelManager::pushToStringMethod(LogLevelToStringMethod newToString) { toStringMethods.emplace (toStringMethods.begin (), newToString); } void LogLevelManager::pushToStringMethod(LogLevelToStringMethod_1_0 newToString) { toStringMethods.emplace (toStringMethods.begin(), newToString); } void LogLevelManager::pushFromStringMethod(StringToLogLevelMethod newFromString) { fromStringMethods.push_back (newFromString); } // // // LogLevelManager::LogLevelToStringMethodRec::LogLevelToStringMethodRec () { } LogLevelManager::LogLevelToStringMethodRec::LogLevelToStringMethodRec ( LogLevelToStringMethod f) : func {f} , use_1_0 {false} { } LogLevelManager::LogLevelToStringMethodRec::LogLevelToStringMethodRec ( LogLevelToStringMethod_1_0 f) : func_1_0 {f} , use_1_0 {true} { } } // namespace log4cplus <|endoftext|>
<commit_before>/************************************************************************** * Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. * * * * Author: The ALICE Off-line Project. * * Contributors are mentioned in the code where appropriate. * * * * Permission to use, copy, modify and distribute this software and its * * documentation strictly for non-commercial purposes is hereby granted * * without fee, provided that the above copyright notice appears in all * * copies and that both the copyright notice and this permission notice * * appear in the supporting documentation. The authors make no claims * * about the suitability of this software for any purpose. It is * * provided "as is" without express or implied warranty. * **************************************************************************/ /* $Log$ Revision 1.7 2001/05/16 14:57:22 alibrary New files for folders and Stack Revision 1.4 2000/10/02 21:28:14 fca Removal of useless dependecies via forward declarations Revision 1.3 2000/07/12 08:56:25 fca Coding convention correction and warning removal Revision 1.2 1999/09/29 09:24:29 fca Introduction of the Copyright and cvs Log */ #include "AliHeader.h" #include <stdio.h> ClassImp(AliHeader) AliHeader::AliHeader() { // // Default constructor // fRun=0; fNvertex=0; fNprimary=0; fNtrack=0; fEvent=0; fStack=0; fGenHeader = 0; } AliHeader::AliHeader(Int_t run, Int_t event) { // // Standard constructor // fRun=run; fNvertex=0; fNprimary=0; fNtrack=0; fEvent=event; fStack=0; fGenHeader = 0; } void AliHeader::Reset(Int_t run, Int_t event) { // // Resets the header with new run and event number // fRun=run; fNvertex=0; fNprimary=0; fNtrack=0; fEvent=event; } void AliHeader::Print(const char* option) { // // Dumps header content // printf( "\n=========== Header for run %d Event %d = beginning ======================================\n", fRun,fEvent); printf(" Number of Vertex %d\n",fNvertex); printf(" Number of Primary %d\n",fNprimary); printf(" Number of Tracks %d\n",fNtrack); printf( "=========== Header for run %d Event %d = end ============================================\n\n", fRun,fEvent); } AliStack* AliHeader::Stack() const { // Return pointer to stack return fStack; } void AliHeader::SetStack(AliStack* stack) { // Set pointer to stack fStack = stack; } void AliHeader::SetGenEventHeader(AliGenEventHeader* header) { // Set pointer to header for generated event fGenHeader = header; } iAliGenEventHeader* AliHeader::GenEventHeader() const { // Get pointer to header for generated event return fGenHeader; } <commit_msg>Typo corrected<commit_after>/************************************************************************** * Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. * * * * Author: The ALICE Off-line Project. * * Contributors are mentioned in the code where appropriate. * * * * Permission to use, copy, modify and distribute this software and its * * documentation strictly for non-commercial purposes is hereby granted * * without fee, provided that the above copyright notice appears in all * * copies and that both the copyright notice and this permission notice * * appear in the supporting documentation. The authors make no claims * * about the suitability of this software for any purpose. It is * * provided "as is" without express or implied warranty. * **************************************************************************/ /* $Log$ Revision 1.8 2001/05/23 08:50:01 hristov Weird inline removed Revision 1.7 2001/05/16 14:57:22 alibrary New files for folders and Stack Revision 1.4 2000/10/02 21:28:14 fca Removal of useless dependecies via forward declarations Revision 1.3 2000/07/12 08:56:25 fca Coding convention correction and warning removal Revision 1.2 1999/09/29 09:24:29 fca Introduction of the Copyright and cvs Log */ #include "AliHeader.h" #include <stdio.h> ClassImp(AliHeader) AliHeader::AliHeader() { // // Default constructor // fRun=0; fNvertex=0; fNprimary=0; fNtrack=0; fEvent=0; fStack=0; fGenHeader = 0; } AliHeader::AliHeader(Int_t run, Int_t event) { // // Standard constructor // fRun=run; fNvertex=0; fNprimary=0; fNtrack=0; fEvent=event; fStack=0; fGenHeader = 0; } void AliHeader::Reset(Int_t run, Int_t event) { // // Resets the header with new run and event number // fRun=run; fNvertex=0; fNprimary=0; fNtrack=0; fEvent=event; } void AliHeader::Print(const char* option) { // // Dumps header content // printf( "\n=========== Header for run %d Event %d = beginning ======================================\n", fRun,fEvent); printf(" Number of Vertex %d\n",fNvertex); printf(" Number of Primary %d\n",fNprimary); printf(" Number of Tracks %d\n",fNtrack); printf( "=========== Header for run %d Event %d = end ============================================\n\n", fRun,fEvent); } AliStack* AliHeader::Stack() const { // Return pointer to stack return fStack; } void AliHeader::SetStack(AliStack* stack) { // Set pointer to stack fStack = stack; } void AliHeader::SetGenEventHeader(AliGenEventHeader* header) { // Set pointer to header for generated event fGenHeader = header; } AliGenEventHeader* AliHeader::GenEventHeader() const { // Get pointer to header for generated event return fGenHeader; } <|endoftext|>
<commit_before>// Copyright 2010-2012 RethinkDB, all rights reserved. #include "serializer/serializer.hpp" #include "arch/arch.hpp" file_account_t *serializer_t::make_io_account(int priority) { assert_thread(); return make_io_account(priority, UNLIMITED_OUTSTANDING_REQUESTS); } serializer_write_t serializer_write_t::make_touch(block_id_t block_id, repli_timestamp_t recency) { serializer_write_t w; w.block_id = block_id; w.action_type = TOUCH; w.action.touch.recency = recency; return w; } serializer_write_t serializer_write_t::make_update( block_id_t block_id, repli_timestamp_t recency, const void *buf, iocallback_t *io_callback, serializer_write_launched_callback_t *launch_callback) { serializer_write_t w; w.block_id = block_id; w.action_type = UPDATE; w.action.update.buf = buf; w.action.update.recency = recency; w.action.update.io_callback = io_callback; w.action.update.launch_callback = launch_callback; return w; } serializer_write_t serializer_write_t::make_delete(block_id_t block_id) { serializer_write_t w; w.block_id = block_id; w.action_type = DELETE; return w; } struct write_cond_t : public cond_t, public iocallback_t { explicit write_cond_t(iocallback_t *cb) : callback(cb) { } void on_io_complete() { if (callback) callback->on_io_complete(); pulse(); } iocallback_t *callback; }; ser_buffer_t *convert_buffer_cache_buf_to_ser_buffer(const void *buf) { return static_cast<ser_buffer_t *>(const_cast<void *>(buf)) - 1; } void do_writes(serializer_t *ser, const std::vector<serializer_write_t> &writes, file_account_t *io_account) { ser->assert_thread(); std::vector<index_write_op_t> index_write_ops; index_write_ops.reserve(writes.size()); // Step 1: Write buffers to disk and assemble index operations std::vector<buf_write_info_t> write_infos; write_infos.reserve(writes.size()); struct : public iocallback_t, public cond_t { void on_io_complete() { pulse(); } } block_write_cond; for (size_t i = 0; i < writes.size(); ++i) { if (writes[i].action_type == serializer_write_t::UPDATE) { write_infos.push_back(buf_write_info_t(convert_buffer_cache_buf_to_ser_buffer(writes[i].action.update.buf), ser->get_block_size().ser_value(), // RSI: Use actual block size. writes[i].block_id)); } } // RSI: Make sure block_writes lets you do zero writes. std::vector<counted_t<standard_block_token_t> > tokens; if (!write_infos.empty()) { tokens = ser->block_writes(write_infos, io_account, &block_write_cond); } else { block_write_cond.pulse(); } guarantee(tokens.size() == write_infos.size()); size_t tokens_index = 0; for (size_t i = 0; i < writes.size(); ++i) { switch (writes[i].action_type) { case serializer_write_t::UPDATE: { guarantee(tokens_index < tokens.size()); index_write_ops.push_back(index_write_op_t(writes[i].block_id, tokens[tokens_index], writes[i].action.update.recency)); if (writes[i].action.update.launch_callback != NULL) { writes[i].action.update.launch_callback->on_write_launched(tokens[tokens_index]); } ++tokens_index; } break; case serializer_write_t::DELETE: { index_write_ops.push_back(index_write_op_t(writes[i].block_id, counted_t<standard_block_token_t>(), repli_timestamp_t::invalid)); } break; case serializer_write_t::TOUCH: { index_write_ops.push_back(index_write_op_t(writes[i].block_id, boost::none, writes[i].action.touch.recency)); } break; default: unreachable(); } } guarantee(tokens_index == tokens.size()); guarantee(index_write_ops.size() == writes.size()); // Step 2: Wait on all writes to finish block_write_cond.wait(); // Step 2.5: Call these annoying io_callbacks. // RSI: Refactor this without pointless individual io callbacks? for (size_t i = 0; i < writes.size(); ++i) { if (writes[i].action_type == serializer_write_t::UPDATE) { // RSI: Check whether any NULLs are really used.. because that's dumb. if (writes[i].action.update.io_callback != NULL) { writes[i].action.update.io_callback->on_io_complete(); } } } // Step 3: Commit the transaction to the serializer ser->index_write(index_write_ops, io_account); } void serializer_data_ptr_t::free() { rassert(ptr_.has()); ptr_.reset(); } void serializer_data_ptr_t::init_malloc(serializer_t *ser) { rassert(!ptr_.has()); ptr_ = ser->malloc(); } void serializer_data_ptr_t::init_clone(serializer_t *ser, const serializer_data_ptr_t &other) { rassert(other.ptr_.has()); rassert(!ptr_.has()); ptr_ = ser->clone(other.ptr_.get()); } // RSI: take a ser_buffer_t * arg. counted_t<standard_block_token_t> serializer_block_write(serializer_t *ser, const void *buf, block_id_t block_id, file_account_t *io_account) { struct : public cond_t, public iocallback_t { void on_io_complete() { pulse(); } } cb; ser_buffer_t *ser_buf = convert_buffer_cache_buf_to_ser_buffer(buf); // RSI: use the real block size thank you. std::vector<counted_t<standard_block_token_t> > tokens = ser->block_writes({ buf_write_info_t(ser_buf, ser->get_block_size().ser_value(), block_id) }, io_account, &cb); guarantee(tokens.size() == 1); cb.wait(); return tokens[0]; } <commit_msg>Removed unused write_cond_t type.<commit_after>// Copyright 2010-2012 RethinkDB, all rights reserved. #include "serializer/serializer.hpp" #include "arch/arch.hpp" file_account_t *serializer_t::make_io_account(int priority) { assert_thread(); return make_io_account(priority, UNLIMITED_OUTSTANDING_REQUESTS); } serializer_write_t serializer_write_t::make_touch(block_id_t block_id, repli_timestamp_t recency) { serializer_write_t w; w.block_id = block_id; w.action_type = TOUCH; w.action.touch.recency = recency; return w; } serializer_write_t serializer_write_t::make_update( block_id_t block_id, repli_timestamp_t recency, const void *buf, iocallback_t *io_callback, serializer_write_launched_callback_t *launch_callback) { serializer_write_t w; w.block_id = block_id; w.action_type = UPDATE; w.action.update.buf = buf; w.action.update.recency = recency; w.action.update.io_callback = io_callback; w.action.update.launch_callback = launch_callback; return w; } serializer_write_t serializer_write_t::make_delete(block_id_t block_id) { serializer_write_t w; w.block_id = block_id; w.action_type = DELETE; return w; } ser_buffer_t *convert_buffer_cache_buf_to_ser_buffer(const void *buf) { return static_cast<ser_buffer_t *>(const_cast<void *>(buf)) - 1; } void do_writes(serializer_t *ser, const std::vector<serializer_write_t> &writes, file_account_t *io_account) { ser->assert_thread(); std::vector<index_write_op_t> index_write_ops; index_write_ops.reserve(writes.size()); // Step 1: Write buffers to disk and assemble index operations std::vector<buf_write_info_t> write_infos; write_infos.reserve(writes.size()); struct : public iocallback_t, public cond_t { void on_io_complete() { pulse(); } } block_write_cond; for (size_t i = 0; i < writes.size(); ++i) { if (writes[i].action_type == serializer_write_t::UPDATE) { write_infos.push_back(buf_write_info_t(convert_buffer_cache_buf_to_ser_buffer(writes[i].action.update.buf), ser->get_block_size().ser_value(), // RSI: Use actual block size. writes[i].block_id)); } } // RSI: Make sure block_writes lets you do zero writes. std::vector<counted_t<standard_block_token_t> > tokens; if (!write_infos.empty()) { tokens = ser->block_writes(write_infos, io_account, &block_write_cond); } else { block_write_cond.pulse(); } guarantee(tokens.size() == write_infos.size()); size_t tokens_index = 0; for (size_t i = 0; i < writes.size(); ++i) { switch (writes[i].action_type) { case serializer_write_t::UPDATE: { guarantee(tokens_index < tokens.size()); index_write_ops.push_back(index_write_op_t(writes[i].block_id, tokens[tokens_index], writes[i].action.update.recency)); if (writes[i].action.update.launch_callback != NULL) { writes[i].action.update.launch_callback->on_write_launched(tokens[tokens_index]); } ++tokens_index; } break; case serializer_write_t::DELETE: { index_write_ops.push_back(index_write_op_t(writes[i].block_id, counted_t<standard_block_token_t>(), repli_timestamp_t::invalid)); } break; case serializer_write_t::TOUCH: { index_write_ops.push_back(index_write_op_t(writes[i].block_id, boost::none, writes[i].action.touch.recency)); } break; default: unreachable(); } } guarantee(tokens_index == tokens.size()); guarantee(index_write_ops.size() == writes.size()); // Step 2: Wait on all writes to finish block_write_cond.wait(); // Step 2.5: Call these annoying io_callbacks. // RSI: Refactor this without pointless individual io callbacks? for (size_t i = 0; i < writes.size(); ++i) { if (writes[i].action_type == serializer_write_t::UPDATE) { // RSI: Check whether any NULLs are really used.. because that's dumb. if (writes[i].action.update.io_callback != NULL) { writes[i].action.update.io_callback->on_io_complete(); } } } // Step 3: Commit the transaction to the serializer ser->index_write(index_write_ops, io_account); } void serializer_data_ptr_t::free() { rassert(ptr_.has()); ptr_.reset(); } void serializer_data_ptr_t::init_malloc(serializer_t *ser) { rassert(!ptr_.has()); ptr_ = ser->malloc(); } void serializer_data_ptr_t::init_clone(serializer_t *ser, const serializer_data_ptr_t &other) { rassert(other.ptr_.has()); rassert(!ptr_.has()); ptr_ = ser->clone(other.ptr_.get()); } // RSI: take a ser_buffer_t * arg. counted_t<standard_block_token_t> serializer_block_write(serializer_t *ser, const void *buf, block_id_t block_id, file_account_t *io_account) { struct : public cond_t, public iocallback_t { void on_io_complete() { pulse(); } } cb; ser_buffer_t *ser_buf = convert_buffer_cache_buf_to_ser_buffer(buf); // RSI: use the real block size thank you. std::vector<counted_t<standard_block_token_t> > tokens = ser->block_writes({ buf_write_info_t(ser_buf, ser->get_block_size().ser_value(), block_id) }, io_account, &cb); guarantee(tokens.size() == 1); cb.wait(); return tokens[0]; } <|endoftext|>
<commit_before>// Copyright 2010-2012 RethinkDB, all rights reserved. #include "serializer/translator.hpp" #include "errors.hpp" #include <boost/bind.hpp> #include "concurrency/pmap.hpp" #include "serializer/types.hpp" #include "serializer/config.hpp" /* serializer_multiplexer_t */ /* The multiplexing serializer slices up the serializers as follows: - Each proxy is assigned to a serializer. The formula is (proxy_id % n_files) - Block ID 0 on each serializer is for static configuration information. - Each proxy uses block IDs of the form (1 + (n * (number of proxies on serializer) + (proxy_id / n_files))). */ const block_magic_t multiplexer_config_block_t::expected_magic = { { 'c', 'f', 'g', '_' } }; void prep_serializer( const std::vector<standard_serializer_t *>& serializers, creation_timestamp_t creation_timestamp, int n_proxies, int i) { standard_serializer_t *ser = serializers[i]; /* Go to the thread the serializer is running on because it can only be accessed safely from that thread */ on_thread_t thread_switcher(ser->home_thread()); /* Write the initial configuration block */ multiplexer_config_block_t *c = reinterpret_cast<multiplexer_config_block_t *>( ser->malloc()); bzero(c, ser->get_block_size().value()); c->magic = multiplexer_config_block_t::expected_magic; c->creation_timestamp = creation_timestamp; c->n_files = serializers.size(); c->this_serializer = i; c->n_proxies = n_proxies; index_write_op_t op(CONFIG_BLOCK_ID.ser_id); op.token = ser->block_write(c, CONFIG_BLOCK_ID.ser_id, DEFAULT_DISK_ACCOUNT); op.recency = repli_timestamp_t::invalid; serializer_index_write(ser, op, DEFAULT_DISK_ACCOUNT); ser->free(c); } /* static */ void serializer_multiplexer_t::create(const std::vector<standard_serializer_t *>& underlying, int n_proxies) { /* Choose a more-or-less unique ID so that we can hopefully catch the case where files are mixed and mismatched. */ creation_timestamp_t creation_timestamp = time(NULL); /* Write a configuration block for each one */ pmap(underlying.size(), boost::bind(&prep_serializer, underlying, creation_timestamp, n_proxies, _1)); } void create_proxies(const std::vector<standard_serializer_t *>& underlying, creation_timestamp_t creation_timestamp, std::vector<translator_serializer_t *> *proxies, int i) { standard_serializer_t *ser = underlying[i]; /* Go to the thread the serializer is running on because it is only safe to access on that thread and because the pseudoserializers must be created on that thread */ on_thread_t thread_switcher(ser->home_thread()); /* Load config block */ multiplexer_config_block_t *c = reinterpret_cast<multiplexer_config_block_t *>(ser->malloc()); ser->block_read(ser->index_read(CONFIG_BLOCK_ID.ser_id), c, DEFAULT_DISK_ACCOUNT); /* Verify that stuff is sane */ if (c->magic != multiplexer_config_block_t::expected_magic) { fail_due_to_user_error("File did not come from 'rethinkdb create'."); } if (c->creation_timestamp != creation_timestamp) { fail_due_to_user_error("The files that the server was started with didn't all come from " "the same call to 'rethinkdb create'."); } if (c->n_files > static_cast<int>(underlying.size())) { fail_due_to_user_error("You forgot to include one of the files/devices that you included " "when the database was first created."); } if (c->n_files < static_cast<int>(underlying.size())) { fail_due_to_user_error("Got more files than expected. Did you give a file that wasn't" "included in the call to 'rethinkdb create'? Did you duplicate one of the files?"); } guarantee(c->this_serializer >= 0 && c->this_serializer < static_cast<int>(underlying.size())); guarantee(c->n_proxies == static_cast<int>(proxies->size())); /* Figure out which serializer we are (in case files were specified to 'rethinkdb serve' in a different order than they were specified to 'rethinkdb create') */ int j = c->this_serializer; int num_on_this_serializer = serializer_multiplexer_t::compute_mod_count( j, underlying.size(), c->n_proxies); /* This is a slightly weird way of phrasing this; it's done this way so I can be sure it's equivalent to the old way of doing things */ for (int k = 0; k < c->n_proxies; k++) { /* Are we responsible for creating this proxy? */ if (k % static_cast<int>(underlying.size()) != j) continue; rassert(!(*proxies)[k]); (*proxies)[k] = new translator_serializer_t( ser, num_on_this_serializer, k / underlying.size(), CONFIG_BLOCK_ID /* Reserve block ID 0 */); } ser->free(c); } serializer_multiplexer_t::serializer_multiplexer_t(const std::vector<standard_serializer_t *>& underlying) { rassert(underlying.size() > 0); for (int i = 0; i < static_cast<int>(underlying.size()); ++i) { rassert(underlying[i]); } /* Figure out how many slices there are gonna be and figure out what the creation magic is */ { on_thread_t thread_switcher(underlying[0]->home_thread()); /* Load config block */ multiplexer_config_block_t *c = reinterpret_cast<multiplexer_config_block_t *>( underlying[0]->malloc()); underlying[0]->block_read(underlying[0]->index_read(CONFIG_BLOCK_ID.ser_id), c, DEFAULT_DISK_ACCOUNT); rassert(c->magic == multiplexer_config_block_t::expected_magic); creation_timestamp = c->creation_timestamp; proxies.resize(c->n_proxies); underlying[0]->free(c); } /* Now go to each serializer and verify it individually. We visit the first serializer twice (because we already visited it to get the creation magic and stuff) but that's OK. Also, create proxies for the serializers (populate the 'proxies' vector) */ pmap(underlying.size(), boost::bind(&create_proxies, underlying, creation_timestamp, &proxies, _1)); for (int i = 0; i < static_cast<int>(proxies.size()); ++i) rassert(proxies[i]); } void destroy_proxy(std::vector<translator_serializer_t *> *proxies, int i) { on_thread_t thread_switcher((*proxies)[i]->home_thread()); delete (*proxies)[i]; } serializer_multiplexer_t::~serializer_multiplexer_t() { pmap(proxies.size(), boost::bind(&destroy_proxy, &proxies, _1)); } int serializer_multiplexer_t::compute_mod_count(int32_t file_number, int32_t n_files, int32_t n_slices) { /* If we have 'n_files', and we distribute 'n_slices' over those 'n_files' such that slice 'n' is on file 'n % n_files', then how many slices will be on file 'file_number'? */ return n_slices / n_files + (n_slices % n_files > file_number); } /* translator_serializer_t */ block_id_t translator_serializer_t::translate_block_id(block_id_t id, int mod_count, int mod_id, config_block_id_t cfgid) { return id * mod_count + mod_id + cfgid.subsequent_ser_id(); } int translator_serializer_t::untranslate_block_id_to_mod_id(block_id_t inner_id, int mod_count, config_block_id_t cfgid) { // We know that inner_id == id * mod_count + mod_id + min. // Thus inner_id - min == id * mod_count + mod_id. // It follows that inner_id - min === mod_id (modulo mod_count). // So (inner_id - min) % mod_count == mod_id (since 0 <= mod_id < mod_count). // (And inner_id - min >= 0, so '%' works as expected.) return (inner_id - cfgid.subsequent_ser_id()) % mod_count; } block_id_t translator_serializer_t::untranslate_block_id_to_id(block_id_t inner_id, int mod_count, int mod_id, config_block_id_t cfgid) { // (simply dividing by mod_count should be sufficient, but this is cleaner) return (inner_id - cfgid.subsequent_ser_id() - mod_id) / mod_count; } block_id_t translator_serializer_t::translate_block_id(block_id_t id) const { rassert(id != NULL_BLOCK_ID); return translate_block_id(id, mod_count, mod_id, cfgid); } translator_serializer_t::translator_serializer_t(standard_serializer_t *_inner, int _mod_count, int _mod_id, config_block_id_t _cfgid) : inner(_inner), mod_count(_mod_count), mod_id(_mod_id), cfgid(_cfgid), read_ahead_callback(NULL) { rassert(mod_count > 0); rassert(mod_id >= 0); rassert(mod_id < mod_count); } void *translator_serializer_t::malloc() { return inner->malloc(); } void *translator_serializer_t::clone(void *data) { return inner->clone(data); } void translator_serializer_t::free(void *ptr) { inner->free(ptr); } file_account_t *translator_serializer_t::make_io_account(int priority, int outstanding_requests_limit) { return inner->make_io_account(priority, outstanding_requests_limit); } void translator_serializer_t::index_write(const std::vector<index_write_op_t>& write_ops, file_account_t *io_account) { std::vector<index_write_op_t> translated_ops(write_ops); for (std::vector<index_write_op_t>::iterator it = translated_ops.begin(); it < translated_ops.end(); ++it) it->block_id = translate_block_id(it->block_id); inner->index_write(translated_ops, io_account); } intrusive_ptr_t<standard_block_token_t> translator_serializer_t::block_write(const void *buf, block_id_t block_id, file_account_t *io_account, iocallback_t *cb) { // TODO: Does anybody even pass NULL_BLOCK_ID? // NULL_BLOCK_ID is special: it indicates no block id specified. if (block_id != NULL_BLOCK_ID) block_id = translate_block_id(block_id); return inner->block_write(buf, block_id, io_account, cb); } void translator_serializer_t::block_read(const intrusive_ptr_t<standard_block_token_t>& token, void *buf, file_account_t *io_account, iocallback_t *cb) { return inner->block_read(token, buf, io_account, cb); } void translator_serializer_t::block_read(const intrusive_ptr_t<standard_block_token_t>& token, void *buf, file_account_t *io_account) { return inner->block_read(token, buf, io_account); } intrusive_ptr_t<standard_block_token_t> translator_serializer_t::index_read(block_id_t block_id) { return inner->index_read(translate_block_id(block_id)); } block_sequence_id_t translator_serializer_t::get_block_sequence_id(block_id_t block_id, const void* buf) const { return inner->get_block_sequence_id(translate_block_id(block_id), buf); } block_size_t translator_serializer_t::get_block_size() { return inner->get_block_size(); } bool translator_serializer_t::coop_lock_and_check() { return inner->coop_lock_and_check(); } block_id_t translator_serializer_t::max_block_id() { int64_t x = inner->max_block_id() - cfgid.subsequent_ser_id(); if (x <= 0) { x = 0; } else { while (x % mod_count != mod_id) x++; x /= mod_count; } rassert(translate_block_id(x) >= inner->max_block_id()); while (x > 0) { --x; if (!get_delete_bit(x)) { ++x; break; } } return x; } repli_timestamp_t translator_serializer_t::get_recency(block_id_t id) { return inner->get_recency(translate_block_id(id)); } bool translator_serializer_t::get_delete_bit(block_id_t id) { return inner->get_delete_bit(translate_block_id(id)); } bool translator_serializer_t::offer_read_ahead_buf(block_id_t block_id, void *buf, const intrusive_ptr_t<standard_block_token_t>& token, repli_timestamp_t recency_timestamp) { inner->assert_thread(); // Offer the buffer if we are the correct shard const int buf_mod_id = untranslate_block_id_to_mod_id(block_id, mod_count, cfgid); if (buf_mod_id != this->mod_id) { // We are not responsible... return false; } if (read_ahead_callback) { const block_id_t inner_block_id = untranslate_block_id_to_id(block_id, mod_count, mod_id, cfgid); if (!read_ahead_callback->offer_read_ahead_buf(inner_block_id, buf, token, recency_timestamp)) { // They aren't going to free the buffer, so we do. inner->free(buf); } } else { // Discard the buffer inner->free(buf); } return true; } void translator_serializer_t::register_read_ahead_cb(serializer_read_ahead_callback_t *cb) { on_thread_t t(inner->home_thread()); rassert(!read_ahead_callback); inner->register_read_ahead_cb(this); read_ahead_callback = cb; } void translator_serializer_t::unregister_read_ahead_cb(DEBUG_VAR serializer_read_ahead_callback_t *cb) { on_thread_t t(inner->home_thread()); rassert(read_ahead_callback == NULL || cb == read_ahead_callback); inner->unregister_read_ahead_cb(this); read_ahead_callback = NULL; } <commit_msg>Answered TODO in translator.cc about who passes in NULL_BLOCK_ID.<commit_after>// Copyright 2010-2012 RethinkDB, all rights reserved. #include "serializer/translator.hpp" #include "errors.hpp" #include <boost/bind.hpp> #include "concurrency/pmap.hpp" #include "serializer/types.hpp" #include "serializer/config.hpp" /* serializer_multiplexer_t */ /* The multiplexing serializer slices up the serializers as follows: - Each proxy is assigned to a serializer. The formula is (proxy_id % n_files) - Block ID 0 on each serializer is for static configuration information. - Each proxy uses block IDs of the form (1 + (n * (number of proxies on serializer) + (proxy_id / n_files))). */ const block_magic_t multiplexer_config_block_t::expected_magic = { { 'c', 'f', 'g', '_' } }; void prep_serializer( const std::vector<standard_serializer_t *>& serializers, creation_timestamp_t creation_timestamp, int n_proxies, int i) { standard_serializer_t *ser = serializers[i]; /* Go to the thread the serializer is running on because it can only be accessed safely from that thread */ on_thread_t thread_switcher(ser->home_thread()); /* Write the initial configuration block */ multiplexer_config_block_t *c = reinterpret_cast<multiplexer_config_block_t *>( ser->malloc()); bzero(c, ser->get_block_size().value()); c->magic = multiplexer_config_block_t::expected_magic; c->creation_timestamp = creation_timestamp; c->n_files = serializers.size(); c->this_serializer = i; c->n_proxies = n_proxies; index_write_op_t op(CONFIG_BLOCK_ID.ser_id); op.token = ser->block_write(c, CONFIG_BLOCK_ID.ser_id, DEFAULT_DISK_ACCOUNT); op.recency = repli_timestamp_t::invalid; serializer_index_write(ser, op, DEFAULT_DISK_ACCOUNT); ser->free(c); } /* static */ void serializer_multiplexer_t::create(const std::vector<standard_serializer_t *>& underlying, int n_proxies) { /* Choose a more-or-less unique ID so that we can hopefully catch the case where files are mixed and mismatched. */ creation_timestamp_t creation_timestamp = time(NULL); /* Write a configuration block for each one */ pmap(underlying.size(), boost::bind(&prep_serializer, underlying, creation_timestamp, n_proxies, _1)); } void create_proxies(const std::vector<standard_serializer_t *>& underlying, creation_timestamp_t creation_timestamp, std::vector<translator_serializer_t *> *proxies, int i) { standard_serializer_t *ser = underlying[i]; /* Go to the thread the serializer is running on because it is only safe to access on that thread and because the pseudoserializers must be created on that thread */ on_thread_t thread_switcher(ser->home_thread()); /* Load config block */ multiplexer_config_block_t *c = reinterpret_cast<multiplexer_config_block_t *>(ser->malloc()); ser->block_read(ser->index_read(CONFIG_BLOCK_ID.ser_id), c, DEFAULT_DISK_ACCOUNT); /* Verify that stuff is sane */ if (c->magic != multiplexer_config_block_t::expected_magic) { fail_due_to_user_error("File did not come from 'rethinkdb create'."); } if (c->creation_timestamp != creation_timestamp) { fail_due_to_user_error("The files that the server was started with didn't all come from " "the same call to 'rethinkdb create'."); } if (c->n_files > static_cast<int>(underlying.size())) { fail_due_to_user_error("You forgot to include one of the files/devices that you included " "when the database was first created."); } if (c->n_files < static_cast<int>(underlying.size())) { fail_due_to_user_error("Got more files than expected. Did you give a file that wasn't" "included in the call to 'rethinkdb create'? Did you duplicate one of the files?"); } guarantee(c->this_serializer >= 0 && c->this_serializer < static_cast<int>(underlying.size())); guarantee(c->n_proxies == static_cast<int>(proxies->size())); /* Figure out which serializer we are (in case files were specified to 'rethinkdb serve' in a different order than they were specified to 'rethinkdb create') */ int j = c->this_serializer; int num_on_this_serializer = serializer_multiplexer_t::compute_mod_count( j, underlying.size(), c->n_proxies); /* This is a slightly weird way of phrasing this; it's done this way so I can be sure it's equivalent to the old way of doing things */ for (int k = 0; k < c->n_proxies; k++) { /* Are we responsible for creating this proxy? */ if (k % static_cast<int>(underlying.size()) != j) continue; rassert(!(*proxies)[k]); (*proxies)[k] = new translator_serializer_t( ser, num_on_this_serializer, k / underlying.size(), CONFIG_BLOCK_ID /* Reserve block ID 0 */); } ser->free(c); } serializer_multiplexer_t::serializer_multiplexer_t(const std::vector<standard_serializer_t *>& underlying) { rassert(underlying.size() > 0); for (int i = 0; i < static_cast<int>(underlying.size()); ++i) { rassert(underlying[i]); } /* Figure out how many slices there are gonna be and figure out what the creation magic is */ { on_thread_t thread_switcher(underlying[0]->home_thread()); /* Load config block */ multiplexer_config_block_t *c = reinterpret_cast<multiplexer_config_block_t *>( underlying[0]->malloc()); underlying[0]->block_read(underlying[0]->index_read(CONFIG_BLOCK_ID.ser_id), c, DEFAULT_DISK_ACCOUNT); rassert(c->magic == multiplexer_config_block_t::expected_magic); creation_timestamp = c->creation_timestamp; proxies.resize(c->n_proxies); underlying[0]->free(c); } /* Now go to each serializer and verify it individually. We visit the first serializer twice (because we already visited it to get the creation magic and stuff) but that's OK. Also, create proxies for the serializers (populate the 'proxies' vector) */ pmap(underlying.size(), boost::bind(&create_proxies, underlying, creation_timestamp, &proxies, _1)); for (int i = 0; i < static_cast<int>(proxies.size()); ++i) rassert(proxies[i]); } void destroy_proxy(std::vector<translator_serializer_t *> *proxies, int i) { on_thread_t thread_switcher((*proxies)[i]->home_thread()); delete (*proxies)[i]; } serializer_multiplexer_t::~serializer_multiplexer_t() { pmap(proxies.size(), boost::bind(&destroy_proxy, &proxies, _1)); } int serializer_multiplexer_t::compute_mod_count(int32_t file_number, int32_t n_files, int32_t n_slices) { /* If we have 'n_files', and we distribute 'n_slices' over those 'n_files' such that slice 'n' is on file 'n % n_files', then how many slices will be on file 'file_number'? */ return n_slices / n_files + (n_slices % n_files > file_number); } /* translator_serializer_t */ block_id_t translator_serializer_t::translate_block_id(block_id_t id, int mod_count, int mod_id, config_block_id_t cfgid) { return id * mod_count + mod_id + cfgid.subsequent_ser_id(); } int translator_serializer_t::untranslate_block_id_to_mod_id(block_id_t inner_id, int mod_count, config_block_id_t cfgid) { // We know that inner_id == id * mod_count + mod_id + min. // Thus inner_id - min == id * mod_count + mod_id. // It follows that inner_id - min === mod_id (modulo mod_count). // So (inner_id - min) % mod_count == mod_id (since 0 <= mod_id < mod_count). // (And inner_id - min >= 0, so '%' works as expected.) return (inner_id - cfgid.subsequent_ser_id()) % mod_count; } block_id_t translator_serializer_t::untranslate_block_id_to_id(block_id_t inner_id, int mod_count, int mod_id, config_block_id_t cfgid) { // (simply dividing by mod_count should be sufficient, but this is cleaner) return (inner_id - cfgid.subsequent_ser_id() - mod_id) / mod_count; } block_id_t translator_serializer_t::translate_block_id(block_id_t id) const { rassert(id != NULL_BLOCK_ID); return translate_block_id(id, mod_count, mod_id, cfgid); } translator_serializer_t::translator_serializer_t(standard_serializer_t *_inner, int _mod_count, int _mod_id, config_block_id_t _cfgid) : inner(_inner), mod_count(_mod_count), mod_id(_mod_id), cfgid(_cfgid), read_ahead_callback(NULL) { rassert(mod_count > 0); rassert(mod_id >= 0); rassert(mod_id < mod_count); } void *translator_serializer_t::malloc() { return inner->malloc(); } void *translator_serializer_t::clone(void *data) { return inner->clone(data); } void translator_serializer_t::free(void *ptr) { inner->free(ptr); } file_account_t *translator_serializer_t::make_io_account(int priority, int outstanding_requests_limit) { return inner->make_io_account(priority, outstanding_requests_limit); } void translator_serializer_t::index_write(const std::vector<index_write_op_t>& write_ops, file_account_t *io_account) { std::vector<index_write_op_t> translated_ops(write_ops); for (std::vector<index_write_op_t>::iterator it = translated_ops.begin(); it < translated_ops.end(); ++it) it->block_id = translate_block_id(it->block_id); inner->index_write(translated_ops, io_account); } intrusive_ptr_t<standard_block_token_t> translator_serializer_t::block_write(const void *buf, block_id_t block_id, file_account_t *io_account, iocallback_t *cb) { // NULL_BLOCK_ID is special: it indicates no block id specified. Right now only the // log_serializer_t ever sees a NULL_BLOCK_ID, passed in from its data block manager in some // ugly circular code. if (block_id != NULL_BLOCK_ID) block_id = translate_block_id(block_id); return inner->block_write(buf, block_id, io_account, cb); } void translator_serializer_t::block_read(const intrusive_ptr_t<standard_block_token_t>& token, void *buf, file_account_t *io_account, iocallback_t *cb) { return inner->block_read(token, buf, io_account, cb); } void translator_serializer_t::block_read(const intrusive_ptr_t<standard_block_token_t>& token, void *buf, file_account_t *io_account) { return inner->block_read(token, buf, io_account); } intrusive_ptr_t<standard_block_token_t> translator_serializer_t::index_read(block_id_t block_id) { return inner->index_read(translate_block_id(block_id)); } block_sequence_id_t translator_serializer_t::get_block_sequence_id(block_id_t block_id, const void* buf) const { return inner->get_block_sequence_id(translate_block_id(block_id), buf); } block_size_t translator_serializer_t::get_block_size() { return inner->get_block_size(); } bool translator_serializer_t::coop_lock_and_check() { return inner->coop_lock_and_check(); } block_id_t translator_serializer_t::max_block_id() { int64_t x = inner->max_block_id() - cfgid.subsequent_ser_id(); if (x <= 0) { x = 0; } else { while (x % mod_count != mod_id) x++; x /= mod_count; } rassert(translate_block_id(x) >= inner->max_block_id()); while (x > 0) { --x; if (!get_delete_bit(x)) { ++x; break; } } return x; } repli_timestamp_t translator_serializer_t::get_recency(block_id_t id) { return inner->get_recency(translate_block_id(id)); } bool translator_serializer_t::get_delete_bit(block_id_t id) { return inner->get_delete_bit(translate_block_id(id)); } bool translator_serializer_t::offer_read_ahead_buf(block_id_t block_id, void *buf, const intrusive_ptr_t<standard_block_token_t>& token, repli_timestamp_t recency_timestamp) { inner->assert_thread(); // Offer the buffer if we are the correct shard const int buf_mod_id = untranslate_block_id_to_mod_id(block_id, mod_count, cfgid); if (buf_mod_id != this->mod_id) { // We are not responsible... return false; } if (read_ahead_callback) { const block_id_t inner_block_id = untranslate_block_id_to_id(block_id, mod_count, mod_id, cfgid); if (!read_ahead_callback->offer_read_ahead_buf(inner_block_id, buf, token, recency_timestamp)) { // They aren't going to free the buffer, so we do. inner->free(buf); } } else { // Discard the buffer inner->free(buf); } return true; } void translator_serializer_t::register_read_ahead_cb(serializer_read_ahead_callback_t *cb) { on_thread_t t(inner->home_thread()); rassert(!read_ahead_callback); inner->register_read_ahead_cb(this); read_ahead_callback = cb; } void translator_serializer_t::unregister_read_ahead_cb(DEBUG_VAR serializer_read_ahead_callback_t *cb) { on_thread_t t(inner->home_thread()); rassert(read_ahead_callback == NULL || cb == read_ahead_callback); inner->unregister_read_ahead_cb(this); read_ahead_callback = NULL; } <|endoftext|>
<commit_before>/* Iridium Utilities -- Iridium Synchronization Utilities * AtomicTypes.hpp * * Copyright (c) 2008, Daniel Reiter Horn * 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 Iridium 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 <stdint.h> #ifdef __APPLE__ #include <libkern/OSAtomic.h> #endif namespace Iridium { #ifdef _WIN32 template <int size> class SizedAtomicValue { }; template<> class SizedAtomicValue<4> { public: template<typename T> static T add(volatile T*scalar, T other) { return (T)InterlockedExchangeAdd((volatile LONG*)&scalar,(int32_t) other); } template<typename T> static T inc(volatile T*scalar) { return (T)InterlockedIncrement((volatile LONG*)&scalar); } template<typename T> static T dec(volatile T*scalar) { return (T)InterlockedDecrement((volatile LONG*)&scalar); } }; template<> class SizedAtomicValue<8> { public: template<typename T> static T add(volatile T*scalar, T other) { return (T)InterlockedExchangeAdd64((volatile LONGLONG*)&scalar,(LONGLONG) other); } template<typename T> static T inc(volatile T*scalar) { return (T)InterlockedIncrement64((volatile LONGLONG*)&scalar); } template<typename T> static T dec(volatile T*scalar) { return (T)InterlockedDecrement64((volatile LONGLONG*)&scalar); } }; #elif defined(__APPLE__) template<int size> class SizedAtomicValue { }; template<> class SizedAtomicValue<4> { public: template <typename T> static T add(volatile T* scalar,T other) { return (T)OSAtomicAdd32((int32_t)other, (int32_t*)scalar); } template <typename T> static T inc(volatile T*scalar) { return (T)OSAtomicIncrement32((int32_t*)scalar); } template <typename T> static T dec(volatile T*scalar) { return (T)OSAtomicDecrement32((int32_t*)scalar); } }; template<> class SizedAtomicValue<8> { public: template <typename T> static T add(volatile T* scalar, T other) { return (T)OSAtomicAdd64((int64_t)other, (int64_t*)scalar); } template <typename T> static T inc(volatile T*scalar) { return (T)OSAtomicIncrement64((int64_t*)scalar); } template <typename T> static T dec(volatile T*scalar) { return (T)OSAtomicDecrement64((int64_t*)scalar); } }; #else template<int size> class SizedAtomicValue { public: template <typename T> static T add(volatile T*scalar, T other) { return __sync_add_and_fetch(scalar, other); } template <typename T> static T inc(volatile T*scalar) { return __sync_add_and_fetch(scalar, 1); } template <typename T> static T dec(volatile T*scalar) { return __sync_sub_and_fetch(scalar, 1); } }; #endif #ifdef _WIN32 #pragma warning( push ) #pragma warning (disable : 4312) #pragma warning (disable : 4197) #endif template <typename T> class AtomicValue { private: volatile char mMemory[sizeof(T)+(sizeof(T)==4?4:(sizeof(T)==2?2:(sizeof(T)==8?8:16)))]; static volatile T*ALIGN(volatile char* data) { size_t shiftammt=sizeof(T)==4?3:(sizeof(T)==2?1:(sizeof(T)==8?7:15)); shiftammt=~shiftammt; return (volatile T*)(((size_t)data)&shiftammt); } static volatile const T*ALIGN(volatile const char* data) { size_t shiftammt=sizeof(T)==4?3:(sizeof(T)==2?1:(sizeof(T)==8?7:15)); shiftammt=~shiftammt; return (volatile const T*)(((size_t)data)&shiftammt); } public: AtomicValue() { } explicit AtomicValue (T other) { *(T*)ALIGN(mMemory)=other; } AtomicValue(const AtomicValue&other) { *(T*)ALIGN(mMemory)=*(T*)ALIGN(other.mMemory); } const AtomicValue<T>& operator =(T other) { *(T*)ALIGN(mMemory)=other; return *this; } const AtomicValue& operator =(const AtomicValue& other) { *(T*)ALIGN(mMemory)=*(T*)ALIGN(other.mMemory); return *this; } bool operator ==(T other) const{ return *(T*)ALIGN(mMemory)==other; } bool operator ==(const AtomicValue& other) const{ return *(T*)ALIGN(mMemory)==*(T*)ALIGN(other.mMemory); } operator T ()const { return *(T*)ALIGN(mMemory); } T read() const { return *(T*)ALIGN(mMemory); } T operator +=(const T&other) { return SizedAtomicValue<sizeof(T)>::add(ALIGN(mMemory),other); } T operator -=(const T&other) { return *this+=-other; } T operator ++() { return (T)SizedAtomicValue<sizeof(T)>::inc(ALIGN(mMemory)); } T operator --() { return (T)SizedAtomicValue<sizeof(T)>::dec(ALIGN(mMemory)); } T operator++(int) { return (++*this)-(T)1; } T operator--(int) { return (--*this)+(T)1; } }; #ifdef _WIN32 #pragma warning( pop ) #endif } <commit_msg>don't put the pointer cart before the array horse<commit_after>/* Iridium Utilities -- Iridium Synchronization Utilities * AtomicTypes.hpp * * Copyright (c) 2008, Daniel Reiter Horn * 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 Iridium 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 <stdint.h> #ifdef __APPLE__ #include <libkern/OSAtomic.h> #endif namespace Iridium { #ifdef _WIN32 template <int size> class SizedAtomicValue { }; template<> class SizedAtomicValue<4> { public: template<typename T> static T add(volatile T*scalar, T other) { return (T)InterlockedExchangeAdd((volatile LONG*)&scalar,(int32_t) other); } template<typename T> static T inc(volatile T*scalar) { return (T)InterlockedIncrement((volatile LONG*)&scalar); } template<typename T> static T dec(volatile T*scalar) { return (T)InterlockedDecrement((volatile LONG*)&scalar); } }; template<> class SizedAtomicValue<8> { public: template<typename T> static T add(volatile T*scalar, T other) { return (T)InterlockedExchangeAdd64((volatile LONGLONG*)&scalar,(LONGLONG) other); } template<typename T> static T inc(volatile T*scalar) { return (T)InterlockedIncrement64((volatile LONGLONG*)&scalar); } template<typename T> static T dec(volatile T*scalar) { return (T)InterlockedDecrement64((volatile LONGLONG*)&scalar); } }; #elif defined(__APPLE__) template<int size> class SizedAtomicValue { }; template<> class SizedAtomicValue<4> { public: template <typename T> static T add(volatile T* scalar,T other) { return (T)OSAtomicAdd32((int32_t)other, (int32_t*)scalar); } template <typename T> static T inc(volatile T*scalar) { return (T)OSAtomicIncrement32((int32_t*)scalar); } template <typename T> static T dec(volatile T*scalar) { return (T)OSAtomicDecrement32((int32_t*)scalar); } }; template<> class SizedAtomicValue<8> { public: template <typename T> static T add(volatile T* scalar, T other) { return (T)OSAtomicAdd64((int64_t)other, (int64_t*)scalar); } template <typename T> static T inc(volatile T*scalar) { return (T)OSAtomicIncrement64((int64_t*)scalar); } template <typename T> static T dec(volatile T*scalar) { return (T)OSAtomicDecrement64((int64_t*)scalar); } }; #else template<int size> class SizedAtomicValue { public: template <typename T> static T add(volatile T*scalar, T other) { return __sync_add_and_fetch(scalar, other); } template <typename T> static T inc(volatile T*scalar) { return __sync_add_and_fetch(scalar, 1); } template <typename T> static T dec(volatile T*scalar) { return __sync_sub_and_fetch(scalar, 1); } }; #endif #ifdef _WIN32 #pragma warning( push ) #pragma warning (disable : 4312) #pragma warning (disable : 4197) #endif template <typename T> class AtomicValue { private: volatile char mMemory[sizeof(T)+(sizeof(T)==4?4:(sizeof(T)==2?2:(sizeof(T)==8?8:16)))]; static volatile T*ALIGN(volatile char* data) { size_t bitandammt=sizeof(T)==4?3:(sizeof(T)==2?1:(sizeof(T)==8?7:15)); size_t notbitandammt=~bitandammt; return (volatile T*)((((size_t)data)+bitandammt)&notbitandammt); } static volatile const T*ALIGN(volatile const char* data) { size_t bitandammt=sizeof(T)==4?3:(sizeof(T)==2?1:(sizeof(T)==8?7:15)); size_t notbitandammt=~bitandammt; return (volatile const T*)((((size_t)data)+bitandammt)&notbitandammt); } public: AtomicValue() { } explicit AtomicValue (T other) { *(T*)ALIGN(mMemory)=other; } AtomicValue(const AtomicValue&other) { *(T*)ALIGN(mMemory)=*(T*)ALIGN(other.mMemory); } const AtomicValue<T>& operator =(T other) { *(T*)ALIGN(mMemory)=other; return *this; } const AtomicValue& operator =(const AtomicValue& other) { *(T*)ALIGN(mMemory)=*(T*)ALIGN(other.mMemory); return *this; } bool operator ==(T other) const{ return *(T*)ALIGN(mMemory)==other; } bool operator ==(const AtomicValue& other) const{ return *(T*)ALIGN(mMemory)==*(T*)ALIGN(other.mMemory); } operator T ()const { return *(T*)ALIGN(mMemory); } T read() const { return *(T*)ALIGN(mMemory); } T operator +=(const T&other) { return SizedAtomicValue<sizeof(T)>::add(ALIGN(mMemory),other); } T operator -=(const T&other) { return *this+=-other; } T operator ++() { return (T)SizedAtomicValue<sizeof(T)>::inc(ALIGN(mMemory)); } T operator --() { return (T)SizedAtomicValue<sizeof(T)>::dec(ALIGN(mMemory)); } T operator++(int) { return (++*this)-(T)1; } T operator--(int) { return (--*this)+(T)1; } }; #ifdef _WIN32 #pragma warning( pop ) #endif } <|endoftext|>
<commit_before>#include <QDebug> #include <QDateTime> #include <QtNetwork/QTcpSocket> #include <QStringList> #include <QRegExp> #include "rpcthread.h" RpcThread::RpcThread(QObject *parent) : QThread(parent), serverName(QString("127.0.0.1")), serverPort(4028), quit(false) { } RpcThread::~RpcThread() { } bool RpcThread::callApi(const char *command) { qDebug() << "Call bfgminer RPC with command : " + QString(command); const int Timeout = 300; //1 * 1000; QTcpSocket socket; socket.connectToHost(serverName, serverPort); if (!socket.waitForConnected(Timeout)) { qDebug() << "socket connect error: " + socket.errorString(); // emit error(socket.error(), socket.errorString()); return false; } emit rpcConnected(); if (socket.write(command) != QString(command).length()) { qDebug() << "socket write error."; return false; } while (socket.bytesAvailable() < (int)sizeof(quint16)) { if (!socket.waitForReadyRead(Timeout)) { qDebug() << "socket read error: " + socket.errorString(); // emit error(socket.error(), socket.errorString()); return false; } } mutex.lock(); buffer = socket.readAll(); mutex.unlock(); socket.close(); return true; } void RpcThread::run() { miner.hashrate_20s = "0"; miner.hashrate_av = "0"; miner.hashrate_cur = "0"; for (int i = 0; i < 3; i ++) { miner.poolUrl[i] = QString(""); miner.active[i] = QString(""); miner.lastCommit[i] = QString(""); } while (!quit) { if (callApi("summary")) { // qDebug() << QDateTime::currentDateTime().toString(Qt::ISODate) + "\n" + buffer + "\n"; parseSummary(); } else { continue; } if (quit) break; if (callApi("pools")) { // qDebug() << QDateTime::currentDateTime().toString(Qt::ISODate) + "\n" + buffer + "\n"; parsePools(); } else { continue; } if (quit) break; emit newInfo(miner); for (int i = 0; i < 25; i ++) { msleep(200); if (quit) break; } } } void RpcThread::request() { mutex.lock(); quit = false; mutex.unlock(); if (!isRunning()) { start(); } else { cond.wakeOne(); } } void RpcThread::stop() { mutex.lock(); quit = true; mutex.unlock(); cond.wakeOne(); wait(); } //static const char SEPARATOR = '|'; //static const char COMMA = ','; //static const char EQ = '='; QString RpcThread::getBfgValue(const char *str) { return getBfgValue(QString(str)); } /* "str" should be sth. like "MHS av", "MHS 20s", etc. */ QString RpcThread::getBfgValue(const QString &str) { QStringList eachSeparator = buffer.split("|"); foreach (const QString &separator, eachSeparator) { QStringList comma = separator.split(","); foreach (const QString &para, comma) { if (para.contains(QRegExp("^" + str + "="))) { QString tmp = para; return tmp.replace(str + "=", ""); } } } return QString(""); } QString RpcThread::getBfgValue(const char *first, const char *second) { return getBfgValue(QString(first), QString(second)); } QString RpcThread::getBfgValue(const QString &first, const char *second) { return getBfgValue(first, QString(second)); } QString RpcThread::getBfgValue(const char *first, const QString &second) { return getBfgValue(QString(first), second); } /* * "first" should be string like "POOL=0", "STATUS=S", etc. * "second" should be a string to get value, such as "URL", "Stratum Active", etc. */ QString RpcThread::getBfgValue(const QString &first, const QString &second) { QStringList eachSeparator = buffer.split("|"); foreach (const QString &separator, eachSeparator) { if (!separator.contains(QRegExp(QString("^" + first)))) continue; QStringList comma = separator.split(","); foreach (const QString &para, comma) { if (para.contains(QRegExp("^" + second + "="))) { QString tmp = para; return tmp.replace(second + "=", ""); } } } return QString(""); } void RpcThread::parseSummary() { mutex.lock(); QString MHS_av = getBfgValue("MHS av"); QString MHS_20s = getBfgValue("MHS 20s"); mutex.unlock(); bool ok; double value = MHS_av.toDouble(&ok); if (ok) { miner.hashrate_av = QString::number(value / 1000.0, 'f', 3); } else { qDebug() << "GHS av = 0 [convert av failed]"; miner.hashrate_av = QString("0"); } // qDebug() << "GHS av = " + miner.hashrate_av; value = MHS_20s.toDouble(&ok); if (ok) { miner.hashrate_20s = QString::number(value / 1000., 'f', 3); } else { qDebug() << "GHS av = 0 [convert 20s failed]"; miner.hashrate_20s = QString("0"); } // qDebug() << "GHS 20s = " + miner.hashrate_20s; /* MHS Cur = Diff1 Work * (Difficulty Accepted/(Difficulty Accepted+Difficulty Rejected+Difficulty Stale)*60/(Device Elapsed)*71582788/(1000000) */ mutex.lock(); QString Diff1_Work = getBfgValue("Diff1 Work"); QString Difficulty_Accepted = getBfgValue("Difficulty Accepted"); QString Difficulty_Rejected = getBfgValue("Difficulty Rejected"); QString Difficulty_Stale = getBfgValue("Difficulty Stale"); QString Elapsed = getBfgValue("Elapsed"); mutex.unlock(); // qDebug() << "Diff1_Work=" + Diff1_Work; // qDebug() << "Difficulty_Accepted=" + Difficulty_Accepted; // qDebug() << "Difficulty_Rejected=" + Difficulty_Rejected; // qDebug() << "Difficulty_Stale=" + Difficulty_Stale; // qDebug() << "Elapsed=" + Elapsed; if (Diff1_Work.isEmpty() || Difficulty_Accepted.isEmpty() || Difficulty_Rejected.isEmpty() || Difficulty_Stale.isEmpty() || Elapsed.isEmpty()) { qDebug() << "GHS cur = 0 [String for CUR is empty]"; miner.hashrate_cur = QString("0"); return; } bool ok_Diff1_Work, ok_Difficulty_Accepted, ok_Difficulty_Rejected, ok_Difficulty_Stale, ok_Elapsed; double val_Diff1_Work = Diff1_Work.toDouble(&ok_Diff1_Work); double val_Difficulty_Accepted = Difficulty_Accepted.toDouble(&ok_Difficulty_Accepted); double val_Difficulty_Rejected = Difficulty_Rejected.toDouble(&ok_Difficulty_Rejected); double val_Difficulty_Stale = Difficulty_Stale.toDouble(&ok_Difficulty_Stale); double val_Elapsed = Elapsed.toDouble(&ok_Elapsed); if (!(ok_Diff1_Work && ok_Difficulty_Accepted && ok_Difficulty_Rejected && ok_Difficulty_Stale && ok_Elapsed)) { qDebug() << "GHS cur = 0 [Convert vale for CUR failed]"; miner.hashrate_cur = QString("0"); return; } if (((val_Difficulty_Accepted + val_Difficulty_Rejected + val_Difficulty_Stale) == 0) || (val_Elapsed == 0)) { qDebug() << "GHS cur = 0 [Divided by ZERO]"; miner.hashrate_cur = QString("0"); return; } value = val_Diff1_Work / (val_Difficulty_Accepted + val_Difficulty_Rejected + val_Difficulty_Stale) * 60 / val_Elapsed * 71582788 / 1000000; miner.hashrate_cur = QString::number(value, 'f', 3); // qDebug() << "GHS cur = " + miner.hashrate_cur; } void RpcThread::parsePools() { for (int i = 0; i < 3; i ++) { mutex.lock(); miner.poolUrl[i] = getBfgValue(QString("POOL=%1").arg(QString::number(i)), "URL"); miner.active[i] = getBfgValue(QString("POOL=%1").arg(QString::number(i)), "Stratum Active"); QString Last_Share_Time = getBfgValue(QString("POOL=%1").arg(QString::number(i)), "Last Share Time"); // QString Last_Share_Time = getBfgValue(QString("STATUS=S"), "When"); /* For Debug Only */ mutex.unlock(); bool ok; uint value = Last_Share_Time.toUInt(&ok); if (ok && (value != 0)) { miner.lastCommit[i] = QDateTime::fromTime_t(value).toString("HH:mm:ss"); } else { qDebug() << "Last Commit = [convert time failed]"; miner.lastCommit[i] = QString(""); } // qDebug() << "url" + QString::number(i) + ":" + miner.poolUrl[i]; // qDebug() << "active" + QString::number(i) + ":" + miner.active[i]; // qDebug() << "lastCommit" + QString::number(i) + ":" + miner.lastCommit[i]; } } <commit_msg>[Bug] GHS cur was MHS, changed to GHS<commit_after>#include <QDebug> #include <QDateTime> #include <QtNetwork/QTcpSocket> #include <QStringList> #include <QRegExp> #include "rpcthread.h" RpcThread::RpcThread(QObject *parent) : QThread(parent), serverName(QString("127.0.0.1")), serverPort(4028), quit(false) { } RpcThread::~RpcThread() { } bool RpcThread::callApi(const char *command) { qDebug() << "Call bfgminer RPC with command : " + QString(command); const int Timeout = 300; //1 * 1000; QTcpSocket socket; socket.connectToHost(serverName, serverPort); if (!socket.waitForConnected(Timeout)) { qDebug() << "socket connect error: " + socket.errorString(); // emit error(socket.error(), socket.errorString()); return false; } emit rpcConnected(); if (socket.write(command) != QString(command).length()) { qDebug() << "socket write error."; return false; } while (socket.bytesAvailable() < (int)sizeof(quint16)) { if (!socket.waitForReadyRead(Timeout)) { qDebug() << "socket read error: " + socket.errorString(); // emit error(socket.error(), socket.errorString()); return false; } } mutex.lock(); buffer = socket.readAll(); mutex.unlock(); socket.close(); return true; } void RpcThread::run() { miner.hashrate_20s = "0"; miner.hashrate_av = "0"; miner.hashrate_cur = "0"; for (int i = 0; i < 3; i ++) { miner.poolUrl[i] = QString(""); miner.active[i] = QString(""); miner.lastCommit[i] = QString(""); } while (!quit) { if (callApi("summary")) { // qDebug() << QDateTime::currentDateTime().toString(Qt::ISODate) + "\n" + buffer + "\n"; parseSummary(); } else { continue; } if (quit) break; if (callApi("pools")) { // qDebug() << QDateTime::currentDateTime().toString(Qt::ISODate) + "\n" + buffer + "\n"; parsePools(); } else { continue; } if (quit) break; emit newInfo(miner); for (int i = 0; i < 25; i ++) { msleep(200); if (quit) break; } } } void RpcThread::request() { mutex.lock(); quit = false; mutex.unlock(); if (!isRunning()) { start(); } else { cond.wakeOne(); } } void RpcThread::stop() { mutex.lock(); quit = true; mutex.unlock(); cond.wakeOne(); wait(); } //static const char SEPARATOR = '|'; //static const char COMMA = ','; //static const char EQ = '='; QString RpcThread::getBfgValue(const char *str) { return getBfgValue(QString(str)); } /* "str" should be sth. like "MHS av", "MHS 20s", etc. */ QString RpcThread::getBfgValue(const QString &str) { QStringList eachSeparator = buffer.split("|"); foreach (const QString &separator, eachSeparator) { QStringList comma = separator.split(","); foreach (const QString &para, comma) { if (para.contains(QRegExp("^" + str + "="))) { QString tmp = para; return tmp.replace(str + "=", ""); } } } return QString(""); } QString RpcThread::getBfgValue(const char *first, const char *second) { return getBfgValue(QString(first), QString(second)); } QString RpcThread::getBfgValue(const QString &first, const char *second) { return getBfgValue(first, QString(second)); } QString RpcThread::getBfgValue(const char *first, const QString &second) { return getBfgValue(QString(first), second); } /* * "first" should be string like "POOL=0", "STATUS=S", etc. * "second" should be a string to get value, such as "URL", "Stratum Active", etc. */ QString RpcThread::getBfgValue(const QString &first, const QString &second) { QStringList eachSeparator = buffer.split("|"); foreach (const QString &separator, eachSeparator) { if (!separator.contains(QRegExp(QString("^" + first)))) continue; QStringList comma = separator.split(","); foreach (const QString &para, comma) { if (para.contains(QRegExp("^" + second + "="))) { QString tmp = para; return tmp.replace(second + "=", ""); } } } return QString(""); } void RpcThread::parseSummary() { mutex.lock(); QString MHS_av = getBfgValue("MHS av"); QString MHS_20s = getBfgValue("MHS 20s"); mutex.unlock(); bool ok; double value = MHS_av.toDouble(&ok); if (ok) { miner.hashrate_av = QString::number(value / 1000.0, 'f', 3); } else { qDebug() << "GHS av = 0 [convert av failed]"; miner.hashrate_av = QString("0"); } // qDebug() << "GHS av = " + miner.hashrate_av; value = MHS_20s.toDouble(&ok); if (ok) { miner.hashrate_20s = QString::number(value / 1000., 'f', 3); } else { qDebug() << "GHS av = 0 [convert 20s failed]"; miner.hashrate_20s = QString("0"); } // qDebug() << "GHS 20s = " + miner.hashrate_20s; /* MHS Cur = Diff1 Work * (Difficulty Accepted/(Difficulty Accepted+Difficulty Rejected+Difficulty Stale)*60/(Device Elapsed)*71582788/(1000000) */ mutex.lock(); QString Diff1_Work = getBfgValue("Diff1 Work"); QString Difficulty_Accepted = getBfgValue("Difficulty Accepted"); QString Difficulty_Rejected = getBfgValue("Difficulty Rejected"); QString Difficulty_Stale = getBfgValue("Difficulty Stale"); QString Elapsed = getBfgValue("Elapsed"); mutex.unlock(); // qDebug() << "Diff1_Work=" + Diff1_Work; // qDebug() << "Difficulty_Accepted=" + Difficulty_Accepted; // qDebug() << "Difficulty_Rejected=" + Difficulty_Rejected; // qDebug() << "Difficulty_Stale=" + Difficulty_Stale; // qDebug() << "Elapsed=" + Elapsed; if (Diff1_Work.isEmpty() || Difficulty_Accepted.isEmpty() || Difficulty_Rejected.isEmpty() || Difficulty_Stale.isEmpty() || Elapsed.isEmpty()) { qDebug() << "GHS cur = 0 [String for CUR is empty]"; miner.hashrate_cur = QString("0"); return; } bool ok_Diff1_Work, ok_Difficulty_Accepted, ok_Difficulty_Rejected, ok_Difficulty_Stale, ok_Elapsed; double val_Diff1_Work = Diff1_Work.toDouble(&ok_Diff1_Work); double val_Difficulty_Accepted = Difficulty_Accepted.toDouble(&ok_Difficulty_Accepted); double val_Difficulty_Rejected = Difficulty_Rejected.toDouble(&ok_Difficulty_Rejected); double val_Difficulty_Stale = Difficulty_Stale.toDouble(&ok_Difficulty_Stale); double val_Elapsed = Elapsed.toDouble(&ok_Elapsed); if (!(ok_Diff1_Work && ok_Difficulty_Accepted && ok_Difficulty_Rejected && ok_Difficulty_Stale && ok_Elapsed)) { qDebug() << "GHS cur = 0 [Convert vale for CUR failed]"; miner.hashrate_cur = QString("0"); return; } if (((val_Difficulty_Accepted + val_Difficulty_Rejected + val_Difficulty_Stale) == 0) || (val_Elapsed == 0)) { qDebug() << "GHS cur = 0 [Divided by ZERO]"; miner.hashrate_cur = QString("0"); return; } value = val_Diff1_Work / (val_Difficulty_Accepted + val_Difficulty_Rejected + val_Difficulty_Stale) * 60 / val_Elapsed * 71582788 / 1000000 / 1000; miner.hashrate_cur = QString::number(value, 'f', 3); // qDebug() << "GHS cur = " + miner.hashrate_cur; } void RpcThread::parsePools() { for (int i = 0; i < 3; i ++) { mutex.lock(); miner.poolUrl[i] = getBfgValue(QString("POOL=%1").arg(QString::number(i)), "URL"); miner.active[i] = getBfgValue(QString("POOL=%1").arg(QString::number(i)), "Stratum Active"); QString Last_Share_Time = getBfgValue(QString("POOL=%1").arg(QString::number(i)), "Last Share Time"); // QString Last_Share_Time = getBfgValue(QString("STATUS=S"), "When"); /* For Debug Only */ mutex.unlock(); bool ok; uint value = Last_Share_Time.toUInt(&ok); if (ok && (value != 0)) { miner.lastCommit[i] = QDateTime::fromTime_t(value).toString("HH:mm:ss"); } else { qDebug() << "Last Commit = [convert time failed]"; miner.lastCommit[i] = QString(""); } // qDebug() << "url" + QString::number(i) + ":" + miner.poolUrl[i]; // qDebug() << "active" + QString::number(i) + ":" + miner.active[i]; // qDebug() << "lastCommit" + QString::number(i) + ":" + miner.lastCommit[i]; } } <|endoftext|>
<commit_before>#include <configure/bind.hpp> #include <configure/bind/path_utils.hpp> #include <configure/Filesystem.hpp> #include <configure/lua/State.hpp> #include <configure/lua/Type.hpp> #include <configure/Node.hpp> #include <configure/bind/path_utils.hpp> #include <boost/filesystem.hpp> namespace fs = boost::filesystem; namespace configure { static int fs_glob(lua_State* state) { Filesystem& self = lua::Converter<std::reference_wrapper<Filesystem>>::extract(state, 1); std::vector<NodePtr> res; if (lua_gettop(state) == 3) { res = self.glob( utils::extract_path(state, 2), lua::Converter<std::string>::extract(state, 3) ); } else if (char const* arg = lua_tostring(state, 2)) { res = self.glob(arg); } else CONFIGURE_THROW( error::InvalidArgument("Expected a glob pattern") ); lua_createtable(state, res.size(), 0); for (int i = 0, len = res.size(); i < len; ++i) { lua::Converter<NodePtr>::push(state, res[i]); lua_rawseti(state, -2, i + 1); } return 1; } static int fs_rglob(lua_State* state) { Filesystem& self = lua::Converter<std::reference_wrapper<Filesystem>>::extract(state, 1); std::vector<NodePtr> res; fs::path dir; if (char const* arg = lua_tostring(state, 2)) dir = arg; else dir = lua::Converter<fs::path>::extract(state, 2); if (char const* arg = lua_tostring(state, 3)) { res = self.rglob(dir, arg); } lua_createtable(state, res.size(), 0); for (int i = 0, len = res.size(); i < len; ++i) { lua::Converter<NodePtr>::push(state, res[i]); lua_rawseti(state, -2, i + 1); } return 1; } static int fs_list_directory(lua_State* state) { Filesystem& self = lua::Converter<std::reference_wrapper<Filesystem>>::extract(state, 1); std::vector<NodePtr> res; if (char const* arg = lua_tostring(state, 2)) res = self.list_directory(arg); else res = self.list_directory( lua::Converter<fs::path>::extract(state, 2) ); lua_createtable(state, res.size(), 0); for (int i = 0, len = res.size(); i < len; ++i) { lua::Converter<NodePtr>::push(state, res[i]); lua_rawseti(state, -2, i + 1); } return 1; } static int fs_find_file(lua_State* state) { Filesystem& self = lua::Converter<std::reference_wrapper<Filesystem>>::extract(state, 1); if (!lua_istable(state, 2)) CONFIGURE_THROW( error::LuaError( "Expected a table, got '" + std::string(luaL_tolstring(state, 2, nullptr)) + "'" ) ); std::vector<fs::path> directories; for (int i = 1, len = lua_rawlen(state, 2); i <= len; ++i) { lua_rawgeti(state, 2, i); directories.push_back(utils::extract_path(state, -1)); } lua::Converter<NodePtr>::push( state, self.find_file(directories, utils::extract_path(state, 3)) ); return 1; } static int fs_which(lua_State* state) { Filesystem& self = lua::Converter<std::reference_wrapper<Filesystem>>::extract(state, 1); std::string arg; if (fs::path* ptr = lua::Converter<fs::path>::extract_ptr(state, 2)) arg = ptr->string(); else if (char const* ptr = lua_tostring(state, 2)) arg = ptr; if (!arg.empty()) { auto res = self.which(arg); if (res) lua::Converter<fs::path>::push(state, *res); else lua_pushnil(state); } else { throw std::runtime_error( "Filesystem.which(): Expected program name, got '" + std::string(luaL_tolstring(state, 2, 0)) + "'"); } return 1; } static int fs_cwd(lua_State* state) { lua::Converter<fs::path>::push(state, fs::current_path()); return 1; } static int fs_current_script(lua_State* state) { lua_Debug ar; if (lua_getstack(state, 1, &ar) != 1) CONFIGURE_THROW(error::LuaError("Couldn't get the stack")); if (lua_getinfo(state, "S", &ar) == 0) CONFIGURE_THROW(error::LuaError("Couldn't get stack info")); if (ar.source == nullptr) CONFIGURE_THROW(error::LuaError("Invalid source file")); fs::path src(ar.source[0] == '@' ? &ar.source[1] : ar.source); if (!src.is_absolute()) src = fs::current_path() / src; if (!fs::exists(src)) CONFIGURE_THROW(error::LuaError("Couldn't find the script path") << error::path(src)); lua::Converter<fs::path>::push(state, src); return 1; } static int fs_copy(lua_State* state) { Filesystem& self = lua::Converter<std::reference_wrapper<Filesystem>>::extract(state, 1); NodePtr res; fs::path dst; if (char const* arg = lua_tostring(state, 3)) dst = arg; else if (fs::path* arg = lua::Converter<fs::path>::extract_ptr(state, 3)) dst = *arg; else CONFIGURE_THROW( error::LuaError("Expected string or path for dest argument") << error::lua_function("Filesystem::copy") ); if (char const* arg = lua_tostring(state, 2)) res = self.copy(arg, dst); else if (fs::path* arg = lua::Converter<fs::path>::extract_ptr(state, 2)) res = self.copy(*arg, dst); else if (NodePtr* arg = lua::Converter<NodePtr>::extract_ptr(state, 2)) res = self.copy(*arg, dst); else CONFIGURE_THROW( error::LuaError("Expected string, path or Node for src argument") << error::lua_function("Filesystem::copy") ); lua::Converter<NodePtr>::push(state, std::move(res)); return 1; } void bind_filesystem(lua::State& state) { /// Filesystem operations. // @classmod Filesystem lua::Type<Filesystem, std::reference_wrapper<Filesystem>>(state, "Filesystem") /// Find files according to a glob pattern // @function Filesystem:glob // @string pattern A glob pattern // @return A list of @{Node}s .def("glob", &fs_glob) /// Find files recursively according to a glob pattern // @function Filesystem:rglob // @tparam string|Path dir The base directory // @string pattern A glob pattern // @return A list of @{Node}s .def("rglob", &fs_rglob) /// List a directory // @function Filesystem:list_directory // @tparam string|Path dir Directory to list // @return A list of @{Node}s .def("list_directory", &fs_list_directory) /// Find a file // @function Filesystem:find_file // @tparam table directories A list of directories to inspect // @tparam string|Path file The file to search for // @return A @{Node} .def("find_file", &fs_find_file) /// Find an executable path // @function Filesystem:which // @tparam string|Path name An executable name // @treturn Path|nil Absolute path to the executable found or nil .def("which", &fs_which) /// Generate rule that copy a file. // @function Filesystem:copy // @treturn Node the target node .def("copy", &fs_copy) /// Return the current working directory // @function Filesystem:cwd // @treturn Path current directory .def("cwd", &fs_cwd) /// Return the current script path // @function Filesystem.current_script .def("current_script", &fs_current_script) ; } } <commit_msg>Add facilities to create new directories.<commit_after>#include <configure/bind.hpp> #include <configure/bind/path_utils.hpp> #include <configure/Filesystem.hpp> #include <configure/lua/State.hpp> #include <configure/lua/Type.hpp> #include <configure/Node.hpp> #include <configure/bind/path_utils.hpp> #include <boost/filesystem.hpp> namespace fs = boost::filesystem; namespace configure { static int fs_glob(lua_State* state) { Filesystem& self = lua::Converter<std::reference_wrapper<Filesystem>>::extract(state, 1); std::vector<NodePtr> res; if (lua_gettop(state) == 3) { res = self.glob( utils::extract_path(state, 2), lua::Converter<std::string>::extract(state, 3) ); } else if (char const* arg = lua_tostring(state, 2)) { res = self.glob(arg); } else CONFIGURE_THROW( error::InvalidArgument("Expected a glob pattern") ); lua_createtable(state, res.size(), 0); for (int i = 0, len = res.size(); i < len; ++i) { lua::Converter<NodePtr>::push(state, res[i]); lua_rawseti(state, -2, i + 1); } return 1; } static int fs_rglob(lua_State* state) { Filesystem& self = lua::Converter<std::reference_wrapper<Filesystem>>::extract(state, 1); std::vector<NodePtr> res; fs::path dir; if (char const* arg = lua_tostring(state, 2)) dir = arg; else dir = lua::Converter<fs::path>::extract(state, 2); if (char const* arg = lua_tostring(state, 3)) { res = self.rglob(dir, arg); } lua_createtable(state, res.size(), 0); for (int i = 0, len = res.size(); i < len; ++i) { lua::Converter<NodePtr>::push(state, res[i]); lua_rawseti(state, -2, i + 1); } return 1; } static int fs_list_directory(lua_State* state) { Filesystem& self = lua::Converter<std::reference_wrapper<Filesystem>>::extract(state, 1); std::vector<NodePtr> res; if (char const* arg = lua_tostring(state, 2)) res = self.list_directory(arg); else res = self.list_directory( lua::Converter<fs::path>::extract(state, 2) ); lua_createtable(state, res.size(), 0); for (int i = 0, len = res.size(); i < len; ++i) { lua::Converter<NodePtr>::push(state, res[i]); lua_rawseti(state, -2, i + 1); } return 1; } static int fs_find_file(lua_State* state) { Filesystem& self = lua::Converter<std::reference_wrapper<Filesystem>>::extract(state, 1); if (!lua_istable(state, 2)) CONFIGURE_THROW( error::LuaError( "Expected a table, got '" + std::string(luaL_tolstring(state, 2, nullptr)) + "'" ) ); std::vector<fs::path> directories; for (int i = 1, len = lua_rawlen(state, 2); i <= len; ++i) { lua_rawgeti(state, 2, i); directories.push_back(utils::extract_path(state, -1)); } lua::Converter<NodePtr>::push( state, self.find_file(directories, utils::extract_path(state, 3)) ); return 1; } static int fs_which(lua_State* state) { Filesystem& self = lua::Converter<std::reference_wrapper<Filesystem>>::extract(state, 1); std::string arg; if (fs::path* ptr = lua::Converter<fs::path>::extract_ptr(state, 2)) arg = ptr->string(); else if (char const* ptr = lua_tostring(state, 2)) arg = ptr; if (!arg.empty()) { auto res = self.which(arg); if (res) lua::Converter<fs::path>::push(state, *res); else lua_pushnil(state); } else { throw std::runtime_error( "Filesystem.which(): Expected program name, got '" + std::string(luaL_tolstring(state, 2, 0)) + "'"); } return 1; } static int fs_cwd(lua_State* state) { lua::Converter<fs::path>::push(state, fs::current_path()); return 1; } static int fs_current_script(lua_State* state) { lua_Debug ar; if (lua_getstack(state, 1, &ar) != 1) CONFIGURE_THROW(error::LuaError("Couldn't get the stack")); if (lua_getinfo(state, "S", &ar) == 0) CONFIGURE_THROW(error::LuaError("Couldn't get stack info")); if (ar.source == nullptr) CONFIGURE_THROW(error::LuaError("Invalid source file")); fs::path src(ar.source[0] == '@' ? &ar.source[1] : ar.source); if (!src.is_absolute()) src = fs::current_path() / src; if (!fs::exists(src)) CONFIGURE_THROW(error::LuaError("Couldn't find the script path") << error::path(src)); lua::Converter<fs::path>::push(state, src); return 1; } static int fs_copy(lua_State* state) { Filesystem& self = lua::Converter<std::reference_wrapper<Filesystem>>::extract(state, 1); NodePtr res; fs::path dst; if (char const* arg = lua_tostring(state, 3)) dst = arg; else if (fs::path* arg = lua::Converter<fs::path>::extract_ptr(state, 3)) dst = *arg; else CONFIGURE_THROW( error::LuaError("Expected string or path for dest argument") << error::lua_function("Filesystem::copy") ); if (char const* arg = lua_tostring(state, 2)) res = self.copy(arg, dst); else if (fs::path* arg = lua::Converter<fs::path>::extract_ptr(state, 2)) res = self.copy(*arg, dst); else if (NodePtr* arg = lua::Converter<NodePtr>::extract_ptr(state, 2)) res = self.copy(*arg, dst); else CONFIGURE_THROW( error::LuaError("Expected string, path or Node for src argument") << error::lua_function("Filesystem::copy") ); lua::Converter<NodePtr>::push(state, std::move(res)); return 1; } static int fs_create_directories(lua_State* state) { lua::Converter<std::reference_wrapper<Filesystem>>::extract(state, 1); bool res = fs::create_directories(utils::extract_path(state, 2)); lua::Converter<bool>::push(state, res); return 1; } void bind_filesystem(lua::State& state) { /// Filesystem operations. // @classmod Filesystem lua::Type<Filesystem, std::reference_wrapper<Filesystem>>(state, "Filesystem") /// Find files according to a glob pattern // @function Filesystem:glob // @string pattern A glob pattern // @return A list of @{Node}s .def("glob", &fs_glob) /// Find files recursively according to a glob pattern // @function Filesystem:rglob // @tparam string|Path dir The base directory // @string pattern A glob pattern // @return A list of @{Node}s .def("rglob", &fs_rglob) /// List a directory // @function Filesystem:list_directory // @tparam string|Path dir Directory to list // @return A list of @{Node}s .def("list_directory", &fs_list_directory) /// Find a file // @function Filesystem:find_file // @tparam table directories A list of directories to inspect // @tparam string|Path file The file to search for // @return A @{Node} .def("find_file", &fs_find_file) /// Find an executable path // @function Filesystem:which // @tparam string|Path name An executable name // @treturn Path|nil Absolute path to the executable found or nil .def("which", &fs_which) /// Generate rule that copy a file. // @function Filesystem:copy // @treturn Node the target node .def("copy", &fs_copy) /// Return the current working directory // @function Filesystem:cwd // @treturn Path current directory .def("cwd", &fs_cwd) /// Return the current script path // @function Filesystem.current_script .def("current_script", &fs_current_script) /// Create directories // @function Filesystem:create_directories // @treturn bool True on success, false if the directories already exist .def("create_directories", &fs_create_directories) ; } } <|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/extensions/api/app_current_window_internal/app_current_window_internal_api.h" #include "apps/shell_window.h" #include "apps/shell_window_registry.h" #include "apps/ui/native_app_window.h" #include "base/command_line.h" #include "chrome/browser/profiles/profile.h" #include "chrome/common/extensions/api/app_current_window_internal.h" #include "chrome/common/extensions/api/app_window.h" #include "chrome/common/extensions/features/feature_channel.h" #include "chrome/common/extensions/features/simple_feature.h" #include "extensions/common/switches.h" #include "third_party/skia/include/core/SkRegion.h" namespace app_current_window_internal = extensions::api::app_current_window_internal; namespace SetBounds = app_current_window_internal::SetBounds; namespace SetMinWidth = app_current_window_internal::SetMinWidth; namespace SetMinHeight = app_current_window_internal::SetMinHeight; namespace SetMaxWidth = app_current_window_internal::SetMaxWidth; namespace SetMaxHeight = app_current_window_internal::SetMaxHeight; namespace SetIcon = app_current_window_internal::SetIcon; namespace SetShape = app_current_window_internal::SetShape; namespace SetAlwaysOnTop = app_current_window_internal::SetAlwaysOnTop; using apps::ShellWindow; using app_current_window_internal::Bounds; using app_current_window_internal::Region; using app_current_window_internal::RegionRect; namespace extensions { namespace { const char kNoAssociatedShellWindow[] = "The context from which the function was called did not have an " "associated shell window."; const char kDevChannelOnly[] = "This function is currently only available in the Dev channel."; const char kRequiresFramelessWindow[] = "This function requires a frameless window (frame:none)."; const char kAlwaysOnTopPermission[] = "The \"alwaysOnTopWindows\" permission is required."; const int kUnboundedSize = apps::ShellWindow::SizeConstraints::kUnboundedSize; } // namespace bool AppCurrentWindowInternalExtensionFunction::RunImpl() { apps::ShellWindowRegistry* registry = apps::ShellWindowRegistry::Get(GetProfile()); DCHECK(registry); content::RenderViewHost* rvh = render_view_host(); if (!rvh) // No need to set an error, since we won't return to the caller anyway if // there's no RVH. return false; ShellWindow* window = registry->GetShellWindowForRenderViewHost(rvh); if (!window) { error_ = kNoAssociatedShellWindow; return false; } return RunWithWindow(window); } bool AppCurrentWindowInternalFocusFunction::RunWithWindow(ShellWindow* window) { window->GetBaseWindow()->Activate(); return true; } bool AppCurrentWindowInternalFullscreenFunction::RunWithWindow( ShellWindow* window) { window->Fullscreen(); return true; } bool AppCurrentWindowInternalMaximizeFunction::RunWithWindow( ShellWindow* window) { window->Maximize(); return true; } bool AppCurrentWindowInternalMinimizeFunction::RunWithWindow( ShellWindow* window) { window->Minimize(); return true; } bool AppCurrentWindowInternalRestoreFunction::RunWithWindow( ShellWindow* window) { window->Restore(); return true; } bool AppCurrentWindowInternalDrawAttentionFunction::RunWithWindow( ShellWindow* window) { window->GetBaseWindow()->FlashFrame(true); return true; } bool AppCurrentWindowInternalClearAttentionFunction::RunWithWindow( ShellWindow* window) { window->GetBaseWindow()->FlashFrame(false); return true; } bool AppCurrentWindowInternalShowFunction::RunWithWindow( ShellWindow* window) { window->Show(ShellWindow::SHOW_ACTIVE); return true; } bool AppCurrentWindowInternalHideFunction::RunWithWindow( ShellWindow* window) { window->Hide(); return true; } bool AppCurrentWindowInternalSetBoundsFunction::RunWithWindow( ShellWindow* window) { // Start with the current bounds, and change any values that are specified in // the incoming parameters. gfx::Rect bounds = window->GetClientBounds(); scoped_ptr<SetBounds::Params> params(SetBounds::Params::Create(*args_)); CHECK(params.get()); if (params->bounds.left) bounds.set_x(*(params->bounds.left)); if (params->bounds.top) bounds.set_y(*(params->bounds.top)); if (params->bounds.width) bounds.set_width(*(params->bounds.width)); if (params->bounds.height) bounds.set_height(*(params->bounds.height)); bounds.Inset(-window->GetBaseWindow()->GetFrameInsets()); window->GetBaseWindow()->SetBounds(bounds); return true; } bool AppCurrentWindowInternalSetMinWidthFunction::RunWithWindow( ShellWindow* window) { if (GetCurrentChannel() > chrome::VersionInfo::CHANNEL_DEV) { error_ = kDevChannelOnly; return false; } scoped_ptr<SetMinWidth::Params> params(SetMinWidth::Params::Create(*args_)); CHECK(params.get()); gfx::Size min_size = window->size_constraints().GetMinimumSize(); min_size.set_width(params->min_width.get() ? *(params->min_width) : kUnboundedSize); window->SetMinimumSize(min_size); return true; } bool AppCurrentWindowInternalSetMinHeightFunction::RunWithWindow( ShellWindow* window) { if (GetCurrentChannel() > chrome::VersionInfo::CHANNEL_DEV) { error_ = kDevChannelOnly; return false; } scoped_ptr<SetMinHeight::Params> params(SetMinHeight::Params::Create(*args_)); CHECK(params.get()); gfx::Size min_size = window->size_constraints().GetMinimumSize(); min_size.set_height(params->min_height.get() ? *(params->min_height) : kUnboundedSize); window->SetMinimumSize(min_size); return true; } bool AppCurrentWindowInternalSetMaxWidthFunction::RunWithWindow( ShellWindow* window) { if (GetCurrentChannel() > chrome::VersionInfo::CHANNEL_DEV) { error_ = kDevChannelOnly; return false; } scoped_ptr<SetMaxWidth::Params> params(SetMaxWidth::Params::Create(*args_)); CHECK(params.get()); gfx::Size max_size = window->size_constraints().GetMaximumSize(); max_size.set_width(params->max_width.get() ? *(params->max_width) : kUnboundedSize); window->SetMaximumSize(max_size); return true; } bool AppCurrentWindowInternalSetMaxHeightFunction::RunWithWindow( ShellWindow* window) { if (GetCurrentChannel() > chrome::VersionInfo::CHANNEL_DEV) { error_ = kDevChannelOnly; return false; } scoped_ptr<SetMaxHeight::Params> params(SetMaxHeight::Params::Create(*args_)); CHECK(params.get()); gfx::Size max_size = window->size_constraints().GetMaximumSize(); max_size.set_height(params->max_height.get() ? *(params->max_height) : kUnboundedSize); window->SetMaximumSize(max_size); return true; } bool AppCurrentWindowInternalSetIconFunction::RunWithWindow( ShellWindow* window) { if (GetCurrentChannel() > chrome::VersionInfo::CHANNEL_DEV && GetExtension()->location() != extensions::Manifest::COMPONENT) { error_ = kDevChannelOnly; return false; } scoped_ptr<SetIcon::Params> params(SetIcon::Params::Create(*args_)); CHECK(params.get()); // The |icon_url| parameter may be a blob url (e.g. an image fetched with an // XMLHttpRequest) or a resource url. GURL url(params->icon_url); if (!url.is_valid()) url = GetExtension()->GetResourceURL(params->icon_url); window->SetAppIconUrl(url); return true; } bool AppCurrentWindowInternalSetShapeFunction::RunWithWindow( ShellWindow* window) { if (window->GetBaseWindow()->IsFrameless()) { error_ = kRequiresFramelessWindow; return false; } const char* whitelist[] = { "0F42756099D914A026DADFA182871C015735DD95", // http://crbug.com/323773 "2D22CDB6583FD0A13758AEBE8B15E45208B4E9A7", // http://crbug.com/323773 "EBA908206905323CECE6DC4B276A58A0F4AC573F", "2775E568AC98F9578791F1EAB65A1BF5F8CEF414", "4AA3C5D69A4AECBD236CAD7884502209F0F5C169", "E410CDAB2C6E6DD408D731016CECF2444000A912", "9E930B2B5EABA6243AE6C710F126E54688E8FAF6" }; if (GetCurrentChannel() > chrome::VersionInfo::CHANNEL_DEV && !SimpleFeature::IsIdInWhitelist( GetExtension()->id(), std::set<std::string>(whitelist, whitelist + arraysize(whitelist)))) { error_ = kDevChannelOnly; return false; } scoped_ptr<SetShape::Params> params( SetShape::Params::Create(*args_)); const Region& shape = params->region; // Build a region from the supplied list of rects. // If |rects| is missing, then the input region is removed. This clears the // input region so that the entire window accepts input events. // To specify an empty input region (so the window ignores all input), // |rects| should be an empty list. scoped_ptr<SkRegion> region(new SkRegion); if (shape.rects) { for (std::vector<linked_ptr<RegionRect> >::const_iterator i = shape.rects->begin(); i != shape.rects->end(); ++i) { const RegionRect& inputRect = **i; int32_t x = inputRect.left; int32_t y = inputRect.top; int32_t width = inputRect.width; int32_t height = inputRect.height; SkIRect rect = SkIRect::MakeXYWH(x, y, width, height); region->op(rect, SkRegion::kUnion_Op); } } else { region.reset(NULL); } window->UpdateShape(region.Pass()); return true; } bool AppCurrentWindowInternalSetAlwaysOnTopFunction::RunWithWindow( ShellWindow* window) { if (!GetExtension()->HasAPIPermission( extensions::APIPermission::kAlwaysOnTopWindows)) { error_ = kAlwaysOnTopPermission; return false; } scoped_ptr<SetAlwaysOnTop::Params> params( SetAlwaysOnTop::Params::Create(*args_)); CHECK(params.get()); window->SetAlwaysOnTop(params->always_on_top); return true; } } // namespace extensions <commit_msg>Fix IsFrameless check in appWindow.SetShape.<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/extensions/api/app_current_window_internal/app_current_window_internal_api.h" #include "apps/shell_window.h" #include "apps/shell_window_registry.h" #include "apps/ui/native_app_window.h" #include "base/command_line.h" #include "chrome/browser/profiles/profile.h" #include "chrome/common/extensions/api/app_current_window_internal.h" #include "chrome/common/extensions/api/app_window.h" #include "chrome/common/extensions/features/feature_channel.h" #include "chrome/common/extensions/features/simple_feature.h" #include "extensions/common/switches.h" #include "third_party/skia/include/core/SkRegion.h" namespace app_current_window_internal = extensions::api::app_current_window_internal; namespace SetBounds = app_current_window_internal::SetBounds; namespace SetMinWidth = app_current_window_internal::SetMinWidth; namespace SetMinHeight = app_current_window_internal::SetMinHeight; namespace SetMaxWidth = app_current_window_internal::SetMaxWidth; namespace SetMaxHeight = app_current_window_internal::SetMaxHeight; namespace SetIcon = app_current_window_internal::SetIcon; namespace SetShape = app_current_window_internal::SetShape; namespace SetAlwaysOnTop = app_current_window_internal::SetAlwaysOnTop; using apps::ShellWindow; using app_current_window_internal::Bounds; using app_current_window_internal::Region; using app_current_window_internal::RegionRect; namespace extensions { namespace { const char kNoAssociatedShellWindow[] = "The context from which the function was called did not have an " "associated shell window."; const char kDevChannelOnly[] = "This function is currently only available in the Dev channel."; const char kRequiresFramelessWindow[] = "This function requires a frameless window (frame:none)."; const char kAlwaysOnTopPermission[] = "The \"alwaysOnTopWindows\" permission is required."; const int kUnboundedSize = apps::ShellWindow::SizeConstraints::kUnboundedSize; } // namespace bool AppCurrentWindowInternalExtensionFunction::RunImpl() { apps::ShellWindowRegistry* registry = apps::ShellWindowRegistry::Get(GetProfile()); DCHECK(registry); content::RenderViewHost* rvh = render_view_host(); if (!rvh) // No need to set an error, since we won't return to the caller anyway if // there's no RVH. return false; ShellWindow* window = registry->GetShellWindowForRenderViewHost(rvh); if (!window) { error_ = kNoAssociatedShellWindow; return false; } return RunWithWindow(window); } bool AppCurrentWindowInternalFocusFunction::RunWithWindow(ShellWindow* window) { window->GetBaseWindow()->Activate(); return true; } bool AppCurrentWindowInternalFullscreenFunction::RunWithWindow( ShellWindow* window) { window->Fullscreen(); return true; } bool AppCurrentWindowInternalMaximizeFunction::RunWithWindow( ShellWindow* window) { window->Maximize(); return true; } bool AppCurrentWindowInternalMinimizeFunction::RunWithWindow( ShellWindow* window) { window->Minimize(); return true; } bool AppCurrentWindowInternalRestoreFunction::RunWithWindow( ShellWindow* window) { window->Restore(); return true; } bool AppCurrentWindowInternalDrawAttentionFunction::RunWithWindow( ShellWindow* window) { window->GetBaseWindow()->FlashFrame(true); return true; } bool AppCurrentWindowInternalClearAttentionFunction::RunWithWindow( ShellWindow* window) { window->GetBaseWindow()->FlashFrame(false); return true; } bool AppCurrentWindowInternalShowFunction::RunWithWindow( ShellWindow* window) { window->Show(ShellWindow::SHOW_ACTIVE); return true; } bool AppCurrentWindowInternalHideFunction::RunWithWindow( ShellWindow* window) { window->Hide(); return true; } bool AppCurrentWindowInternalSetBoundsFunction::RunWithWindow( ShellWindow* window) { // Start with the current bounds, and change any values that are specified in // the incoming parameters. gfx::Rect bounds = window->GetClientBounds(); scoped_ptr<SetBounds::Params> params(SetBounds::Params::Create(*args_)); CHECK(params.get()); if (params->bounds.left) bounds.set_x(*(params->bounds.left)); if (params->bounds.top) bounds.set_y(*(params->bounds.top)); if (params->bounds.width) bounds.set_width(*(params->bounds.width)); if (params->bounds.height) bounds.set_height(*(params->bounds.height)); bounds.Inset(-window->GetBaseWindow()->GetFrameInsets()); window->GetBaseWindow()->SetBounds(bounds); return true; } bool AppCurrentWindowInternalSetMinWidthFunction::RunWithWindow( ShellWindow* window) { if (GetCurrentChannel() > chrome::VersionInfo::CHANNEL_DEV) { error_ = kDevChannelOnly; return false; } scoped_ptr<SetMinWidth::Params> params(SetMinWidth::Params::Create(*args_)); CHECK(params.get()); gfx::Size min_size = window->size_constraints().GetMinimumSize(); min_size.set_width(params->min_width.get() ? *(params->min_width) : kUnboundedSize); window->SetMinimumSize(min_size); return true; } bool AppCurrentWindowInternalSetMinHeightFunction::RunWithWindow( ShellWindow* window) { if (GetCurrentChannel() > chrome::VersionInfo::CHANNEL_DEV) { error_ = kDevChannelOnly; return false; } scoped_ptr<SetMinHeight::Params> params(SetMinHeight::Params::Create(*args_)); CHECK(params.get()); gfx::Size min_size = window->size_constraints().GetMinimumSize(); min_size.set_height(params->min_height.get() ? *(params->min_height) : kUnboundedSize); window->SetMinimumSize(min_size); return true; } bool AppCurrentWindowInternalSetMaxWidthFunction::RunWithWindow( ShellWindow* window) { if (GetCurrentChannel() > chrome::VersionInfo::CHANNEL_DEV) { error_ = kDevChannelOnly; return false; } scoped_ptr<SetMaxWidth::Params> params(SetMaxWidth::Params::Create(*args_)); CHECK(params.get()); gfx::Size max_size = window->size_constraints().GetMaximumSize(); max_size.set_width(params->max_width.get() ? *(params->max_width) : kUnboundedSize); window->SetMaximumSize(max_size); return true; } bool AppCurrentWindowInternalSetMaxHeightFunction::RunWithWindow( ShellWindow* window) { if (GetCurrentChannel() > chrome::VersionInfo::CHANNEL_DEV) { error_ = kDevChannelOnly; return false; } scoped_ptr<SetMaxHeight::Params> params(SetMaxHeight::Params::Create(*args_)); CHECK(params.get()); gfx::Size max_size = window->size_constraints().GetMaximumSize(); max_size.set_height(params->max_height.get() ? *(params->max_height) : kUnboundedSize); window->SetMaximumSize(max_size); return true; } bool AppCurrentWindowInternalSetIconFunction::RunWithWindow( ShellWindow* window) { if (GetCurrentChannel() > chrome::VersionInfo::CHANNEL_DEV && GetExtension()->location() != extensions::Manifest::COMPONENT) { error_ = kDevChannelOnly; return false; } scoped_ptr<SetIcon::Params> params(SetIcon::Params::Create(*args_)); CHECK(params.get()); // The |icon_url| parameter may be a blob url (e.g. an image fetched with an // XMLHttpRequest) or a resource url. GURL url(params->icon_url); if (!url.is_valid()) url = GetExtension()->GetResourceURL(params->icon_url); window->SetAppIconUrl(url); return true; } bool AppCurrentWindowInternalSetShapeFunction::RunWithWindow( ShellWindow* window) { if (!window->GetBaseWindow()->IsFrameless()) { error_ = kRequiresFramelessWindow; return false; } const char* whitelist[] = { "0F42756099D914A026DADFA182871C015735DD95", // http://crbug.com/323773 "2D22CDB6583FD0A13758AEBE8B15E45208B4E9A7", // http://crbug.com/323773 "EBA908206905323CECE6DC4B276A58A0F4AC573F", "2775E568AC98F9578791F1EAB65A1BF5F8CEF414", "4AA3C5D69A4AECBD236CAD7884502209F0F5C169", "E410CDAB2C6E6DD408D731016CECF2444000A912", "9E930B2B5EABA6243AE6C710F126E54688E8FAF6" }; if (GetCurrentChannel() > chrome::VersionInfo::CHANNEL_DEV && !SimpleFeature::IsIdInWhitelist( GetExtension()->id(), std::set<std::string>(whitelist, whitelist + arraysize(whitelist)))) { error_ = kDevChannelOnly; return false; } scoped_ptr<SetShape::Params> params( SetShape::Params::Create(*args_)); const Region& shape = params->region; // Build a region from the supplied list of rects. // If |rects| is missing, then the input region is removed. This clears the // input region so that the entire window accepts input events. // To specify an empty input region (so the window ignores all input), // |rects| should be an empty list. scoped_ptr<SkRegion> region(new SkRegion); if (shape.rects) { for (std::vector<linked_ptr<RegionRect> >::const_iterator i = shape.rects->begin(); i != shape.rects->end(); ++i) { const RegionRect& inputRect = **i; int32_t x = inputRect.left; int32_t y = inputRect.top; int32_t width = inputRect.width; int32_t height = inputRect.height; SkIRect rect = SkIRect::MakeXYWH(x, y, width, height); region->op(rect, SkRegion::kUnion_Op); } } else { region.reset(NULL); } window->UpdateShape(region.Pass()); return true; } bool AppCurrentWindowInternalSetAlwaysOnTopFunction::RunWithWindow( ShellWindow* window) { if (!GetExtension()->HasAPIPermission( extensions::APIPermission::kAlwaysOnTopWindows)) { error_ = kAlwaysOnTopPermission; return false; } scoped_ptr<SetAlwaysOnTop::Params> params( SetAlwaysOnTop::Params::Create(*args_)); CHECK(params.get()); window->SetAlwaysOnTop(params->always_on_top); return true; } } // namespace extensions <|endoftext|>
<commit_before> /* * Copyright 2006 The Android Open Source Project * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include "SkImageDecoder.h" #include "SkColor.h" #include "SkColorPriv.h" #include "SkMath.h" #include "SkStream.h" #include "SkTemplates.h" #include "SkUtils.h" class SkWBMPImageDecoder : public SkImageDecoder { public: virtual Format getFormat() const { return kWBMP_Format; } protected: virtual bool onDecode(SkStream* stream, SkBitmap* bm, Mode); }; static bool read_byte(SkStream* stream, uint8_t* data) { return stream->read(data, 1) == 1; } static bool read_mbf(SkStream* stream, int* value) { int n = 0; uint8_t data; do { if (!read_byte(stream, &data)) { return false; } n = (n << 7) | (data & 0x7F); } while (data & 0x80); *value = n; return true; } struct wbmp_head { int fWidth; int fHeight; bool init(SkStream* stream) { uint8_t data; if (!read_byte(stream, &data) || data != 0) { // unknown type return false; } if (!read_byte(stream, &data) || (data & 0x9F)) { // skip fixed header return false; } if (!read_mbf(stream, &fWidth) || (unsigned)fWidth > 0xFFFF) { return false; } if (!read_mbf(stream, &fHeight) || (unsigned)fHeight > 0xFFFF) { return false; } return fWidth != 0 && fHeight != 0; } }; static void expand_bits_to_bytes(uint8_t dst[], const uint8_t src[], int bits) { int bytes = bits >> 3; for (int i = 0; i < bytes; i++) { unsigned mask = *src++; dst[0] = (mask >> 7) & 1; dst[1] = (mask >> 6) & 1; dst[2] = (mask >> 5) & 1; dst[3] = (mask >> 4) & 1; dst[4] = (mask >> 3) & 1; dst[5] = (mask >> 2) & 1; dst[6] = (mask >> 1) & 1; dst[7] = (mask >> 0) & 1; dst += 8; } bits &= 7; if (bits > 0) { unsigned mask = *src; do { *dst++ = (mask >> 7) & 1;; mask <<= 1; } while (--bits != 0); } } #define SkAlign8(x) (((x) + 7) & ~7) bool SkWBMPImageDecoder::onDecode(SkStream* stream, SkBitmap* decodedBitmap, Mode mode) { wbmp_head head; if (!head.init(stream)) { return false; } int width = head.fWidth; int height = head.fHeight; // assign these directly, in case we return kDimensions_Result decodedBitmap->setConfig(SkBitmap::kIndex8_Config, width, height); decodedBitmap->setIsOpaque(true); if (SkImageDecoder::kDecodeBounds_Mode == mode) return true; const SkPMColor colors[] = { SK_ColorBLACK, SK_ColorWHITE }; SkColorTable* ct = SkNEW_ARGS(SkColorTable, (colors, 2)); SkAutoUnref aur(ct); if (!this->allocPixelRef(decodedBitmap, ct)) { return false; } SkAutoLockPixels alp(*decodedBitmap); uint8_t* dst = decodedBitmap->getAddr8(0, 0); // store the 1-bit valuess at the end of our pixels, so we won't stomp // on them before we're read them. Just trying to avoid a temp allocation size_t srcRB = SkAlign8(width) >> 3; size_t srcSize = height * srcRB; uint8_t* src = dst + decodedBitmap->getSize() - srcSize; if (stream->read(src, srcSize) != srcSize) { return false; } for (int y = 0; y < height; y++) { expand_bits_to_bytes(dst, src, width); dst += decodedBitmap->rowBytes(); src += srcRB; } return true; } /////////////////////////////////////////////////////////////////////////////// DEFINE_DECODER_CREATOR(WBMPImageDecoder); /////////////////////////////////////////////////////////////////////////////// #include "SkTRegistry.h" static SkImageDecoder* sk_wbmp_dfactory(SkStream* stream) { wbmp_head head; if (head.init(stream)) { return SkNEW(SkWBMPImageDecoder); } return NULL; } static SkTRegistry<SkImageDecoder*, SkStream*> gReg(sk_wbmp_dfactory); <commit_msg>remove duplicate definition of SkAlign8()<commit_after> /* * Copyright 2006 The Android Open Source Project * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include "SkImageDecoder.h" #include "SkColor.h" #include "SkColorPriv.h" #include "SkMath.h" #include "SkStream.h" #include "SkTemplates.h" #include "SkUtils.h" class SkWBMPImageDecoder : public SkImageDecoder { public: virtual Format getFormat() const { return kWBMP_Format; } protected: virtual bool onDecode(SkStream* stream, SkBitmap* bm, Mode); }; static bool read_byte(SkStream* stream, uint8_t* data) { return stream->read(data, 1) == 1; } static bool read_mbf(SkStream* stream, int* value) { int n = 0; uint8_t data; do { if (!read_byte(stream, &data)) { return false; } n = (n << 7) | (data & 0x7F); } while (data & 0x80); *value = n; return true; } struct wbmp_head { int fWidth; int fHeight; bool init(SkStream* stream) { uint8_t data; if (!read_byte(stream, &data) || data != 0) { // unknown type return false; } if (!read_byte(stream, &data) || (data & 0x9F)) { // skip fixed header return false; } if (!read_mbf(stream, &fWidth) || (unsigned)fWidth > 0xFFFF) { return false; } if (!read_mbf(stream, &fHeight) || (unsigned)fHeight > 0xFFFF) { return false; } return fWidth != 0 && fHeight != 0; } }; static void expand_bits_to_bytes(uint8_t dst[], const uint8_t src[], int bits) { int bytes = bits >> 3; for (int i = 0; i < bytes; i++) { unsigned mask = *src++; dst[0] = (mask >> 7) & 1; dst[1] = (mask >> 6) & 1; dst[2] = (mask >> 5) & 1; dst[3] = (mask >> 4) & 1; dst[4] = (mask >> 3) & 1; dst[5] = (mask >> 2) & 1; dst[6] = (mask >> 1) & 1; dst[7] = (mask >> 0) & 1; dst += 8; } bits &= 7; if (bits > 0) { unsigned mask = *src; do { *dst++ = (mask >> 7) & 1;; mask <<= 1; } while (--bits != 0); } } bool SkWBMPImageDecoder::onDecode(SkStream* stream, SkBitmap* decodedBitmap, Mode mode) { wbmp_head head; if (!head.init(stream)) { return false; } int width = head.fWidth; int height = head.fHeight; // assign these directly, in case we return kDimensions_Result decodedBitmap->setConfig(SkBitmap::kIndex8_Config, width, height); decodedBitmap->setIsOpaque(true); if (SkImageDecoder::kDecodeBounds_Mode == mode) return true; const SkPMColor colors[] = { SK_ColorBLACK, SK_ColorWHITE }; SkColorTable* ct = SkNEW_ARGS(SkColorTable, (colors, 2)); SkAutoUnref aur(ct); if (!this->allocPixelRef(decodedBitmap, ct)) { return false; } SkAutoLockPixels alp(*decodedBitmap); uint8_t* dst = decodedBitmap->getAddr8(0, 0); // store the 1-bit valuess at the end of our pixels, so we won't stomp // on them before we're read them. Just trying to avoid a temp allocation size_t srcRB = SkAlign8(width) >> 3; size_t srcSize = height * srcRB; uint8_t* src = dst + decodedBitmap->getSize() - srcSize; if (stream->read(src, srcSize) != srcSize) { return false; } for (int y = 0; y < height; y++) { expand_bits_to_bytes(dst, src, width); dst += decodedBitmap->rowBytes(); src += srcRB; } return true; } /////////////////////////////////////////////////////////////////////////////// DEFINE_DECODER_CREATOR(WBMPImageDecoder); /////////////////////////////////////////////////////////////////////////////// #include "SkTRegistry.h" static SkImageDecoder* sk_wbmp_dfactory(SkStream* stream) { wbmp_head head; if (head.init(stream)) { return SkNEW(SkWBMPImageDecoder); } return NULL; } static SkTRegistry<SkImageDecoder*, SkStream*> gReg(sk_wbmp_dfactory); <|endoftext|>
<commit_before>#include "pixelboost/debug/log.h" #include "pixelboost/file/fileSystem.h" #include "pixelboost/graphics/device/program.h" #include "pixelboost/graphics/resources/shaderResource.h" #include "pixelboost/graphics/shader/shader.h" using namespace pb; PB_DEFINE_RESOURCE(pb::ShaderResource) ShaderResource::ShaderResource(ResourcePool* pool, const std::string& filename) : Resource(pool, filename) { _Shader = 0; } ShaderResource::~ShaderResource() { } ResourceError ShaderResource::ProcessResource(ResourcePool* pool, ResourceProcess process, const std::string& filename, std::string& errorDetails) { switch (process) { case kResourceProcessLoad: { auto file = FileSystem::Instance()->OpenFile(filename); std::string contents; if (!file) { return kResourceErrorNoSuchResource; } file->ReadAll(contents); if (!_Document.load(contents.c_str())) { errorDetails = "Xml parse error"; return kResourceErrorSystemError; } return kResourceErrorNone; } case kResourceProcessProcess: { _Shader = new Shader(); if (!ParseShader(errorDetails)) { delete _Shader; _Shader = 0; return kResourceErrorUnknown; } return kResourceErrorNone; } case kResourceProcessUnload: { delete _Shader; _Shader = 0; return kResourceErrorNone; } case kResourceProcessPostProcess: { return kResourceErrorNone; } } } ResourceThread ShaderResource::GetResourceThread(ResourceProcess process) { if (process == kResourceProcessProcess) return kResourceThreadMain; return kResourceThreadAny; } Shader* ShaderResource::GetShader() { return _Shader; } bool ShaderResource::ParseShader(std::string& errorDetails) { pugi::xml_node root = _Document.child("shader"); if (root.empty()) { errorDetails = "Root node is empty"; return false; } //pugi::xml_node properties = root.child("properties"); pugi::xml_node techniques = root.child("technique"); while (!techniques.empty()) { ShaderTechnique* technique = new ShaderTechnique(TypeHash(techniques.attribute("name").value())); bool status = true; pugi::xml_node pass = techniques.child("pass"); while (!pass.empty()) { ShaderPass* shaderPass = new ShaderPass(); pugi::xml_node program = pass.find_child_by_attribute("program", "language", shaderPass->GetShaderProgram()->GetShaderLanguage().c_str()); if (program.empty() || !shaderPass->GetShaderProgram()->SetSource(program.child_value())) { delete shaderPass; status = false; } technique->AddPass(shaderPass); pass = pass.next_sibling("pass"); } if (status) { _Shader->AddTechnique(technique); } else { delete technique; } techniques = techniques.next_sibling("technique"); } if (_Shader->GetNumTechniques() == 0) { errorDetails = "Failed to load shader, no techniques were loaded (are they compatible with this card?)"; return false; } return true; } <commit_msg>Fix crash when shader is invalid<commit_after>#include "pixelboost/debug/log.h" #include "pixelboost/file/fileSystem.h" #include "pixelboost/graphics/device/program.h" #include "pixelboost/graphics/resources/shaderResource.h" #include "pixelboost/graphics/shader/shader.h" using namespace pb; PB_DEFINE_RESOURCE(pb::ShaderResource) ShaderResource::ShaderResource(ResourcePool* pool, const std::string& filename) : Resource(pool, filename) { _Shader = 0; } ShaderResource::~ShaderResource() { } ResourceError ShaderResource::ProcessResource(ResourcePool* pool, ResourceProcess process, const std::string& filename, std::string& errorDetails) { switch (process) { case kResourceProcessLoad: { auto file = FileSystem::Instance()->OpenFile(filename); std::string contents; if (!file) { return kResourceErrorNoSuchResource; } file->ReadAll(contents); if (!_Document.load(contents.c_str())) { errorDetails = "Xml parse error"; return kResourceErrorSystemError; } return kResourceErrorNone; } case kResourceProcessProcess: { _Shader = new Shader(); if (!ParseShader(errorDetails)) { delete _Shader; _Shader = 0; return kResourceErrorUnknown; } return kResourceErrorNone; } case kResourceProcessUnload: { delete _Shader; _Shader = 0; return kResourceErrorNone; } case kResourceProcessPostProcess: { return kResourceErrorNone; } } } ResourceThread ShaderResource::GetResourceThread(ResourceProcess process) { if (process == kResourceProcessProcess) return kResourceThreadMain; return kResourceThreadAny; } Shader* ShaderResource::GetShader() { return _Shader; } bool ShaderResource::ParseShader(std::string& errorDetails) { pugi::xml_node root = _Document.child("shader"); if (root.empty()) { errorDetails = "Root node is empty"; return false; } //pugi::xml_node properties = root.child("properties"); pugi::xml_node techniques = root.child("technique"); while (!techniques.empty()) { ShaderTechnique* technique = new ShaderTechnique(TypeHash(techniques.attribute("name").value())); bool status = true; pugi::xml_node pass = techniques.child("pass"); while (!pass.empty()) { ShaderPass* shaderPass = new ShaderPass(); pugi::xml_node program = pass.find_child_by_attribute("program", "language", shaderPass->GetShaderProgram()->GetShaderLanguage().c_str()); if (program.empty() || !shaderPass->GetShaderProgram()->SetSource(program.child_value())) { delete shaderPass; status = false; } else { technique->AddPass(shaderPass); } pass = pass.next_sibling("pass"); } if (status) { _Shader->AddTechnique(technique); } else { delete technique; } techniques = techniques.next_sibling("technique"); } if (_Shader->GetNumTechniques() == 0) { errorDetails = "Failed to load shader, no techniques were loaded (are they compatible with this card?)"; return false; } return true; } <|endoftext|>
<commit_before>// __BEGIN_LICENSE__ // Copyright (C) 2006-2010 United States Government as represented by // the Administrator of the National Aeronautics and Space Administration. // All Rights Reserved. // __END_LICENSE__ #ifdef _MSC_VER #pragma warning(disable:4244) #pragma warning(disable:4267) #pragma warning(disable:4996) #endif #ifdef NDEBUG #undef NDEBUG #endif #include <cstdlib> #include <boost/program_options.hpp> namespace po = boost::program_options; #include <boost/filesystem/path.hpp> namespace fs = boost::filesystem; #include <vw/Core/Functors.h> #include <vw/Image/Algorithms.h> #include <vw/Image/ImageMath.h> #include <vw/Image/ImageViewRef.h> #include <vw/Image/PerPixelViews.h> #include <vw/Image/PixelMask.h> #include <vw/Image/MaskViews.h> #include <vw/Image/PixelTypes.h> #include <vw/Image/Statistics.h> #include <vw/FileIO/DiskImageView.h> #include <vw/Cartography/GeoReference.h> using namespace vw; // Global variables std::string input_file_name, output_file_name = "", shaded_relief_file_name; float nodata_value; float min_val = 0, max_val = 0; // Colormap function class ColormapFunc : public ReturnFixedType<PixelMask<PixelRGB<float> > > { public: ColormapFunc() {} template <class PixelT> PixelMask<PixelRGB<float> > operator() (PixelT const& pix) const { if (is_transparent(pix)) return PixelMask<PixelRGB<float> >(); float val = compound_select_channel<const float&>(pix,0); if (val > 1.0) val = 1.0; if (val < 0.0) val = 0.0; Vector2 red_range(3/8.0, 1.0); Vector2 green_range(2/8.0, 6/8.0); Vector2 blue_range(0.0, 5/8.0); float red_span = red_range[1] - red_range[0]; float blue_span = blue_range[1] - blue_range[0]; float green_span = green_range[1] - green_range[0]; float red = 0; float green = 0; float blue = 0; // Red if (val >= red_range[0] && val <= red_range[0]+red_span/3) red = (val-red_range[0])/(red_span/3); if (val >= red_range[0]+red_span/3 && val <= red_range[0]+2*red_span/3) red = 1.0; if (val >= red_range[0]+2*red_span/3 && val <= red_range[1]) red = 1-((val-(red_range[0]+2*red_span/3))/(red_span/3)); // Blue if (val >= blue_range[0] && val <= blue_range[0]+blue_span/3) blue = (val-blue_range[0])/(blue_span/3); if (val >= blue_range[0]+blue_span/3 && val <= blue_range[0]+2*blue_span/3) blue = 1.0; if (val >= blue_range[0]+2*blue_span/3 && val <= blue_range[1]) blue = 1-((val-(blue_range[0]+2*blue_span/3))/(blue_span/3)); // Green if (val >= green_range[0] && val <= green_range[0]+green_span/3) green = (val-green_range[0])/(green_span/3); if (val >= green_range[0]+green_span/3 && val <= green_range[0]+2*green_span/3) green = 1.0; if (val >= green_range[0]+2*green_span/3 && val <= green_range[1]) green = 1-((val-(green_range[0]+2*green_span/3))/(green_span/3)); return PixelRGB<float> ( red, green, blue ); } }; template <class ViewT> UnaryPerPixelView<ViewT, ColormapFunc> colormap(ImageViewBase<ViewT> const& view) { return UnaryPerPixelView<ViewT, ColormapFunc>(view.impl(), ColormapFunc()); } // --------------------------------------------------------------------------------------------------- template <class PixelT> void do_colorized_dem(po::variables_map const& vm) { vw_out() << "Creating colorized DEM.\n"; cartography::GeoReference georef; cartography::read_georeference(georef, input_file_name); // Attempt to extract nodata value DiskImageResource *disk_dem_rsrc = DiskImageResource::open(input_file_name); if (vm.count("nodata-value")) { vw_out() << "\t--> Using user-supplied nodata value: " << nodata_value << ".\n"; } else if ( disk_dem_rsrc->has_nodata_value() ) { nodata_value = disk_dem_rsrc->nodata_value(); vw_out() << "\t--> Extracted nodata value from file: " << nodata_value << ".\n"; } // Compute min/max DiskImageView<PixelT> disk_dem_file(input_file_name); ImageViewRef<PixelGray<float> > input_image = pixel_cast<PixelGray<float> >(select_channel(disk_dem_file,0)); if (min_val == 0 && max_val == 0) { min_max_channel_values( create_mask( input_image, nodata_value), min_val, max_val); vw_out() << "\t--> DEM color map range: [" << min_val << " " << max_val << "]\n"; } else { vw_out() << "\t--> Using user-specified color map range: [" << min_val << " " << max_val << "]\n"; } ImageViewRef<PixelMask<PixelGray<float> > > dem; if ( PixelHasAlpha<PixelT>::value ) { dem = alpha_to_mask(channel_cast<float>(disk_dem_file) ); } else if (vm.count("nodata-value")) { dem = channel_cast<float>(create_mask(input_image, nodata_value)); } else if ( disk_dem_rsrc->has_nodata_value() ) { dem = create_mask(input_image, nodata_value); } else { dem = pixel_cast<PixelMask<PixelGray<float> > >(input_image); } delete disk_dem_rsrc; ImageViewRef<PixelMask<PixelRGB<float> > > colorized_image = colormap(normalize(dem,min_val,max_val,0,1.0)); if (shaded_relief_file_name != "") { vw_out() << "\t--> Incorporating hillshading from: " << shaded_relief_file_name << ".\n"; DiskImageView<PixelMask<float> > shaded_relief_image(shaded_relief_file_name); ImageViewRef<PixelMask<PixelRGB<float> > > shaded_image = copy_mask(colorized_image*apply_mask(shaded_relief_image), shaded_relief_image); vw_out() << "Writing image color-mapped image: " << output_file_name << "\n"; write_georeferenced_image(output_file_name, channel_cast_rescale<uint8>(shaded_image), georef, TerminalProgressCallback( "tools.colormap", "Writing:")); } else { vw_out() << "Writing image color-mapped image: " << output_file_name << "\n"; write_georeferenced_image(output_file_name, channel_cast_rescale<uint8>(colorized_image), georef, TerminalProgressCallback( "tools.colormap", "Writing:")); } } void save_legend() { min_val = 0.0; max_val = 1.0; ImageView<PixelGray<float> > img(200, 500); for (int j = 0; j < img.rows(); ++j) { float val = float(j) / img.rows(); for (int i = 0; i < img.cols(); ++i) { img(i,j) = val; } } ImageViewRef<PixelMask<PixelRGB<float> > > colorized_image = colormap(img); write_image("legend.png", channel_cast_rescale<uint8>(apply_mask(colorized_image))); } int main( int argc, char *argv[] ) { po::options_description desc("Description: Produces a colorized image of a DEM \n\nUsage: colormap [options] <input file> \n\nOptions"); desc.add_options() ("input-file", po::value<std::string>(&input_file_name), "Explicitly specify the input file") ("shaded-relief-file,s", po::value<std::string>(&shaded_relief_file_name)->default_value(""), "Specify a shaded relief image (grayscale) to apply to the colorized image.") ("output-file,o", po::value<std::string>(&output_file_name), "Specify the output file") ("nodata-value", po::value<float>(&nodata_value), "Remap the DEM default value to the min altitude value.") ("min", po::value<float>(&min_val), "Minimum height of the color map.") ("max", po::value<float>(&max_val), "Maximum height of the color map.") ("moon", "Set the min and max values to [-8499 10208] meters, which is suitable for covering elevations on the Moon.") ("mars", "Set the min and max values to [-8208 21249] meters, which is suitable for covering elevations on Mars.") ("legend", "Generate the colormap legend. This image is saved (without labels) as \'legend.png\'") ("help,h", "Display this help message"); po::positional_options_description p; p.add("input-file", 1); po::variables_map vm; try { po::store( po::command_line_parser( argc, argv ).options(desc).positional(p).run(), vm ); po::notify( vm ); } catch (po::error &e) { std::cout << "An error occured while parsing command line arguments.\n"; std::cout << "\t" << e.what() << "\n\n"; std::cout << desc << std::endl; return 1; } if( vm.count("help") ) { std::cout << desc << std::endl; return 1; } if( vm.count("legend") ) { std::cout << "\t--> Saving legend file to disk as \'legend.png\'\n"; save_legend(); exit(0); } // This is a reasonable range of elevation values to cover global // lunar topography. if( vm.count("moon") ) { min_val = -8499; max_val = 10208; } // This is a reasonable range of elevation values to cover global // mars topography. if( vm.count("mars") ) { min_val = -8208; max_val = 21249; } if( vm.count("input-file") != 1 ) { std::cout << "Error: Must specify exactly one input file!\n" << std::endl; std::cout << desc << std::endl; return 1; } if( output_file_name == "" ) { output_file_name = fs::path(input_file_name).replace_extension().string() + "_CMAP.tif"; } try { // Get the right pixel/channel type. DiskImageResource *rsrc = DiskImageResource::open(input_file_name); ChannelTypeEnum channel_type = rsrc->channel_type(); PixelFormatEnum pixel_format = rsrc->pixel_format(); delete rsrc; switch(pixel_format) { case VW_PIXEL_GRAY: switch(channel_type) { case VW_CHANNEL_UINT8: do_colorized_dem<PixelGray<uint8> >(vm); break; case VW_CHANNEL_INT16: do_colorized_dem<PixelGray<int16> >(vm); break; case VW_CHANNEL_UINT16: do_colorized_dem<PixelGray<uint16> >(vm); break; default: do_colorized_dem<PixelGray<float32> >(vm); break; } break; case VW_PIXEL_GRAYA: switch(channel_type) { case VW_CHANNEL_UINT8: do_colorized_dem<PixelGrayA<uint8> >(vm); break; case VW_CHANNEL_INT16: do_colorized_dem<PixelGrayA<int16> >(vm); break; case VW_CHANNEL_UINT16: do_colorized_dem<PixelGrayA<uint16> >(vm); break; default: do_colorized_dem<PixelGrayA<float32> >(vm); break; } break; default: std::cout << "Error: Unsupported pixel format. The DEM image must have only one channel."; exit(0); } } catch( Exception& e ) { std::cerr << "Error: " << e.what() << std::endl; } return 0; } <commit_msg>Reorganize colormap and add LUT option<commit_after>// __BEGIN_LICENSE__ // Copyright (C) 2006-2010 United States Government as represented by // the Administrator of the National Aeronautics and Space Administration. // All Rights Reserved. // __END_LICENSE__ #ifdef _MSC_VER #pragma warning(disable:4244) #pragma warning(disable:4267) #pragma warning(disable:4996) #endif #include <cstdlib> #include <boost/tokenizer.hpp> #include <boost/lexical_cast.hpp> #include <boost/numeric/conversion/cast.hpp> #include <boost/program_options.hpp> #include <boost/filesystem/path.hpp> #include <boost/foreach.hpp> namespace fs = boost::filesystem; namespace po = boost::program_options; #include <vw/Core/Functors.h> #include <vw/Image/Algorithms.h> #include <vw/Image/ImageMath.h> #include <vw/Image/ImageViewRef.h> #include <vw/Image/PerPixelViews.h> #include <vw/Image/PixelMask.h> #include <vw/Image/MaskViews.h> #include <vw/Image/PixelTypes.h> #include <vw/Image/Statistics.h> #include <vw/FileIO/DiskImageView.h> #include <vw/Cartography/GeoReference.h> using namespace vw; struct Options { // Input std::string input_file_name; std::string shaded_relief_file_name; // Settings std::string output_file_name, lut_file_name; float nodata_value, min_val, max_val; bool draw_legend; typedef Vector<uint8,3> Vector3u; typedef std::pair<std::string,Vector3u> lut_element; typedef std::vector<lut_element> lut_type; lut_type lut; std::map<float,Vector3u> lut_map; }; // Colormap function class ColormapFunc : public ReturnFixedType<PixelMask<PixelRGB<uint8> > > { typedef std::map<float,Options::Vector3u> map_type; map_type m_colormap; public: ColormapFunc( std::map<float,Options::Vector3u> const& map) : m_colormap(map) {} template <class PixelT> PixelMask<PixelRGB<uint8> > operator() (PixelT const& pix) const { if (is_transparent(pix)) return PixelMask<PixelRGB<uint8> >(); float val = compound_select_channel<const float&>(pix,0); if (val > 1.0) val = 1.0; if (val < 0.0) val = 0.0; map_type::const_iterator bot = m_colormap.upper_bound( val ); bot--; map_type::const_iterator top = m_colormap.upper_bound( val ); if ( top == m_colormap.end() ) return PixelRGB<uint8>(bot->second[0],bot->second[1],bot->second[2]); Options::Vector3u output = bot->second + ((val-bot->first)/(top->first-bot->first))*(Vector3i(top->second)-Vector3i(bot->second)); return PixelRGB<uint8>(output[0],output[1],output[2]); } }; template <class ViewT> UnaryPerPixelView<ViewT, ColormapFunc> colormap(ImageViewBase<ViewT> const& view, std::map<float,Options::Vector3u> const& map) { return UnaryPerPixelView<ViewT, ColormapFunc>(view.impl(), ColormapFunc(map)); } // ------------------------------------------------------------------------------------- template <class PixelT> void do_colorized_dem(Options& opt) { vw_out() << "Creating colorized DEM.\n"; cartography::GeoReference georef; cartography::read_georeference(georef, opt.input_file_name); // Attempt to extract nodata value DiskImageResource *disk_dem_rsrc = DiskImageResource::open(opt.input_file_name); if (opt.nodata_value != std::numeric_limits<float>::max()) { vw_out() << "\t--> Using user-supplied nodata value: " << opt.nodata_value << ".\n"; } else if ( disk_dem_rsrc->has_nodata_value() ) { opt.nodata_value = disk_dem_rsrc->nodata_value(); vw_out() << "\t--> Extracted nodata value from file: " << opt.nodata_value << ".\n"; } // Compute min/max DiskImageView<PixelT> disk_dem_file(opt.input_file_name); ImageViewRef<PixelGray<float> > input_image = pixel_cast<PixelGray<float> >(select_channel(disk_dem_file,0)); if (opt.min_val == 0 && opt.max_val == 0) { min_max_channel_values( create_mask( input_image, opt.nodata_value), opt.min_val, opt.max_val); vw_out() << "\t--> DEM color map range: [" << opt.min_val << " " << opt.max_val << "]\n"; } else { vw_out() << "\t--> Using user-specified color map range: [" << opt.min_val << " " << opt.max_val << "]\n"; } // Convert lut to lut_map ( converts altitudes to relative percent ) opt.lut_map.clear(); BOOST_FOREACH( Options::lut_element const& pair, opt.lut ) { try { if ( boost::contains(pair.first,"%") ) { float key = boost::lexical_cast<float>(boost::erase_all_copy(pair.first,"%"))/100.0; opt.lut_map[ key ] = pair.second; } else { float key = boost::lexical_cast<float>(pair.first); opt.lut_map[ ( key - opt.min_val ) / ( opt.max_val - opt.min_val ) ] = pair.second; } } catch ( boost::bad_lexical_cast const& e ) { continue; } } // Mask input ImageViewRef<PixelMask<PixelGray<float> > > dem; if ( PixelHasAlpha<PixelT>::value ) dem = alpha_to_mask(channel_cast<float>(disk_dem_file) ); else if (opt.nodata_value != std::numeric_limits<float>::max()) dem = channel_cast<float>(create_mask(input_image, opt.nodata_value)); else if ( disk_dem_rsrc->has_nodata_value() ) dem = create_mask(input_image, opt.nodata_value); else dem = pixel_cast<PixelMask<PixelGray<float> > >(input_image); delete disk_dem_rsrc; // Apply colormap ImageViewRef<PixelMask<PixelRGB<uint8> > > colorized_image = colormap(normalize(dem,opt.min_val,opt.max_val,0,1.0), opt.lut_map); if (!opt.shaded_relief_file_name.empty()) { vw_out() << "\t--> Incorporating hillshading from: " << opt.shaded_relief_file_name << ".\n"; DiskImageView<PixelMask<float> > shaded_relief_image(opt.shaded_relief_file_name); ImageViewRef<PixelMask<PixelRGB<uint8> > > shaded_image = copy_mask(channel_cast<uint8>(colorized_image*apply_mask(shaded_relief_image)), shaded_relief_image); vw_out() << "Writing image color-mapped image: " << opt.output_file_name << "\n"; write_georeferenced_image(opt.output_file_name, shaded_image, georef, TerminalProgressCallback( "tools.colormap", "Writing:")); } else { vw_out() << "Writing image color-mapped image: " << opt.output_file_name << "\n"; write_georeferenced_image(opt.output_file_name, colorized_image, georef, TerminalProgressCallback( "tools.colormap", "Writing:")); } } void save_legend( Options const& opt) { ImageView<PixelGray<float> > img(100, 500); for (int j = 0; j < img.rows(); ++j) { float val = float(j) / img.rows(); for (int i = 0; i < img.cols(); ++i) { img(i,j) = val; } } ImageViewRef<PixelMask<PixelRGB<uint8> > > colorized_image = colormap(img, opt.lut_map); write_image("legend.png", channel_cast_rescale<uint8>(apply_mask(colorized_image))); } void handle_arguments( int argc, char *argv[], Options& opt ) { po::options_description general_options(""); general_options.add_options() ("shaded-relief-file,s", po::value(&opt.shaded_relief_file_name), "Specify a shaded relief image (grayscale) to apply to the colorized image.") ("output-file,o", po::value(&opt.output_file_name), "Specify the output file") ("lut-file", po::value(&opt.lut_file_name), "Specify look up file for color output. It is similar to the file used by gdaldem. Without we revert to our standard LUT") ("nodata-value", po::value(&opt.nodata_value)->default_value(std::numeric_limits<float>::max()), "Remap the DEM default value to the min altitude value.") ("min", po::value(&opt.min_val)->default_value(0), "Minimum height of the color map.") ("max", po::value(&opt.max_val)->default_value(0), "Maximum height of the color map.") ("moon", "Set the min and max values to [-8499 10208] meters, which is suitable for covering elevations on the Moon.") ("mars", "Set the min and max values to [-8208 21249] meters, which is suitable for covering elevations on Mars.") ("legend", "Generate the colormap legend. This image is saved (without labels) as \'legend.png\'") ("help,h", "Display this help message"); po::options_description positional(""); positional.add_options() ("input-file", po::value(&opt.input_file_name), "Input disparity map"); po::positional_options_description positional_desc; positional_desc.add("input-file", 1); po::options_description all_options; all_options.add(general_options).add(positional); po::variables_map vm; try { po::store( po::command_line_parser( argc, argv ).options(all_options).positional(positional_desc).run(), vm ); po::notify( vm ); } catch (po::error &e) { vw_throw( ArgumentErr() << "Error parsing input:\n\t" << e.what() << general_options ); } std::ostringstream usage; usage << "Usage: " << argv[0] << " [options] <input dem> \n"; if ( vm.count("help") ) vw_throw( ArgumentErr() << usage.str() << general_options ); if ( opt.input_file_name.empty() ) vw_throw( ArgumentErr() << "Missing input file!\n" << usage.str() << general_options ); if ( vm.count("moon") ) { opt.min_val = -8499; opt.max_val = 10208; } if ( vm.count("mars") ) { opt.min_val = -8208; opt.max_val = 21249; } if ( opt.output_file_name.empty() ) opt.output_file_name = fs::path(opt.input_file_name).replace_extension().string()+"_CMAP.tif"; opt.draw_legend = vm.count("legend"); } int main( int argc, char *argv[] ) { Options opt; try { handle_arguments( argc, argv, opt ); // Decide legend if ( opt.lut_file_name.empty() ) { opt.lut.clear(); opt.lut.push_back( Options::lut_element("0%", Options::Vector3u(0,0,0)) ); opt.lut.push_back( Options::lut_element("20.8%",Options::Vector3u(0,0,255)) ); opt.lut.push_back( Options::lut_element("25%", Options::Vector3u(0,0,255)) ); opt.lut.push_back( Options::lut_element("37.5%",Options::Vector3u(0,191,255)) ); opt.lut.push_back( Options::lut_element("41.7%",Options::Vector3u(0,255,255)) ); opt.lut.push_back( Options::lut_element("58.3%",Options::Vector3u(255,255,51)) ); opt.lut.push_back( Options::lut_element("62.5%",Options::Vector3u(255,191,0)) ); opt.lut.push_back( Options::lut_element("75%", Options::Vector3u(255,0,0)) ); opt.lut.push_back( Options::lut_element("79.1%",Options::Vector3u(255,0,0)) ); opt.lut.push_back( Options::lut_element("100%", Options::Vector3u(0,0,0)) ); } else { // Read input LUT typedef boost::tokenizer<> tokenizer; boost::char_delimiters_separator<char> sep(false,",:"); std::ifstream lut_file( opt.lut_file_name.c_str() ); if ( !lut_file.is_open() ) vw_throw( IOErr() << "Unable to open LUT: " << opt.lut_file_name ); std::string line; std::getline( lut_file, line ); while ( lut_file.good() ) { tokenizer tokens(line,sep); tokenizer::iterator iter = tokens.begin(); std::string key; Options::Vector3u value; try { if ( iter == tokens.end()) vw_throw( IOErr() << "Unable to read input LUT" ); key = *iter; iter++; if ( iter == tokens.end()) vw_throw( IOErr() << "Unable to read input LUT" ); value[0] = boost::numeric_cast<uint8>(boost::lexical_cast<int>(*iter)); iter++; if ( iter == tokens.end()) vw_throw( IOErr() << "Unable to read input LUT" ); value[1] = boost::numeric_cast<uint8>(boost::lexical_cast<int>(*iter)); iter++; if ( iter == tokens.end()) vw_throw( IOErr() << "Unable to read input LUT" ); value[2] = boost::numeric_cast<uint8>(boost::lexical_cast<int>(*iter)); } catch ( boost::bad_lexical_cast const& e ) { std::getline( lut_file, line ); continue; } opt.lut.push_back( Options::lut_element(key, value) ); std::getline( lut_file, line ); } lut_file.close(); } // Get the right pixel/channel type. DiskImageResource *rsrc = DiskImageResource::open(opt.input_file_name); ChannelTypeEnum channel_type = rsrc->channel_type(); PixelFormatEnum pixel_format = rsrc->pixel_format(); delete rsrc; switch(pixel_format) { case VW_PIXEL_GRAY: switch(channel_type) { case VW_CHANNEL_UINT8: do_colorized_dem<PixelGray<uint8> >(opt); break; case VW_CHANNEL_INT16: do_colorized_dem<PixelGray<int16> >(opt); break; case VW_CHANNEL_UINT16: do_colorized_dem<PixelGray<uint16> >(opt); break; default: do_colorized_dem<PixelGray<float32> >(opt); break; } break; case VW_PIXEL_GRAYA: switch(channel_type) { case VW_CHANNEL_UINT8: do_colorized_dem<PixelGrayA<uint8> >(opt); break; case VW_CHANNEL_INT16: do_colorized_dem<PixelGrayA<int16> >(opt); break; case VW_CHANNEL_UINT16: do_colorized_dem<PixelGrayA<uint16> >(opt); break; default: do_colorized_dem<PixelGrayA<float32> >(opt); break; } break; default: vw_throw( ArgumentErr() << "Unsupported pixel format. The DEM image must have only one channel." ); } // Draw legend if ( opt.draw_legend ) save_legend(opt); } catch ( const ArgumentErr& e ) { vw_out() << e.what() << std::endl; return 1; } catch ( const Exception& e ) { std::cerr << "Error: " << e.what() << std::endl; return 1; } return 0; } <|endoftext|>
<commit_before>/* * Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. * * This code 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 * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. * */ #include "precompiled.hpp" #include "runtime/gpu.hpp" #include "runtime/handles.hpp" int Gpu::_initialized_gpus_count = 0; Gpu* Gpu::_initialized_gpus[MAX_GPUS]; void Gpu::initialized_gpu(Gpu* gpu) { // GPUs are always initialized on the same thread so no need for locking guarantee(_initialized_gpus_count < MAX_GPUS, "oob"); if (TraceGPUInteraction) { tty->print_cr("[GPU] registered initialization of %s (total initialized: %d)", gpu->name(), _initialized_gpus); } _initialized_gpus[_initialized_gpus_count++] = gpu; } void Gpu::safepoint_event(SafepointEvent event) { for (int i = 0; i < _initialized_gpus_count; i++) { if (event == SafepointBegin) { _initialized_gpus[i]->notice_safepoints(); } else { _initialized_gpus[i]->ignore_safepoints(); } } } <commit_msg>fix log message stating how many GPUs have been initialized<commit_after>/* * Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. * * This code 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 * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. * */ #include "precompiled.hpp" #include "runtime/gpu.hpp" #include "runtime/handles.hpp" int Gpu::_initialized_gpus_count = 0; Gpu* Gpu::_initialized_gpus[MAX_GPUS]; void Gpu::initialized_gpu(Gpu* gpu) { // GPUs are always initialized on the same thread so no need for locking guarantee(_initialized_gpus_count < MAX_GPUS, "oob"); _initialized_gpus[_initialized_gpus_count++] = gpu; if (TraceGPUInteraction) { tty->print_cr("[GPU] registered initialization of %s (total initialized: %d)", gpu->name(), _initialized_gpus_count); } } void Gpu::safepoint_event(SafepointEvent event) { for (int i = 0; i < _initialized_gpus_count; i++) { if (event == SafepointBegin) { _initialized_gpus[i]->notice_safepoints(); } else { _initialized_gpus[i]->ignore_safepoints(); } } } <|endoftext|>
<commit_before>/* -*- mode: C++; c-basic-offset: 2; indent-tabs-mode: nil -*- */ /* * Main authors: * Jip J. Dekker <jip@dekker.li> */ /* 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 <minizinc/presolve_utils.hh> #include <fstream> #include <minizinc/astiterator.hh> namespace MiniZinc{ void recursiveRegisterFns(Model* model, EnvI& env, FunctionI* fn) { // TODO: Can't use Evisitor because of const in parameter. class RegisterCalls { public: Model* model1; EnvI& env1; RegisterCalls(Model* _model, EnvI& _env) : model1(_model), env1(_env) { } /// Visit integer literal void vIntLit(const IntLit&) {} /// Visit floating point literal void vFloatLit(const FloatLit&) {} /// Visit Boolean literal void vBoolLit(const BoolLit&) {} /// Visit set literal void vSetLit(const SetLit&) {} /// Visit string literal void vStringLit(const StringLit&) {} /// Visit identifier void vId(const Id&) {} /// Visit anonymous variable void vAnonVar(const AnonVar&) {} /// Visit array literal void vArrayLit(const ArrayLit&) {} /// Visit array access void vArrayAccess(const ArrayAccess&) {} /// Visit array comprehension void vComprehension(const Comprehension&) {} /// Visit array comprehension (only generator \a gen_i) void vComprehensionGenerator(const Comprehension&, int gen_i) { (void) gen_i; } /// Visit if-then-else void vITE(const ITE&) {} /// Visit binary operator void vBinOp(const BinOp&) {} /// Visit unary operator void vUnOp(const UnOp&) {} /// Visit call void vCall(Call& call) { if (call.decl() && (model1->matchFn(env1, &call) == nullptr) ) { model1->registerFn(env1, call.decl()); RegisterCalls rc(model1, env1); TopDownIterator<RegisterCalls> tdi(rc); tdi.run(call.decl()->e()); } } /// Visit let void vLet(const Let&) {} /// Visit variable declaration void vVarDecl(const VarDecl&) {} /// Visit type inst void vTypeInst(const TypeInst&) {} /// Visit TIId void vTIId(const TIId&) {} /// Determine whether to enter node bool enter(Expression* e) { return true; } /// Exit node after processing has finished void exit(Expression* e) {} } rc(model, env); model->registerFn(env, fn); TopDownIterator<RegisterCalls> tdi(rc); tdi.run(fn->e()); } Expression* computeDomainExpr(EnvI& env, Expression* exp) { // TODO: Should we compute the unions manually? if (exp->eid() == Expression::E_ID ) return exp->cast<Id>()->decl()->ti()->domain(); Expression* type = nullptr; if(exp->type().dim() > 0) { // TODO: Use eval_array_lit instead? switch (exp->eid()) { case Expression::E_ARRAYLIT: { ArrayLit* arr = exp->cast<ArrayLit>(); if (arr->length() > 0) { type = computeDomainExpr(env, arr->v()[0]); if (!type) return nullptr; for (int i = 1; i < arr->length(); ++i) { Expression* type2 = computeDomainExpr(env, arr->v()[i]); if(!type2) return nullptr; type = new BinOp(Location(), type, BOT_UNION, type2); type->type( type2->type() ); } } return type; } case Expression::E_CALL: { Call* c = exp->cast<Call>(); if ( c->id().str().find("array") ) { return c->args()[c->args().size() == 1 ? 0 : 1]->cast<ArrayLit>(); } else { // TODO: Are there more cases in which we can compute this? return nullptr; } } case Expression::E_BINOP: { BinOp* op = exp->cast<BinOp>(); if (op->op() == BinOpType::BOT_PLUSPLUS) { Expression* left = computeDomainExpr(env, op->lhs()); Expression* right = computeDomainExpr(env, op->rhs()); if (!left || !right) return nullptr; type = new BinOp(Location(), left, BOT_UNION, right); type->type( left->type() ); } else { return nullptr; } } case Expression::E_COMP: { Comprehension* comp = exp->cast<Comprehension>(); return computeDomainExpr(env, comp->e()); } default: { // TODO: Print expression for error throw InternalError("Presolver couldn't determine counds of expression"); } } } // TODO: How about booleans? switch (exp->type().bt()) { case Type::BT_INT: { IntBounds ib = compute_int_bounds(env, exp); if (ib.valid) { type = new SetLit( Location(), IntSetVal::a(ib.l, ib.u) ); type->type(Type::parsetint()); return type; } break; } case Type::BT_FLOAT: { FloatBounds ib = compute_float_bounds(env, exp); if (ib.valid) { type = new SetLit(Location(), IntSetVal::a(ib.l, ib.u)); type->type(Type::parsetfloat()); return type; } break; } default: return nullptr; } return nullptr; } void computeRanges(EnvI& env, Expression* exp, std::vector<TypeInst*>& ranges) { assert(exp->type().dim() > 0); if (exp->eid() == Expression::E_ID) { ASTExprVec<TypeInst> id_ranges = exp->cast<Id>()->decl()->ti()->ranges(); for (TypeInst* range : id_ranges) { ranges.push_back(new TypeInst(Location(), Type::parsetint(), range->domain())); } } else { ArrayLit* al = eval_array_lit(env, exp); std::vector<TypeInst*> ranges; for (int j = 0; j < al->dims(); ++j) { TypeInst* ti = new TypeInst(Location(), Type::parsetint(), new SetLit(Location(), IntSetVal::a(IntVal(al->min(j)), IntVal(al->max(j))) )); ranges.push_back(ti); } } } void generateFlatZinc(Env& env, bool rangeDomains, bool optimizeFZN, bool newFZN) { // TODO: Should this be integrated in Flattener? FlatteningOptions fopts; fopts.onlyRangeDomains = rangeDomains; flatten(env, fopts); if(optimizeFZN) optimize(env); if (!newFZN) { oldflatzinc(env); } else { env.flat()->compact(); env.output()->compact(); } } bool Presolver::Solns2Vector::evalOutput() { GCLock lock; std::unordered_map<std::string, Expression*>* solution = new std::unordered_map<std::string, Expression*>(); for (unsigned int i = 0; i < getModel()->size(); i++) { if (VarDeclI* vdi = (*getModel())[i]->dyn_cast<VarDeclI>()) { Expression* cpi = copy(copyEnv, vdi->e()->e()); solution->insert(std::pair<std::string, Expression*>(vdi->e()->id()->str().str(), cpi)); GCProhibitors.emplace_back(cpi); } } solutions.push_back(solution); return true; } void Presolver::TableBuilder::buildFromSolver(FunctionI* f, Solns2Vector* solns, ASTExprVec<Expression> variables) { rows = static_cast<long long int>( solns->getSolutions().size()); if (variables.size() == 0) { for (auto it = f->params().begin(); it != f->params().end(); ++it) { Expression* id = new Id(Location(), (*it)->id()->str(), (*it)); id->type((*it)->type()); addVariable(id); } } else { for (auto it = variables.begin(); it != variables.end(); ++it) { addVariable(*it); } } for (int i = 0; i < solns->getSolutions().size(); ++i) { auto sol = solns->getSolutions()[i]; for (auto it = f->params().begin(); it != f->params().end(); ++it) { Expression* exp = sol->at((*it)->id()->str().str()); exp->type(exp->type().bt() == Type::BT_BOOL ? Type::parbool((*it)->type().dim()) : Type::parint( (*it)->type().dim())); addData(exp); } } } Call* Presolver::TableBuilder::getExpression() { storeVars(); ArrayLit* dataExpr = new ArrayLit(Location(), data); dataExpr->type(boolTable ? Type::parbool(1) : Type::parint(1)); std::vector<Expression*> conversionArgs; SetLit* index1 = new SetLit(Location(), IntSetVal::a( std::vector<IntSetVal::Range>(1, IntSetVal::Range(IntVal(1), IntVal(rows))) )); index1->type(Type::parsetint()); conversionArgs.push_back(index1); Call* index2 = new Call(Location(), "index_set", std::vector<Expression*>(1, variables)); index2->type(Type::parsetint()); index2->decl(m->matchFn(env, index2)); conversionArgs.push_back(index2); conversionArgs.push_back(dataExpr); Call* tableData = new Call(Location(), "array2d", conversionArgs); tableData->type(boolTable ? Type::parbool(2) : Type::parint(2)); tableData->decl(m->matchFn(env, tableData)); std::vector<Expression*> tableArgs; tableArgs.push_back(variables); tableArgs.push_back(tableData); Call* tableCall = new Call(Location(), boolTable ? "table_bool" : "table_int", tableArgs); FunctionI* tableDecl = m->matchFn(env, tableCall); if (tableDecl == nullptr) { registerTableConstraint(); tableDecl = m->matchFn(env, tableCall); assert(tableDecl != nullptr); } tableCall->decl(tableDecl); tableCall->type(Type::varbool()); return tableCall; } void Presolver::TableBuilder::addVariable(Expression* var) { if (var->type().dim() > 1) { Call* c = new Call(Location(), "array1d", std::vector<Expression*>(1, var)); c->type(var->type().bt() == Type::BT_BOOL ? Type::varbool(1) : Type::varint(1)); c->decl(m->matchFn(env, c)); var = c; } if (var->type().bt() == Type::BT_BOOL && !boolTable) { Call* c = new Call(Location(), "bool2int", std::vector<Expression*>(1, var)); c->type(Type::varint(var->type().dim())); c->decl(m->matchFn(env, c)); var = c; } if (var->type().dim() > 0) { storeVars(); if (variables == nullptr) { variables = var; } else { variables = new BinOp(Location(), variables, BOT_PLUSPLUS, var); variables->type(boolTable ? Type::varbool(1) : Type::varint(1)); } } else { vVariables.push_back(var); } } void Presolver::TableBuilder::addData(Expression* dat) { if (dat->type().dim() > 0) { ArrayLit* arr = nullptr; if (dat->eid() == Expression::E_CALL) { Call* c = dat->cast<Call>(); arr = c->args()[c->args().size() - 1]->cast<ArrayLit>(); } else if (dat->eid() == Expression::E_ARRAYLIT) { ArrayLit* arr = dat->cast<ArrayLit>(); } assert(arr != nullptr); for (auto it = arr->v().begin(); it != arr->v().end(); ++it) { data.push_back(*it); } } else { data.push_back(dat); } } void Presolver::TableBuilder::storeVars() { if (vVariables.empty()) return; if (variables == nullptr) { variables = new ArrayLit(Location(), vVariables); } else { Expression* arr = new ArrayLit(Location(), vVariables); arr->type(boolTable ? Type::varbool(1) : Type::varint(1)); variables = new BinOp(Location(), variables, BOT_PLUSPLUS, arr); } variables->type(boolTable ? Type::varbool(1) : Type::varint(1)); vVariables.clear(); } void Presolver::TableBuilder::registerTableConstraint() { GCLock lock; std::string loc = boolTable ? "/table_bool.mzn" : "/table_int.mzn"; std::ifstream file(options.stdLibDir + "/" + options.globalsDir + loc); bool exists = file.is_open(); file.close(); Model* table_model = nullptr; if (exists) { table_model = parse(std::vector<std::string>(1, options.stdLibDir + "/" + options.globalsDir + loc), std::vector<std::string>(), options.includePaths, false, false, false, std::cerr); } else { table_model = parse(std::vector<std::string>(1, options.stdLibDir + "/std" + loc), std::vector<std::string>(), options.includePaths, false, false, false, std::cerr); } Env table_env(table_model); std::vector<TypeError> typeErrors; typecheck(table_env, table_model, typeErrors, false); assert(typeErrors.size() == 0); registerBuiltins(table_env, table_model); class RegisterTable : public ItemVisitor { public: EnvI& env; Model* model; RegisterTable(EnvI& env, Model* model) : env(env), model(model) { } void vFunctionI(FunctionI* i) { if (i->id().str() == "table_int" || i->id().str() == "table_bool") { FunctionI* ci = copy(env, i, false, true, false)->cast<FunctionI>(); model->addItem(ci); model->registerFn(env, ci); } } } rt(env, m); iterItems(rt, table_model); } }<commit_msg>Fixes an copying mistake<commit_after>/* -*- mode: C++; c-basic-offset: 2; indent-tabs-mode: nil -*- */ /* * Main authors: * Jip J. Dekker <jip@dekker.li> */ /* 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 <minizinc/presolve_utils.hh> #include <fstream> #include <minizinc/astiterator.hh> namespace MiniZinc{ void recursiveRegisterFns(Model* model, EnvI& env, FunctionI* fn) { // TODO: Can't use Evisitor because of const in parameter. class RegisterCalls { public: Model* model1; EnvI& env1; RegisterCalls(Model* _model, EnvI& _env) : model1(_model), env1(_env) { } /// Visit integer literal void vIntLit(const IntLit&) {} /// Visit floating point literal void vFloatLit(const FloatLit&) {} /// Visit Boolean literal void vBoolLit(const BoolLit&) {} /// Visit set literal void vSetLit(const SetLit&) {} /// Visit string literal void vStringLit(const StringLit&) {} /// Visit identifier void vId(const Id&) {} /// Visit anonymous variable void vAnonVar(const AnonVar&) {} /// Visit array literal void vArrayLit(const ArrayLit&) {} /// Visit array access void vArrayAccess(const ArrayAccess&) {} /// Visit array comprehension void vComprehension(const Comprehension&) {} /// Visit array comprehension (only generator \a gen_i) void vComprehensionGenerator(const Comprehension&, int gen_i) { (void) gen_i; } /// Visit if-then-else void vITE(const ITE&) {} /// Visit binary operator void vBinOp(const BinOp&) {} /// Visit unary operator void vUnOp(const UnOp&) {} /// Visit call void vCall(Call& call) { if (call.decl() && (model1->matchFn(env1, &call) == nullptr) ) { model1->registerFn(env1, call.decl()); RegisterCalls rc(model1, env1); TopDownIterator<RegisterCalls> tdi(rc); tdi.run(call.decl()->e()); } } /// Visit let void vLet(const Let&) {} /// Visit variable declaration void vVarDecl(const VarDecl&) {} /// Visit type inst void vTypeInst(const TypeInst&) {} /// Visit TIId void vTIId(const TIId&) {} /// Determine whether to enter node bool enter(Expression* e) { return true; } /// Exit node after processing has finished void exit(Expression* e) {} } rc(model, env); model->registerFn(env, fn); TopDownIterator<RegisterCalls> tdi(rc); tdi.run(fn->e()); } Expression* computeDomainExpr(EnvI& env, Expression* exp) { // TODO: Should we compute the unions manually? if (exp->eid() == Expression::E_ID ) return exp->cast<Id>()->decl()->ti()->domain(); Expression* type = nullptr; if(exp->type().dim() > 0) { // TODO: Use eval_array_lit instead? switch (exp->eid()) { case Expression::E_ARRAYLIT: { ArrayLit* arr = exp->cast<ArrayLit>(); if (arr->length() > 0) { type = computeDomainExpr(env, arr->v()[0]); if (!type) return nullptr; for (int i = 1; i < arr->length(); ++i) { Expression* type2 = computeDomainExpr(env, arr->v()[i]); if(!type2) return nullptr; type = new BinOp(Location(), type, BOT_UNION, type2); type->type( type2->type() ); } } return type; } case Expression::E_CALL: { Call* c = exp->cast<Call>(); if ( c->id().str().find("array") ) { return c->args()[c->args().size() == 1 ? 0 : 1]->cast<ArrayLit>(); } else { // TODO: Are there more cases in which we can compute this? return nullptr; } } case Expression::E_BINOP: { BinOp* op = exp->cast<BinOp>(); if (op->op() == BinOpType::BOT_PLUSPLUS) { Expression* left = computeDomainExpr(env, op->lhs()); Expression* right = computeDomainExpr(env, op->rhs()); if (!left || !right) return nullptr; type = new BinOp(Location(), left, BOT_UNION, right); type->type( left->type() ); } else { return nullptr; } } case Expression::E_COMP: { Comprehension* comp = exp->cast<Comprehension>(); return computeDomainExpr(env, comp->e()); } default: { // TODO: Print expression for error throw InternalError("Presolver couldn't determine counds of expression"); } } } // TODO: How about booleans? switch (exp->type().bt()) { case Type::BT_INT: { IntBounds ib = compute_int_bounds(env, exp); if (ib.valid) { type = new SetLit( Location(), IntSetVal::a(ib.l, ib.u) ); type->type(Type::parsetint()); return type; } break; } case Type::BT_FLOAT: { FloatBounds ib = compute_float_bounds(env, exp); if (ib.valid) { type = new SetLit(Location(), IntSetVal::a(ib.l, ib.u)); type->type(Type::parsetfloat()); return type; } break; } default: return nullptr; } return nullptr; } void computeRanges(EnvI& env, Expression* exp, std::vector<TypeInst*>& ranges) { assert(exp->type().dim() > 0); if (exp->eid() == Expression::E_ID) { ASTExprVec<TypeInst> id_ranges = exp->cast<Id>()->decl()->ti()->ranges(); for (TypeInst* range : id_ranges) { ranges.push_back(new TypeInst(Location(), Type::parsetint(), range->domain())); } } else { ArrayLit* al = eval_array_lit(env, exp); for (int j = 0; j < al->dims(); ++j) { TypeInst* ti = new TypeInst(Location(), Type::parsetint(), new SetLit(Location(), IntSetVal::a(IntVal(al->min(j)), IntVal(al->max(j))) )); ranges.push_back(ti); } } } void generateFlatZinc(Env& env, bool rangeDomains, bool optimizeFZN, bool newFZN) { // TODO: Should this be integrated in Flattener? FlatteningOptions fopts; fopts.onlyRangeDomains = rangeDomains; flatten(env, fopts); if(optimizeFZN) optimize(env); if (!newFZN) { oldflatzinc(env); } else { env.flat()->compact(); env.output()->compact(); } } bool Presolver::Solns2Vector::evalOutput() { GCLock lock; std::unordered_map<std::string, Expression*>* solution = new std::unordered_map<std::string, Expression*>(); for (unsigned int i = 0; i < getModel()->size(); i++) { if (VarDeclI* vdi = (*getModel())[i]->dyn_cast<VarDeclI>()) { Expression* cpi = copy(copyEnv, vdi->e()->e()); solution->insert(std::pair<std::string, Expression*>(vdi->e()->id()->str().str(), cpi)); GCProhibitors.emplace_back(cpi); } } solutions.push_back(solution); return true; } void Presolver::TableBuilder::buildFromSolver(FunctionI* f, Solns2Vector* solns, ASTExprVec<Expression> variables) { rows = static_cast<long long int>( solns->getSolutions().size()); if (variables.size() == 0) { for (auto it = f->params().begin(); it != f->params().end(); ++it) { Expression* id = new Id(Location(), (*it)->id()->str(), (*it)); id->type((*it)->type()); addVariable(id); } } else { for (auto it = variables.begin(); it != variables.end(); ++it) { addVariable(*it); } } for (int i = 0; i < solns->getSolutions().size(); ++i) { auto sol = solns->getSolutions()[i]; for (auto it = f->params().begin(); it != f->params().end(); ++it) { Expression* exp = sol->at((*it)->id()->str().str()); exp->type(exp->type().bt() == Type::BT_BOOL ? Type::parbool((*it)->type().dim()) : Type::parint( (*it)->type().dim())); addData(exp); } } } Call* Presolver::TableBuilder::getExpression() { storeVars(); ArrayLit* dataExpr = new ArrayLit(Location(), data); dataExpr->type(boolTable ? Type::parbool(1) : Type::parint(1)); std::vector<Expression*> conversionArgs; SetLit* index1 = new SetLit(Location(), IntSetVal::a( std::vector<IntSetVal::Range>(1, IntSetVal::Range(IntVal(1), IntVal(rows))) )); index1->type(Type::parsetint()); conversionArgs.push_back(index1); Call* index2 = new Call(Location(), "index_set", std::vector<Expression*>(1, variables)); index2->type(Type::parsetint()); index2->decl(m->matchFn(env, index2)); conversionArgs.push_back(index2); conversionArgs.push_back(dataExpr); Call* tableData = new Call(Location(), "array2d", conversionArgs); tableData->type(boolTable ? Type::parbool(2) : Type::parint(2)); tableData->decl(m->matchFn(env, tableData)); std::vector<Expression*> tableArgs; tableArgs.push_back(variables); tableArgs.push_back(tableData); Call* tableCall = new Call(Location(), boolTable ? "table_bool" : "table_int", tableArgs); FunctionI* tableDecl = m->matchFn(env, tableCall); if (tableDecl == nullptr) { registerTableConstraint(); tableDecl = m->matchFn(env, tableCall); assert(tableDecl != nullptr); } tableCall->decl(tableDecl); tableCall->type(Type::varbool()); return tableCall; } void Presolver::TableBuilder::addVariable(Expression* var) { if (var->type().dim() > 1) { Call* c = new Call(Location(), "array1d", std::vector<Expression*>(1, var)); c->type(var->type().bt() == Type::BT_BOOL ? Type::varbool(1) : Type::varint(1)); c->decl(m->matchFn(env, c)); var = c; } if (var->type().bt() == Type::BT_BOOL && !boolTable) { Call* c = new Call(Location(), "bool2int", std::vector<Expression*>(1, var)); c->type(Type::varint(var->type().dim())); c->decl(m->matchFn(env, c)); var = c; } if (var->type().dim() > 0) { storeVars(); if (variables == nullptr) { variables = var; } else { variables = new BinOp(Location(), variables, BOT_PLUSPLUS, var); variables->type(boolTable ? Type::varbool(1) : Type::varint(1)); } } else { vVariables.push_back(var); } } void Presolver::TableBuilder::addData(Expression* dat) { if (dat->type().dim() > 0) { ArrayLit* arr = nullptr; if (dat->eid() == Expression::E_CALL) { Call* c = dat->cast<Call>(); arr = c->args()[c->args().size() - 1]->cast<ArrayLit>(); } else if (dat->eid() == Expression::E_ARRAYLIT) { ArrayLit* arr = dat->cast<ArrayLit>(); } assert(arr != nullptr); for (auto it = arr->v().begin(); it != arr->v().end(); ++it) { data.push_back(*it); } } else { data.push_back(dat); } } void Presolver::TableBuilder::storeVars() { if (vVariables.empty()) return; if (variables == nullptr) { variables = new ArrayLit(Location(), vVariables); } else { Expression* arr = new ArrayLit(Location(), vVariables); arr->type(boolTable ? Type::varbool(1) : Type::varint(1)); variables = new BinOp(Location(), variables, BOT_PLUSPLUS, arr); } variables->type(boolTable ? Type::varbool(1) : Type::varint(1)); vVariables.clear(); } void Presolver::TableBuilder::registerTableConstraint() { GCLock lock; std::string loc = boolTable ? "/table_bool.mzn" : "/table_int.mzn"; std::ifstream file(options.stdLibDir + "/" + options.globalsDir + loc); bool exists = file.is_open(); file.close(); Model* table_model = nullptr; if (exists) { table_model = parse(std::vector<std::string>(1, options.stdLibDir + "/" + options.globalsDir + loc), std::vector<std::string>(), options.includePaths, false, false, false, std::cerr); } else { table_model = parse(std::vector<std::string>(1, options.stdLibDir + "/std" + loc), std::vector<std::string>(), options.includePaths, false, false, false, std::cerr); } Env table_env(table_model); std::vector<TypeError> typeErrors; typecheck(table_env, table_model, typeErrors, false); assert(typeErrors.size() == 0); registerBuiltins(table_env, table_model); class RegisterTable : public ItemVisitor { public: EnvI& env; Model* model; RegisterTable(EnvI& env, Model* model) : env(env), model(model) { } void vFunctionI(FunctionI* i) { if (i->id().str() == "table_int" || i->id().str() == "table_bool") { FunctionI* ci = copy(env, i, false, true, false)->cast<FunctionI>(); model->addItem(ci); model->registerFn(env, ci); } } } rt(env, m); iterItems(rt, table_model); } }<|endoftext|>
<commit_before>/* * fMBT, free Model Based Testing tool * Copyright (c) 2011, Intel Corporation. * * This program is free software; you can redistribute it and/or modify it * under the terms and conditions of the GNU Lesser General Public License, * version 2.1, as published by the Free Software Foundation. * * This program is distributed in the hope 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 program; if not, write to the Free Software Foundation, Inc., * 51 Franklin St - Fifth Floor, Boston, MA 02110-1301 USA. * */ #include "model.hh" class Model_yes: public Model { public: Model_yes(Log& l,const std::string& params) : Model(l, params), model(NULL) { } virtual ~Model_yes() { if (model) { delete model; } model=NULL; } virtual int getActions(int** _act) { *_act=&act[0]; return act.size(); } virtual int getIActions(int** _act) { *_act=&iact[0]; return iact.size(); } virtual int execute(int action) { return action; } virtual int getprops(int** pro) { *pro=&props[0]; return props.size(); } virtual bool reset() { return true; } virtual void push() {}; virtual void pop() {}; virtual bool init() { return true; }; void set_model(Alphabet* m); void set_props(std::string p); protected: std::vector<int> act; std::vector<int> iact; std::vector<int> props; Alphabet* model; }; <commit_msg>Let's not dump the core at fmbt-ucheck<commit_after>/* * fMBT, free Model Based Testing tool * Copyright (c) 2011, Intel Corporation. * * This program is free software; you can redistribute it and/or modify it * under the terms and conditions of the GNU Lesser General Public License, * version 2.1, as published by the Free Software Foundation. * * This program is distributed in the hope 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 program; if not, write to the Free Software Foundation, Inc., * 51 Franklin St - Fifth Floor, Boston, MA 02110-1301 USA. * */ #include "model.hh" class Model_yes: public Model { public: Model_yes(Log& l,const std::string& params) : Model(l, params), model(NULL) { } virtual ~Model_yes() { /* if (model) { delete model; } */ model=NULL; } virtual int getActions(int** _act) { *_act=&act[0]; return act.size(); } virtual int getIActions(int** _act) { *_act=&iact[0]; return iact.size(); } virtual int execute(int action) { return action; } virtual int getprops(int** pro) { *pro=&props[0]; return props.size(); } virtual bool reset() { return true; } virtual void push() {}; virtual void pop() {}; virtual bool init() { return true; }; void set_model(Alphabet* m); void set_props(std::string p); protected: std::vector<int> act; std::vector<int> iact; std::vector<int> props; Alphabet* model; }; <|endoftext|>
<commit_before>// include library #include <iostream> // using std::string using namespace std; // pretty print option // set by command line int pretty = 0; // whitespace buffer string whitespace; // concatenate comma lists bool comma = false; // comment context string comment = ""; // indent level int level = 0; // indent strings // length should be dynamic // but my c++ is very rusty string indents[255]; // helper function static string closer () { return pretty > 0 ? "\n" + indents[level] + "}" : " }"; } // helper function static string opener () { return pretty > 1 ? "\n" + indents[level] + "{" : " {"; } // flush whitespace and // print additional text // but only print additional // chars and buffer whitespace // *************************************************************************************** void flush (ostream& os, string& str) { // print whitespace os << whitespace; // reset whitespace whitespace = ""; // remove newlines int pos = str.find_last_not_of("\n\r"); string lfs = str.substr(pos + 1); str = str.substr(0, pos + 1); // getline discharged newline whitespace += lfs + "\n"; // print text os << str; } // process a line of the sass text void process (ostream& os, string& str, bool final = false) { // get postion of first meaningfull char int pos_left = str.find_first_not_of(" \t\n\v\f\r"); // special case for final run if (final) pos_left = 0; // has only whitespace if (pos_left == string::npos) { // add whitespace whitespace += str; } // have meaningfull first char else { // store indentation string string indent = str.substr(0, pos_left); // is a one-line comment if (comment == "//") { // close comment os << " */"; // unset flase comment = ""; } // special case for multiline comment, when the next // line is on the same indentation as the actual comment // I assume that this means we should close the comment node else if (comment == "/*" && indent.length() == indents[level].length()) { // close comment os << " */"; // unset flag comment = ""; } // current line has less or same indentation else if (level > 0 && indent.length() <= indents[level].length()) { // add semicolon if not in concat mode if (comment == "" && comma == false) os << ";"; } // make sure we close every "higher" block while (indent.length() < indents[level].length()) { // close block (lower level) indents[level] = ""; level --; // print closer if (comment != "") { os << " */"; } else { os << closer(); } // reset comment comment = ""; } // current line has more indentation if (indent.length() > indents[level].length()) { // not in comment mode if (comment == "") { // print block opener os << opener(); // open new block level ++; // store block indentation indents[level] = indent; } // open new block if comment is opening // be smart and only require the same indentation // level as the comment node itself, plus one char if (comment == "/*") { // open new block level ++; // only increase indentation minimaly // this will accept everything that is more // indented than the opening comment line indents[level] = indents[level - 1] + ' '; } // set comment to current indent // multiline comments must be indented // indicates multiline if not eq "*" if (comment != "") comment = indent; } // check if current line starts a comment string opener = str.substr(pos_left, 2); if (opener == "/*" || opener == "//") { // force single line comments // into a correct css comment str[pos_left + 1] = '*'; // close previous comment if (comment != "") os << " */";; // remove indentation from previous comment if (comment == "//") { // reset string indents[level] == ""; // close block level --; } // set comment flag comment = opener; } // flush line flush(os, str); // get postion of last meaningfull char int pos_right = str.find_last_not_of(" \t\n\v\f\r"); // check for invalid result if (pos_right != string::npos) { // get the last meaningfull char string closer = str.substr(pos_right, 1); // check if next line should be concatenated if (comment == "" && closer == ",") comma = true; // check if we have more than // one meaningfull char if (pos_right > 0) { // get the last two chars from string string closer = str.substr(pos_right - 1, 2); // is comment node closed expicitly if (closer == "*/") { // close implicit comment comment = ""; // reset string indents[level] == ""; // close block level --; } } // EO have meaningfull chars from end } } // EO have meaningfull chars from start } int main (int argc, char** argv) { // process command line arguments for (int i = 0; i < argc; ++i) { // only handle prettyfying option if ("-p" == string(argv[i])) pretty ++; if ("--pretty" == string(argv[i])) pretty ++; } // declare variable string line; // init variables whitespace = ""; indents[0] = ""; // read from stdin while (cin) { // read a line getline(cin, line); // process the line process(cout, line); // break if at end of file if (cin.eof()) break; }; // flush buffer string end = ""; process(cout, end, true); } <commit_msg>Adds more major fixes<commit_after>// include library #include <iostream> // using std::string using namespace std; // pretty print option // set by command line int pretty = 0; // whitespace buffer string whitespace; // concatenate comma lists bool comma = false; // comment context string comment = ""; // indent level int level = 0; // indent strings // length should be dynamic // but my c++ is very rusty string indents[255]; // helper function static string closer () { return pretty > 0 ? "\n" + indents[level] + "}" : " }"; } // helper function static string opener () { return pretty > 1 ? "\n" + indents[level] + "{" : " {"; } // flush whitespace and // print additional text // but only print additional // chars and buffer whitespace // *************************************************************************************** void flush (ostream& os, string& str) { // print whitespace os << whitespace; // reset whitespace whitespace = ""; // remove newlines int pos = str.find_last_not_of("\n\r"); string lfs = str.substr(pos + 1); str = str.substr(0, pos + 1); // getline discharged newline whitespace += lfs + "\n"; // print text os << str; } // process a line of the sass text void process (ostream& os, string& str, bool final = false) { // get postion of first meaningfull char int pos_left = str.find_first_not_of(" \t\n\v\f\r"); // special case for final run if (final) pos_left = 0; // has only whitespace if (pos_left == string::npos) { // add whitespace whitespace += str; } // have meaningfull first char else { // store indentation string string indent = str.substr(0, pos_left); // special case for multiline comment, when the next // line is on the same indentation as the actual comment // I assume that this means we should close the comment node if (comment != "" && indent.length() <= indents[level].length()) { // close comment os << " */"; // unset flag comment = ""; } // current line has less or same indentation else if (level > 0 && indent.length() <= indents[level].length()) { // add semicolon if not in concat mode if (comment == "" && comma == false) os << ";"; } // make sure we close every "higher" block while (indent.length() < indents[level].length()) { // reset string indents[level] == ""; // close block level --; // print closer if (comment == "") { os << closer(); } else { os << " */"; } // reset comment comment = ""; } // check if current line starts a comment string open = str.substr(pos_left, 2); // current line has more indentation if (indent.length() > indents[level].length()) { // not in comment mode if (comment == "") { // print block opener os << opener(); // open new block level ++; // store block indentation indents[level] = indent; } // open new block if comment is opening // be smart and only require the same indentation // level as the comment node itself, plus one char if (comment == "/*" && comment == "//") { // open new block level ++; // only increase indentation minimaly // this will accept everything that is more // indented than the opening comment line indents[level] = indents[level - 1] + ' '; } // set comment to current indent // multiline comments must be indented // indicates multiline if not eq "*" if (comment != "") comment = indent; } if (open == "/*" || open == "//") { // force single line comments // into a correct css comment str[pos_left + 1] = '*'; // close previous comment if (comment != "") os << " */";; // remove indentation from previous comment if (comment == "//") { // reset string indents[level] == ""; // close block level --; } // set comment flag comment = open; } // flush line flush(os, str); // get postion of last meaningfull char int pos_right = str.find_last_not_of(" \t\n\v\f\r"); // check for invalid result if (pos_right != string::npos) { // get the last meaningfull char string close = str.substr(pos_right, 1); // check if next line should be concatenated if (comment == "" && close == ",") comma = true; // check if we have more than // one meaningfull char if (pos_right > 0) { // get the last two chars from string string close = str.substr(pos_right - 1, 2); // is comment node closed expicitly if (close == "*/") { // close implicit comment comment = ""; // reset string indents[level] == ""; // close block level --; } } // EO have meaningfull chars from end } } // EO have meaningfull chars from start } int main (int argc, char** argv) { // process command line arguments for (int i = 0; i < argc; ++i) { // only handle prettyfying option if ("-p" == string(argv[i])) pretty ++; if ("--pretty" == string(argv[i])) pretty ++; } // declare variable string line; // init variables whitespace = ""; indents[0] = ""; // read from stdin while (cin) { // read a line getline(cin, line); // process the line process(cout, line); // break if at end of file if (cin.eof()) break; }; // flush buffer string end = ""; process(cout, end, true); } <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: javaoptions.cxx,v $ * * $Revision: 1.9 $ * * last change: $Author: rt $ $Date: 2005-09-08 02:17:45 $ * * 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 * ************************************************************************/ #include <stdio.h> #include <string.h> #include "javaoptions.hxx" #include "osl/process.h" #include "osl/thread.h" using namespace rtl; sal_Bool JavaOptions::initOptions(int ac, char* av[], sal_Bool bCmdFile) throw( IllegalArgument ) { sal_Bool ret = sal_True; sal_uInt16 i=0; if (!bCmdFile) { bCmdFile = sal_True; m_program = av[0]; if (ac < 2) { fprintf(stderr, "%s", prepareHelp().getStr()); ret = sal_False; } i = 1; } else { i = 0; } char *s=NULL; for( ; i < ac; i++) { if (av[i][0] == '-') { switch (av[i][1]) { case 'O': if (av[i][2] == '\0') { if (i < ac - 1 && av[i+1][0] != '-') { i++; s = av[i]; } else { OString tmp("'-O', please check"); if (i <= ac - 1) { tmp += " your input '" + OString(av[i+1]) + "'"; } throw IllegalArgument(tmp); } } else { s = av[i] + 2; } m_options["-O"] = OString(s); break; case 'B': if (av[i][2] == '\0') { if (i < ac - 1 && av[i+1][0] != '-') { i++; s = av[i]; } else { OString tmp("'-B', please check"); if (i <= ac - 1) { tmp += " your input '" + OString(av[i+1]) + "'"; } throw IllegalArgument(tmp); } } else { s = av[i] + 2; } m_options["-B"] = OString(s); break; case 'n': if (av[i][2] != 'D' || av[i][3] != '\0') { OString tmp("'-nD', please check"); tmp += " your input '" + OString(av[i]) + "'"; throw IllegalArgument(tmp); } m_options["-nD"] = OString(""); break; case 'T': if (av[i][2] == '\0') { if (i < ac - 1 && av[i+1][0] != '-') { i++; s = av[i]; } else { OString tmp("'-T', please check"); if (i <= ac - 1) { tmp += " your input '" + OString(av[i+1]) + "'"; } throw IllegalArgument(tmp); } } else { s = av[i] + 2; } if (m_options.count("-T") > 0) { OString tmp(m_options["-T"]); tmp = tmp + ";" + s; m_options["-T"] = tmp; } else { m_options["-T"] = OString(s); } break; case 'G': if (av[i][2] == 'c') { if (av[i][3] != '\0') { OString tmp("'-Gc', please check"); if (i <= ac - 1) { tmp += " your input '" + OString(av[i]) + "'"; } throw IllegalArgument(tmp); } m_options["-Gc"] = OString(""); break; } else if (av[i][2] != '\0') { OString tmp("'-G', please check"); if (i <= ac - 1) { tmp += " your input '" + OString(av[i]) + "'"; } throw IllegalArgument(tmp); } m_options["-G"] = OString(""); break; case 'X': // support for eXtra type rdbs { if (av[i][2] == '\0') { if (i < ac - 1 && av[i+1][0] != '-') { i++; s = av[i]; } else { OString tmp("'-X', please check"); if (i <= ac - 1) { tmp += " your input '" + OString(av[i+1]) + "'"; } throw IllegalArgument(tmp); } } else { s = av[i] + 2; } m_extra_input_files.push_back( s ); break; } default: throw IllegalArgument("the option is unknown" + OString(av[i])); break; } } else { if (av[i][0] == '@') { FILE* cmdFile = fopen(av[i]+1, "r"); if( cmdFile == NULL ) { fprintf(stderr, "%s", prepareHelp().getStr()); ret = sal_False; } else { int rargc=0; char* rargv[512]; char buffer[512]; while ( fscanf(cmdFile, "%s", buffer) != EOF ) { rargv[rargc]= strdup(buffer); rargc++; } fclose(cmdFile); ret = initOptions(rargc, rargv, bCmdFile); for (long i=0; i < rargc; i++) { free(rargv[i]); } } } else { if (bCmdFile) { m_inputFiles.push_back(av[i]); } else { OUString system_filepath; OSL_VERIFY( osl_Process_E_None == osl_getCommandArg( i-1, &system_filepath.pData ) ); m_inputFiles.push_back(OUStringToOString(system_filepath, osl_getThreadTextEncoding())); } } } } return ret; } OString JavaOptions::prepareHelp() { OString help("\nusing: "); help += m_program + " [-options] file_1 ... file_n -Xfile_n+1 -Xfile_n+2\nOptions:\n"; help += " -O<path> = path describes the root directory for the generated output.\n"; help += " The output directory tree is generated under this directory.\n"; help += " -T<name> = name specifies a type or a list of types. The output for this\n"; help += " [t1;...] type and all dependent types are generated. If no '-T' option is \n"; help += " specified, then output for all types is generated.\n"; help += " Example: 'com.sun.star.uno.XInterface' is a valid type.\n"; help += " -B<name> = name specifies the base node. All types are searched under this\n"; help += " node. Default is the root '/' of the registry files.\n"; help += " -nD = no dependent types are generated.\n"; help += " -G = generate only target files which does not exists.\n"; help += " -Gc = generate only target files which content will be changed.\n"; help += " -X<file> = extra types which will not be taken into account for generation.\n"; help += prepareVersion(); return help; } OString JavaOptions::prepareVersion() { OString version("\nSun Microsystems (R) "); version += m_program + " Version 2.0\n\n"; return version; } <commit_msg>INTEGRATION: CWS warnings01 (1.8.48); FILE MERGED 2005/09/22 22:29:05 sb 1.8.48.2: RESYNC: (1.8-1.9); FILE MERGED 2005/09/05 13:32:29 sb 1.8.48.1: #i53898# Made code warning-free.<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: javaoptions.cxx,v $ * * $Revision: 1.10 $ * * last change: $Author: hr $ $Date: 2006-06-20 02:25:07 $ * * 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 * ************************************************************************/ #include <stdio.h> #include <string.h> #include "javaoptions.hxx" #include "osl/process.h" #include "osl/thread.h" using namespace rtl; sal_Bool JavaOptions::initOptions(int ac, char* av[], sal_Bool bCmdFile) throw( IllegalArgument ) { sal_Bool ret = sal_True; sal_uInt16 i=0; if (!bCmdFile) { bCmdFile = sal_True; m_program = av[0]; if (ac < 2) { fprintf(stderr, "%s", prepareHelp().getStr()); ret = sal_False; } i = 1; } else { i = 0; } char *s=NULL; for( ; i < ac; i++) { if (av[i][0] == '-') { switch (av[i][1]) { case 'O': if (av[i][2] == '\0') { if (i < ac - 1 && av[i+1][0] != '-') { i++; s = av[i]; } else { OString tmp("'-O', please check"); if (i <= ac - 1) { tmp += " your input '" + OString(av[i+1]) + "'"; } throw IllegalArgument(tmp); } } else { s = av[i] + 2; } m_options["-O"] = OString(s); break; case 'B': if (av[i][2] == '\0') { if (i < ac - 1 && av[i+1][0] != '-') { i++; s = av[i]; } else { OString tmp("'-B', please check"); if (i <= ac - 1) { tmp += " your input '" + OString(av[i+1]) + "'"; } throw IllegalArgument(tmp); } } else { s = av[i] + 2; } m_options["-B"] = OString(s); break; case 'n': if (av[i][2] != 'D' || av[i][3] != '\0') { OString tmp("'-nD', please check"); tmp += " your input '" + OString(av[i]) + "'"; throw IllegalArgument(tmp); } m_options["-nD"] = OString(""); break; case 'T': if (av[i][2] == '\0') { if (i < ac - 1 && av[i+1][0] != '-') { i++; s = av[i]; } else { OString tmp("'-T', please check"); if (i <= ac - 1) { tmp += " your input '" + OString(av[i+1]) + "'"; } throw IllegalArgument(tmp); } } else { s = av[i] + 2; } if (m_options.count("-T") > 0) { OString tmp(m_options["-T"]); tmp = tmp + ";" + s; m_options["-T"] = tmp; } else { m_options["-T"] = OString(s); } break; case 'G': if (av[i][2] == 'c') { if (av[i][3] != '\0') { OString tmp("'-Gc', please check"); if (i <= ac - 1) { tmp += " your input '" + OString(av[i]) + "'"; } throw IllegalArgument(tmp); } m_options["-Gc"] = OString(""); break; } else if (av[i][2] != '\0') { OString tmp("'-G', please check"); if (i <= ac - 1) { tmp += " your input '" + OString(av[i]) + "'"; } throw IllegalArgument(tmp); } m_options["-G"] = OString(""); break; case 'X': // support for eXtra type rdbs { if (av[i][2] == '\0') { if (i < ac - 1 && av[i+1][0] != '-') { i++; s = av[i]; } else { OString tmp("'-X', please check"); if (i <= ac - 1) { tmp += " your input '" + OString(av[i+1]) + "'"; } throw IllegalArgument(tmp); } } else { s = av[i] + 2; } m_extra_input_files.push_back( s ); break; } default: throw IllegalArgument("the option is unknown" + OString(av[i])); } } else { if (av[i][0] == '@') { FILE* cmdFile = fopen(av[i]+1, "r"); if( cmdFile == NULL ) { fprintf(stderr, "%s", prepareHelp().getStr()); ret = sal_False; } else { int rargc=0; char* rargv[512]; char buffer[512]; while ( fscanf(cmdFile, "%s", buffer) != EOF ) { rargv[rargc]= strdup(buffer); rargc++; } fclose(cmdFile); ret = initOptions(rargc, rargv, bCmdFile); for (long j=0; j < rargc; j++) { free(rargv[j]); } } } else { if (bCmdFile) { m_inputFiles.push_back(av[i]); } else { OUString system_filepath; if (osl_getCommandArg( i-1, &system_filepath.pData ) != osl_Process_E_None) { OSL_ASSERT(false); } m_inputFiles.push_back(OUStringToOString(system_filepath, osl_getThreadTextEncoding())); } } } } return ret; } OString JavaOptions::prepareHelp() { OString help("\nusing: "); help += m_program + " [-options] file_1 ... file_n -Xfile_n+1 -Xfile_n+2\nOptions:\n"; help += " -O<path> = path describes the root directory for the generated output.\n"; help += " The output directory tree is generated under this directory.\n"; help += " -T<name> = name specifies a type or a list of types. The output for this\n"; help += " [t1;...] type and all dependent types are generated. If no '-T' option is \n"; help += " specified, then output for all types is generated.\n"; help += " Example: 'com.sun.star.uno.XInterface' is a valid type.\n"; help += " -B<name> = name specifies the base node. All types are searched under this\n"; help += " node. Default is the root '/' of the registry files.\n"; help += " -nD = no dependent types are generated.\n"; help += " -G = generate only target files which does not exists.\n"; help += " -Gc = generate only target files which content will be changed.\n"; help += " -X<file> = extra types which will not be taken into account for generation.\n"; help += prepareVersion(); return help; } OString JavaOptions::prepareVersion() { OString version("\nSun Microsystems (R) "); version += m_program + " Version 2.0\n\n"; return version; } <|endoftext|>
<commit_before>/* $Id: queuetest.cpp,v 1.1.2.1 2012/11/21 10:03:55 matthewmulhern Exp $ * * OpenMAMA: The open middleware agnostic messaging API * Copyright (C) 2011 NYSE Technologies, Inc. * * 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 <gtest/gtest.h> #include "MainUnitTestC.h" #include "wombat/wConfig.h" #include <sys/types.h> #include <cstring> #include <cstdio> #include <cstdlib> #include "wombat/port.h" #include "wombat/queue.h" #include "wombat/wSemaphore.h" class CommonQueueTestC : public ::testing::Test { protected: CommonQueueTestC(); virtual ~CommonQueueTestC(); virtual void SetUp(); virtual void TearDown (); public: }; CommonQueueTestC::CommonQueueTestC() { } CommonQueueTestC::~CommonQueueTestC() { } void CommonQueueTestC::SetUp(void) { } void CommonQueueTestC::TearDown(void) { } #if defined(__cplusplus) extern "C" { #endif static void MAMACALLTYPE onEvent(wombatQueue queue, void* closure) { } #if defined(__cplusplus) } #endif /* ************************************************************************* */ /* Test Functions */ /* ************************************************************************* */ /* Description: Allocates space for a queue * * Expected Result: WOMBAT_QUEUE_OK */ TEST_F (CommonQueueTestC, allocate) { wombatQueue queue = NULL; ASSERT_EQ (WOMBAT_QUEUE_OK, wombatQueue_allocate(&queue)); free (queue); } /* Description: Allocates space for a queue, creates it then destroys it. * * Expected Result: WOMBAT_QUEUE_OK */ TEST_F (CommonQueueTestC, createDestroy) { wombatQueue queue = NULL; uint32_t maxSize = 1000; uint32_t initialSize = 10; uint32_t growBySize = 100; ASSERT_EQ (WOMBAT_QUEUE_OK, wombatQueue_allocate(&queue)); ASSERT_EQ (WOMBAT_QUEUE_OK, wombatQueue_create(queue, maxSize, initialSize, growBySize)); ASSERT_EQ (WOMBAT_QUEUE_OK, wombatQueue_destroy(queue)); } /* Description: Allocates space for 100 queues, creates them then * destroys them. * * Expected Result: WOMBAT_QUEUE_OK */ TEST_F (CommonQueueTestC, createDestroyMany) { wombatQueue queue[100] = {NULL}; uint32_t maxSize = 1000; uint32_t initialSize = 10; uint32_t growBySize = 100; for(int i=0;i<100;i++) { ASSERT_EQ (WOMBAT_QUEUE_OK, wombatQueue_allocate(&queue[i])); } for(int i=0;i<100;i++) { ASSERT_EQ (WOMBAT_QUEUE_OK, wombatQueue_create(queue[i], maxSize, initialSize, growBySize)); } for(int i=0;i<100;i++) { ASSERT_EQ (WOMBAT_QUEUE_OK, wombatQueue_destroy(queue[i])); } } /* Description: Creates a Queue, sets a new max size, gets that max size * and compares the two. * * Expected Result: newsize=checksize=3000 */ TEST_F (CommonQueueTestC, SetGetMaxSize) { wombatQueue queue = NULL; uint32_t maxSize = 1000; uint32_t initialSize = 10; uint32_t growBySize = 100; unsigned int newMaxSize = 3000; unsigned int checkMaxSize = 0; ASSERT_EQ (WOMBAT_QUEUE_OK, wombatQueue_allocate(&queue)); ASSERT_EQ (WOMBAT_QUEUE_OK, wombatQueue_create(queue, maxSize, initialSize, growBySize)); ASSERT_EQ (WOMBAT_QUEUE_OK, wombatQueue_setMaxSize(queue, newMaxSize)); ASSERT_EQ (WOMBAT_QUEUE_OK, wombatQueue_getMaxSize(queue, &checkMaxSize)); ASSERT_EQ (newMaxSize, checkMaxSize); ASSERT_EQ (WOMBAT_QUEUE_OK, wombatQueue_destroy(queue)); } /* Description: Creates a queue and enqueues 200 events. getSize * is then called which gives the number of undispatched * events on queue. * * Expected Result: size=200 */ TEST_F (CommonQueueTestC, getSize) { wombatQueue queue = NULL; uint32_t maxSize = 1000; uint32_t initialSize = 10; uint32_t growBySize = 100; int size = 0; void* data = NULL; void* closure = NULL; ASSERT_EQ (WOMBAT_QUEUE_OK, wombatQueue_allocate(&queue)); ASSERT_EQ (WOMBAT_QUEUE_OK, wombatQueue_create(queue, maxSize, initialSize, growBySize)); for(int i=0;i<200;i++) { ASSERT_EQ (WOMBAT_QUEUE_OK, wombatQueue_enqueue(queue, onEvent, &data, &closure)); } ASSERT_EQ (WOMBAT_QUEUE_OK, wombatQueue_getSize(queue,&size)); ASSERT_EQ (200, size); ASSERT_EQ (WOMBAT_QUEUE_OK, wombatQueue_destroy(queue)); } /* Description: Creates a queue, enqueues event, dispatches it then * queue is destroyed. * * Expected Result: WOMBAT_QUEUE_OK */ TEST_F (CommonQueueTestC, EnqueueDispatch) { wombatQueue queue = NULL; uint32_t maxSize = 1000; uint32_t initialSize = 10; uint32_t growBySize = 100; void* data = NULL; void* closure = NULL; ASSERT_EQ (WOMBAT_QUEUE_OK, wombatQueue_allocate(&queue)); ASSERT_EQ (WOMBAT_QUEUE_OK, wombatQueue_create(queue, maxSize, initialSize, growBySize)); ASSERT_EQ (WOMBAT_QUEUE_OK, wombatQueue_enqueue (queue, onEvent, data, closure)); ASSERT_EQ (WOMBAT_QUEUE_OK, wombatQueue_dispatch (queue, &data, &closure)); ASSERT_EQ (WOMBAT_QUEUE_OK, wombatQueue_destroy (queue)); } /* Description: Creates a queue, enqueues 200 events, dispatches them then * queue is destroyed. * * Expected Result: WOMBAT_QUEUE_OK */ TEST_F (CommonQueueTestC, EnqueueDispatchMany) { wombatQueue queue = NULL; uint32_t maxSize = 1000; uint32_t initialSize = 10; uint32_t growBySize = 100; void* data = NULL; void* closure = NULL; ASSERT_EQ (WOMBAT_QUEUE_OK, wombatQueue_allocate(&queue)); ASSERT_EQ (WOMBAT_QUEUE_OK, wombatQueue_create(queue, maxSize, initialSize, growBySize)); for(int i=0;i<200;i++) { ASSERT_EQ (WOMBAT_QUEUE_OK, wombatQueue_enqueue(queue, onEvent, data, closure)); } for(int i=0;i<200;i++) { ASSERT_EQ (WOMBAT_QUEUE_OK, wombatQueue_dispatch(queue, &data, &closure)); } ASSERT_EQ (WOMBAT_QUEUE_OK, wombatQueue_destroy(queue)); } /* Description: Creates a queue and enqueues 200 events. timedDispatched * waits 500 microseconds then dispatches each event. * * Expected Result: WOMBAT_QUEUE_OK */ TEST_F (CommonQueueTestC, TimedDispatch) { wombatQueue queue = NULL; uint32_t maxSize = 1000; uint32_t initialSize = 10; uint32_t growBySize = 100; uint64_t timeout = 500; void* data = NULL; void* closure = NULL; ASSERT_EQ (WOMBAT_QUEUE_OK, wombatQueue_allocate(&queue)); ASSERT_EQ (WOMBAT_QUEUE_OK, wombatQueue_create(queue, maxSize, initialSize, growBySize)); for(int i=0;i<200;i++) { ASSERT_EQ (WOMBAT_QUEUE_OK, wombatQueue_enqueue(queue, onEvent, &data, &closure)); } for(int i=0;i<200;i++) { ASSERT_EQ (WOMBAT_QUEUE_OK, wombatQueue_timedDispatch(queue, &data, &closure, timeout)); } ASSERT_EQ (WOMBAT_QUEUE_OK, wombatQueue_destroy(queue)); } /* Description: Enqueues 3 events, then polls 4 times to dispatch the 3 * events and return status. * * Expected Result: WOMBAT_QUEUE_WOULD_BLOCK */ TEST_F (CommonQueueTestC, Poll) { wombatQueue queue = NULL; uint32_t maxSize = 1000; uint32_t initialSize = 10; uint32_t growBySize = 100; void* data = NULL; void* closure = NULL; ASSERT_EQ (WOMBAT_QUEUE_OK, wombatQueue_allocate(&queue)); ASSERT_EQ (WOMBAT_QUEUE_OK, wombatQueue_create(queue, maxSize, initialSize, growBySize)); for(int i=0;i<3;i++) { ASSERT_EQ (WOMBAT_QUEUE_OK, wombatQueue_enqueue (queue, onEvent, data, closure)); } for(int i=0;i<3;i++) { ASSERT_EQ (WOMBAT_QUEUE_OK, wombatQueue_poll(queue, &data, &closure)); } ASSERT_EQ (WOMBAT_QUEUE_WOULD_BLOCK, wombatQueue_poll(queue, &data, &closure)); ASSERT_EQ (WOMBAT_QUEUE_OK, wombatQueue_destroy (queue)); } /* Description: Allocates space for 100 queues, enqueues and dispatches * 200 events on each queue then queues are destroyed. * * Expected Result: WOMBAT_QUEUE_OK */ TEST_F (CommonQueueTestC, EnqueueDispatchManyQueues) { wombatQueue queue[100] = {NULL}; uint32_t maxSize = 1000; uint32_t initialSize = 10; uint32_t growBySize = 100; void* data = NULL; void* closure = NULL; for(int i=0;i<100;i++) { ASSERT_EQ (WOMBAT_QUEUE_OK, wombatQueue_allocate(&queue[i])); } for(int i=0;i<100;i++) { ASSERT_EQ (WOMBAT_QUEUE_OK, wombatQueue_create(queue[i], maxSize, initialSize, growBySize)); } for(int i=0;i<100;i++) { for(int x=0;x<200;x++) { ASSERT_EQ (WOMBAT_QUEUE_OK, wombatQueue_enqueue(queue[i], onEvent, data, closure)); } } for(int i=0;i<100;i++) { for(int x=0;x<200;x++) { ASSERT_EQ (WOMBAT_QUEUE_OK, wombatQueue_dispatch(queue[i], &data, &closure)); } } for(int i=0;i<100;i++) { ASSERT_EQ (WOMBAT_QUEUE_OK, wombatQueue_destroy (queue[i])); } } <commit_msg>Issue: Mama-5329 Submitted by: Adrienne Ambrose Reviewed by: Ian Bell Description: Modification as wombatQueue_enqueue does not free a lock if it is attempting to enqueue an already full queue.<commit_after>/* $Id: queuetest.cpp,v 1.1.2.1 2012/11/21 10:03:55 matthewmulhern Exp $ * * OpenMAMA: The open middleware agnostic messaging API * Copyright (C) 2011 NYSE Technologies, Inc. * * 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 <gtest/gtest.h> #include "MainUnitTestC.h" #include "wombat/wConfig.h" #include <sys/types.h> #include <cstring> #include <cstdio> #include <cstdlib> #include "wombat/port.h" #include "wombat/queue.h" #include "wombat/wSemaphore.h" class CommonQueueTestC : public ::testing::Test { protected: CommonQueueTestC(); virtual ~CommonQueueTestC(); virtual void SetUp(); virtual void TearDown (); public: }; CommonQueueTestC::CommonQueueTestC() { } CommonQueueTestC::~CommonQueueTestC() { } void CommonQueueTestC::SetUp(void) { } void CommonQueueTestC::TearDown(void) { } #if defined(__cplusplus) extern "C" { #endif static void MAMACALLTYPE onEvent(wombatQueue queue, void* closure) { } #if defined(__cplusplus) } #endif /* ************************************************************************* */ /* Test Functions */ /* ************************************************************************* */ /* Description: Allocates space for a queue * * Expected Result: WOMBAT_QUEUE_OK */ TEST_F (CommonQueueTestC, allocate) { wombatQueue queue = NULL; ASSERT_EQ (WOMBAT_QUEUE_OK, wombatQueue_allocate(&queue)); free (queue); } /* Description: Allocates space for a queue, creates it then destroys it. * * Expected Result: WOMBAT_QUEUE_OK */ TEST_F (CommonQueueTestC, createDestroy) { wombatQueue queue = NULL; uint32_t maxSize = 1000; uint32_t initialSize = 10; uint32_t growBySize = 100; ASSERT_EQ (WOMBAT_QUEUE_OK, wombatQueue_allocate(&queue)); ASSERT_EQ (WOMBAT_QUEUE_OK, wombatQueue_create(queue, maxSize, initialSize, growBySize)); ASSERT_EQ (WOMBAT_QUEUE_OK, wombatQueue_destroy(queue)); } /* Description: Allocates space for 100 queues, creates them then * destroys them. * * Expected Result: WOMBAT_QUEUE_OK */ TEST_F (CommonQueueTestC, createDestroyMany) { wombatQueue queue[100] = {NULL}; uint32_t maxSize = 1000; uint32_t initialSize = 10; uint32_t growBySize = 100; for(int i=0;i<100;i++) { ASSERT_EQ (WOMBAT_QUEUE_OK, wombatQueue_allocate(&queue[i])); } for(int i=0;i<100;i++) { ASSERT_EQ (WOMBAT_QUEUE_OK, wombatQueue_create(queue[i], maxSize, initialSize, growBySize)); } for(int i=0;i<100;i++) { ASSERT_EQ (WOMBAT_QUEUE_OK, wombatQueue_destroy(queue[i])); } } /* Description: Creates a Queue, sets a new max size, gets that max size * and compares the two. * * Expected Result: newsize=checksize=3000 */ TEST_F (CommonQueueTestC, SetGetMaxSize) { wombatQueue queue = NULL; uint32_t maxSize = 1000; uint32_t initialSize = 10; uint32_t growBySize = 100; unsigned int newMaxSize = 3000; unsigned int checkMaxSize = 0; ASSERT_EQ (WOMBAT_QUEUE_OK, wombatQueue_allocate(&queue)); ASSERT_EQ (WOMBAT_QUEUE_OK, wombatQueue_create(queue, maxSize, initialSize, growBySize)); ASSERT_EQ (WOMBAT_QUEUE_OK, wombatQueue_setMaxSize(queue, newMaxSize)); ASSERT_EQ (WOMBAT_QUEUE_OK, wombatQueue_getMaxSize(queue, &checkMaxSize)); ASSERT_EQ (newMaxSize, checkMaxSize); ASSERT_EQ (WOMBAT_QUEUE_OK, wombatQueue_destroy(queue)); } /* Description: Creates a queue and enqueues 200 events. getSize * is then called which gives the number of undispatched * events on queue. * * Expected Result: size=200 */ TEST_F (CommonQueueTestC, getSize) { wombatQueue queue = NULL; uint32_t maxSize = 1000; uint32_t initialSize = 10; uint32_t growBySize = 100; int size = 0; void* data = NULL; void* closure = NULL; ASSERT_EQ (WOMBAT_QUEUE_OK, wombatQueue_allocate(&queue)); ASSERT_EQ (WOMBAT_QUEUE_OK, wombatQueue_create(queue, maxSize, initialSize, growBySize)); for(int i=0;i<200;i++) { ASSERT_EQ (WOMBAT_QUEUE_OK, wombatQueue_enqueue(queue, onEvent, &data, &closure)); } ASSERT_EQ (WOMBAT_QUEUE_OK, wombatQueue_getSize(queue,&size)); ASSERT_EQ (200, size); ASSERT_EQ (WOMBAT_QUEUE_OK, wombatQueue_destroy(queue)); } /* Description: Creates a queue, enqueues event, dispatches it then * queue is destroyed. * * Expected Result: WOMBAT_QUEUE_OK */ TEST_F (CommonQueueTestC, EnqueueDispatch) { wombatQueue queue = NULL; uint32_t maxSize = 1000; uint32_t initialSize = 10; uint32_t growBySize = 100; void* data = NULL; void* closure = NULL; ASSERT_EQ (WOMBAT_QUEUE_OK, wombatQueue_allocate(&queue)); ASSERT_EQ (WOMBAT_QUEUE_OK, wombatQueue_create(queue, maxSize, initialSize, growBySize)); ASSERT_EQ (WOMBAT_QUEUE_OK, wombatQueue_enqueue (queue, onEvent, data, closure)); ASSERT_EQ (WOMBAT_QUEUE_OK, wombatQueue_dispatch (queue, &data, &closure)); ASSERT_EQ (WOMBAT_QUEUE_OK, wombatQueue_destroy (queue)); } /* Description: Creates a queue, enqueues 200 events, dispatches them then * queue is destroyed. * * Expected Result: WOMBAT_QUEUE_OK */ TEST_F (CommonQueueTestC, EnqueueDispatchMany) { wombatQueue queue = NULL; uint32_t maxSize = 1000; uint32_t initialSize = 10; uint32_t growBySize = 100; void* data = NULL; void* closure = NULL; ASSERT_EQ (WOMBAT_QUEUE_OK, wombatQueue_allocate(&queue)); ASSERT_EQ (WOMBAT_QUEUE_OK, wombatQueue_create(queue, maxSize, initialSize, growBySize)); for(int i=0;i<200;i++) { ASSERT_EQ (WOMBAT_QUEUE_OK, wombatQueue_enqueue(queue, onEvent, data, closure)); } for(int i=0;i<200;i++) { ASSERT_EQ (WOMBAT_QUEUE_OK, wombatQueue_dispatch(queue, &data, &closure)); } ASSERT_EQ (WOMBAT_QUEUE_OK, wombatQueue_destroy(queue)); } /* Description: Creates a queue and enqueues 200 events. timedDispatched * waits 500 microseconds then dispatches each event. * * Expected Result: WOMBAT_QUEUE_OK */ TEST_F (CommonQueueTestC, TimedDispatch) { wombatQueue queue = NULL; uint32_t maxSize = 1000; uint32_t initialSize = 10; uint32_t growBySize = 100; uint64_t timeout = 500; void* data = NULL; void* closure = NULL; ASSERT_EQ (WOMBAT_QUEUE_OK, wombatQueue_allocate(&queue)); ASSERT_EQ (WOMBAT_QUEUE_OK, wombatQueue_create(queue, maxSize, initialSize, growBySize)); for(int i=0;i<200;i++) { ASSERT_EQ (WOMBAT_QUEUE_OK, wombatQueue_enqueue(queue, onEvent, &data, &closure)); } for(int i=0;i<200;i++) { ASSERT_EQ (WOMBAT_QUEUE_OK, wombatQueue_timedDispatch(queue, &data, &closure, timeout)); } ASSERT_EQ (WOMBAT_QUEUE_OK, wombatQueue_destroy(queue)); } /* Description: Enqueues 3 events, then polls 4 times to dispatch the 3 * events and return status. * * Expected Result: WOMBAT_QUEUE_WOULD_BLOCK */ TEST_F (CommonQueueTestC, Poll) { wombatQueue queue = NULL; uint32_t maxSize = 1000; uint32_t initialSize = 10; uint32_t growBySize = 100; void* data = NULL; void* closure = NULL; ASSERT_EQ (WOMBAT_QUEUE_OK, wombatQueue_allocate(&queue)); ASSERT_EQ (WOMBAT_QUEUE_OK, wombatQueue_create(queue, maxSize, initialSize, growBySize)); for(int i=0;i<3;i++) { ASSERT_EQ (WOMBAT_QUEUE_OK, wombatQueue_enqueue (queue, onEvent, data, closure)); } for(int i=0;i<3;i++) { ASSERT_EQ (WOMBAT_QUEUE_OK, wombatQueue_poll(queue, &data, &closure)); } ASSERT_EQ (WOMBAT_QUEUE_WOULD_BLOCK, wombatQueue_poll(queue, &data, &closure)); ASSERT_EQ (WOMBAT_QUEUE_OK, wombatQueue_destroy (queue)); } /* Description: Allocates space for 100 queues, enqueues and dispatches * 200 events on each queue then queues are destroyed. * * Expected Result: WOMBAT_QUEUE_OK */ TEST_F (CommonQueueTestC, EnqueueDispatchManyQueues) { wombatQueue queue[100] = {NULL}; uint32_t maxSize = 1000; uint32_t initialSize = 10; uint32_t growBySize = 100; void* data = NULL; void* closure = NULL; for(int i=0;i<100;i++) { ASSERT_EQ (WOMBAT_QUEUE_OK, wombatQueue_allocate(&queue[i])); } for(int i=0;i<100;i++) { ASSERT_EQ (WOMBAT_QUEUE_OK, wombatQueue_create(queue[i], maxSize, initialSize, growBySize)); } for(int i=0;i<100;i++) { for(int x=0;x<200;x++) { ASSERT_EQ (WOMBAT_QUEUE_OK, wombatQueue_enqueue(queue[i], onEvent, data, closure)); } } for(int i=0;i<100;i++) { for(int x=0;x<200;x++) { ASSERT_EQ (WOMBAT_QUEUE_OK, wombatQueue_dispatch(queue[i], &data, &closure)); } } for(int i=0;i<100;i++) { ASSERT_EQ (WOMBAT_QUEUE_OK, wombatQueue_destroy (queue[i])); } } /* Description: Creates a queue then attempts to enqueue more * events than max size. * * Expected Result: WOMBAT_QUEUE_OK */ TEST_F (CommonQueueTestC, EnqueueMoreThanMaxSize) { wombatQueue queue = NULL; uint32_t maxSize = 100; uint32_t initialSize = 100; uint32_t growBySize = 100; int toEnqueue = 101; void* data = NULL; void* closure = NULL; ASSERT_EQ (WOMBAT_QUEUE_OK, wombatQueue_allocate(&queue)); EXPECT_EQ (WOMBAT_QUEUE_OK, wombatQueue_create(queue, maxSize, initialSize, growBySize)); /*Enqueue 100 items, the maximum allowed in the queue when created.*/ for(int i=0;i!=(toEnqueue-1);i++) { EXPECT_EQ (WOMBAT_QUEUE_OK, wombatQueue_enqueue (queue, onEvent, data, closure)); } /*Try to enqueue one more than the maximum amount, the call to * *wombatQueue_enqueue should fail and retuen WOMBAT_QUEUE_FULL */ EXPECT_EQ (WOMBAT_QUEUE_FULL, wombatQueue_enqueue (queue, onEvent, data, closure)); ASSERT_EQ (WOMBAT_QUEUE_OK, wombatQueue_destroy (queue)); } <|endoftext|>
<commit_before>/* * Copyright (c) 2015 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 "webrtc/common_audio/audio_ring_buffer.h" #include "testing/gtest/include/gtest/gtest.h" #include "webrtc/modules/audio_processing/channel_buffer.h" namespace webrtc { class AudioRingBufferTest : public ::testing::TestWithParam< ::testing::tuple<int, int, int, int> > { }; void ReadAndWriteTest(const ChannelBuffer<float>& input, size_t num_write_chunk_frames, size_t num_read_chunk_frames, size_t buffer_frames, ChannelBuffer<float>* output) { const size_t num_channels = input.num_channels(); const size_t total_frames = input.samples_per_channel(); AudioRingBuffer buf(num_channels, buffer_frames); scoped_ptr<float*[]> slice(new float*[num_channels]); size_t input_pos = 0; size_t output_pos = 0; while (input_pos + buf.WriteFramesAvailable() < total_frames) { // Write until the buffer is as full as possible. while (buf.WriteFramesAvailable() >= num_write_chunk_frames) { buf.Write(input.Slice(slice.get(), static_cast<int>(input_pos)), num_channels, num_write_chunk_frames); input_pos += num_write_chunk_frames; } // Read until the buffer is as empty as possible. while (buf.ReadFramesAvailable() >= num_read_chunk_frames) { EXPECT_LT(output_pos, total_frames); buf.Read(output->Slice(slice.get(), static_cast<int>(output_pos)), num_channels, num_read_chunk_frames); output_pos += num_read_chunk_frames; } } // Write and read the last bit. if (input_pos < total_frames) buf.Write(input.Slice(slice.get(), static_cast<int>(input_pos)), num_channels, total_frames - input_pos); if (buf.ReadFramesAvailable()) buf.Read(output->Slice(slice.get(), static_cast<int>(output_pos)), num_channels, buf.ReadFramesAvailable()); EXPECT_EQ(0u, buf.ReadFramesAvailable()); } TEST_P(AudioRingBufferTest, ReadDataMatchesWrittenData) { const size_t kFrames = 5000; const size_t num_channels = ::testing::get<3>(GetParam()); // Initialize the input data to an increasing sequence. ChannelBuffer<float> input(kFrames, static_cast<int>(num_channels)); for (size_t i = 0; i < num_channels; ++i) for (size_t j = 0; j < kFrames; ++j) input.channels()[i][j] = i * j; ChannelBuffer<float> output(kFrames, static_cast<int>(num_channels)); ReadAndWriteTest(input, ::testing::get<0>(GetParam()), ::testing::get<1>(GetParam()), ::testing::get<2>(GetParam()), &output); // Verify the read data matches the input. for (size_t i = 0; i < num_channels; ++i) for (size_t j = 0; j < kFrames; ++j) EXPECT_EQ(input.channels()[i][j], output.channels()[i][j]); } INSTANTIATE_TEST_CASE_P( AudioRingBufferTest, AudioRingBufferTest, ::testing::Combine(::testing::Values(10, 20, 42), // num_write_chunk_frames ::testing::Values(1, 10, 17), // num_read_chunk_frames ::testing::Values(100, 256), // buffer_frames ::testing::Values(1, 4))); // num_channels TEST_F(AudioRingBufferTest, MoveReadPosition) { const size_t kNumChannels = 1; const float kInputArray[] = {1, 2, 3, 4}; const size_t kNumFrames = sizeof(kInputArray) / sizeof(*kInputArray); ChannelBuffer<float> input(kInputArray, kNumFrames, kNumChannels); AudioRingBuffer buf(kNumChannels, kNumFrames); buf.Write(input.channels(), kNumChannels, kNumFrames); buf.MoveReadPosition(3); ChannelBuffer<float> output(1, kNumChannels); buf.Read(output.channels(), kNumChannels, 1); EXPECT_EQ(4, output.data()[0]); buf.MoveReadPosition(-3); buf.Read(output.channels(), kNumChannels, 1); EXPECT_EQ(2, output.data()[0]); } } // namespace webrtc <commit_msg>Use non-zero data in AudioRingBufferTest.<commit_after>/* * Copyright (c) 2015 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 "webrtc/common_audio/audio_ring_buffer.h" #include "testing/gtest/include/gtest/gtest.h" #include "webrtc/modules/audio_processing/channel_buffer.h" namespace webrtc { class AudioRingBufferTest : public ::testing::TestWithParam< ::testing::tuple<int, int, int, int> > { }; void ReadAndWriteTest(const ChannelBuffer<float>& input, size_t num_write_chunk_frames, size_t num_read_chunk_frames, size_t buffer_frames, ChannelBuffer<float>* output) { const size_t num_channels = input.num_channels(); const size_t total_frames = input.samples_per_channel(); AudioRingBuffer buf(num_channels, buffer_frames); scoped_ptr<float*[]> slice(new float*[num_channels]); size_t input_pos = 0; size_t output_pos = 0; while (input_pos + buf.WriteFramesAvailable() < total_frames) { // Write until the buffer is as full as possible. while (buf.WriteFramesAvailable() >= num_write_chunk_frames) { buf.Write(input.Slice(slice.get(), static_cast<int>(input_pos)), num_channels, num_write_chunk_frames); input_pos += num_write_chunk_frames; } // Read until the buffer is as empty as possible. while (buf.ReadFramesAvailable() >= num_read_chunk_frames) { EXPECT_LT(output_pos, total_frames); buf.Read(output->Slice(slice.get(), static_cast<int>(output_pos)), num_channels, num_read_chunk_frames); output_pos += num_read_chunk_frames; } } // Write and read the last bit. if (input_pos < total_frames) buf.Write(input.Slice(slice.get(), static_cast<int>(input_pos)), num_channels, total_frames - input_pos); if (buf.ReadFramesAvailable()) buf.Read(output->Slice(slice.get(), static_cast<int>(output_pos)), num_channels, buf.ReadFramesAvailable()); EXPECT_EQ(0u, buf.ReadFramesAvailable()); } TEST_P(AudioRingBufferTest, ReadDataMatchesWrittenData) { const size_t kFrames = 5000; const size_t num_channels = ::testing::get<3>(GetParam()); // Initialize the input data to an increasing sequence. ChannelBuffer<float> input(kFrames, static_cast<int>(num_channels)); for (size_t i = 0; i < num_channels; ++i) for (size_t j = 0; j < kFrames; ++j) input.channels()[i][j] = (i + 1) * (j + 1); ChannelBuffer<float> output(kFrames, static_cast<int>(num_channels)); ReadAndWriteTest(input, ::testing::get<0>(GetParam()), ::testing::get<1>(GetParam()), ::testing::get<2>(GetParam()), &output); // Verify the read data matches the input. for (size_t i = 0; i < num_channels; ++i) for (size_t j = 0; j < kFrames; ++j) EXPECT_EQ(input.channels()[i][j], output.channels()[i][j]); } INSTANTIATE_TEST_CASE_P( AudioRingBufferTest, AudioRingBufferTest, ::testing::Combine(::testing::Values(10, 20, 42), // num_write_chunk_frames ::testing::Values(1, 10, 17), // num_read_chunk_frames ::testing::Values(100, 256), // buffer_frames ::testing::Values(1, 4))); // num_channels TEST_F(AudioRingBufferTest, MoveReadPosition) { const size_t kNumChannels = 1; const float kInputArray[] = {1, 2, 3, 4}; const size_t kNumFrames = sizeof(kInputArray) / sizeof(*kInputArray); ChannelBuffer<float> input(kInputArray, kNumFrames, kNumChannels); AudioRingBuffer buf(kNumChannels, kNumFrames); buf.Write(input.channels(), kNumChannels, kNumFrames); buf.MoveReadPosition(3); ChannelBuffer<float> output(1, kNumChannels); buf.Read(output.channels(), kNumChannels, 1); EXPECT_EQ(4, output.data()[0]); buf.MoveReadPosition(-3); buf.Read(output.channels(), kNumChannels, 1); EXPECT_EQ(2, output.data()[0]); } } // namespace webrtc <|endoftext|>
<commit_before>#pragma once namespace densitas { namespace model_adapter { /** * Trains the model with given features X and target y. y should be * a binary target containing 'yes' and 'no' */ template<typename ModelType, typename MatrixType, typename VectorType> void train(ModelType& model, MatrixType& X, VectorType& y) { model.train(X, y); } /** * Predicts events using a trained model for given features X. Should * return probability values between 0 and 1 */ template<typename VectorType, typename ModelType, typename MatrixType> VectorType predict_proba(const ModelType& model, MatrixType& X) { return model.predict_proba(X); } /** * Returns the numerical representation of 'yes' as valid for the model type */ template<typename ModelType> constexpr int yes() { return 1; } /** * Returns the numerical representation of 'no' as valid for the model type */ template<typename ModelType> constexpr int no() { return -1; } } // model_adapter } // densitas <commit_msg>predict_proba may not be declared const<commit_after>#pragma once namespace densitas { namespace model_adapter { /** * Trains the model with given features X and target y. y should be * a binary target containing 'yes' and 'no' */ template<typename ModelType, typename MatrixType, typename VectorType> void train(ModelType& model, MatrixType& X, VectorType& y) { model.train(X, y); } /** * Predicts events using a trained model for given features X. Should * return probability values between 0 and 1 */ template<typename VectorType, typename ModelType, typename MatrixType> VectorType predict_proba(ModelType& model, MatrixType& X) { return model.predict_proba(X); } /** * Returns the numerical representation of 'yes' as valid for the model type */ template<typename ModelType> constexpr int yes() { return 1; } /** * Returns the numerical representation of 'no' as valid for the model type */ template<typename ModelType> constexpr int no() { return -1; } } // model_adapter } // densitas <|endoftext|>
<commit_before><commit_msg>Expr::EvaluateAs... does not work for type-dependent expressions<commit_after><|endoftext|>
<commit_before>/** * @author ChalkPE <chalk@chalk.pe> * @since 2016-06-03 */ #include <stdio.h> int main(){ int i, n; scanf("%d", &n); for(i = 2; i <= n; i += 2) printf("%d ", i); } <commit_msg>Updated p1076<commit_after>/** * @author ChalkPE <chalk@chalk.pe> * @since 2016-06-03 */ #include <stdio.h> int main(){ int n, i; for(scanf("%d", &n), i = 2; i <= n; i += 2) printf("%d ", i); } <|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 "src/libfuzzer/libfuzzer_mutator.h" #include <string.h> #include <cassert> #include <memory> #include <string> #include "port/protobuf.h" #include "src/mutator.h" // see compiler-rt/lib/sanitizer-common/sanitizer_internal_defs.h; usage of // SANITIZER_INTERFACE_WEAK_DEF is the same with some functionality removed #ifdef _MSC_VER #if defined(_M_IX86) || defined(__i386__) #define WIN_SYM_PREFIX "_" #else #define WIN_SYM_PREFIX #endif #define STRINGIFY_(A) #A #define STRINGIFY(A) STRINGIFY_(A) #define WEAK_DEFAULT_NAME(Name) Name##__def // clang-format off #define SANITIZER_INTERFACE_WEAK_DEF(ReturnType, Name, ...) \ __pragma(comment(linker, "/alternatename:" \ WIN_SYM_PREFIX STRINGIFY(Name) "=" \ WIN_SYM_PREFIX STRINGIFY(WEAK_DEFAULT_NAME(Name))))\ extern "C" ReturnType Name(__VA_ARGS__); \ extern "C" ReturnType WEAK_DEFAULT_NAME(Name)(__VA_ARGS__) // clang-format on #else #define SANITIZER_INTERFACE_WEAK_DEF(ReturnType, Name, ...) \ extern "C" __attribute__((weak)) ReturnType Name(__VA_ARGS__) #endif SANITIZER_INTERFACE_WEAK_DEF(size_t, LLVMFuzzerMutate, uint8_t*, size_t, size_t) { return 0; } namespace protobuf_mutator { namespace libfuzzer { namespace { template <class T> T MutateValue(T v) { size_t size = LLVMFuzzerMutate(reinterpret_cast<uint8_t*>(&v), sizeof(v), sizeof(v)); memset(reinterpret_cast<uint8_t*>(&v) + size, 0, sizeof(v) - size); return v; } } // namespace int32_t Mutator::MutateInt32(int32_t value) { return MutateValue(value); } int64_t Mutator::MutateInt64(int64_t value) { return MutateValue(value); } uint32_t Mutator::MutateUInt32(uint32_t value) { return MutateValue(value); } uint64_t Mutator::MutateUInt64(uint64_t value) { return MutateValue(value); } float Mutator::MutateFloat(float value) { return MutateValue(value); } double Mutator::MutateDouble(double value) { return MutateValue(value); } std::string Mutator::MutateString(const std::string& value, size_t size_increase_hint) { // Randomly return empty strings as LLVMFuzzerMutate does not produce them. // Use uint16_t because on Windows, uniform_int_distribution does not support // any 8 bit types. if (!std::uniform_int_distribution<uint16_t>(0, 20)(*random())) return {}; std::string result = value; result.resize(value.size() + size_increase_hint); if (result.empty()) result.push_back(0); result.resize(LLVMFuzzerMutate(reinterpret_cast<uint8_t*>(&result[0]), value.size(), result.size())); return result; } } // namespace libfuzzer } // namespace protobuf_mutator <commit_msg>Renames SANITIZER_INTERFACE_WEAK_DEF to LIB_PROTO_MUTATOR_WEAK_DEF<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 "src/libfuzzer/libfuzzer_mutator.h" #include <string.h> #include <cassert> #include <memory> #include <string> #include "port/protobuf.h" #include "src/mutator.h" // see compiler-rt/lib/sanitizer-common/sanitizer_internal_defs.h; usage same as // SANITIZER_INTERFACE_WEAK_DEF with some functionality removed #ifdef _MSC_VER #if defined(_M_IX86) || defined(__i386__) #define WIN_SYM_PREFIX "_" #else #define WIN_SYM_PREFIX #endif #define STRINGIFY_(A) #A #define STRINGIFY(A) STRINGIFY_(A) #define WEAK_DEFAULT_NAME(Name) Name##__def // clang-format off #define LIB_PROTO_MUTATOR_WEAK_DEF(ReturnType, Name, ...) \ __pragma(comment(linker, "/alternatename:" \ WIN_SYM_PREFIX STRINGIFY(Name) "=" \ WIN_SYM_PREFIX STRINGIFY(WEAK_DEFAULT_NAME(Name))))\ extern "C" ReturnType Name(__VA_ARGS__); \ extern "C" ReturnType WEAK_DEFAULT_NAME(Name)(__VA_ARGS__) // clang-format on #else #define LIB_PROTO_MUTATOR_WEAK_DEF(ReturnType, Name, ...) \ extern "C" __attribute__((weak)) ReturnType Name(__VA_ARGS__) #endif LIB_PROTO_MUTATOR_WEAK_DEF(size_t, LLVMFuzzerMutate, uint8_t*, size_t, size_t) { return 0; } namespace protobuf_mutator { namespace libfuzzer { namespace { template <class T> T MutateValue(T v) { size_t size = LLVMFuzzerMutate(reinterpret_cast<uint8_t*>(&v), sizeof(v), sizeof(v)); memset(reinterpret_cast<uint8_t*>(&v) + size, 0, sizeof(v) - size); return v; } } // namespace int32_t Mutator::MutateInt32(int32_t value) { return MutateValue(value); } int64_t Mutator::MutateInt64(int64_t value) { return MutateValue(value); } uint32_t Mutator::MutateUInt32(uint32_t value) { return MutateValue(value); } uint64_t Mutator::MutateUInt64(uint64_t value) { return MutateValue(value); } float Mutator::MutateFloat(float value) { return MutateValue(value); } double Mutator::MutateDouble(double value) { return MutateValue(value); } std::string Mutator::MutateString(const std::string& value, size_t size_increase_hint) { // Randomly return empty strings as LLVMFuzzerMutate does not produce them. // Use uint16_t because on Windows, uniform_int_distribution does not support // any 8 bit types. if (!std::uniform_int_distribution<uint16_t>(0, 20)(*random())) return {}; std::string result = value; result.resize(value.size() + size_increase_hint); if (result.empty()) result.push_back(0); result.resize(LLVMFuzzerMutate(reinterpret_cast<uint8_t*>(&result[0]), value.size(), result.size())); return result; } } // namespace libfuzzer } // namespace protobuf_mutator <|endoftext|>
<commit_before>#include <v8.h> #include <node.h> #include <node_buffer.h> #include <node_version.h> #include <zlib.h> #include <cstring> using namespace v8; using namespace node; // node v0.2 compatibility #if NODE_VERSION_AT_LEAST(0,3,0) #define Buffer_Data Buffer::Data #define Buffer_Length Buffer::Length #define Buffer_New Buffer::New #else inline char* Buffer_Data(Handle<Object> obj) { return (ObjectWrap::Unwrap<Buffer>(obj))->data(); } inline size_t Buffer_Length(Handle<Object> obj) { return (ObjectWrap::Unwrap<Buffer>(obj))->length(); } inline Buffer* Buffer_New(char* data, size_t length) { Buffer* buffer = Buffer::New(length); memcpy(buffer->data(), data, length); return buffer; } #endif z_stream deflate_s; class ZLib { public: static inline Handle<Value> Error(const char* msg = NULL) { return ThrowException(Exception::Error( String::New(msg ? msg : "Unknown Error"))); } static Handle<Value> Deflate(const Arguments& args) { HandleScope scope; if (args.Length() < 1 || !Buffer::HasInstance(args[0])) { return Error("Expected Buffer as first argument"); } Local<Object> input = args[0]->ToObject(); deflate_s.next_in = (Bytef*)Buffer_Data(input); int length = deflate_s.avail_in = Buffer_Length(input); int status; char* result = NULL; int compressed = 0; do { result = (char*)realloc(result, compressed + length); if (!result) return Error("Could not allocate memory"); deflate_s.avail_out = length; deflate_s.next_out = (Bytef*)result + compressed; status = deflate(&deflate_s, Z_FINISH); if (status != Z_STREAM_END && status != Z_OK) { free(result); return Error(deflate_s.msg); } compressed += (length - deflate_s.avail_out); } while (deflate_s.avail_out == 0); status = deflateReset(&deflate_s); if (status != Z_OK) { free(result); return Error(deflate_s.msg); } Buffer* output = Buffer_New(result, compressed); free(result); return scope.Close(Local<Value>::New(output->handle_)); } }; extern "C" void init (Handle<Object> target) { deflate_s.zalloc = Z_NULL; deflate_s.zfree = Z_NULL; deflate_s.opaque = Z_NULL; deflateInit(&deflate_s, Z_DEFAULT_COMPRESSION); NODE_SET_METHOD(target, "deflate", ZLib::Deflate); } <commit_msg>add inflate support<commit_after>#include <v8.h> #include <node.h> #include <node_buffer.h> #include <node_version.h> #include <zlib.h> #include <cstring> using namespace v8; using namespace node; // node v0.2.x compatibility #if NODE_VERSION_AT_LEAST(0,3,0) #define Buffer_Data Buffer::Data #define Buffer_Length Buffer::Length #define Buffer_New Buffer::New #else inline char* Buffer_Data(Handle<Object> obj) { return (ObjectWrap::Unwrap<Buffer>(obj))->data(); } inline size_t Buffer_Length(Handle<Object> obj) { return (ObjectWrap::Unwrap<Buffer>(obj))->length(); } inline Buffer* Buffer_New(char* data, size_t length) { Buffer* buffer = Buffer::New(length); memcpy(buffer->data(), data, length); return buffer; } #endif z_stream deflate_s; z_stream inflate_s; inline Handle<Value> ZLib_error(const char* msg = NULL) { return ThrowException(Exception::Error( String::New(msg ? msg : "Unknown Error"))); } #define ZLib_Xflate(x, factor) \ Handle<Value> ZLib_##x##flate(const Arguments& args) { \ HandleScope scope; \ \ if (args.Length() < 1 || !Buffer::HasInstance(args[0])) { \ return ZLib_error("Expected Buffer as first argument"); \ } \ \ Local<Object> input = args[0]->ToObject(); \ x##flate_s.next_in = (Bytef*)Buffer_Data(input); \ int length = x##flate_s.avail_in = Buffer_Length(input); \ \ int status; \ char* result = NULL; \ \ int compressed = 0; \ do { \ result = (char*)realloc(result, compressed + factor * length); \ if (!result) return ZLib_error("Could not allocate memory"); \ \ x##flate_s.avail_out = factor * length; \ x##flate_s.next_out = (Bytef*)result + compressed; \ \ status = x##flate(&x##flate_s, Z_FINISH); \ if (status != Z_STREAM_END && status != Z_OK) { \ free(result); \ return ZLib_error(x##flate_s.msg); \ } \ \ compressed += (factor * length - x##flate_s.avail_out); \ } while (x##flate_s.avail_out == 0); \ \ status = x##flateReset(&x##flate_s); \ if (status != Z_OK) { \ free(result); \ return ZLib_error(x##flate_s.msg); \ } \ \ Buffer* output = Buffer_New(result, compressed); \ free(result); \ return scope.Close(Local<Value>::New(output->handle_)); \ } ZLib_Xflate(de, 1); ZLib_Xflate(in, 2); extern "C" void init (Handle<Object> target) { deflate_s.zalloc = inflate_s.zalloc = Z_NULL; deflate_s.zfree = inflate_s.zfree = Z_NULL; deflate_s.opaque = inflate_s.opaque = Z_NULL; deflateInit(&deflate_s, Z_DEFAULT_COMPRESSION); inflateInit(&inflate_s); NODE_SET_METHOD(target, "deflate", ZLib_deflate); NODE_SET_METHOD(target, "inflate", ZLib_inflate); } <|endoftext|>
<commit_before>// tinygettext - A gettext replacement that works directly on .po files // Copyright (C) 2009 Ingo Ruhnke <grumbel@gmx.de> // // This program is free software; you can redistribute it and/or // modify it under the terms of the GNU General Public License // as published by the Free Software Foundation; either version 2 // of the License, or (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. #ifndef HEADER_TINYGETTEXT_PO_PARSER_HPP #define HEADER_TINYGETTEXT_PO_PARSER_HPP #include <iosfwd> #include "iconv.hpp" namespace tinygettext { class Dictionary; class POParser { private: std::string filename; std::istream& in; Dictionary& dict; bool use_fuzzy; bool running; bool eof; bool big5; int line_number; std::string current_line; IConv conv; POParser(const std::string& filename, std::istream& in_, Dictionary& dict_, bool use_fuzzy = true); ~POParser(); void parse_header(const std::string& header); void parse(); void next_line(); std::string get_string(unsigned int skip); void get_string_line(std::ostringstream& str,unsigned int skip); bool is_empty_line(); bool prefix(const char* ); void error(const std::string& msg) __attribute__((__noreturn__)); void warning(const std::string& msg); public: /** @param filename name of the istream, only used in error messages @param in stream from which the PO file is read. @param dict dictionary to which the strings are written */ static void parse(const std::string& filename, std::istream& in, Dictionary& dict); static bool pedantic; private: POParser (const POParser&); POParser& operator= (const POParser&); }; } // namespace tinygettext #endif /* EOF */ <commit_msg>VS doesn't like __attribute__<commit_after>// tinygettext - A gettext replacement that works directly on .po files // Copyright (C) 2009 Ingo Ruhnke <grumbel@gmx.de> // // This program is free software; you can redistribute it and/or // modify it under the terms of the GNU General Public License // as published by the Free Software Foundation; either version 2 // of the License, or (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. #ifndef HEADER_TINYGETTEXT_PO_PARSER_HPP #define HEADER_TINYGETTEXT_PO_PARSER_HPP #if !defined(__GNUC__) && !defined(__clang__) #define __attribute__( x ) #endif #include <iosfwd> #include "iconv.hpp" namespace tinygettext { class Dictionary; class POParser { private: std::string filename; std::istream& in; Dictionary& dict; bool use_fuzzy; bool running; bool eof; bool big5; int line_number; std::string current_line; IConv conv; POParser(const std::string& filename, std::istream& in_, Dictionary& dict_, bool use_fuzzy = true); ~POParser(); void parse_header(const std::string& header); void parse(); void next_line(); std::string get_string(unsigned int skip); void get_string_line(std::ostringstream& str,unsigned int skip); bool is_empty_line(); bool prefix(const char* ); void error(const std::string& msg) __attribute__((__noreturn__)); void warning(const std::string& msg); public: /** @param filename name of the istream, only used in error messages @param in stream from which the PO file is read. @param dict dictionary to which the strings are written */ static void parse(const std::string& filename, std::istream& in, Dictionary& dict); static bool pedantic; private: POParser (const POParser&); POParser& operator= (const POParser&); }; } // namespace tinygettext #endif /* EOF */ <|endoftext|>
<commit_before>/** @file A brief file description @section license License Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to you 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 "ts/ink_assert.h" #include "ts/ink_atomic.h" #include "ts/ink_resource.h" #include <execinfo.h> volatile int res_track_memory = 0; // Disabled by default std::map<const char *, Resource *> ResourceTracker::_resourceMap; ink_mutex ResourceTracker::resourceLock = PTHREAD_MUTEX_INITIALIZER; /** * Individual resource to keep track of. A map of these are in the ResourceTracker. */ class Resource { public: Resource() : _incrementCount(0), _decrementCount(0), _value(0), _symbol(NULL) { _name[0] = '\0'; } void increment(const int64_t size); int64_t getValue() const { return _value; } int64_t getIncrement() const { return _incrementCount; } int64_t getDecrement() const { return _decrementCount; } void setSymbol(const void *symbol) { _symbol = symbol; } void setName(const char *name) { strncpy(_name, name, sizeof(_name)); _name[sizeof(_name) - 1] = '\0'; } void setName(const void *symbol, const char *name) { Dl_info info; dladdr(symbol, &info); snprintf(_name, sizeof(_name), "%s/%s", name, info.dli_sname); } const char * getName() const { return _name; } const void * getSymbol() const { return _symbol; } private: int64_t _incrementCount; int64_t _decrementCount; int64_t _value; const void *_symbol; char _name[128]; }; void Resource::increment(const int64_t size) { ink_atomic_increment(&_value, size); if (size >= 0) { ink_atomic_increment(&_incrementCount, 1); } else { ink_atomic_increment(&_decrementCount, 1); } } void ResourceTracker::increment(const char *name, const int64_t size) { Resource &resource = lookup(name); const char *lookup_name = resource.getName(); if (lookup_name[0] == '\0') { resource.setName(name); } resource.increment(size); } void ResourceTracker::increment(const void *symbol, const int64_t size, const char *name) { Resource &resource = lookup((const char *)symbol); if (resource.getSymbol() == NULL && name != NULL) { resource.setName(symbol, name); resource.setSymbol(symbol); } resource.increment(size); } Resource & ResourceTracker::lookup(const char *name) { Resource *resource = NULL; ink_mutex_acquire(&resourceLock); std::map<const char *, Resource *>::iterator it = _resourceMap.find(name); if (it != _resourceMap.end()) { resource = it->second; } else { // create a new entry resource = new Resource; _resourceMap[name] = resource; } ink_mutex_release(&resourceLock); ink_release_assert(resource != NULL); return *resource; } void ResourceTracker::dump(FILE *fd) { if (!res_track_memory) { return; } int64_t total = 0; ink_mutex_acquire(&resourceLock); if (!_resourceMap.empty()) { fprintf(fd, "\n%-10s | %-10s | %-20s | %-10s | %-50s\n", "Allocs", "Frees", "Size In-use", "Avg Size", "Location"); fprintf(fd, "-----------|------------|----------------------|------------|" "--------------------------------------------------------------------\n"); for (std::map<const char *, Resource *>::const_iterator it = _resourceMap.begin(); it != _resourceMap.end(); ++it) { const Resource &resource = *it->second; if (resource.getIncrement() - resource.getDecrement()) { fprintf(fd, "%10" PRId64 " | %10" PRId64 " | %20" PRId64 " | %10" PRId64 " | %-50s\n", resource.getIncrement(), resource.getDecrement(), resource.getValue(), resource.getValue() / (resource.getIncrement() - resource.getDecrement()), resource.getName()); total += resource.getValue(); } } fprintf(fd, " %20" PRId64 " | | %-50s\n", total, "TOTAL"); } ink_mutex_release(&resourceLock); } <commit_msg>TS-3877: Add a tracking ClassAllocator to keep track of where the allocation happened Display entries where the Allocs are equal to the Frees<commit_after>/** @file A brief file description @section license License Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to you 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 "ts/ink_assert.h" #include "ts/ink_atomic.h" #include "ts/ink_resource.h" #include <execinfo.h> volatile int res_track_memory = 0; // Disabled by default std::map<const char *, Resource *> ResourceTracker::_resourceMap; ink_mutex ResourceTracker::resourceLock = PTHREAD_MUTEX_INITIALIZER; /** * Individual resource to keep track of. A map of these are in the ResourceTracker. */ class Resource { public: Resource() : _incrementCount(0), _decrementCount(0), _value(0), _symbol(NULL) { _name[0] = '\0'; } void increment(const int64_t size); int64_t getValue() const { return _value; } int64_t getIncrement() const { return _incrementCount; } int64_t getDecrement() const { return _decrementCount; } void setSymbol(const void *symbol) { _symbol = symbol; } void setName(const char *name) { strncpy(_name, name, sizeof(_name)); _name[sizeof(_name) - 1] = '\0'; } void setName(const void *symbol, const char *name) { Dl_info info; dladdr(symbol, &info); snprintf(_name, sizeof(_name), "%s/%s", name, info.dli_sname); } const char * getName() const { return _name; } const void * getSymbol() const { return _symbol; } private: int64_t _incrementCount; int64_t _decrementCount; int64_t _value; const void *_symbol; char _name[128]; }; void Resource::increment(const int64_t size) { ink_atomic_increment(&_value, size); if (size >= 0) { ink_atomic_increment(&_incrementCount, 1); } else { ink_atomic_increment(&_decrementCount, 1); } } void ResourceTracker::increment(const char *name, const int64_t size) { Resource &resource = lookup(name); const char *lookup_name = resource.getName(); if (lookup_name[0] == '\0') { resource.setName(name); } resource.increment(size); } void ResourceTracker::increment(const void *symbol, const int64_t size, const char *name) { Resource &resource = lookup((const char *)symbol); if (resource.getSymbol() == NULL && name != NULL) { resource.setName(symbol, name); resource.setSymbol(symbol); } resource.increment(size); } Resource & ResourceTracker::lookup(const char *name) { Resource *resource = NULL; ink_mutex_acquire(&resourceLock); std::map<const char *, Resource *>::iterator it = _resourceMap.find(name); if (it != _resourceMap.end()) { resource = it->second; } else { // create a new entry resource = new Resource; _resourceMap[name] = resource; } ink_mutex_release(&resourceLock); ink_release_assert(resource != NULL); return *resource; } void ResourceTracker::dump(FILE *fd) { if (!res_track_memory) { return; } int64_t total = 0; ink_mutex_acquire(&resourceLock); if (!_resourceMap.empty()) { fprintf(fd, "\n%-10s | %-10s | %-20s | %-10s | %-50s\n", "Allocs", "Frees", "Size In-use", "Avg Size", "Location"); fprintf(fd, "-----------|------------|----------------------|------------|" "--------------------------------------------------------------------\n"); for (std::map<const char *, Resource *>::const_iterator it = _resourceMap.begin(); it != _resourceMap.end(); ++it) { const Resource &resource = *it->second; int64_t average_size = 0; if (resource.getIncrement() - resource.getDecrement() > 0) { average_size = resource.getValue() / (resource.getIncrement() - resource.getDecrement()); } fprintf(fd, "%10" PRId64 " | %10" PRId64 " | %20" PRId64 " | %10" PRId64 " | %-50s\n", resource.getIncrement(), resource.getDecrement(), resource.getValue(), average_size, resource.getName()); total += resource.getValue(); } } fprintf(fd, " %20" PRId64 " | | %-50s\n", total, "TOTAL"); ink_mutex_release(&resourceLock); } <|endoftext|>
<commit_before>#ifndef SAVE_STATE_H # define SAVE_STATE_H # pragma once struct statebuf { void* sp; void* bp; void* label; }; #if defined(__GNUC__) static inline bool __attribute__((always_inline)) savestate( statebuf& ssb) noexcept { bool r; #if defined(i386) || defined(__i386) || defined(__i386__) asm volatile ( "movl %%esp, %0\n\t" // store sp "movl %%ebp, %1\n\t" // store bp "movl $1f, %2\n\t" // store label "movb $0, %3\n\t" // return false "jmp 2f\n\t" "1:" "movb $1, %3\n\t" // return true "2:" : "=m" (ssb.sp), "=m" (ssb.bp), "=m" (ssb.label), "=r" (r) : : "memory" ); #elif defined(__amd64__) || defined(__amd64) || defined(__x86_64__) || defined(__x86_64) asm volatile ( "movq %%rsp, %0\n\t" // store sp "movq %%rbp, %1\n\t" // store bp "movq $1f, %2\n\t" // store label "movb $0, %3\n\t" // return false "jmp 2f\n\t" "1:" "movb $1, %3\n\t" // return true "2:" : "=m" (ssb.sp), "=m" (ssb.bp), "=m" (ssb.label), "=r" (r) : : "memory" ); #elif defined(__aarch64__) asm volatile ( "mov x3, sp\n\t" "str x3, %0\n\t" // store sp "str x7, %1\n\t" // store fp "ldr x3, =1f\n\t" // load label into x3 "str x3, %2\n\t" // store x3 into label "mov %3, $0\n\t" // store 0 into result "b 2f\n\t" "1:" "mov %3, $1\n\t" // store 1 into result "2:" : "=m" (ssb.sp), "=m" (ssb.bp), "=m" (ssb.label), "=r" (r) : : "x3", "memory" ); #elif defined(__arm__) && defined(__ARM_ARCH_7__) asm volatile ( "str sp, %0\n\t" // store sp "str r7, %1\n\t" // store fp "ldr r3, =1f\n\t" // load label into r3 "str r3, %2\n\t" // store r3 into label "mov %3, $0\n\t" // store 0 into result "b 2f\n\t" "1:" "mov %3, $1\n\t" // store 1 into result "2:" : "=m" (ssb.sp), "=m" (ssb.bp), "=m" (ssb.label), "=r" (r) : : "r3", "memory" ); #elif defined(__arm__) asm volatile ( "str sp, %0\n\t" // store sp "str fp, %1\n\t" // store fp "ldr r3, =1f\n\t" // load label into r3 "str r3, %2\n\t" // store r3 into label "mov %3, $0\n\t" // store 0 into result "b 2f\n\t" "1:" "mov %3, $1\n\t" // store 1 into result "2:" : "=m" (ssb.sp), "=m" (ssb.bp), "=m" (ssb.label), "=r" (r) : : "r3", "memory" ); #endif return r; } #elif defined(_MSC_VER) __forceinline bool savestate(statebuf& ssb) noexcept { bool r; __asm { mov ebx, ssb mov [ebx]ssb.sp, esp mov [ebx]ssb.bp, ebp mov [ebx]ssb.label, offset _1f mov r, 0x0 jmp _2f _1f: mov r, 0x1 _2f: } return r; } #else # error "unsupported compiler" #endif #if defined(__GNUC__) #if defined(i386) || defined(__i386) || defined(__i386__) #define restorestate(SSB) \ asm volatile ( \ "movl %0, %%esp\n\t" \ "movl %1, %%ebp\n\t" \ "jmp *%2" \ : \ : "m" (SSB.sp), "r" (SSB.bp), "r" (SSB.label)\ ); #elif defined(__amd64__) || defined(__amd64) || defined(__x86_64__) || defined(__x86_64) #define restorestate(SSB) \ asm volatile ( \ "movq %0, %%rsp\n\t" \ "movq %1, %%rbp\n\t" \ "jmp *%2" \ : \ : "m" (SSB.sp), "r" (SSB.bp), "r" (SSB.label)\ ); #elif defined(__aarch64__) #define restorestate(SSB) \ asm volatile ( \ "mov sp, %0\n\t" \ "mov x7, %1\n\t" \ "ret %2" \ : \ : "r" (SSB.sp), "r" (SSB.bp), "r" (SSB.label)\ ); #elif defined(__arm__) && defined(__ARM_ARCH_7__) #define restorestate(SSB) \ asm volatile ( \ "ldr sp, %0\n\t" \ "mov r7, %1\n\t" \ "mov pc, %2" \ : \ : "m" (SSB.sp), "r" (SSB.bp), "r" (SSB.label)\ ); #elif defined(__arm__) #define restorestate(SSB) \ asm volatile ( \ "ldr sp, %0\n\t" \ "mov fp, %1\n\t" \ "mov pc, %2" \ : \ : "m" (SSB.sp), "r" (SSB.bp), "r" (SSB.label)\ ); #else # error "unsupported architecture" #endif #elif defined(_MSC_VER) #define restorestate(SSB) \ __asm mov ebx, this \ __asm add ebx, [SSB] \ __asm mov esp, [ebx]SSB.sp\ __asm mov ebp, [ebx]SSB.bp\ __asm jmp [ebx]SSB.label #else # error "unsupported compiler" #endif #endif // SAVE_STATE_H <commit_msg>some fixes<commit_after>#ifndef SAVE_STATE_H # define SAVE_STATE_H # pragma once struct statebuf { void* sp; void* bp; void* label; }; #if defined(__GNUC__) static inline bool __attribute__((always_inline)) savestate( statebuf& ssb) noexcept { bool r; #if defined(i386) || defined(__i386) || defined(__i386__) asm volatile ( "movl %%esp, %0\n\t" // store sp "movl %%ebp, %1\n\t" // store bp "movl $1f, %2\n\t" // store label "movb $0, %3\n\t" // return false "jmp 2f\n\t" "1:" "movb $1, %3\n\t" // return true "2:" : "=m" (ssb.sp), "=m" (ssb.bp), "=m" (ssb.label), "=r" (r) : : "memory" ); #elif defined(__amd64__) || defined(__amd64) || defined(__x86_64__) || defined(__x86_64) asm volatile ( "movq %%rsp, %0\n\t" // store sp "movq %%rbp, %1\n\t" // store bp "movq $1f, %2\n\t" // store label "movb $0, %3\n\t" // return false "jmp 2f\n\t" "1:" "movb $1, %3\n\t" // return true "2:" : "=m" (ssb.sp), "=m" (ssb.bp), "=m" (ssb.label), "=r" (r) : : "memory" ); #elif defined(__aarch64__) asm volatile ( "mov x3, sp\n\t" "str x3, %0\n\t" // store sp "str x7, %1\n\t" // store fp "ldr x3, =1f\n\t" // load label into x3 "str x3, %2\n\t" // store x3 into label "mov %3, #0\n\t" // store 0 into result "b 2f\n\t" "1:" "mov %3, #1\n\t" // store 1 into result "2:" : "=m" (ssb.sp), "=m" (ssb.bp), "=m" (ssb.label), "=r" (r) : : "x3", "memory" ); #elif defined(__arm__) && defined(__ARM_ARCH_7__) asm volatile ( "str sp, %0\n\t" // store sp "str r7, %1\n\t" // store fp "ldr r3, =1f\n\t" // load label into r3 "str r3, %2\n\t" // store r3 into label "mov %3, $0\n\t" // store 0 into result "b 2f\n\t" "1:" "mov %3, $1\n\t" // store 1 into result "2:" : "=m" (ssb.sp), "=m" (ssb.bp), "=m" (ssb.label), "=r" (r) : : "r3", "memory" ); #elif defined(__arm__) asm volatile ( "str sp, %0\n\t" // store sp "str fp, %1\n\t" // store fp "ldr r3, =1f\n\t" // load label into r3 "str r3, %2\n\t" // store r3 into label "mov %3, $0\n\t" // store 0 into result "b 2f\n\t" "1:" "mov %3, $1\n\t" // store 1 into result "2:" : "=m" (ssb.sp), "=m" (ssb.bp), "=m" (ssb.label), "=r" (r) : : "r3", "memory" ); #endif return r; } #elif defined(_MSC_VER) __forceinline bool savestate(statebuf& ssb) noexcept { bool r; __asm { mov ebx, ssb mov [ebx]ssb.sp, esp mov [ebx]ssb.bp, ebp mov [ebx]ssb.label, offset _1f mov r, 0x0 jmp _2f _1f: mov r, 0x1 _2f: } return r; } #else # error "unsupported compiler" #endif #if defined(__GNUC__) #if defined(i386) || defined(__i386) || defined(__i386__) #define restorestate(SSB) \ asm volatile ( \ "movl %0, %%esp\n\t" \ "movl %1, %%ebp\n\t" \ "jmp *%2" \ : \ : "m" (SSB.sp), "r" (SSB.bp), "r" (SSB.label)\ ); #elif defined(__amd64__) || defined(__amd64) || defined(__x86_64__) || defined(__x86_64) #define restorestate(SSB) \ asm volatile ( \ "movq %0, %%rsp\n\t" \ "movq %1, %%rbp\n\t" \ "jmp *%2" \ : \ : "m" (SSB.sp), "r" (SSB.bp), "r" (SSB.label)\ ); #elif defined(__aarch64__) #define restorestate(SSB) \ asm volatile ( \ "mov sp, %0\n\t" \ "mov x7, %1\n\t" \ "ret %2" \ : \ : "r" (SSB.sp), "r" (SSB.bp), "r" (SSB.label)\ ); #elif defined(__arm__) && defined(__ARM_ARCH_7__) #define restorestate(SSB) \ asm volatile ( \ "ldr sp, %0\n\t" \ "mov r7, %1\n\t" \ "mov pc, %2" \ : \ : "m" (SSB.sp), "r" (SSB.bp), "r" (SSB.label)\ ); #elif defined(__arm__) #define restorestate(SSB) \ asm volatile ( \ "ldr sp, %0\n\t" \ "mov fp, %1\n\t" \ "mov pc, %2" \ : \ : "m" (SSB.sp), "r" (SSB.bp), "r" (SSB.label)\ ); #else # error "unsupported architecture" #endif #elif defined(_MSC_VER) #define restorestate(SSB) \ __asm mov ebx, this \ __asm add ebx, [SSB] \ __asm mov esp, [ebx]SSB.sp\ __asm mov ebp, [ebx]SSB.bp\ __asm jmp [ebx]SSB.label #else # error "unsupported compiler" #endif #endif // SAVE_STATE_H <|endoftext|>
<commit_before>/** * @file * * Defines the operations freeze, thaw, finish, etc. These are overloaded * with the correct behaviour for types internal to the Birch type system, * with appropriate defaults or null operations for external types that may * be encountered in C++ interactions. */ #pragma once namespace libbirch { class Label; template<class T> auto clone(Label* label, T& o) { return o; } template<class T> void freeze(T& o) { // } template<class T> void thaw(T& o, Label* label) { // } template<class T> void finish(T& o) { // } template<class T> void freeze(std::function<T>& o) { assert(false); /// @todo Need to freeze any objects in the closure here, which may require /// a custom implementation of lambda functions in a similar way to fibers, /// rather than using std::function } template<class T> void thaw(Label* label, std::function<T>& o) { assert(false); /// @todo Need to thaw any objects in the closure here, which may require /// a custom implementation of lambda functions in a similar way to fibers, /// rather than using std::function } template<class T> void finish(std::function<T>& o) { assert(false); /// @todo Need to finish any objects in the closure here, which may require /// a custom implementation of lambda functions in a similar way to fibers, /// rather than using std::function } } <commit_msg>Added stub for libbirch::assign().<commit_after>/** * @file * * Defines the operations freeze, thaw, finish, etc. These are overloaded * with the correct behaviour for types internal to the Birch type system, * with appropriate defaults or null operations for external types that may * be encountered in C++ interactions. */ #pragma once namespace libbirch { class Label; template<class T, class... Args> auto construct(Label* context, Args... args) { return T(args...); } template<class T> auto clone(Label* context, Label* label, T& o) { return o; } template<class T, class U> auto assign(Label* context, T& left, const U& right) { return left; } template<class T> void freeze(T& o) { // } template<class T> void thaw(T& o, Label* label) { // } template<class T> void finish(T& o) { // } template<class T> void freeze(std::function<T>& o) { assert(false); /// @todo Need to freeze any objects in the closure here, which may require /// a custom implementation of lambda functions in a similar way to fibers, /// rather than using std::function } template<class T> void thaw(Label* label, std::function<T>& o) { assert(false); /// @todo Need to thaw any objects in the closure here, which may require /// a custom implementation of lambda functions in a similar way to fibers, /// rather than using std::function } template<class T> void finish(std::function<T>& o) { assert(false); /// @todo Need to finish any objects in the closure here, which may require /// a custom implementation of lambda functions in a similar way to fibers, /// rather than using std::function } } <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: testloader.cxx,v $ * * $Revision: 1.7 $ * * last change: $Author: hr $ $Date: 2002-08-19 14:19:55 $ * * 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): _______________________________________ * * ************************************************************************/ #include <stdio.h> #ifndef _OSL_MODULE_H_ #include <osl/module.hxx> #endif #ifndef _OSL_DIAGNOSE_H_ #include <osl/diagnose.h> #endif #include <com/sun/star/loader/XImplementationLoader.hpp> #include <com/sun/star/lang/XServiceInfo.hpp> #include <com/sun/star/lang/XSingleServiceFactory.hpp> #include <com/sun/star/lang/XSingleComponentFactory.hpp> #include <cppuhelper/implbase1.hxx> #ifndef _CPPUHELPER_FACTORY_HXX_ #include <cppuhelper/factory.hxx> #endif #if defined ( UNX ) || defined ( MAC ) #include <limits.h> #define _MAX_PATH PATH_MAX #endif using namespace com::sun::star::uno; using namespace com::sun::star::loader; using namespace com::sun::star::lang; using namespace osl; using namespace rtl; using namespace cppu; #ifdef _DEBUG #define TEST_ENSHURE(c, m) OSL_ENSURE(c, m) #else #define TEST_ENSHURE(c, m) OSL_VERIFY(c) #endif class EmptyComponentContext : public WeakImplHelper1< XComponentContext > { public: virtual Any SAL_CALL getValueByName( const OUString& Name ) throw (RuntimeException) { return Any(); } virtual Reference< XMultiComponentFactory > SAL_CALL getServiceManager( ) throw (RuntimeException) { return Reference< XMultiComponentFactory > (); } }; #if (defined UNX) || (defined OS2) int main( int argc, char * argv[] ) #else int _cdecl main( int argc, char * argv[] ) #endif { Reference<XInterface> xIFace; Module module; #ifdef SAL_W32 OUString dllName( OUString::createFromAscii("cpld.dll") ); #else #ifdef MACOSX OUString dllName( OUString::createFromAscii("libcpld.dylib") ); #else OUString dllName( OUString::createFromAscii("libcpld.so") ); #endif #endif if (module.load(dllName)) { // try to get provider from module component_getFactoryFunc pCompFactoryFunc = (component_getFactoryFunc) module.getSymbol( OUString::createFromAscii(COMPONENT_GETFACTORY) ); if (pCompFactoryFunc) { XSingleServiceFactory * pRet = (XSingleServiceFactory *)(*pCompFactoryFunc)( "com.sun.star.comp.stoc.DLLComponentLoader", 0, 0 ); if (pRet) { xIFace = pRet; pRet->release(); } } } TEST_ENSHURE( xIFace.is(), "testloader error1"); Reference<XSingleComponentFactory> xFactory( Reference<XSingleComponentFactory>::query(xIFace) ); TEST_ENSHURE( xFactory.is(), "testloader error2"); Reference<XInterface> xLoader = xFactory->createInstanceWithContext( new EmptyComponentContext ); TEST_ENSHURE( xLoader.is(), "testloader error3"); Reference<XServiceInfo> xServInfo( Reference<XServiceInfo>::query(xLoader) ); TEST_ENSHURE( xServInfo.is(), "testloader error4"); TEST_ENSHURE( xServInfo->getImplementationName().equalsAsciiL( RTL_CONSTASCII_STRINGPARAM("com.sun.star.comp.stoc.DLLComponentLoader") ), "testloader error5"); TEST_ENSHURE( xServInfo->supportsService(OUString( RTL_CONSTASCII_USTRINGPARAM("com.sun.star.loader.SharedLibrary")) ), "testloader error6"); TEST_ENSHURE( xServInfo->getSupportedServiceNames().getLength() == 1, "testloader error7"); xIFace.clear(); xFactory.clear(); xLoader.clear(); xServInfo.clear(); printf("Test Dll ComponentLoader, OK!\n"); return(0); } <commit_msg>INTEGRATION: CWS dbgmacros1 (1.7.44); FILE MERGED 2003/04/10 08:38:23 kso 1.7.44.1: #108413# - debug macro unification.<commit_after>/************************************************************************* * * $RCSfile: testloader.cxx,v $ * * $Revision: 1.8 $ * * last change: $Author: vg $ $Date: 2003-04-15 17:14:35 $ * * 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): _______________________________________ * * ************************************************************************/ #include <stdio.h> #ifndef _OSL_MODULE_H_ #include <osl/module.hxx> #endif #ifndef _OSL_DIAGNOSE_H_ #include <osl/diagnose.h> #endif #include <com/sun/star/loader/XImplementationLoader.hpp> #include <com/sun/star/lang/XServiceInfo.hpp> #include <com/sun/star/lang/XSingleServiceFactory.hpp> #include <com/sun/star/lang/XSingleComponentFactory.hpp> #include <cppuhelper/implbase1.hxx> #ifndef _CPPUHELPER_FACTORY_HXX_ #include <cppuhelper/factory.hxx> #endif #if defined ( UNX ) || defined ( MAC ) #include <limits.h> #define _MAX_PATH PATH_MAX #endif using namespace com::sun::star::uno; using namespace com::sun::star::loader; using namespace com::sun::star::lang; using namespace osl; using namespace rtl; using namespace cppu; #if OSL_DEBUG_LEVEL > 0 #define TEST_ENSHURE(c, m) OSL_ENSURE(c, m) #else #define TEST_ENSHURE(c, m) OSL_VERIFY(c) #endif class EmptyComponentContext : public WeakImplHelper1< XComponentContext > { public: virtual Any SAL_CALL getValueByName( const OUString& Name ) throw (RuntimeException) { return Any(); } virtual Reference< XMultiComponentFactory > SAL_CALL getServiceManager( ) throw (RuntimeException) { return Reference< XMultiComponentFactory > (); } }; #if (defined UNX) || (defined OS2) int main( int argc, char * argv[] ) #else int _cdecl main( int argc, char * argv[] ) #endif { Reference<XInterface> xIFace; Module module; #ifdef SAL_W32 OUString dllName( OUString::createFromAscii("cpld.dll") ); #else #ifdef MACOSX OUString dllName( OUString::createFromAscii("libcpld.dylib") ); #else OUString dllName( OUString::createFromAscii("libcpld.so") ); #endif #endif if (module.load(dllName)) { // try to get provider from module component_getFactoryFunc pCompFactoryFunc = (component_getFactoryFunc) module.getSymbol( OUString::createFromAscii(COMPONENT_GETFACTORY) ); if (pCompFactoryFunc) { XSingleServiceFactory * pRet = (XSingleServiceFactory *)(*pCompFactoryFunc)( "com.sun.star.comp.stoc.DLLComponentLoader", 0, 0 ); if (pRet) { xIFace = pRet; pRet->release(); } } } TEST_ENSHURE( xIFace.is(), "testloader error1"); Reference<XSingleComponentFactory> xFactory( Reference<XSingleComponentFactory>::query(xIFace) ); TEST_ENSHURE( xFactory.is(), "testloader error2"); Reference<XInterface> xLoader = xFactory->createInstanceWithContext( new EmptyComponentContext ); TEST_ENSHURE( xLoader.is(), "testloader error3"); Reference<XServiceInfo> xServInfo( Reference<XServiceInfo>::query(xLoader) ); TEST_ENSHURE( xServInfo.is(), "testloader error4"); TEST_ENSHURE( xServInfo->getImplementationName().equalsAsciiL( RTL_CONSTASCII_STRINGPARAM("com.sun.star.comp.stoc.DLLComponentLoader") ), "testloader error5"); TEST_ENSHURE( xServInfo->supportsService(OUString( RTL_CONSTASCII_USTRINGPARAM("com.sun.star.loader.SharedLibrary")) ), "testloader error6"); TEST_ENSHURE( xServInfo->getSupportedServiceNames().getLength() == 1, "testloader error7"); xIFace.clear(); xFactory.clear(); xLoader.clear(); xServInfo.clear(); printf("Test Dll ComponentLoader, OK!\n"); return(0); } <|endoftext|>
<commit_before>#include <ros/ros.h> #include <moveit/move_group_interface/move_group.h> #include <moveit/warehouse/planning_scene_storage.h> #include <boost/program_options.hpp> #include <view_controller_msgs/CameraPlacement.h> #include "moveit_recorder/TrajectoryRetimer.h" #include "moveit_recorder/AnimationRecorder.h" #include <moveit_recorder/AnimationRequest.h> #include <rosbag/bag.h> #include <rosbag/query.h> #include <rosbag/view.h> bool static ready; void animationResponseCallback(const boost::shared_ptr<std_msgs::Bool const>& msg) { ready = msg->data; } int main(int argc, char** argv) { ros::init(argc, argv, "playback"); ros::NodeHandle node_handle; ros::AsyncSpinner spinner(1); spinner.start(); sleep(20); // to let RVIZ come up boost::program_options::options_description desc; desc.add_options() ("help", "Show help message") ("host", boost::program_options::value<std::string>(), "Host for the MongoDB.") ("port", boost::program_options::value<std::size_t>(), "Port for the MongoDB.") ("views",boost::program_options::value<std::string>(), "Bag file for viewpoints"); boost::program_options::variables_map vm; boost::program_options::parsed_options po = boost::program_options::parse_command_line(argc, argv, desc); boost::program_options::store(po, vm); boost::program_options::notify(vm); if (vm.count("help") || argc == 1) // show help if no parameters passed { std::cout << desc << std::endl; return 1; } try { //connect to the DB std::string host = vm.count("host") ? vm["host"].as<std::string>() : ""; size_t port = vm.count("port") ? vm["port"].as<std::size_t>() : 0; moveit_warehouse::PlanningSceneStorage pss(host, port); ROS_INFO("Connected to Warehouse DB at host (%s) and port (%d)", host.c_str(), (int)port); //load the viewpoints std::string bagfilename = vm.count("views") ? vm["views"].as<std::string>() : ""; std::vector<view_controller_msgs::CameraPlacement> views; rosbag::Bag viewbag; viewbag.open(bagfilename, rosbag::bagmode::Read); std::vector<std::string> topics; topics.push_back("viewpoints"); rosbag::View view_t(viewbag, rosbag::TopicQuery(topics)); BOOST_FOREACH(rosbag::MessageInstance const m, view_t) { view_controller_msgs::CameraPlacement::ConstPtr i = m.instantiate<view_controller_msgs::CameraPlacement>(); if (i != NULL) views.push_back(*i); } viewbag.close(); ROS_INFO("%d views loaded",(int)views.size()); // response sub ros::Subscriber animation_sub = node_handle.subscribe("animation_response", 1, animationResponseCallback); while(animation_sub.getNumPublishers() < 1) { ros::WallDuration sleep_t(0.5); ROS_INFO("[Playback] Not enough publishers to \"%s\" topic...", "animation_response"); sleep_t.sleep(); } // request pub ros::Publisher animation_pub = node_handle.advertise<moveit_recorder::AnimationRequest>("animation_request",1); while(animation_pub.getNumSubscribers() < 1) { ros::WallDuration sleep_t(0.5); ROS_INFO("[Playback] Not enough subscribers to \"%s\" topic... ", "animation_request"); sleep_t.sleep(); } // ask the warehouse for the scenes std::vector<std::string> ps_names; pss.getPlanningSceneNames( ps_names ); ROS_INFO("%d available scenes to display", (int)ps_names.size()); // iterate over scenes std::vector<std::string>::iterator scene_name = ps_names.begin(); for(; scene_name!=ps_names.end(); ++scene_name) { ROS_INFO("Retrieving scene %s", scene_name->c_str()); moveit_warehouse::PlanningSceneWithMetadata pswm; pss.getPlanningScene(pswm, *scene_name); moveit_msgs::PlanningScene ps_msg = static_cast<const moveit_msgs::PlanningScene&>(*pswm); // ask qarehosue for the queries std::vector<std::string> pq_names; pss.getPlanningQueriesNames( pq_names, *scene_name); ROS_INFO("%d available queries to display", (int)pq_names.size()); // iterate over the queries std::vector<std::string>::iterator query_name = pq_names.begin(); for(; query_name!=pq_names.end(); ++query_name) { ROS_INFO("Retrieving query %s", query_name->c_str()); moveit_warehouse::MotionPlanRequestWithMetadata mprwm; pss.getPlanningQuery(mprwm, *scene_name, *query_name); moveit_msgs::MotionPlanRequest mpr_msg = static_cast<const moveit_msgs::MotionPlanRequest&>(*mprwm); // ask warehouse for stored trajectories std::vector<moveit_warehouse::RobotTrajectoryWithMetadata> planning_results; pss.getPlanningResults(planning_results, *scene_name, *query_name); ROS_INFO("Loaded %d trajectories", (int)planning_results.size()); // animate each trajectory std::vector<moveit_warehouse::RobotTrajectoryWithMetadata>::iterator traj_w_mdata = planning_results.begin(); for(; traj_w_mdata!=planning_results.end(); ++traj_w_mdata) { moveit_msgs::RobotTrajectory rt_msg; rt_msg = static_cast<const moveit_msgs::RobotTrajectory&>(**traj_w_mdata); // retime it TrajectoryRetimer retimer( "robot_description", mpr_msg.group_name ); retimer.configure(ps_msg, mpr_msg); bool result = retimer.retime(rt_msg); ROS_INFO("Retiming success? %s", result? "yes" : "no" ); std::vector<view_controller_msgs::CameraPlacement>::iterator view_msg; for(view_msg=views.begin(); view_msg!=views.end(); ++view_msg) { moveit_recorder::AnimationRequest req; view_msg->time_from_start = ros::Duration(0.1); ros::Time t_now = ros::Time::now(); view_msg->eye.header.stamp = t_now; view_msg->focus.header.stamp = t_now; view_msg->up.header.stamp = t_now; req.camera_placement = *view_msg; req.planning_scene = ps_msg; req.motion_plan_request = mpr_msg; req.robot_trajectory = rt_msg; req.filepath.data = "/tmp/video.ogv"; animation_pub.publish(req); usleep(1000); ready = false; while(ros::ok() && !ready) { ros::spinOnce(); //updates the ready status usleep(1000); } ROS_INFO("RECORDING DONE!"); sleep(2); }//view }//traj }//query }//scene } catch(mongo_ros::DbConnectException &ex) { ROS_ERROR_STREAM("Unable to connect to warehouse. If you just created the database, it could take a while for initial setup. Please try to run the benchmark again." << std::endl << ex.what()); } ROS_ERROR("Successfully performed trajectory playback"); ros::shutdown(); return 0; } <commit_msg>changed ros out from error to info<commit_after>#include <ros/ros.h> #include <moveit/move_group_interface/move_group.h> #include <moveit/warehouse/planning_scene_storage.h> #include <boost/program_options.hpp> #include <view_controller_msgs/CameraPlacement.h> #include "moveit_recorder/TrajectoryRetimer.h" #include "moveit_recorder/AnimationRecorder.h" #include <moveit_recorder/AnimationRequest.h> #include <rosbag/bag.h> #include <rosbag/query.h> #include <rosbag/view.h> bool static ready; void animationResponseCallback(const boost::shared_ptr<std_msgs::Bool const>& msg) { ready = msg->data; } int main(int argc, char** argv) { ros::init(argc, argv, "playback"); ros::NodeHandle node_handle; ros::AsyncSpinner spinner(1); spinner.start(); sleep(20); // to let RVIZ come up boost::program_options::options_description desc; desc.add_options() ("help", "Show help message") ("host", boost::program_options::value<std::string>(), "Host for the MongoDB.") ("port", boost::program_options::value<std::size_t>(), "Port for the MongoDB.") ("views",boost::program_options::value<std::string>(), "Bag file for viewpoints"); boost::program_options::variables_map vm; boost::program_options::parsed_options po = boost::program_options::parse_command_line(argc, argv, desc); boost::program_options::store(po, vm); boost::program_options::notify(vm); if (vm.count("help") || argc == 1) // show help if no parameters passed { std::cout << desc << std::endl; return 1; } try { //connect to the DB std::string host = vm.count("host") ? vm["host"].as<std::string>() : ""; size_t port = vm.count("port") ? vm["port"].as<std::size_t>() : 0; moveit_warehouse::PlanningSceneStorage pss(host, port); ROS_INFO("Connected to Warehouse DB at host (%s) and port (%d)", host.c_str(), (int)port); //load the viewpoints std::string bagfilename = vm.count("views") ? vm["views"].as<std::string>() : ""; std::vector<view_controller_msgs::CameraPlacement> views; rosbag::Bag viewbag; viewbag.open(bagfilename, rosbag::bagmode::Read); std::vector<std::string> topics; topics.push_back("viewpoints"); rosbag::View view_t(viewbag, rosbag::TopicQuery(topics)); BOOST_FOREACH(rosbag::MessageInstance const m, view_t) { view_controller_msgs::CameraPlacement::ConstPtr i = m.instantiate<view_controller_msgs::CameraPlacement>(); if (i != NULL) views.push_back(*i); } viewbag.close(); ROS_INFO("%d views loaded",(int)views.size()); // response sub ros::Subscriber animation_sub = node_handle.subscribe("animation_response", 1, animationResponseCallback); while(animation_sub.getNumPublishers() < 1) { ros::WallDuration sleep_t(0.5); ROS_INFO("[Playback] Not enough publishers to \"%s\" topic...", "animation_response"); sleep_t.sleep(); } // request pub ros::Publisher animation_pub = node_handle.advertise<moveit_recorder::AnimationRequest>("animation_request",1); while(animation_pub.getNumSubscribers() < 1) { ros::WallDuration sleep_t(0.5); ROS_INFO("[Playback] Not enough subscribers to \"%s\" topic... ", "animation_request"); sleep_t.sleep(); } // ask the warehouse for the scenes std::vector<std::string> ps_names; pss.getPlanningSceneNames( ps_names ); ROS_INFO("%d available scenes to display", (int)ps_names.size()); // iterate over scenes std::vector<std::string>::iterator scene_name = ps_names.begin(); for(; scene_name!=ps_names.end(); ++scene_name) { ROS_INFO("Retrieving scene %s", scene_name->c_str()); moveit_warehouse::PlanningSceneWithMetadata pswm; pss.getPlanningScene(pswm, *scene_name); moveit_msgs::PlanningScene ps_msg = static_cast<const moveit_msgs::PlanningScene&>(*pswm); // ask qarehosue for the queries std::vector<std::string> pq_names; pss.getPlanningQueriesNames( pq_names, *scene_name); ROS_INFO("%d available queries to display", (int)pq_names.size()); // iterate over the queries std::vector<std::string>::iterator query_name = pq_names.begin(); for(; query_name!=pq_names.end(); ++query_name) { ROS_INFO("Retrieving query %s", query_name->c_str()); moveit_warehouse::MotionPlanRequestWithMetadata mprwm; pss.getPlanningQuery(mprwm, *scene_name, *query_name); moveit_msgs::MotionPlanRequest mpr_msg = static_cast<const moveit_msgs::MotionPlanRequest&>(*mprwm); // ask warehouse for stored trajectories std::vector<moveit_warehouse::RobotTrajectoryWithMetadata> planning_results; pss.getPlanningResults(planning_results, *scene_name, *query_name); ROS_INFO("Loaded %d trajectories", (int)planning_results.size()); // animate each trajectory std::vector<moveit_warehouse::RobotTrajectoryWithMetadata>::iterator traj_w_mdata = planning_results.begin(); for(; traj_w_mdata!=planning_results.end(); ++traj_w_mdata) { moveit_msgs::RobotTrajectory rt_msg; rt_msg = static_cast<const moveit_msgs::RobotTrajectory&>(**traj_w_mdata); // retime it TrajectoryRetimer retimer( "robot_description", mpr_msg.group_name ); retimer.configure(ps_msg, mpr_msg); bool result = retimer.retime(rt_msg); ROS_INFO("Retiming success? %s", result? "yes" : "no" ); std::vector<view_controller_msgs::CameraPlacement>::iterator view_msg; for(view_msg=views.begin(); view_msg!=views.end(); ++view_msg) { moveit_recorder::AnimationRequest req; view_msg->time_from_start = ros::Duration(0.1); ros::Time t_now = ros::Time::now(); view_msg->eye.header.stamp = t_now; view_msg->focus.header.stamp = t_now; view_msg->up.header.stamp = t_now; req.camera_placement = *view_msg; req.planning_scene = ps_msg; req.motion_plan_request = mpr_msg; req.robot_trajectory = rt_msg; req.filepath.data = "/tmp/video.ogv"; animation_pub.publish(req); usleep(1000); ready = false; while(ros::ok() && !ready) { ros::spinOnce(); //updates the ready status usleep(1000); } ROS_INFO("RECORDING DONE!"); sleep(2); }//view }//traj }//query }//scene } catch(mongo_ros::DbConnectException &ex) { ROS_ERROR_STREAM("Unable to connect to warehouse. If you just created the database, it could take a while for initial setup. Please try to run the benchmark again." << std::endl << ex.what()); } ROS_INFO("Successfully performed trajectory playback"); ros::shutdown(); return 0; } <|endoftext|>
<commit_before>/** * Copyright © 2017 INFN Torino - INDIGO-DataCloud * * 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 "VMPool.h" #include <libxml/parser.h> #include <libxml/tree.h> #include <libxml/xpath.h> #include <libxml/xpathInternals.h> #include <assert.h> #include <stdexcept> #include <iomanip> #include <vector> void VMPool::add_object(xmlNodePtr node) { if ( node == 0 || node->children == 0 || node->children->next==0 ) { FassLog::log("VMPOOL",Log::ERROR, "XML Node does not represent a valid Virtual Machine"); return; } VirtualMachine* vm = new VirtualMachine(node); objects.insert(pair<int, VirtualMachine*>(vm->get_oid(), vm)); ostringstream oss; oss << "Inserting VM object with ID: " << vm->get_oid() << "\n"; FassLog::log("VMPOOL",Log::DDEBUG, oss); }; void VMPool::flush() { map<int,VirtualMachine*>::iterator it; for (it = objects.begin(); it != objects.end(); it++) { delete it->second; } objects.clear(); }; int VMPool::set_up() { int rc; ostringstream oss; // clean the pool to get updated data from OpenNebula VMPool::flush(); // load the complete pool of VMs from OpenNebula xmlrpc_c::value result; rc = load_vms(result); if ( rc != 0 ) { FassLog::log("VMPOOL", Log::ERROR, "Could not retrieve VM pool info from ONE"); return -1; } // read the response vector<xmlrpc_c::value> values = xmlrpc_c::value_array(result).vectorValueValue(); bool success = xmlrpc_c::value_boolean(values[0]); // OpenNebula says failure if (!success) { string message = xmlrpc_c::value_string(values[1]); oss << "Oned returned failure... Error: " << message << "\n"; FassLog::log("VMPOOL", Log::ERROR, oss); return -1; } // the output of the one.vmpool.info method is always a string string vmlist(static_cast<string>(xmlrpc_c::value_string(values[1]))); // parse the response and select only pending/rescheduling VMs xmlInitParser(); xml_parse(vmlist); std::vector<xmlNodePtr> nodes; int n_nodes; n_nodes = get_nodes("/VM_POOL/VM[STATE=1 or ((LCM_STATE=3 or LCM_STATE=16) and RESCHED=1)]", nodes); oss << "I got " << n_nodes << " pending VMs!"; FassLog::log("VMPOOL",Log::DEBUG, oss); for (unsigned int i = 0 ; i < nodes.size(); i++) { VMPool::add_object(nodes[i]); } // free_nodes(nodes); // clean global variables that might have been allocated by the parser xmlCleanupParser(); return rc; } int VMPool::load_vms(xmlrpc_c::value &result) { try { xmlrpc_c::paramList plist; plist.add(xmlrpc_c::value_int(-2)); plist.add(xmlrpc_c::value_int(-1)); plist.add(xmlrpc_c::value_int(-1)); plist.add(xmlrpc_c::value_int(-1)); client->call("one.vmpool.info", plist, &result); return 0; } catch (exception const& e) { ostringstream oss; oss << "Exception raised: " << e.what(); FassLog::log("VMPool", Log::ERROR, oss); return -1; } } bool VMPool::xml_parse(const string &xml_doc) { // copied from ONE ObjectXML xmlDocPtr xml = xmlReadMemory (xml_doc.c_str(),xml_doc.length(),0,0,XML_PARSE_HUGE); if (xml == 0) { throw runtime_error("Error parsing XML Document"); return false; } ctx = xmlXPathNewContext(xml); if (ctx == 0) { xmlFreeDoc(xml); throw runtime_error("Unable to create new XPath context"); return false; } return true; }; int VMPool::get_nodes(const string& xpath_expr, std::vector<xmlNodePtr>& content) { // copied from ONE xmlXPathObjectPtr obj; obj = xmlXPathEvalExpression( reinterpret_cast<const xmlChar *>(xpath_expr.c_str()), ctx); if (obj == 0) { return 0; } if (obj->nodesetval == 0) { xmlXPathFreeObject(obj); return 0; } xmlNodeSetPtr ns = obj->nodesetval; int size = ns->nodeNr; int num_nodes = 0; xmlNodePtr cur; for(int i = 0; i < size; ++i) { cur = xmlCopyNode(ns->nodeTab[i], 1); if ( cur == 0 || cur->type != XML_ELEMENT_NODE ) { xmlFreeNode(cur); continue; } content.push_back(cur); num_nodes++; } xmlXPathFreeObject(obj); return num_nodes; } /* int VMPool::update(int vid) const //, const string &st) const { xmlrpc_c::value result; try { client->call("one.vm.update", "is", &result, vid); //, st.c_str()); } catch (exception const& e) { return -1; } return 0; } */ <commit_msg>code style fix pm<commit_after>/** * Copyright © 2017 INFN Torino - INDIGO-DataCloud * * 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 "VMPool.h" #include <libxml/parser.h> #include <libxml/tree.h> #include <libxml/xpath.h> #include <libxml/xpathInternals.h> #include <assert.h> #include <stdexcept> #include <iomanip> #include <vector> void VMPool::add_object(xmlNodePtr node) { if ( node == 0 || node->children == 0 || node->children->next == 0 ) { FassLog::log("VMPOOL", Log::ERROR, "XML Node does not represent a valid Virtual Machine"); return; } VirtualMachine* vm = new VirtualMachine(node); objects.insert(pair<int, VirtualMachine*>(vm->get_oid(), vm)); ostringstream oss; oss << "Inserting VM object with ID: " << vm->get_oid() << "\n"; FassLog::log("VMPOOL", Log::DDEBUG, oss); } void VMPool::flush() { map<int, VirtualMachine*>::iterator it; for (it = objects.begin(); it != objects.end(); it++) { delete it->second; } objects.clear(); } int VMPool::set_up() { int rc; ostringstream oss; // clean the pool to get updated data from OpenNebula VMPool::flush(); // load the complete pool of VMs from OpenNebula xmlrpc_c::value result; rc = load_vms(result); if ( rc != 0 ) { FassLog::log("VMPOOL", Log::ERROR, "Could not retrieve VM pool info from ONE"); return -1; } // read the response vector<xmlrpc_c::value> values = xmlrpc_c::value_array(result).vectorValueValue(); bool success = xmlrpc_c::value_boolean(values[0]); // OpenNebula says failure if (!success) { string message = xmlrpc_c::value_string(values[1]); oss << "Oned returned failure... Error: " << message << "\n"; FassLog::log("VMPOOL", Log::ERROR, oss); return -1; } // the output of the one.vmpool.info method is always a string string vmlist(static_cast<string>(xmlrpc_c::value_string(values[1]))); // parse the response and select only pending/rescheduling VMs xmlInitParser(); xml_parse(vmlist); std::vector<xmlNodePtr> nodes; int n_nodes; n_nodes = get_nodes ("/VM_POOL/VM[STATE=1 or ((LCM_STATE=3 or LCM_STATE=16) and RESCHED=1)]", nodes); oss << "I got " << n_nodes << " pending VMs!"; FassLog::log("VMPOOL", Log::DEBUG, oss); for (unsigned int i = 0 ; i < nodes.size(); i++) { VMPool::add_object(nodes[i]); } // free_nodes(nodes); // clean global variables that might have been allocated by the parser xmlCleanupParser(); return rc; } int VMPool::load_vms(xmlrpc_c::value &result) { try { xmlrpc_c::paramList plist; plist.add(xmlrpc_c::value_int(-2)); plist.add(xmlrpc_c::value_int(-1)); plist.add(xmlrpc_c::value_int(-1)); plist.add(xmlrpc_c::value_int(-1)); client->call("one.vmpool.info", plist, &result); return 0; } catch (exception const& e) { ostringstream oss; oss << "Exception raised: " << e.what(); FassLog::log("VMPool", Log::ERROR, oss); return -1; } } bool VMPool::xml_parse(const string &xml_doc) { // copied from ONE ObjectXML xmlDocPtr xml = xmlReadMemory(xml_doc.c_str(), xml_doc.length(), 0, 0, XML_PARSE_HUGE); if (xml == 0) { throw runtime_error("Error parsing XML Document"); return false; } ctx = xmlXPathNewContext(xml); if (ctx == 0) { xmlFreeDoc(xml); throw runtime_error("Unable to create new XPath context"); return false; } return true; } int VMPool::get_nodes(const string& xpath_expr, std::vector<xmlNodePtr>& content) { // copied from ONE xmlXPathObjectPtr obj; obj = xmlXPathEvalExpression( reinterpret_cast<const xmlChar *>(xpath_expr.c_str()), ctx); if (obj == 0) { return 0; } if (obj->nodesetval == 0) { xmlXPathFreeObject(obj); return 0; } xmlNodeSetPtr ns = obj->nodesetval; int size = ns->nodeNr; int num_nodes = 0; xmlNodePtr cur; for (int i = 0; i < size; ++i) { cur = xmlCopyNode(ns->nodeTab[i], 1); if ( cur == 0 || cur->type != XML_ELEMENT_NODE ) { xmlFreeNode(cur); continue; } content.push_back(cur); num_nodes++; } xmlXPathFreeObject(obj); return num_nodes; } /* int VMPool::update(int vid) const //, const string &st) const { xmlrpc_c::value result; try { client->call("one.vm.update", "is", &result, vid); //, st.c_str()); } catch (exception const& e) { return -1; } return 0; } */ <|endoftext|>
<commit_before> #include <thread> #include <string> //#include <processthreadsapi.h> #include "NFComm/NFPluginModule/NFPlatform.h" #include "NFComm/NFCore/NFTimer.h" #include "NFNet/NFServer.h" #include "NFNet/NFIPacket.h" #ifdef NF_DEBUG_MODE #pragma comment(lib,"NFNet_d.lib") #pragma comment(lib,"NFCore_d.lib") #else #pragma comment(lib,"NFNet.lib") #pragma comment(lib,"NFCore.lib") #endif #pragma comment(lib,"ws2_32.lib") #pragma comment(lib,"libevent.lib") #pragma comment(lib,"libevent_core.lib") class TestServerClass { public: TestServerClass() { //pNet = new NFCMulNet(this, &TestServerClass::ReciveHandler, &TestServerClass::EventHandler); //pNet->Initialization(10000, 8088, 2, 4); //nSendMsgCount = 0; //nReciveMsgCount = 0; //nStartTime = NFTime::GetNowTime(); //nLastTime = nStartTime; //nLastSendCount = 0; //nLasterReciveCount = 0; pNet = new NFServer(IMsgHead::NF_MIN_HEAD_LENGTH, this, &TestServerClass::ReciveHandler, &TestServerClass::EventHandler); pNet->StartServer(8088, 4, 8000, 300, 300); } //void ReciveHandler(const int nSockIndex, const int nMsgID, const char* msg, const uint32_t nLen, const NFGUID& xClientID) //{ // std::string str; // str.assign(msg, nLen); // nReciveMsgCount++; // nSendMsgCount++; // pNet->SendMsgWithOutHead(nMsgID, msg, nLen, nSockIndex); // //std::cout << " nSendMsgCount: " << nSendMsgCount << "nReciveMsgCount" << nReciveMsgCount << " fd: " << nSockIndex << " msg_id: " << nMsgID /*<< " data: " << str*/ << " thread_id: " << GetCurrentThreadId() << std::endl; //} int ReciveHandler(const NFIPacket& msg) { //std::string str; //str.assign(msg, nLen); //nReciveMsgCount++; //nSendMsgCount++; //pNet->SendMsgWithOutHead(nMsgID, msg, nLen, nSockIndex); //std::cout << " nSendMsgCount: " << nSendMsgCount << "nReciveMsgCount" << nReciveMsgCount << " fd: " << nSockIndex << " msg_id: " << nMsgID /*<< " data: " << str*/ << " thread_id: " << GetCurrentThreadId() << std::endl; std::string strMsg = "11111111111111111111111111111111111111111111111111112222222222222222222222222222222222222222222222222222222222222222223333333333333333333333444"; pNet->SendMsg(strMsg.c_str(), strMsg.size(), msg.GetFd(), false); return 1; } //void EventHandler(const int nSockIndex, const NF_NET_EVENT e, const NFGUID& xClientID, const int nServerID) //{ // std::cout << " fd: " << nSockIndex << " event_id: " << e << " thread_id: " << std::this_thread::get_id() << std::endl; //} int EventHandler(const int nSockIndex, const NF_NET_EVENT nEvent, NFIServer* pNet) { std::cout << " fd: " << nSockIndex << " event_id: " << nEvent << " thread_id: " << std::this_thread::get_id() << std::endl; return 1; } void Execute() { pNet->Execute(); int nNowTime = NFTime::GetNowTime(); int nSpanTime = nNowTime - nLastTime; int nAllSpanTime = nNowTime - nStartTime; if(nSpanTime > 5 && nAllSpanTime > 0) { nLastTime = nNowTime; const int nLastPerSend = (nSendMsgCount - nLastSendCount) / nSpanTime; const int nLastPerReceive = (nReciveMsgCount - nLasterReciveCount) / nSpanTime; const int nToltalPerSend = nSendMsgCount / nAllSpanTime; const int nToltalPerReceive = nReciveMsgCount / nAllSpanTime; nLastSendCount = nSendMsgCount; nLasterReciveCount = nReciveMsgCount; std::cout << " All Send: [" << nSendMsgCount << "] All Receive: [" << nReciveMsgCount << "] All Per Send per second : [" << nToltalPerSend << "] All Per Receive per second : [" << nToltalPerReceive << "] Last Second Per Send :[" << nLastPerSend << "] Last Second Per Received [" << nLastPerReceive /*<< " data: " << str*/ << "] thread_id: " << GetCurrentThreadId() << std::endl; } } protected: NFServer* pNet; int nSendMsgCount; int nReciveMsgCount; int nStartTime; int nLastTime; int nLasterReciveCount; int nLastSendCount; }; int main(int argc, char** argv) { TestServerClass x; while(1) { x.Execute(); NFSLEEP(1); } return 0; } <commit_msg>add send msg<commit_after> #include <thread> #include <string> //#include <processthreadsapi.h> #include "NFComm/NFPluginModule/NFPlatform.h" #include "NFComm/NFCore/NFTimer.h" #include "NFNet/NFServer.h" #include "NFNet/NFIPacket.h" #ifdef NF_DEBUG_MODE #pragma comment(lib,"NFNet_d.lib") #pragma comment(lib,"NFCore_d.lib") #else #pragma comment(lib,"NFNet.lib") #pragma comment(lib,"NFCore.lib") #endif #pragma comment(lib,"ws2_32.lib") #pragma comment(lib,"libevent.lib") #pragma comment(lib,"libevent_core.lib") class TestServerClass { public: TestServerClass() { //pNet = new NFCMulNet(this, &TestServerClass::ReciveHandler, &TestServerClass::EventHandler); //pNet->Initialization(10000, 8088, 2, 4); //nSendMsgCount = 0; //nReciveMsgCount = 0; //nStartTime = NFTime::GetNowTime(); //nLastTime = nStartTime; //nLastSendCount = 0; //nLasterReciveCount = 0; pNet = new NFServer(IMsgHead::NF_MIN_HEAD_LENGTH, this, &TestServerClass::ReciveHandler, &TestServerClass::EventHandler); pNet->StartServer(8088, 4, 8000, 300, 300); } //void ReciveHandler(const int nSockIndex, const int nMsgID, const char* msg, const uint32_t nLen, const NFGUID& xClientID) //{ // std::string str; // str.assign(msg, nLen); // nReciveMsgCount++; // nSendMsgCount++; // pNet->SendMsgWithOutHead(nMsgID, msg, nLen, nSockIndex); // //std::cout << " nSendMsgCount: " << nSendMsgCount << "nReciveMsgCount" << nReciveMsgCount << " fd: " << nSockIndex << " msg_id: " << nMsgID /*<< " data: " << str*/ << " thread_id: " << GetCurrentThreadId() << std::endl; //} int ReciveHandler(const NFIPacket& msg) { //std::string str; //str.assign(msg, nLen); //nReciveMsgCount++; //nSendMsgCount++; //pNet->SendMsgWithOutHead(nMsgID, msg, nLen, nSockIndex); //std::cout << " nSendMsgCount: " << nSendMsgCount << "nReciveMsgCount" << nReciveMsgCount << " fd: " << nSockIndex << " msg_id: " << nMsgID /*<< " data: " << str*/ << " thread_id: " << GetCurrentThreadId() << std::endl; std::string strMsg = "11111111111111111111111111111111111111111111111111112222222222222222222222222222222222222222222222222222222222222222223333333333333333333333444"; pNet->SendMsgWithOutHead(1, strMsg.c_str(), strMsg.size(), msg.GetFd(), false); return 1; } //void EventHandler(const int nSockIndex, const NF_NET_EVENT e, const NFGUID& xClientID, const int nServerID) //{ // std::cout << " fd: " << nSockIndex << " event_id: " << e << " thread_id: " << std::this_thread::get_id() << std::endl; //} int EventHandler(const int nSockIndex, const NF_NET_EVENT nEvent, NFIServer* pNet) { std::cout << " fd: " << nSockIndex << " event_id: " << nEvent << " thread_id: " << std::this_thread::get_id() << std::endl; return 1; } void Execute() { pNet->Execute(); int nNowTime = NFTime::GetNowTime(); int nSpanTime = nNowTime - nLastTime; int nAllSpanTime = nNowTime - nStartTime; if(nSpanTime > 5 && nAllSpanTime > 0) { nLastTime = nNowTime; const int nLastPerSend = (nSendMsgCount - nLastSendCount) / nSpanTime; const int nLastPerReceive = (nReciveMsgCount - nLasterReciveCount) / nSpanTime; const int nToltalPerSend = nSendMsgCount / nAllSpanTime; const int nToltalPerReceive = nReciveMsgCount / nAllSpanTime; nLastSendCount = nSendMsgCount; nLasterReciveCount = nReciveMsgCount; std::cout << " All Send: [" << nSendMsgCount << "] All Receive: [" << nReciveMsgCount << "] All Per Send per second : [" << nToltalPerSend << "] All Per Receive per second : [" << nToltalPerReceive << "] Last Second Per Send :[" << nLastPerSend << "] Last Second Per Received [" << nLastPerReceive /*<< " data: " << str*/ << "] thread_id: " << GetCurrentThreadId() << std::endl; } } protected: NFServer* pNet; int nSendMsgCount; int nReciveMsgCount; int nStartTime; int nLastTime; int nLasterReciveCount; int nLastSendCount; }; int main(int argc, char** argv) { TestServerClass x; while(1) { x.Execute(); NFSLEEP(1); } return 0; } <|endoftext|>
<commit_before>// Copyright (c) 2011-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. #if defined(HAVE_CONFIG_H) #include <config/syscoin-config.h> #endif #include <chainparams.h> #include <fs.h> #include <qt/intro.h> #include <qt/forms/ui_intro.h> #include <qt/guiconstants.h> #include <qt/guiutil.h> #include <qt/optionsmodel.h> #include <interfaces/node.h> #include <util/system.h> #include <validation.h> #include <QFileDialog> #include <QSettings> #include <QMessageBox> #include <math.h> /* Check free space asynchronously to prevent hanging the UI thread. Up to one request to check a path is in flight to this thread; when the check() function runs, the current path is requested from the associated Intro object. The reply is sent back through a signal. This ensures that no queue of checking requests is built up while the user is still entering the path, and that always the most recently entered path is checked as soon as the thread becomes available. */ class FreespaceChecker : public QObject { Q_OBJECT public: explicit FreespaceChecker(Intro *intro); enum Status { ST_OK, ST_ERROR }; public Q_SLOTS: void check(); Q_SIGNALS: void reply(int status, const QString &message, quint64 available); private: Intro *intro; }; #include <qt/intro.moc> FreespaceChecker::FreespaceChecker(Intro *_intro) { this->intro = _intro; } void FreespaceChecker::check() { QString dataDirStr = intro->getPathToCheck(); fs::path dataDir = GUIUtil::qstringToBoostPath(dataDirStr); uint64_t freeBytesAvailable = 0; int replyStatus = ST_OK; QString replyMessage = tr("A new data directory will be created."); /* Find first parent that exists, so that fs::space does not fail */ fs::path parentDir = dataDir; fs::path parentDirOld = fs::path(); while(parentDir.has_parent_path() && !fs::exists(parentDir)) { parentDir = parentDir.parent_path(); /* Check if we make any progress, break if not to prevent an infinite loop here */ if (parentDirOld == parentDir) break; parentDirOld = parentDir; } try { freeBytesAvailable = fs::space(parentDir).available; if(fs::exists(dataDir)) { if(fs::is_directory(dataDir)) { QString separator = "<code>" + QDir::toNativeSeparators("/") + tr("name") + "</code>"; replyStatus = ST_OK; replyMessage = tr("Directory already exists. Add %1 if you intend to create a new directory here.").arg(separator); } else { replyStatus = ST_ERROR; replyMessage = tr("Path already exists, and is not a directory."); } } } catch (const fs::filesystem_error&) { /* Parent directory does not exist or is not accessible */ replyStatus = ST_ERROR; replyMessage = tr("Cannot create data directory here."); } Q_EMIT reply(replyStatus, replyMessage, freeBytesAvailable); } namespace { //! Return pruning size that will be used if automatic pruning is enabled. int GetPruneTargetGB() { int64_t prune_target_mib = gArgs.GetArg("-prune", 0); // >1 means automatic pruning is enabled by config, 1 means manual pruning, 0 means no pruning. return prune_target_mib > 1 ? PruneMiBtoGB(prune_target_mib) : DEFAULT_PRUNE_TARGET_GB; } } // namespace Intro::Intro(QWidget *parent, int64_t blockchain_size_gb, int64_t chain_state_size_gb) : QDialog(parent, GUIUtil::dialog_flags), ui(new Ui::Intro), thread(nullptr), signalled(false), m_blockchain_size_gb(blockchain_size_gb), m_chain_state_size_gb(chain_state_size_gb), m_prune_target_gb{GetPruneTargetGB()} { ui->setupUi(this); ui->welcomeLabel->setText(ui->welcomeLabel->text().arg(PACKAGE_NAME)); ui->storageLabel->setText(ui->storageLabel->text().arg(PACKAGE_NAME)); ui->lblExplanation1->setText(ui->lblExplanation1->text() .arg(PACKAGE_NAME) .arg(m_blockchain_size_gb) .arg(2014) .arg(tr("Syscoin")) ); ui->lblExplanation2->setText(ui->lblExplanation2->text().arg(PACKAGE_NAME)); const int min_prune_target_GB = std::ceil(MIN_DISK_SPACE_FOR_BLOCK_FILES / 1e9); ui->pruneGB->setRange(min_prune_target_GB, std::numeric_limits<int>::max()); if (gArgs.GetArg("-prune", 0) > 1) { // -prune=1 means enabled, above that it's a size in MiB ui->prune->setChecked(true); ui->prune->setEnabled(false); } ui->pruneGB->setValue(m_prune_target_gb); ui->pruneGB->setToolTip(ui->prune->toolTip()); ui->lblPruneSuffix->setToolTip(ui->prune->toolTip()); UpdatePruneLabels(ui->prune->isChecked()); connect(ui->prune, &QCheckBox::toggled, [this](bool prune_checked) { UpdatePruneLabels(prune_checked); UpdateFreeSpaceLabel(); }); connect(ui->pruneGB, qOverload<int>(&QSpinBox::valueChanged), [this](int prune_GB) { m_prune_target_gb = prune_GB; UpdatePruneLabels(ui->prune->isChecked()); UpdateFreeSpaceLabel(); }); startThread(); } Intro::~Intro() { delete ui; /* Ensure thread is finished before it is deleted */ thread->quit(); thread->wait(); } QString Intro::getDataDirectory() { return ui->dataDirectory->text(); } void Intro::setDataDirectory(const QString &dataDir) { ui->dataDirectory->setText(dataDir); if(dataDir == GUIUtil::getDefaultDataDirectory()) { ui->dataDirDefault->setChecked(true); ui->dataDirectory->setEnabled(false); ui->ellipsisButton->setEnabled(false); } else { ui->dataDirCustom->setChecked(true); ui->dataDirectory->setEnabled(true); ui->ellipsisButton->setEnabled(true); } } int64_t Intro::getPruneMiB() const { switch (ui->prune->checkState()) { case Qt::Checked: return PruneGBtoMiB(m_prune_target_gb); case Qt::Unchecked: default: return 0; } } bool Intro::showIfNeeded(bool& did_show_intro, int64_t& prune_MiB) { did_show_intro = false; QSettings settings; /* If data directory provided on command line, no need to look at settings or show a picking dialog */ if(!gArgs.GetArg("-datadir", "").empty()) return true; // SYSCOIN /* 1) Default data directory for operating system */ QString defaultDir = GUIUtil::getDefaultDataDirectory(); /* 2) Allow QSettings to override default dir only if not syscoincore which was used in v3 */ QString dataDir = settings.value("strDataDir", defaultDir).toString(); if(QString::compare(dataDir, "syscoincore", Qt::CaseInsensitive) == 0) dataDir = defaultDir; if(!fs::exists(GUIUtil::qstringToBoostPath(dataDir)) || gArgs.GetBoolArg("-choosedatadir", DEFAULT_CHOOSE_DATADIR) || settings.value("fReset", false).toBool() || gArgs.GetBoolArg("-resetguisettings", false)) { /* Use selectParams here to guarantee Params() can be used by node interface */ try { SelectParams(gArgs.GetChainName()); } catch (const std::exception&) { return false; } /* If current default data directory does not exist, let the user choose one */ Intro intro(0, Params().AssumedBlockchainSize(), Params().AssumedChainStateSize()); intro.setDataDirectory(dataDir); intro.setWindowIcon(QIcon(":icons/syscoin")); did_show_intro = true; while(true) { if(!intro.exec()) { /* Cancel clicked */ return false; } dataDir = intro.getDataDirectory(); try { if (TryCreateDirectories(GUIUtil::qstringToBoostPath(dataDir))) { // If a new data directory has been created, make wallets subdirectory too TryCreateDirectories(GUIUtil::qstringToBoostPath(dataDir) / "wallets"); } break; } catch (const fs::filesystem_error&) { QMessageBox::critical(nullptr, PACKAGE_NAME, tr("Error: Specified data directory \"%1\" cannot be created.").arg(dataDir)); /* fall through, back to choosing screen */ } } // Additional preferences: prune_MiB = intro.getPruneMiB(); settings.setValue("strDataDir", dataDir); settings.setValue("fReset", false); } /* Only override -datadir if different from the default, to make it possible to * override -datadir in the syscoin.conf file in the default data directory * (to be consistent with syscoind behavior) */ if(dataDir != GUIUtil::getDefaultDataDirectory()) { gArgs.SoftSetArg("-datadir", GUIUtil::qstringToBoostPath(dataDir).string()); // use OS locale for path setting } return true; } void Intro::setStatus(int status, const QString &message, quint64 bytesAvailable) { switch(status) { case FreespaceChecker::ST_OK: ui->errorMessage->setText(message); ui->errorMessage->setStyleSheet(""); break; case FreespaceChecker::ST_ERROR: ui->errorMessage->setText(tr("Error") + ": " + message); ui->errorMessage->setStyleSheet("QLabel { color: #800000 }"); break; } /* Indicate number of bytes available */ if(status == FreespaceChecker::ST_ERROR) { ui->freeSpace->setText(""); } else { m_bytes_available = bytesAvailable; if (ui->prune->isEnabled()) { ui->prune->setChecked(m_bytes_available < (m_blockchain_size_gb + m_chain_state_size_gb + 10) * GB_BYTES); } UpdateFreeSpaceLabel(); } /* Don't allow confirm in ERROR state */ ui->buttonBox->button(QDialogButtonBox::Ok)->setEnabled(status != FreespaceChecker::ST_ERROR); } void Intro::UpdateFreeSpaceLabel() { QString freeString = tr("%1 GB of free space available").arg(m_bytes_available / GB_BYTES); if (m_bytes_available < m_required_space_gb * GB_BYTES) { freeString += " " + tr("(of %1 GB needed)").arg(m_required_space_gb); ui->freeSpace->setStyleSheet("QLabel { color: #800000 }"); } else if (m_bytes_available / GB_BYTES - m_required_space_gb < 10) { freeString += " " + tr("(%1 GB needed for full chain)").arg(m_required_space_gb); ui->freeSpace->setStyleSheet("QLabel { color: #999900 }"); } else { ui->freeSpace->setStyleSheet(""); } ui->freeSpace->setText(freeString + "."); } void Intro::on_dataDirectory_textChanged(const QString &dataDirStr) { /* Disable OK button until check result comes in */ ui->buttonBox->button(QDialogButtonBox::Ok)->setEnabled(false); checkPath(dataDirStr); } void Intro::on_ellipsisButton_clicked() { QString dir = QDir::toNativeSeparators(QFileDialog::getExistingDirectory(nullptr, "Choose data directory", ui->dataDirectory->text())); if(!dir.isEmpty()) ui->dataDirectory->setText(dir); } void Intro::on_dataDirDefault_clicked() { setDataDirectory(GUIUtil::getDefaultDataDirectory()); } void Intro::on_dataDirCustom_clicked() { ui->dataDirectory->setEnabled(true); ui->ellipsisButton->setEnabled(true); } void Intro::startThread() { thread = new QThread(this); FreespaceChecker *executor = new FreespaceChecker(this); executor->moveToThread(thread); connect(executor, &FreespaceChecker::reply, this, &Intro::setStatus); connect(this, &Intro::requestCheck, executor, &FreespaceChecker::check); /* make sure executor object is deleted in its own thread */ connect(thread, &QThread::finished, executor, &QObject::deleteLater); thread->start(); } void Intro::checkPath(const QString &dataDir) { mutex.lock(); pathToCheck = dataDir; if(!signalled) { signalled = true; Q_EMIT requestCheck(); } mutex.unlock(); } QString Intro::getPathToCheck() { QString retval; mutex.lock(); retval = pathToCheck; signalled = false; /* new request can be queued now */ mutex.unlock(); return retval; } void Intro::UpdatePruneLabels(bool prune_checked) { m_required_space_gb = m_blockchain_size_gb + m_chain_state_size_gb; QString storageRequiresMsg = tr("At least %1 GB of data will be stored in this directory, and it will grow over time."); if (prune_checked && m_prune_target_gb <= m_blockchain_size_gb) { m_required_space_gb = m_prune_target_gb + m_chain_state_size_gb; storageRequiresMsg = tr("Approximately %1 GB of data will be stored in this directory."); } ui->lblExplanation3->setVisible(prune_checked); ui->pruneGB->setEnabled(prune_checked); // SYSCOIN static constexpr uint64_t nPowTargetSpacing = 60; // from chainparams, which we don't have at this stage static constexpr uint32_t expected_block_data_size = 250000; // includes undo data const uint64_t expected_backup_days = m_prune_target_gb * 1e9 / (uint64_t(expected_block_data_size) * 86400 / nPowTargetSpacing); ui->lblPruneSuffix->setText(tr("(sufficient to restore backups %n day(s) old)", "block chain pruning", expected_backup_days)); ui->sizeWarningLabel->setText( tr("%1 will download and store a copy of the Syscoin block chain.").arg(PACKAGE_NAME) + " " + storageRequiresMsg.arg(m_required_space_gb) + " " + tr("The wallet will also be stored in this directory.") ); this->adjustSize(); } <commit_msg>fix legacy SyscoinCore regkey issue re: strDataDir / strSyscoinDataDir<commit_after>// Copyright (c) 2011-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. #if defined(HAVE_CONFIG_H) #include <config/syscoin-config.h> #endif #include <chainparams.h> #include <fs.h> #include <qt/intro.h> #include <qt/forms/ui_intro.h> #include <qt/guiconstants.h> #include <qt/guiutil.h> #include <qt/optionsmodel.h> #include <interfaces/node.h> #include <util/system.h> #include <validation.h> #include <QFileDialog> #include <QSettings> #include <QMessageBox> #include <math.h> /* Check free space asynchronously to prevent hanging the UI thread. Up to one request to check a path is in flight to this thread; when the check() function runs, the current path is requested from the associated Intro object. The reply is sent back through a signal. This ensures that no queue of checking requests is built up while the user is still entering the path, and that always the most recently entered path is checked as soon as the thread becomes available. */ class FreespaceChecker : public QObject { Q_OBJECT public: explicit FreespaceChecker(Intro *intro); enum Status { ST_OK, ST_ERROR }; public Q_SLOTS: void check(); Q_SIGNALS: void reply(int status, const QString &message, quint64 available); private: Intro *intro; }; #include <qt/intro.moc> FreespaceChecker::FreespaceChecker(Intro *_intro) { this->intro = _intro; } void FreespaceChecker::check() { QString dataDirStr = intro->getPathToCheck(); fs::path dataDir = GUIUtil::qstringToBoostPath(dataDirStr); uint64_t freeBytesAvailable = 0; int replyStatus = ST_OK; QString replyMessage = tr("A new data directory will be created."); /* Find first parent that exists, so that fs::space does not fail */ fs::path parentDir = dataDir; fs::path parentDirOld = fs::path(); while(parentDir.has_parent_path() && !fs::exists(parentDir)) { parentDir = parentDir.parent_path(); /* Check if we make any progress, break if not to prevent an infinite loop here */ if (parentDirOld == parentDir) break; parentDirOld = parentDir; } try { freeBytesAvailable = fs::space(parentDir).available; if(fs::exists(dataDir)) { if(fs::is_directory(dataDir)) { QString separator = "<code>" + QDir::toNativeSeparators("/") + tr("name") + "</code>"; replyStatus = ST_OK; replyMessage = tr("Directory already exists. Add %1 if you intend to create a new directory here.").arg(separator); } else { replyStatus = ST_ERROR; replyMessage = tr("Path already exists, and is not a directory."); } } } catch (const fs::filesystem_error&) { /* Parent directory does not exist or is not accessible */ replyStatus = ST_ERROR; replyMessage = tr("Cannot create data directory here."); } Q_EMIT reply(replyStatus, replyMessage, freeBytesAvailable); } namespace { //! Return pruning size that will be used if automatic pruning is enabled. int GetPruneTargetGB() { int64_t prune_target_mib = gArgs.GetArg("-prune", 0); // >1 means automatic pruning is enabled by config, 1 means manual pruning, 0 means no pruning. return prune_target_mib > 1 ? PruneMiBtoGB(prune_target_mib) : DEFAULT_PRUNE_TARGET_GB; } } // namespace Intro::Intro(QWidget *parent, int64_t blockchain_size_gb, int64_t chain_state_size_gb) : QDialog(parent, GUIUtil::dialog_flags), ui(new Ui::Intro), thread(nullptr), signalled(false), m_blockchain_size_gb(blockchain_size_gb), m_chain_state_size_gb(chain_state_size_gb), m_prune_target_gb{GetPruneTargetGB()} { ui->setupUi(this); ui->welcomeLabel->setText(ui->welcomeLabel->text().arg(PACKAGE_NAME)); ui->storageLabel->setText(ui->storageLabel->text().arg(PACKAGE_NAME)); ui->lblExplanation1->setText(ui->lblExplanation1->text() .arg(PACKAGE_NAME) .arg(m_blockchain_size_gb) .arg(2014) .arg(tr("Syscoin")) ); ui->lblExplanation2->setText(ui->lblExplanation2->text().arg(PACKAGE_NAME)); const int min_prune_target_GB = std::ceil(MIN_DISK_SPACE_FOR_BLOCK_FILES / 1e9); ui->pruneGB->setRange(min_prune_target_GB, std::numeric_limits<int>::max()); if (gArgs.GetArg("-prune", 0) > 1) { // -prune=1 means enabled, above that it's a size in MiB ui->prune->setChecked(true); ui->prune->setEnabled(false); } ui->pruneGB->setValue(m_prune_target_gb); ui->pruneGB->setToolTip(ui->prune->toolTip()); ui->lblPruneSuffix->setToolTip(ui->prune->toolTip()); UpdatePruneLabels(ui->prune->isChecked()); connect(ui->prune, &QCheckBox::toggled, [this](bool prune_checked) { UpdatePruneLabels(prune_checked); UpdateFreeSpaceLabel(); }); connect(ui->pruneGB, qOverload<int>(&QSpinBox::valueChanged), [this](int prune_GB) { m_prune_target_gb = prune_GB; UpdatePruneLabels(ui->prune->isChecked()); UpdateFreeSpaceLabel(); }); startThread(); } Intro::~Intro() { delete ui; /* Ensure thread is finished before it is deleted */ thread->quit(); thread->wait(); } QString Intro::getDataDirectory() { return ui->dataDirectory->text(); } void Intro::setDataDirectory(const QString &dataDir) { ui->dataDirectory->setText(dataDir); if(dataDir == GUIUtil::getDefaultDataDirectory()) { ui->dataDirDefault->setChecked(true); ui->dataDirectory->setEnabled(false); ui->ellipsisButton->setEnabled(false); } else { ui->dataDirCustom->setChecked(true); ui->dataDirectory->setEnabled(true); ui->ellipsisButton->setEnabled(true); } } int64_t Intro::getPruneMiB() const { switch (ui->prune->checkState()) { case Qt::Checked: return PruneGBtoMiB(m_prune_target_gb); case Qt::Unchecked: default: return 0; } } bool Intro::showIfNeeded(bool& did_show_intro, int64_t& prune_MiB) { did_show_intro = false; QSettings settings; /* If data directory provided on command line, no need to look at settings or show a picking dialog */ if(!gArgs.GetArg("-datadir", "").empty()) return true; // SYSCOIN /* 1) Default data directory for operating system */ QString defaultDir = GUIUtil::getDefaultDataDirectory(); /* 2) Allow QSettings to override default dir only if not SyscoinCore which was used in v3 */ QString dataDir = settings.value("strDataDir", defaultDir).toString(); if(dataDir.endsWith(QString("SyscoinCore"), Qt::CaseInsensitive)) dataDir = defaultDir; if(!fs::exists(GUIUtil::qstringToBoostPath(dataDir)) || gArgs.GetBoolArg("-choosedatadir", DEFAULT_CHOOSE_DATADIR) || settings.value("fReset", false).toBool() || gArgs.GetBoolArg("-resetguisettings", false)) { /* Use selectParams here to guarantee Params() can be used by node interface */ try { SelectParams(gArgs.GetChainName()); } catch (const std::exception&) { return false; } /* If current default data directory does not exist, let the user choose one */ Intro intro(0, Params().AssumedBlockchainSize(), Params().AssumedChainStateSize()); intro.setDataDirectory(dataDir); intro.setWindowIcon(QIcon(":icons/syscoin")); did_show_intro = true; while(true) { if(!intro.exec()) { /* Cancel clicked */ return false; } dataDir = intro.getDataDirectory(); try { if (TryCreateDirectories(GUIUtil::qstringToBoostPath(dataDir))) { // If a new data directory has been created, make wallets subdirectory too TryCreateDirectories(GUIUtil::qstringToBoostPath(dataDir) / "wallets"); } break; } catch (const fs::filesystem_error&) { QMessageBox::critical(nullptr, PACKAGE_NAME, tr("Error: Specified data directory \"%1\" cannot be created.").arg(dataDir)); /* fall through, back to choosing screen */ } } // Additional preferences: prune_MiB = intro.getPruneMiB(); settings.setValue("strDataDir", dataDir); settings.setValue("fReset", false); } /* Only override -datadir if different from the default, to make it possible to * override -datadir in the syscoin.conf file in the default data directory * (to be consistent with syscoind behavior) */ if(dataDir != GUIUtil::getDefaultDataDirectory()) { gArgs.SoftSetArg("-datadir", GUIUtil::qstringToBoostPath(dataDir).string()); // use OS locale for path setting } return true; } void Intro::setStatus(int status, const QString &message, quint64 bytesAvailable) { switch(status) { case FreespaceChecker::ST_OK: ui->errorMessage->setText(message); ui->errorMessage->setStyleSheet(""); break; case FreespaceChecker::ST_ERROR: ui->errorMessage->setText(tr("Error") + ": " + message); ui->errorMessage->setStyleSheet("QLabel { color: #800000 }"); break; } /* Indicate number of bytes available */ if(status == FreespaceChecker::ST_ERROR) { ui->freeSpace->setText(""); } else { m_bytes_available = bytesAvailable; if (ui->prune->isEnabled()) { ui->prune->setChecked(m_bytes_available < (m_blockchain_size_gb + m_chain_state_size_gb + 10) * GB_BYTES); } UpdateFreeSpaceLabel(); } /* Don't allow confirm in ERROR state */ ui->buttonBox->button(QDialogButtonBox::Ok)->setEnabled(status != FreespaceChecker::ST_ERROR); } void Intro::UpdateFreeSpaceLabel() { QString freeString = tr("%1 GB of free space available").arg(m_bytes_available / GB_BYTES); if (m_bytes_available < m_required_space_gb * GB_BYTES) { freeString += " " + tr("(of %1 GB needed)").arg(m_required_space_gb); ui->freeSpace->setStyleSheet("QLabel { color: #800000 }"); } else if (m_bytes_available / GB_BYTES - m_required_space_gb < 10) { freeString += " " + tr("(%1 GB needed for full chain)").arg(m_required_space_gb); ui->freeSpace->setStyleSheet("QLabel { color: #999900 }"); } else { ui->freeSpace->setStyleSheet(""); } ui->freeSpace->setText(freeString + "."); } void Intro::on_dataDirectory_textChanged(const QString &dataDirStr) { /* Disable OK button until check result comes in */ ui->buttonBox->button(QDialogButtonBox::Ok)->setEnabled(false); checkPath(dataDirStr); } void Intro::on_ellipsisButton_clicked() { QString dir = QDir::toNativeSeparators(QFileDialog::getExistingDirectory(nullptr, "Choose data directory", ui->dataDirectory->text())); if(!dir.isEmpty()) ui->dataDirectory->setText(dir); } void Intro::on_dataDirDefault_clicked() { setDataDirectory(GUIUtil::getDefaultDataDirectory()); } void Intro::on_dataDirCustom_clicked() { ui->dataDirectory->setEnabled(true); ui->ellipsisButton->setEnabled(true); } void Intro::startThread() { thread = new QThread(this); FreespaceChecker *executor = new FreespaceChecker(this); executor->moveToThread(thread); connect(executor, &FreespaceChecker::reply, this, &Intro::setStatus); connect(this, &Intro::requestCheck, executor, &FreespaceChecker::check); /* make sure executor object is deleted in its own thread */ connect(thread, &QThread::finished, executor, &QObject::deleteLater); thread->start(); } void Intro::checkPath(const QString &dataDir) { mutex.lock(); pathToCheck = dataDir; if(!signalled) { signalled = true; Q_EMIT requestCheck(); } mutex.unlock(); } QString Intro::getPathToCheck() { QString retval; mutex.lock(); retval = pathToCheck; signalled = false; /* new request can be queued now */ mutex.unlock(); return retval; } void Intro::UpdatePruneLabels(bool prune_checked) { m_required_space_gb = m_blockchain_size_gb + m_chain_state_size_gb; QString storageRequiresMsg = tr("At least %1 GB of data will be stored in this directory, and it will grow over time."); if (prune_checked && m_prune_target_gb <= m_blockchain_size_gb) { m_required_space_gb = m_prune_target_gb + m_chain_state_size_gb; storageRequiresMsg = tr("Approximately %1 GB of data will be stored in this directory."); } ui->lblExplanation3->setVisible(prune_checked); ui->pruneGB->setEnabled(prune_checked); // SYSCOIN static constexpr uint64_t nPowTargetSpacing = 60; // from chainparams, which we don't have at this stage static constexpr uint32_t expected_block_data_size = 250000; // includes undo data const uint64_t expected_backup_days = m_prune_target_gb * 1e9 / (uint64_t(expected_block_data_size) * 86400 / nPowTargetSpacing); ui->lblPruneSuffix->setText(tr("(sufficient to restore backups %n day(s) old)", "block chain pruning", expected_backup_days)); ui->sizeWarningLabel->setText( tr("%1 will download and store a copy of the Syscoin block chain.").arg(PACKAGE_NAME) + " " + storageRequiresMsg.arg(m_required_space_gb) + " " + tr("The wallet will also be stored in this directory.") ); this->adjustSize(); } <|endoftext|>
<commit_before>// Copyright (c) 2011-2018 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #if defined(HAVE_CONFIG_H) #include <config/bitcoin-config.h> #endif #include <fs.h> #include <qt/intro.h> #include <qt/forms/ui_intro.h> #include <qt/guiutil.h> #include <interfaces/node.h> #include <util.h> #include <QFileDialog> #include <QSettings> #include <QMessageBox> #include <cmath> static const uint64_t GB_BYTES = 1000000000LL; /* Minimum free space (in GB) needed for data directory */ constexpr uint64_t BLOCK_CHAIN_SIZE = 220; /* Minimum free space (in GB) needed for data directory when pruned; Does not include prune target */ static const uint64_t CHAIN_STATE_SIZE = 3; /* Total required space (in GB) depending on user choice (prune, not prune) */ static uint64_t requiredSpace; /* Check free space asynchronously to prevent hanging the UI thread. Up to one request to check a path is in flight to this thread; when the check() function runs, the current path is requested from the associated Intro object. The reply is sent back through a signal. This ensures that no queue of checking requests is built up while the user is still entering the path, and that always the most recently entered path is checked as soon as the thread becomes available. */ class FreespaceChecker : public QObject { Q_OBJECT public: explicit FreespaceChecker(Intro *intro); enum Status { ST_OK, ST_ERROR }; public Q_SLOTS: void check(); Q_SIGNALS: void reply(int status, const QString &message, quint64 available); private: Intro *intro; }; #include <qt/intro.moc> FreespaceChecker::FreespaceChecker(Intro *_intro) { this->intro = _intro; } void FreespaceChecker::check() { QString dataDirStr = intro->getPathToCheck(); fs::path dataDir = GUIUtil::qstringToBoostPath(dataDirStr); uint64_t freeBytesAvailable = 0; int replyStatus = ST_OK; QString replyMessage = tr("A new data directory will be created."); /* Find first parent that exists, so that fs::space does not fail */ fs::path parentDir = dataDir; fs::path parentDirOld = fs::path(); while(parentDir.has_parent_path() && !fs::exists(parentDir)) { parentDir = parentDir.parent_path(); /* Check if we make any progress, break if not to prevent an infinite loop here */ if (parentDirOld == parentDir) break; parentDirOld = parentDir; } try { freeBytesAvailable = fs::space(parentDir).available; if(fs::exists(dataDir)) { if(fs::is_directory(dataDir)) { QString separator = "<code>" + QDir::toNativeSeparators("/") + tr("name") + "</code>"; replyStatus = ST_OK; replyMessage = tr("Directory already exists. Add %1 if you intend to create a new directory here.").arg(separator); } else { replyStatus = ST_ERROR; replyMessage = tr("Path already exists, and is not a directory."); } } } catch (const fs::filesystem_error&) { /* Parent directory does not exist or is not accessible */ replyStatus = ST_ERROR; replyMessage = tr("Cannot create data directory here."); } Q_EMIT reply(replyStatus, replyMessage, freeBytesAvailable); } Intro::Intro(QWidget *parent) : QDialog(parent), ui(new Ui::Intro), thread(0), signalled(false) { ui->setupUi(this); ui->welcomeLabel->setText(ui->welcomeLabel->text().arg(tr(PACKAGE_NAME))); ui->storageLabel->setText(ui->storageLabel->text().arg(tr(PACKAGE_NAME))); ui->lblExplanation1->setText(ui->lblExplanation1->text() .arg(tr(PACKAGE_NAME)) .arg(BLOCK_CHAIN_SIZE) .arg(2009) .arg(tr("Bitcoin")) ); ui->lblExplanation2->setText(ui->lblExplanation2->text().arg(tr(PACKAGE_NAME))); uint64_t pruneTarget = std::max<int64_t>(0, gArgs.GetArg("-prune", 0)); requiredSpace = BLOCK_CHAIN_SIZE; QString storageRequiresMsg = tr("At least %1 GB of data will be stored in this directory, and it will grow over time."); if (pruneTarget) { uint64_t prunedGBs = std::ceil(pruneTarget * 1024 * 1024.0 / GB_BYTES); if (prunedGBs <= requiredSpace) { requiredSpace = prunedGBs; storageRequiresMsg = tr("Approximately %1 GB of data will be stored in this directory."); } ui->lblExplanation3->setVisible(true); } else { ui->lblExplanation3->setVisible(false); } requiredSpace += CHAIN_STATE_SIZE; ui->sizeWarningLabel->setText( tr("%1 will download and store a copy of the Bitcoin block chain.").arg(tr(PACKAGE_NAME)) + " " + storageRequiresMsg.arg(requiredSpace) + " " + tr("The wallet will also be stored in this directory.") ); startThread(); } Intro::~Intro() { delete ui; /* Ensure thread is finished before it is deleted */ Q_EMIT stopThread(); thread->wait(); } QString Intro::getDataDirectory() { return ui->dataDirectory->text(); } void Intro::setDataDirectory(const QString &dataDir) { ui->dataDirectory->setText(dataDir); if(dataDir == getDefaultDataDirectory()) { ui->dataDirDefault->setChecked(true); ui->dataDirectory->setEnabled(false); ui->ellipsisButton->setEnabled(false); } else { ui->dataDirCustom->setChecked(true); ui->dataDirectory->setEnabled(true); ui->ellipsisButton->setEnabled(true); } } QString Intro::getDefaultDataDirectory() { return GUIUtil::boostPathToQString(GetDefaultDataDir()); } bool Intro::pickDataDirectory(interfaces::Node& node) { QSettings settings; /* If data directory provided on command line, no need to look at settings or show a picking dialog */ if(!gArgs.GetArg("-datadir", "").empty()) return true; /* 1) Default data directory for operating system */ QString dataDir = getDefaultDataDirectory(); /* 2) Allow QSettings to override default dir */ dataDir = settings.value("strDataDir", dataDir).toString(); if(!fs::exists(GUIUtil::qstringToBoostPath(dataDir)) || gArgs.GetBoolArg("-choosedatadir", DEFAULT_CHOOSE_DATADIR) || settings.value("fReset", false).toBool() || gArgs.GetBoolArg("-resetguisettings", false)) { /* If current default data directory does not exist, let the user choose one */ Intro intro; intro.setDataDirectory(dataDir); intro.setWindowIcon(QIcon(":icons/bitcoin")); while(true) { if(!intro.exec()) { /* Cancel clicked */ return false; } dataDir = intro.getDataDirectory(); try { if (TryCreateDirectories(GUIUtil::qstringToBoostPath(dataDir))) { // If a new data directory has been created, make wallets subdirectory too TryCreateDirectories(GUIUtil::qstringToBoostPath(dataDir) / "wallets"); } break; } catch (const fs::filesystem_error&) { QMessageBox::critical(0, tr(PACKAGE_NAME), tr("Error: Specified data directory \"%1\" cannot be created.").arg(dataDir)); /* fall through, back to choosing screen */ } } settings.setValue("strDataDir", dataDir); settings.setValue("fReset", false); } /* Only override -datadir if different from the default, to make it possible to * override -datadir in the bitcoin.conf file in the default data directory * (to be consistent with bitcoind behavior) */ if(dataDir != getDefaultDataDirectory()) { node.softSetArg("-datadir", GUIUtil::qstringToBoostPath(dataDir).string()); // use OS locale for path setting } return true; } void Intro::setStatus(int status, const QString &message, quint64 bytesAvailable) { switch(status) { case FreespaceChecker::ST_OK: ui->errorMessage->setText(message); ui->errorMessage->setStyleSheet(""); break; case FreespaceChecker::ST_ERROR: ui->errorMessage->setText(tr("Error") + ": " + message); ui->errorMessage->setStyleSheet("QLabel { color: #800000 }"); break; } /* Indicate number of bytes available */ if(status == FreespaceChecker::ST_ERROR) { ui->freeSpace->setText(""); } else { QString freeString = tr("%n GB of free space available", "", bytesAvailable/GB_BYTES); if(bytesAvailable < requiredSpace * GB_BYTES) { freeString += " " + tr("(of %n GB needed)", "", requiredSpace); ui->freeSpace->setStyleSheet("QLabel { color: #800000 }"); } else { ui->freeSpace->setStyleSheet(""); } ui->freeSpace->setText(freeString + "."); } /* Don't allow confirm in ERROR state */ ui->buttonBox->button(QDialogButtonBox::Ok)->setEnabled(status != FreespaceChecker::ST_ERROR); } void Intro::on_dataDirectory_textChanged(const QString &dataDirStr) { /* Disable OK button until check result comes in */ ui->buttonBox->button(QDialogButtonBox::Ok)->setEnabled(false); checkPath(dataDirStr); } void Intro::on_ellipsisButton_clicked() { QString dir = QDir::toNativeSeparators(QFileDialog::getExistingDirectory(0, "Choose data directory", ui->dataDirectory->text())); if(!dir.isEmpty()) ui->dataDirectory->setText(dir); } void Intro::on_dataDirDefault_clicked() { setDataDirectory(getDefaultDataDirectory()); } void Intro::on_dataDirCustom_clicked() { ui->dataDirectory->setEnabled(true); ui->ellipsisButton->setEnabled(true); } void Intro::startThread() { thread = new QThread(this); FreespaceChecker *executor = new FreespaceChecker(this); executor->moveToThread(thread); connect(executor, &FreespaceChecker::reply, this, &Intro::setStatus); connect(this, &Intro::requestCheck, executor, &FreespaceChecker::check); /* make sure executor object is deleted in its own thread */ connect(this, &Intro::stopThread, executor, &QObject::deleteLater); connect(this, &Intro::stopThread, thread, &QThread::quit); thread->start(); } void Intro::checkPath(const QString &dataDir) { mutex.lock(); pathToCheck = dataDir; if(!signalled) { signalled = true; Q_EMIT requestCheck(); } mutex.unlock(); } QString Intro::getPathToCheck() { QString retval; mutex.lock(); retval = pathToCheck; signalled = false; /* new request can be queued now */ mutex.unlock(); return retval; } <commit_msg>GUI: Adjust blockchain and chainstate sizes in Intro<commit_after>// Copyright (c) 2011-2018 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #if defined(HAVE_CONFIG_H) #include <config/bitcoin-config.h> #endif #include <fs.h> #include <qt/intro.h> #include <qt/forms/ui_intro.h> #include <qt/guiutil.h> #include <interfaces/node.h> #include <util.h> #include <QFileDialog> #include <QSettings> #include <QMessageBox> #include <cmath> static const uint64_t GB_BYTES = 1000000000LL; /* Minimum free space (in GB) needed for data directory */ constexpr uint64_t BLOCK_CHAIN_SIZE = 1; /* Minimum free space (in GB) needed for data directory when pruned; Does not include prune target */ static const uint64_t CHAIN_STATE_SIZE = 0; /* Total required space (in GB) depending on user choice (prune, not prune) */ static uint64_t requiredSpace; /* Check free space asynchronously to prevent hanging the UI thread. Up to one request to check a path is in flight to this thread; when the check() function runs, the current path is requested from the associated Intro object. The reply is sent back through a signal. This ensures that no queue of checking requests is built up while the user is still entering the path, and that always the most recently entered path is checked as soon as the thread becomes available. */ class FreespaceChecker : public QObject { Q_OBJECT public: explicit FreespaceChecker(Intro *intro); enum Status { ST_OK, ST_ERROR }; public Q_SLOTS: void check(); Q_SIGNALS: void reply(int status, const QString &message, quint64 available); private: Intro *intro; }; #include <qt/intro.moc> FreespaceChecker::FreespaceChecker(Intro *_intro) { this->intro = _intro; } void FreespaceChecker::check() { QString dataDirStr = intro->getPathToCheck(); fs::path dataDir = GUIUtil::qstringToBoostPath(dataDirStr); uint64_t freeBytesAvailable = 0; int replyStatus = ST_OK; QString replyMessage = tr("A new data directory will be created."); /* Find first parent that exists, so that fs::space does not fail */ fs::path parentDir = dataDir; fs::path parentDirOld = fs::path(); while(parentDir.has_parent_path() && !fs::exists(parentDir)) { parentDir = parentDir.parent_path(); /* Check if we make any progress, break if not to prevent an infinite loop here */ if (parentDirOld == parentDir) break; parentDirOld = parentDir; } try { freeBytesAvailable = fs::space(parentDir).available; if(fs::exists(dataDir)) { if(fs::is_directory(dataDir)) { QString separator = "<code>" + QDir::toNativeSeparators("/") + tr("name") + "</code>"; replyStatus = ST_OK; replyMessage = tr("Directory already exists. Add %1 if you intend to create a new directory here.").arg(separator); } else { replyStatus = ST_ERROR; replyMessage = tr("Path already exists, and is not a directory."); } } } catch (const fs::filesystem_error&) { /* Parent directory does not exist or is not accessible */ replyStatus = ST_ERROR; replyMessage = tr("Cannot create data directory here."); } Q_EMIT reply(replyStatus, replyMessage, freeBytesAvailable); } Intro::Intro(QWidget *parent) : QDialog(parent), ui(new Ui::Intro), thread(0), signalled(false) { ui->setupUi(this); ui->welcomeLabel->setText(ui->welcomeLabel->text().arg(tr(PACKAGE_NAME))); ui->storageLabel->setText(ui->storageLabel->text().arg(tr(PACKAGE_NAME))); ui->lblExplanation1->setText(ui->lblExplanation1->text() .arg(tr(PACKAGE_NAME)) .arg(BLOCK_CHAIN_SIZE) .arg(2009) .arg(tr("Bitcoin")) ); ui->lblExplanation2->setText(ui->lblExplanation2->text().arg(tr(PACKAGE_NAME))); uint64_t pruneTarget = std::max<int64_t>(0, gArgs.GetArg("-prune", 0)); requiredSpace = BLOCK_CHAIN_SIZE; QString storageRequiresMsg = tr("At least %1 GB of data will be stored in this directory, and it will grow over time."); if (pruneTarget) { uint64_t prunedGBs = std::ceil(pruneTarget * 1024 * 1024.0 / GB_BYTES); if (prunedGBs <= requiredSpace) { requiredSpace = prunedGBs; storageRequiresMsg = tr("Approximately %1 GB of data will be stored in this directory."); } ui->lblExplanation3->setVisible(true); } else { ui->lblExplanation3->setVisible(false); } requiredSpace += CHAIN_STATE_SIZE; ui->sizeWarningLabel->setText( tr("%1 will download and store a copy of the Bitcoin block chain.").arg(tr(PACKAGE_NAME)) + " " + storageRequiresMsg.arg(requiredSpace) + " " + tr("The wallet will also be stored in this directory.") ); startThread(); } Intro::~Intro() { delete ui; /* Ensure thread is finished before it is deleted */ Q_EMIT stopThread(); thread->wait(); } QString Intro::getDataDirectory() { return ui->dataDirectory->text(); } void Intro::setDataDirectory(const QString &dataDir) { ui->dataDirectory->setText(dataDir); if(dataDir == getDefaultDataDirectory()) { ui->dataDirDefault->setChecked(true); ui->dataDirectory->setEnabled(false); ui->ellipsisButton->setEnabled(false); } else { ui->dataDirCustom->setChecked(true); ui->dataDirectory->setEnabled(true); ui->ellipsisButton->setEnabled(true); } } QString Intro::getDefaultDataDirectory() { return GUIUtil::boostPathToQString(GetDefaultDataDir()); } bool Intro::pickDataDirectory(interfaces::Node& node) { QSettings settings; /* If data directory provided on command line, no need to look at settings or show a picking dialog */ if(!gArgs.GetArg("-datadir", "").empty()) return true; /* 1) Default data directory for operating system */ QString dataDir = getDefaultDataDirectory(); /* 2) Allow QSettings to override default dir */ dataDir = settings.value("strDataDir", dataDir).toString(); if(!fs::exists(GUIUtil::qstringToBoostPath(dataDir)) || gArgs.GetBoolArg("-choosedatadir", DEFAULT_CHOOSE_DATADIR) || settings.value("fReset", false).toBool() || gArgs.GetBoolArg("-resetguisettings", false)) { /* If current default data directory does not exist, let the user choose one */ Intro intro; intro.setDataDirectory(dataDir); intro.setWindowIcon(QIcon(":icons/bitcoin")); while(true) { if(!intro.exec()) { /* Cancel clicked */ return false; } dataDir = intro.getDataDirectory(); try { if (TryCreateDirectories(GUIUtil::qstringToBoostPath(dataDir))) { // If a new data directory has been created, make wallets subdirectory too TryCreateDirectories(GUIUtil::qstringToBoostPath(dataDir) / "wallets"); } break; } catch (const fs::filesystem_error&) { QMessageBox::critical(0, tr(PACKAGE_NAME), tr("Error: Specified data directory \"%1\" cannot be created.").arg(dataDir)); /* fall through, back to choosing screen */ } } settings.setValue("strDataDir", dataDir); settings.setValue("fReset", false); } /* Only override -datadir if different from the default, to make it possible to * override -datadir in the bitcoin.conf file in the default data directory * (to be consistent with bitcoind behavior) */ if(dataDir != getDefaultDataDirectory()) { node.softSetArg("-datadir", GUIUtil::qstringToBoostPath(dataDir).string()); // use OS locale for path setting } return true; } void Intro::setStatus(int status, const QString &message, quint64 bytesAvailable) { switch(status) { case FreespaceChecker::ST_OK: ui->errorMessage->setText(message); ui->errorMessage->setStyleSheet(""); break; case FreespaceChecker::ST_ERROR: ui->errorMessage->setText(tr("Error") + ": " + message); ui->errorMessage->setStyleSheet("QLabel { color: #800000 }"); break; } /* Indicate number of bytes available */ if(status == FreespaceChecker::ST_ERROR) { ui->freeSpace->setText(""); } else { QString freeString = tr("%n GB of free space available", "", bytesAvailable/GB_BYTES); if(bytesAvailable < requiredSpace * GB_BYTES) { freeString += " " + tr("(of %n GB needed)", "", requiredSpace); ui->freeSpace->setStyleSheet("QLabel { color: #800000 }"); } else { ui->freeSpace->setStyleSheet(""); } ui->freeSpace->setText(freeString + "."); } /* Don't allow confirm in ERROR state */ ui->buttonBox->button(QDialogButtonBox::Ok)->setEnabled(status != FreespaceChecker::ST_ERROR); } void Intro::on_dataDirectory_textChanged(const QString &dataDirStr) { /* Disable OK button until check result comes in */ ui->buttonBox->button(QDialogButtonBox::Ok)->setEnabled(false); checkPath(dataDirStr); } void Intro::on_ellipsisButton_clicked() { QString dir = QDir::toNativeSeparators(QFileDialog::getExistingDirectory(0, "Choose data directory", ui->dataDirectory->text())); if(!dir.isEmpty()) ui->dataDirectory->setText(dir); } void Intro::on_dataDirDefault_clicked() { setDataDirectory(getDefaultDataDirectory()); } void Intro::on_dataDirCustom_clicked() { ui->dataDirectory->setEnabled(true); ui->ellipsisButton->setEnabled(true); } void Intro::startThread() { thread = new QThread(this); FreespaceChecker *executor = new FreespaceChecker(this); executor->moveToThread(thread); connect(executor, &FreespaceChecker::reply, this, &Intro::setStatus); connect(this, &Intro::requestCheck, executor, &FreespaceChecker::check); /* make sure executor object is deleted in its own thread */ connect(this, &Intro::stopThread, executor, &QObject::deleteLater); connect(this, &Intro::stopThread, thread, &QThread::quit); thread->start(); } void Intro::checkPath(const QString &dataDir) { mutex.lock(); pathToCheck = dataDir; if(!signalled) { signalled = true; Q_EMIT requestCheck(); } mutex.unlock(); } QString Intro::getPathToCheck() { QString retval; mutex.lock(); retval = pathToCheck; signalled = false; /* new request can be queued now */ mutex.unlock(); return retval; } <|endoftext|>
<commit_before>// Copyright (c) 2011-2017 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #if defined(HAVE_CONFIG_H) #include <config/bitcoin-config.h> #endif #include <fs.h> #include <qt/intro.h> #include <qt/forms/ui_intro.h> #include <qt/guiutil.h> #include <util.h> #include <QFileDialog> #include <QSettings> #include <QMessageBox> #include <cmath> static const uint64_t GB_BYTES = 1000000000LL; /* Minimum free space (in GB) needed for data directory */ static const uint64_t BLOCK_CHAIN_SIZE = 14; /* Minimum free space (in GB) needed for data directory when pruned; Does not include prune target */ static const uint64_t CHAIN_STATE_SIZE = 3; /* Total required space (in GB) depending on user choice (prune, not prune) */ static uint64_t requiredSpace; /* Check free space asynchronously to prevent hanging the UI thread. Up to one request to check a path is in flight to this thread; when the check() function runs, the current path is requested from the associated Intro object. The reply is sent back through a signal. This ensures that no queue of checking requests is built up while the user is still entering the path, and that always the most recently entered path is checked as soon as the thread becomes available. */ class FreespaceChecker : public QObject { Q_OBJECT public: explicit FreespaceChecker(Intro *intro); enum Status { ST_OK, ST_ERROR }; public Q_SLOTS: void check(); Q_SIGNALS: void reply(int status, const QString &message, quint64 available); private: Intro *intro; }; #include <qt/intro.moc> FreespaceChecker::FreespaceChecker(Intro *_intro) { this->intro = _intro; } void FreespaceChecker::check() { QString dataDirStr = intro->getPathToCheck(); fs::path dataDir = GUIUtil::qstringToBoostPath(dataDirStr); uint64_t freeBytesAvailable = 0; int replyStatus = ST_OK; QString replyMessage = tr("A new data directory will be created."); /* Find first parent that exists, so that fs::space does not fail */ fs::path parentDir = dataDir; fs::path parentDirOld = fs::path(); while(parentDir.has_parent_path() && !fs::exists(parentDir)) { parentDir = parentDir.parent_path(); /* Check if we make any progress, break if not to prevent an infinite loop here */ if (parentDirOld == parentDir) break; parentDirOld = parentDir; } try { freeBytesAvailable = fs::space(parentDir).available; if(fs::exists(dataDir)) { if(fs::is_directory(dataDir)) { QString separator = "<code>" + QDir::toNativeSeparators("/") + tr("name") + "</code>"; replyStatus = ST_OK; replyMessage = tr("Directory already exists. Add %1 if you intend to create a new directory here.").arg(separator); } else { replyStatus = ST_ERROR; replyMessage = tr("Path already exists, and is not a directory."); } } } catch (const fs::filesystem_error&) { /* Parent directory does not exist or is not accessible */ replyStatus = ST_ERROR; replyMessage = tr("Cannot create data directory here."); } Q_EMIT reply(replyStatus, replyMessage, freeBytesAvailable); } Intro::Intro(QWidget *parent) : QDialog(parent), ui(new Ui::Intro), thread(0), signalled(false) { ui->setupUi(this); ui->welcomeLabel->setText(ui->welcomeLabel->text().arg(tr(PACKAGE_NAME))); ui->storageLabel->setText(ui->storageLabel->text().arg(tr(PACKAGE_NAME))); ui->lblExplanation1->setText(ui->lblExplanation1->text() .arg(tr(PACKAGE_NAME)) .arg(BLOCK_CHAIN_SIZE) .arg(2009) .arg(tr("DeepOnion")) ); ui->lblExplanation2->setText(ui->lblExplanation2->text().arg(tr(PACKAGE_NAME))); uint64_t pruneTarget = std::max<int64_t>(0, gArgs.GetArg("-prune", 0)); requiredSpace = BLOCK_CHAIN_SIZE; QString storageRequiresMsg = tr("At least %1 GB of data will be stored in this directory, and it will grow over time."); if (pruneTarget) { uint64_t prunedGBs = std::ceil(pruneTarget * 1024 * 1024.0 / GB_BYTES); if (prunedGBs <= requiredSpace) { requiredSpace = prunedGBs; storageRequiresMsg = tr("Approximately %1 GB of data will be stored in this directory."); } ui->lblExplanation3->setVisible(true); } else { ui->lblExplanation3->setVisible(false); } requiredSpace += CHAIN_STATE_SIZE; ui->sizeWarningLabel->setText( tr("%1 will download and store a copy of the DeepOnion block chain.").arg(tr(PACKAGE_NAME)) + " " + storageRequiresMsg.arg(requiredSpace) + " " + tr("The wallet will also be stored in this directory.") ); startThread(); } Intro::~Intro() { delete ui; /* Ensure thread is finished before it is deleted */ Q_EMIT stopThread(); thread->wait(); } QString Intro::getDataDirectory() { return ui->dataDirectory->text(); } void Intro::setDataDirectory(const QString &dataDir) { ui->dataDirectory->setText(dataDir); if(dataDir == getDefaultDataDirectory()) { ui->dataDirDefault->setChecked(true); ui->dataDirectory->setEnabled(false); ui->ellipsisButton->setEnabled(false); } else { ui->dataDirCustom->setChecked(true); ui->dataDirectory->setEnabled(true); ui->ellipsisButton->setEnabled(true); } } QString Intro::getDefaultDataDirectory() { return GUIUtil::boostPathToQString(GetDefaultDataDir()); } bool Intro::pickDataDirectory() { QSettings settings; /* If data directory provided on command line, no need to look at settings or show a picking dialog */ if(!gArgs.GetArg("-datadir", "").empty()) return true; /* 1) Default data directory for operating system */ QString dataDir = getDefaultDataDirectory(); /* 2) Allow QSettings to override default dir */ dataDir = settings.value("strDataDir", dataDir).toString(); if(!fs::exists(GUIUtil::qstringToBoostPath(dataDir)) || gArgs.GetBoolArg("-choosedatadir", DEFAULT_CHOOSE_DATADIR) || settings.value("fReset", false).toBool() || gArgs.GetBoolArg("-resetguisettings", false)) { /* If current default data directory does not exist, let the user choose one */ Intro intro; intro.setDataDirectory(dataDir); intro.setWindowIcon(QIcon(":icons/bitcoin")); while(true) { if(!intro.exec()) { /* Cancel clicked */ return false; } dataDir = intro.getDataDirectory(); try { if (TryCreateDirectories(GUIUtil::qstringToBoostPath(dataDir))) { // If a new data directory has been created, make wallets subdirectory too TryCreateDirectories(GUIUtil::qstringToBoostPath(dataDir) / "wallets"); } break; } catch (const fs::filesystem_error&) { QMessageBox::critical(0, tr(PACKAGE_NAME), tr("Error: Specified data directory \"%1\" cannot be created.").arg(dataDir)); /* fall through, back to choosing screen */ } } settings.setValue("strDataDir", dataDir); settings.setValue("fReset", false); } /* Only override -datadir if different from the default, to make it possible to * override -datadir in the bitcoin.conf file in the default data directory * (to be consistent with bitcoind behavior) */ if(dataDir != getDefaultDataDirectory()) gArgs.SoftSetArg("-datadir", GUIUtil::qstringToBoostPath(dataDir).string()); // use OS locale for path setting return true; } void Intro::setStatus(int status, const QString &message, quint64 bytesAvailable) { switch(status) { case FreespaceChecker::ST_OK: ui->errorMessage->setText(message); ui->errorMessage->setStyleSheet(""); break; case FreespaceChecker::ST_ERROR: ui->errorMessage->setText(tr("Error") + ": " + message); ui->errorMessage->setStyleSheet("QLabel { color: #800000 }"); break; } /* Indicate number of bytes available */ if(status == FreespaceChecker::ST_ERROR) { ui->freeSpace->setText(""); } else { QString freeString = tr("%n GB of free space available", "", bytesAvailable/GB_BYTES); if(bytesAvailable < requiredSpace * GB_BYTES) { freeString += " " + tr("(of %n GB needed)", "", requiredSpace); ui->freeSpace->setStyleSheet("QLabel { color: #800000 }"); } else { ui->freeSpace->setStyleSheet(""); } ui->freeSpace->setText(freeString + "."); } /* Don't allow confirm in ERROR state */ ui->buttonBox->button(QDialogButtonBox::Ok)->setEnabled(status != FreespaceChecker::ST_ERROR); } void Intro::on_dataDirectory_textChanged(const QString &dataDirStr) { /* Disable OK button until check result comes in */ ui->buttonBox->button(QDialogButtonBox::Ok)->setEnabled(false); checkPath(dataDirStr); } void Intro::on_ellipsisButton_clicked() { QString dir = QDir::toNativeSeparators(QFileDialog::getExistingDirectory(0, "Choose data directory", ui->dataDirectory->text())); if(!dir.isEmpty()) ui->dataDirectory->setText(dir); } void Intro::on_dataDirDefault_clicked() { setDataDirectory(getDefaultDataDirectory()); } void Intro::on_dataDirCustom_clicked() { ui->dataDirectory->setEnabled(true); ui->ellipsisButton->setEnabled(true); } void Intro::startThread() { thread = new QThread(this); FreespaceChecker *executor = new FreespaceChecker(this); executor->moveToThread(thread); connect(executor, SIGNAL(reply(int,QString,quint64)), this, SLOT(setStatus(int,QString,quint64))); connect(this, SIGNAL(requestCheck()), executor, SLOT(check())); /* make sure executor object is deleted in its own thread */ connect(this, SIGNAL(stopThread()), executor, SLOT(deleteLater())); connect(this, SIGNAL(stopThread()), thread, SLOT(quit())); thread->start(); } void Intro::checkPath(const QString &dataDir) { mutex.lock(); pathToCheck = dataDir; if(!signalled) { signalled = true; Q_EMIT requestCheck(); } mutex.unlock(); } QString Intro::getPathToCheck() { QString retval; mutex.lock(); retval = pathToCheck; signalled = false; /* new request can be queued now */ mutex.unlock(); return retval; } <commit_msg>fix blockchain size and time frame in entry dialog<commit_after>// Copyright (c) 2011-2017 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #if defined(HAVE_CONFIG_H) #include <config/bitcoin-config.h> #endif #include <fs.h> #include <qt/intro.h> #include <qt/forms/ui_intro.h> #include <qt/guiutil.h> #include <util.h> #include <QFileDialog> #include <QSettings> #include <QMessageBox> #include <cmath> static const uint64_t GB_BYTES = 1000000000LL; /* Minimum free space (in GB) needed for data directory */ static const uint64_t BLOCK_CHAIN_SIZE = 3; /* Minimum free space (in GB) needed for data directory when pruned; Does not include prune target */ static const uint64_t CHAIN_STATE_SIZE = 1; /* Total required space (in GB) depending on user choice (prune, not prune) */ static uint64_t requiredSpace; /* Check free space asynchronously to prevent hanging the UI thread. Up to one request to check a path is in flight to this thread; when the check() function runs, the current path is requested from the associated Intro object. The reply is sent back through a signal. This ensures that no queue of checking requests is built up while the user is still entering the path, and that always the most recently entered path is checked as soon as the thread becomes available. */ class FreespaceChecker : public QObject { Q_OBJECT public: explicit FreespaceChecker(Intro *intro); enum Status { ST_OK, ST_ERROR }; public Q_SLOTS: void check(); Q_SIGNALS: void reply(int status, const QString &message, quint64 available); private: Intro *intro; }; #include <qt/intro.moc> FreespaceChecker::FreespaceChecker(Intro *_intro) { this->intro = _intro; } void FreespaceChecker::check() { QString dataDirStr = intro->getPathToCheck(); fs::path dataDir = GUIUtil::qstringToBoostPath(dataDirStr); uint64_t freeBytesAvailable = 0; int replyStatus = ST_OK; QString replyMessage = tr("A new data directory will be created."); /* Find first parent that exists, so that fs::space does not fail */ fs::path parentDir = dataDir; fs::path parentDirOld = fs::path(); while(parentDir.has_parent_path() && !fs::exists(parentDir)) { parentDir = parentDir.parent_path(); /* Check if we make any progress, break if not to prevent an infinite loop here */ if (parentDirOld == parentDir) break; parentDirOld = parentDir; } try { freeBytesAvailable = fs::space(parentDir).available; if(fs::exists(dataDir)) { if(fs::is_directory(dataDir)) { QString separator = "<code>" + QDir::toNativeSeparators("/") + tr("name") + "</code>"; replyStatus = ST_OK; replyMessage = tr("Directory already exists. Add %1 if you intend to create a new directory here.").arg(separator); } else { replyStatus = ST_ERROR; replyMessage = tr("Path already exists, and is not a directory."); } } } catch (const fs::filesystem_error&) { /* Parent directory does not exist or is not accessible */ replyStatus = ST_ERROR; replyMessage = tr("Cannot create data directory here."); } Q_EMIT reply(replyStatus, replyMessage, freeBytesAvailable); } Intro::Intro(QWidget *parent) : QDialog(parent), ui(new Ui::Intro), thread(0), signalled(false) { ui->setupUi(this); ui->welcomeLabel->setText(ui->welcomeLabel->text().arg(tr(PACKAGE_NAME))); ui->storageLabel->setText(ui->storageLabel->text().arg(tr(PACKAGE_NAME))); ui->lblExplanation1->setText(ui->lblExplanation1->text() .arg(tr(PACKAGE_NAME)) .arg(BLOCK_CHAIN_SIZE) .arg(2017) .arg(tr("DeepOnion")) ); ui->lblExplanation2->setText(ui->lblExplanation2->text().arg(tr(PACKAGE_NAME))); uint64_t pruneTarget = std::max<int64_t>(0, gArgs.GetArg("-prune", 0)); requiredSpace = BLOCK_CHAIN_SIZE; QString storageRequiresMsg = tr("At least %1 GB of data will be stored in this directory, and it will grow over time."); if (pruneTarget) { uint64_t prunedGBs = std::ceil(pruneTarget * 1024 * 1024.0 / GB_BYTES); if (prunedGBs <= requiredSpace) { requiredSpace = prunedGBs; storageRequiresMsg = tr("Approximately %1 GB of data will be stored in this directory."); } ui->lblExplanation3->setVisible(true); } else { ui->lblExplanation3->setVisible(false); } requiredSpace += CHAIN_STATE_SIZE; ui->sizeWarningLabel->setText( tr("%1 will download and store a copy of the DeepOnion block chain.").arg(tr(PACKAGE_NAME)) + " " + storageRequiresMsg.arg(requiredSpace) + " " + tr("The wallet will also be stored in this directory.") ); startThread(); } Intro::~Intro() { delete ui; /* Ensure thread is finished before it is deleted */ Q_EMIT stopThread(); thread->wait(); } QString Intro::getDataDirectory() { return ui->dataDirectory->text(); } void Intro::setDataDirectory(const QString &dataDir) { ui->dataDirectory->setText(dataDir); if(dataDir == getDefaultDataDirectory()) { ui->dataDirDefault->setChecked(true); ui->dataDirectory->setEnabled(false); ui->ellipsisButton->setEnabled(false); } else { ui->dataDirCustom->setChecked(true); ui->dataDirectory->setEnabled(true); ui->ellipsisButton->setEnabled(true); } } QString Intro::getDefaultDataDirectory() { return GUIUtil::boostPathToQString(GetDefaultDataDir()); } bool Intro::pickDataDirectory() { QSettings settings; /* If data directory provided on command line, no need to look at settings or show a picking dialog */ if(!gArgs.GetArg("-datadir", "").empty()) return true; /* 1) Default data directory for operating system */ QString dataDir = getDefaultDataDirectory(); /* 2) Allow QSettings to override default dir */ dataDir = settings.value("strDataDir", dataDir).toString(); if(!fs::exists(GUIUtil::qstringToBoostPath(dataDir)) || gArgs.GetBoolArg("-choosedatadir", DEFAULT_CHOOSE_DATADIR) || settings.value("fReset", false).toBool() || gArgs.GetBoolArg("-resetguisettings", false)) { /* If current default data directory does not exist, let the user choose one */ Intro intro; intro.setDataDirectory(dataDir); intro.setWindowIcon(QIcon(":icons/bitcoin")); while(true) { if(!intro.exec()) { /* Cancel clicked */ return false; } dataDir = intro.getDataDirectory(); try { if (TryCreateDirectories(GUIUtil::qstringToBoostPath(dataDir))) { // If a new data directory has been created, make wallets subdirectory too TryCreateDirectories(GUIUtil::qstringToBoostPath(dataDir) / "wallets"); } break; } catch (const fs::filesystem_error&) { QMessageBox::critical(0, tr(PACKAGE_NAME), tr("Error: Specified data directory \"%1\" cannot be created.").arg(dataDir)); /* fall through, back to choosing screen */ } } settings.setValue("strDataDir", dataDir); settings.setValue("fReset", false); } /* Only override -datadir if different from the default, to make it possible to * override -datadir in the bitcoin.conf file in the default data directory * (to be consistent with bitcoind behavior) */ if(dataDir != getDefaultDataDirectory()) gArgs.SoftSetArg("-datadir", GUIUtil::qstringToBoostPath(dataDir).string()); // use OS locale for path setting return true; } void Intro::setStatus(int status, const QString &message, quint64 bytesAvailable) { switch(status) { case FreespaceChecker::ST_OK: ui->errorMessage->setText(message); ui->errorMessage->setStyleSheet(""); break; case FreespaceChecker::ST_ERROR: ui->errorMessage->setText(tr("Error") + ": " + message); ui->errorMessage->setStyleSheet("QLabel { color: #800000 }"); break; } /* Indicate number of bytes available */ if(status == FreespaceChecker::ST_ERROR) { ui->freeSpace->setText(""); } else { QString freeString = tr("%n GB of free space available", "", bytesAvailable/GB_BYTES); if(bytesAvailable < requiredSpace * GB_BYTES) { freeString += " " + tr("(of %n GB needed)", "", requiredSpace); ui->freeSpace->setStyleSheet("QLabel { color: #800000 }"); } else { ui->freeSpace->setStyleSheet(""); } ui->freeSpace->setText(freeString + "."); } /* Don't allow confirm in ERROR state */ ui->buttonBox->button(QDialogButtonBox::Ok)->setEnabled(status != FreespaceChecker::ST_ERROR); } void Intro::on_dataDirectory_textChanged(const QString &dataDirStr) { /* Disable OK button until check result comes in */ ui->buttonBox->button(QDialogButtonBox::Ok)->setEnabled(false); checkPath(dataDirStr); } void Intro::on_ellipsisButton_clicked() { QString dir = QDir::toNativeSeparators(QFileDialog::getExistingDirectory(0, "Choose data directory", ui->dataDirectory->text())); if(!dir.isEmpty()) ui->dataDirectory->setText(dir); } void Intro::on_dataDirDefault_clicked() { setDataDirectory(getDefaultDataDirectory()); } void Intro::on_dataDirCustom_clicked() { ui->dataDirectory->setEnabled(true); ui->ellipsisButton->setEnabled(true); } void Intro::startThread() { thread = new QThread(this); FreespaceChecker *executor = new FreespaceChecker(this); executor->moveToThread(thread); connect(executor, SIGNAL(reply(int,QString,quint64)), this, SLOT(setStatus(int,QString,quint64))); connect(this, SIGNAL(requestCheck()), executor, SLOT(check())); /* make sure executor object is deleted in its own thread */ connect(this, SIGNAL(stopThread()), executor, SLOT(deleteLater())); connect(this, SIGNAL(stopThread()), thread, SLOT(quit())); thread->start(); } void Intro::checkPath(const QString &dataDir) { mutex.lock(); pathToCheck = dataDir; if(!signalled) { signalled = true; Q_EMIT requestCheck(); } mutex.unlock(); } QString Intro::getPathToCheck() { QString retval; mutex.lock(); retval = pathToCheck; signalled = false; /* new request can be queued now */ mutex.unlock(); return retval; } <|endoftext|>
<commit_before>/* * Copyright (c) 2012, Dennis Hedback * 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. * * 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. */ #include <iostream> #include <iterator> #include <set> #include <string> #include <vector> #include "common.hpp" void read_tuples(Product &prod) { Tuple current_tuple; std::string current_elem; for (std::istreambuf_iterator<char> it(std::cin), end; it != end; it++) { char c = *it; if (c == ',' || c == '\n') { current_tuple.push_back(current_elem); current_elem.clear(); if (c == '\n') { prod.insert(current_tuple); current_tuple.clear(); } } else { current_elem += c; } } } void init_generator(Generator &gen, size_t size) { for (unsigned int i = 0; i < size; i++) gen.push_back(Set()); } bool product_contains(Product &prod, Tuple tuple) { return prod.find(tuple) != prod.end(); } void print_generator(Generator &gen) { for (Generator::const_iterator gi = gen.begin(); gi != gen.end(); gi++) { for (Set::const_iterator si = gi->begin(); si != gi->end(); si++) { std::cout << *si; if (++si != gi->end()) std::cout << ','; si--; } std::cout << '\n'; } std::cout << "%%\n"; } void generating_sets(Product &prod) { Product ref_prod = prod; while (prod.size() > 0) { Generator current_generator; init_generator(current_generator, prod.begin()->size()); for (Product::iterator pi = prod.begin(); pi != prod.end();) { Tuple current_tuple = *pi; Generator tmp = current_generator; size_t tup_size = current_tuple.size(); for (unsigned int i = 0; i < tup_size; i++) { tmp[i].insert(current_tuple[i]); } Product tmp_product; cartesian_product(tmp, tmp_product, false); for (Product::const_iterator tmpi = tmp_product.begin(); tmpi != tmp_product.end(); tmpi++) { if (!product_contains(ref_prod, *tmpi)) { ++pi; // FIXME: Go away ugly goto, go away! goto foo; } } current_generator = tmp; prod.erase(pi++); // FIXME: Ugly "expected primary-expression before '}' token" fix foo: if (1 == 2) break; } print_generator(current_generator); } } int main(int argc, char *argv[]) { Product prod; read_tuples(prod); generating_sets(prod); return 0; } <commit_msg>Refactored code and broke generating_sets up into smaller functions. Got rid of two unneeded copy-ctor calls. 'Is subset of set' logic now using std::includes from std::algorithm. Changed one function from using indexing calls to iterators instead. I imagine there's a small drop in benchmark execution time.<commit_after>/* * Copyright (c) 2012, Dennis Hedback * 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. * * 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. */ #include <algorithm> #include <iostream> #include <iterator> #include <set> #include <string> #include <vector> #include "common.hpp" void read_tuples(Product &prod) { Tuple current_tuple; std::string current_elem; for (std::istreambuf_iterator<char> it(std::cin), end; it != end; it++) { char c = *it; if (c == ',' || c == '\n') { current_tuple.push_back(current_elem); current_elem.clear(); if (c == '\n') { prod.insert(current_tuple); current_tuple.clear(); } } else { current_elem += c; } } } void init_generator(Generator &gen, size_t size) { for (unsigned int i = 0; i < size; i++) gen.push_back(Set()); } bool product_contains(Product &prod, Tuple const &tuple) { return prod.find(tuple) != prod.end(); } void print_generator(Generator &gen) { for (Generator::const_iterator gi = gen.begin(); gi != gen.end(); gi++) { for (Set::const_iterator si = gi->begin(); si != gi->end(); si++) { std::cout << *si; if (++si != gi->end()) std::cout << ','; si--; } std::cout << '\n'; } std::cout << "%%\n"; } void insert_tuple(Generator &gen, Tuple const &tup) { // FIXME: Handle cases where tup.size() != gen.size() Generator::iterator set = gen.begin(); Tuple::const_iterator elem = tup.begin(); for (; set != gen.end() && elem != tup.end(); set++, elem++) { set->insert(*elem); } } bool is_subset(Product &subset, Product &superset) { return std::includes(superset.begin(), superset.end(), subset.begin(), subset.end()); } void generating_sets(Product &prod) { Product ref_prod = prod; while (prod.size() > 0) { Generator gen; init_generator(gen, prod.begin()->size()); for (Product::iterator prod_it = prod.begin(); prod_it != prod.end();) { Generator tmp_gen = gen; Product tmp_prod; insert_tuple(tmp_gen, *prod_it); cartesian_product(tmp_gen, tmp_prod, false); if (is_subset(tmp_prod, ref_prod)) { gen = tmp_gen; prod.erase(prod_it++); } else { ++prod_it; } } print_generator(gen); } } int main(int argc, char *argv[]) { Product prod; read_tuples(prod); generating_sets(prod); return 0; } <|endoftext|>
<commit_before>#include <cfloat> #include <omp.h> #include "renderer.h" #define PI 3.141592653589793826433 void Camera::init(Vec3 from, Vec3 lookat, Vec3 up, double fov, double aspect, double aperture, double focus_dist) { lens_radius_ = aperture / 2; double theta = fov * PI / 180; double half_height = tan(theta / 2); double half_width = aspect * half_height; origin_ = from; Vec3 d = from - lookat; w_ = d.normalize(); u_ = cross(up, w_).normalize(); v_ = cross(w_, u_); lower_left_corner_ = origin_ - u_ * (half_width * focus_dist) - v_ * (half_height * focus_dist) - w_ * focus_dist; horizontal_ = u_ * (2.0 * half_width * focus_dist); vertical_ = v_ * (2.0 * half_height * focus_dist); } renderer::renderer(int w, int h) :steps_(0) { WIDTH = w; HEIGHT = h; // camera Vec3 from(13, 3, 3); Vec3 lookat(0, 0.5, 0); Vec3 up(0, 1, 0); double fov = 20.0; double aspect = (double)WIDTH / (double)HEIGHT; double dist_to_focus = 10.0; double aperture = 0.1; cam_.init(from, lookat, up, fov, aspect, aperture, dist_to_focus); // scene double R = cos(PI / 4); scene_.Append(new Sphere(Vec3(0, -1000, 0), 1000, new Lambertian(Vec3(0.5, 0.5, 0.5)))); scene_.Append(new Sphere(Vec3(0, 1, 0), 1.0, new Dielectric(1.5))); scene_.Append(new Sphere(Vec3(-4, 1, 0), 1.0, new Lambertian(Vec3(0.4, 0.2, 0.1)))); scene_.Append(new Sphere(Vec3(4, 1, 0), 1.0, new Metal(Vec3(0.7, 0.6, 0.5), 0.0))); } renderer::~renderer() { } Vec3 renderer::raytrace(Ray r, int depth, my_rand &rnd)const { // noise for debug // return Vec3(0,0,0); // return Vec3(rand_.get(), rand_.get(), rand_.get()); HitRecord rec; if (false) { // if (scene_.hit(r, 0.001, DBL_MAX, rec)) { Ray scattered; Vec3 attenuation; if (depth < 50 && rec.mat_ptr->scatter(r, rec, attenuation, scattered, rnd)) { return attenuation * raytrace(scattered, depth + 1, rnd); } else { return Vec3(0, 0, 0); } } else { Vec3 unit_direction = r.direction().normalize(); double t = 0.5*(unit_direction.y + 1.0); return (1.0 - t)*Vec3(1.0, 1.0, 1.0) + t * Vec3(0.5, 0.7, 1.0); } } Vec3 renderer::color(double u, double v, my_rand &rnd)const { Ray r = cam_.get_ray(u, v, rnd); return raytrace(r, 0, rnd); } void renderer::update(const double *src, double *dest, my_rand *a_rand)const { const double INV_WIDTH = 1.0 / (double)WIDTH; const double INV_HEIGHT = 1.0 / (double)HEIGHT; #pragma omp parallel for for (int y = 0; y < HEIGHT; y++) { my_rand &rnd = a_rand[omp_get_thread_num()]; for (int x = 0; x < WIDTH; x++) { int index = 3 * (y * WIDTH + x); double u = ((double)x + rnd.get()) * INV_WIDTH; double v = 1.0 - ((double)y + rnd.get()) * INV_HEIGHT; Vec3 color = this->color(u, v, rnd); dest[index + 0] = src[index + 0] + color.x; dest[index + 1] = src[index + 1] + color.y; dest[index + 2] = src[index + 2] + color.z; } } } <commit_msg>Update renderer.cpp<commit_after>#include <cfloat> #include <omp.h> #include "renderer.h" #define PI 3.141592653589793826433 void Camera::init(Vec3 from, Vec3 lookat, Vec3 up, double fov, double aspect, double aperture, double focus_dist) { lens_radius_ = aperture / 2; double theta = fov * PI / 180; double half_height = tan(theta / 2); double half_width = aspect * half_height; origin_ = from; Vec3 d = from - lookat; w_ = d.normalize(); u_ = cross(up, w_).normalize(); v_ = cross(w_, u_); lower_left_corner_ = origin_ - u_ * (half_width * focus_dist) - v_ * (half_height * focus_dist) - w_ * focus_dist; horizontal_ = u_ * (2.0 * half_width * focus_dist); vertical_ = v_ * (2.0 * half_height * focus_dist); } renderer::renderer(int w, int h) :steps_(0) { WIDTH = w; HEIGHT = h; // camera Vec3 from(13, 3, 3); Vec3 lookat(0, 0.5, 0); Vec3 up(0, 1, 0); double fov = 20.0; double aspect = (double)WIDTH / (double)HEIGHT; double dist_to_focus = 10.0; double aperture = 0.1; cam_.init(from, lookat, up, fov, aspect, aperture, dist_to_focus); // scene double R = cos(PI / 4); scene_.Append(new Sphere(Vec3(0, -1000, 0), 1000, new Lambertian(Vec3(0.5, 0.5, 0.5)))); scene_.Append(new Sphere(Vec3(0, 1, 0), 1.0, new Dielectric(1.5))); scene_.Append(new Sphere(Vec3(-4, 1, 0), 1.0, new Lambertian(Vec3(0.4, 0.2, 0.1)))); scene_.Append(new Sphere(Vec3(4, 1, 0), 1.0, new Metal(Vec3(0.7, 0.6, 0.5), 0.0))); } renderer::~renderer() { } Vec3 renderer::raytrace(Ray r, int depth, my_rand &rnd)const { // noise for debug return Vec3(0,0,0); // return Vec3(rand_.get(), rand_.get(), rand_.get()); HitRecord rec; if (scene_.hit(r, 0.001, DBL_MAX, rec)) { Ray scattered; Vec3 attenuation; if (depth < 50 && rec.mat_ptr->scatter(r, rec, attenuation, scattered, rnd)) { return attenuation * raytrace(scattered, depth + 1, rnd); } else { return Vec3(0, 0, 0); } } else { Vec3 unit_direction = r.direction().normalize(); double t = 0.5*(unit_direction.y + 1.0); return (1.0 - t)*Vec3(1.0, 1.0, 1.0) + t * Vec3(0.5, 0.7, 1.0); } } Vec3 renderer::color(double u, double v, my_rand &rnd)const { Ray r = cam_.get_ray(u, v, rnd); return raytrace(r, 0, rnd); } void renderer::update(const double *src, double *dest, my_rand *a_rand)const { const double INV_WIDTH = 1.0 / (double)WIDTH; const double INV_HEIGHT = 1.0 / (double)HEIGHT; #pragma omp parallel for for (int y = 0; y < HEIGHT; y++) { my_rand &rnd = a_rand[omp_get_thread_num()]; for (int x = 0; x < WIDTH; x++) { int index = 3 * (y * WIDTH + x); double u = ((double)x + rnd.get()) * INV_WIDTH; double v = 1.0 - ((double)y + rnd.get()) * INV_HEIGHT; Vec3 color = this->color(u, v, rnd); dest[index + 0] = src[index + 0] + color.x; dest[index + 1] = src[index + 1] + color.y; dest[index + 2] = src[index + 2] + color.z; } } } <|endoftext|>
<commit_before>#include "Maze.h" #include <cstdlib> #include <fstream> #include <iostream> #include <iterator> #include <sstream> #include <time.h> #include <queue> #include <vector> #include "Constants.h" #include "Parameters.h" #include "Tile.h" namespace sim{ Maze::Maze(int width, int height, std::string mazeFileDirPath, std::string mazeFile){ // Misc errand - seed the random number generator srand(time(NULL)); // Initialize the tile positions for (int x = 0; x < width; x++){ std::vector<Tile> col; for (int y = 0; y < height; y++){ Tile tile; tile.setPos(x, y); col.push_back(tile); } m_maze.push_back(col); } // Initialize the tile wall values and tile neighbors by either loading // an existing maze file or randomly generating a valid maze if (mazeFile == ""){ std::cout << "No maze file provided. Generating random maze..." << std::endl; randomize(); while (!(solveShortestPath().at(0) && solveShortestPath().at(1))){ randomize(); } // Optional - can be used to generate more maze files saveMaze(mazeFileDirPath += "/auto_generated_maze.maz"); } else{ // Complete path to the given mazefile std::string path = mazeFileDirPath += mazeFile; // Check to see if the file exists std::fstream file(path.c_str()); if (file){ // Load the maze given by mazefile loadMaze(path); // Ensures that the maze is solvable if (!solveShortestPath().at(0)){ std::cout << "Unsolvable Maze detected. Generating solvable maze..." << std::endl; while (!(solveShortestPath().at(0) && solveShortestPath().at(1))){ randomize(); } } } else{ // If the file doesn't exist, generate a random maze file std::cout << "File \"" << path << "\" not found. Generating random maze..." << std::endl; randomize(); while (!(solveShortestPath().at(0) && solveShortestPath().at(1))){ randomize(); } } } // Increment the passes for the starting position m_maze.at(0).at(0).incrementPasses(); } Maze::~Maze() { } int Maze::getWidth(){ return m_maze.size(); } int Maze::getHeight(){ if (m_maze.size() > 0){ return m_maze.at(0).size(); } return 0; } Tile* Maze::getTile(int x, int y){ return &m_maze.at(x).at(y); } void Maze::resetColors(int curX, int curY){ for (int x = 0; x < getWidth(); x++){ for (int y = 0; y < getHeight(); y++){ getTile(x, y)->resetPasses(); } } getTile(curX, curY)->incrementPasses(); } void Maze::randomize(){ // Declare width and height locally to reduce function calls int width = getWidth(); int height = getHeight(); // The probability of any one wall appearing is 1/probDenom int probDenom = 2; for (int x = 0; x < width; x++){ for (int y = 0; y < height; y++){ bool walls[4]; // Make a walls array for tile (x, y) for (int k = 0; k < 4; k++){ walls[k] = rand() % probDenom == 0; switch (k){ case NORTH: if (y + 1 < height){ getTile(x, y+1)->setWall(SOUTH, walls[k]); getTile(x, y)->setWall(NORTH, walls[k]); } else { getTile(x, y)->setWall(NORTH, true); } break; case EAST: if (x + 1 < width){ getTile(x+1, y)->setWall(WEST, walls[k]); getTile(x, y)->setWall(EAST, walls[k]); } else { getTile(x, y)->setWall(EAST, true); } break; case SOUTH: if (y > 0){ getTile(x, y-1)->setWall(NORTH, walls[k]); getTile(x, y)->setWall(SOUTH, walls[k]); } else { getTile(x, y)->setWall(SOUTH, true); } break; case WEST: if (x > 0){ getTile(x-1, y)->setWall(EAST, walls[k]); getTile(x, y)->setWall(WEST, walls[k]); } else { getTile(x, y)->setWall(WEST, true); } break; } } } } // Ensures that the middle is hallowed out if (width % 2 == 0){ if (height % 2 == 0){ getTile(width/2-1, height/2-1)->setWall(NORTH, false); getTile(width/2-1, height/2)->setWall(SOUTH, false); getTile(width/2, height/2-1)->setWall(NORTH, false); getTile(width/2, height/2)->setWall(SOUTH, false); getTile(width/2-1, height/2-1)->setWall(EAST, false); getTile(width/2, height/2-1)->setWall(WEST, false); } getTile(width/2-1, height/2)->setWall(EAST, false); getTile(width/2, height/2)->setWall(WEST, false); } if (height % 2 == 0){ getTile(width/2, height/2-1)->setWall(NORTH, false); getTile(width/2, height/2)->setWall(SOUTH, false); } // Once the walls are assigned, we can assign neighbors assignNeighbors(); } void Maze::saveMaze(std::string mazeFile){ // Create the stream std::ofstream file(mazeFile.c_str()); if (file.is_open()){ // Very primitive, but will work for (int x = 0; x < getWidth(); x++){ for (int y = 0; y < getHeight(); y++){ file << x << " " << y; for (int k = 0; k < 4; k++){ file << " " << (getTile(x, y)->isWall(k) ? 1 : 0); } file << std::endl; } } file.close(); } } void Maze::loadMaze(std::string mazeFile){ // Create the stream std::ifstream file(mazeFile.c_str()); // Initialize a string variable std::string line(""); if (file.is_open()){ // Very primitive, but will work while (getline(file, line)){ std::istringstream iss(line); std::vector<std::string> tokens; copy(std::istream_iterator<std::string>(iss), std::istream_iterator<std::string>(), std::back_inserter<std::vector<std::string> >(tokens)); for (int i = 0; i < 4; i++){ // Set the values of all of the walls getTile(atoi(tokens.at(0).c_str()), atoi(tokens.at(1).c_str())) ->setWall(i, atoi(tokens.at(2+i).c_str())); } } file.close(); // Once the walls are assigned, we can assign neighbors assignNeighbors(); } } void Maze::assignNeighbors(){ for (int x = 0; x < getWidth(); x++){ for (int y = 0; y < getHeight(); y++){ Tile* tile = getTile(x, y); // First we ensure that we have a fresh (empty) list tile->resetNeighbors(); // Then we assign new neighbors if (!tile->isWall(NORTH)){ tile->addNeighbor(getTile(x, y+1)); } if (!tile->isWall(EAST)){ tile->addNeighbor(getTile(x+1, y)); } if (!tile->isWall(SOUTH)){ tile->addNeighbor(getTile(x, y-1)); } if (!tile->isWall(WEST)){ tile->addNeighbor(getTile(x-1, y)); } } } } void Maze::printDistances(){ std::cout << std::endl; for (int y = getHeight()-1; y >= 0; y--){ for (int x = 0; x < getWidth(); x++){ if (getTile(x, y)->getDistance() < 100){ std::cout << " "; if (getTile(x, y)->getDistance() < 10){ std::cout << " "; } } std::cout << getTile(x, y)->getDistance() << " "; } std::cout << std::endl; } } std::vector<bool> Maze::solveShortestPath(){ // Solves the maze, assigns tiles that are part of the shortest path std::vector<Tile*> sp = findPathToCenter(); for (int i = 0; i < sp.size(); i++){ getTile(sp.at(i)->getX(), sp.at(i)->getY())->setPosp(true); } // Returns whether or not the maze is solvable and whether or not // it satisfies the minimum number of steps std::vector<bool> conditions; conditions.push_back(getClosestCenterTile()->getDistance() < MAX_DISTANCE); conditions.push_back(getClosestCenterTile()->getDistance() > MIN_MAZE_STEPS); return conditions; } std::vector<Tile*> Maze::findPath(int x1, int y1, int x2, int y2){ setDistancesFrom(x1, x2); return backtrace(getTile(x2, y2)); } std::vector<Tile*> Maze::findPathToCenter(){ setDistancesFrom(0, 0); return backtrace(getClosestCenterTile()); } std::vector<Tile*> Maze::backtrace(Tile* end){ // The vector to hold the solution nodes std::vector<Tile*> path; // Start at the ending node and simply trace back through the values std::queue<Tile*> queue; queue.push(end); path.push_back(end); while (!queue.empty()){ Tile* node = queue.front(); queue.pop(); // Removes the element std::vector<Tile*> neighbors = node->getNeighbors(); for (int i = 0; i < neighbors.size(); i++){ if (neighbors.at(i)->getDistance() == node->getDistance() - 1){ path.push_back(neighbors.at(i)); queue.push(neighbors.at(i)); } } } return path; } void Maze::setDistancesFrom(int x, int y){ // Ensure that the nodes are fresh every time this function is called for (int x = 0; x < getWidth(); x++){ for (int y = 0; y < getHeight(); y++){ Tile* tile = getTile(x, y); tile->setDistance(MAX_DISTANCE); tile->setExplored(false); tile->setPosp(false); } } // Queue for BFS std::queue<Tile*> queue; queue.push(getTile(x, y)); getTile(x, y)->setDistance(0); getTile(x, y)->setExplored(true); while (!queue.empty()){ Tile* node = queue.front(); queue.pop(); // Removes the element std::vector<Tile*> neighbors = node->getNeighbors(); for (int i = 0; i < neighbors.size(); i++){ if (!neighbors.at(i)->getExplored()){ neighbors.at(i)->setDistance(node->getDistance() + 1); queue.push(neighbors.at(i)); neighbors.at(i)->setExplored(true); } } } } Tile* Maze::getClosestCenterTile(){ if (getWidth() > 0 && getHeight() > 0){ int midWidth = getWidth()/2; int midHeight = getHeight()/2; Tile* closest = getTile(midWidth, midHeight); if (getWidth() % 2 == 0){ if (getTile(midWidth-1, midHeight)->getDistance() < closest->getDistance()){ closest = getTile(midWidth-1, midHeight); } } if (getHeight() % 2 == 0){ if (getTile(midWidth, midHeight-1)->getDistance() < closest->getDistance()){ closest = getTile(midWidth, midHeight-1); } } if (getWidth() % 2 == 0 && getHeight() % 2 == 0){ if (getTile(midWidth-1, midHeight-1)->getDistance() < closest->getDistance()){ closest = getTile(midWidth-1, midHeight-1); } } return closest; } // If either the width or the height is zero return NULL return NULL; } } // namespace sim <commit_msg>Random Number Fix<commit_after>#include "Maze.h" #include <cstdlib> #include <fstream> #include <iostream> #include <iterator> #include <sstream> #include <time.h> #include <queue> #include <vector> #include "Constants.h" #include "Parameters.h" #include "Tile.h" namespace sim{ Maze::Maze(int width, int height, std::string mazeFileDirPath, std::string mazeFile){ // Misc errand - seed the random number generator srand(time(NULL)); // Initialize the tile positions for (int x = 0; x < width; x++){ std::vector<Tile> col; for (int y = 0; y < height; y++){ Tile tile; tile.setPos(x, y); col.push_back(tile); } m_maze.push_back(col); } // Initialize the tile wall values and tile neighbors by either loading // an existing maze file or randomly generating a valid maze if (mazeFile == ""){ std::cout << "No maze file provided. Generating random maze..." << std::endl; randomize(); while (!(solveShortestPath().at(0) && solveShortestPath().at(1))){ randomize(); } // Optional - can be used to generate more maze files saveMaze(mazeFileDirPath += "/auto_generated_maze.maz"); } else{ // Complete path to the given mazefile std::string path = mazeFileDirPath += mazeFile; // Check to see if the file exists std::fstream file(path.c_str()); if (file){ // Load the maze given by mazefile loadMaze(path); // Ensures that the maze is solvable if (!solveShortestPath().at(0)){ std::cout << "Unsolvable Maze detected. Generating solvable maze..." << std::endl; while (!(solveShortestPath().at(0) && solveShortestPath().at(1))){ randomize(); } } } else{ // If the file doesn't exist, generate a random maze file std::cout << "File \"" << path << "\" not found. Generating random maze..." << std::endl; randomize(); while (!(solveShortestPath().at(0) && solveShortestPath().at(1))){ randomize(); } } } // Increment the passes for the starting position m_maze.at(0).at(0).incrementPasses(); } Maze::~Maze() { } int Maze::getWidth(){ return m_maze.size(); } int Maze::getHeight(){ if (m_maze.size() > 0){ return m_maze.at(0).size(); } return 0; } Tile* Maze::getTile(int x, int y){ return &m_maze.at(x).at(y); } void Maze::resetColors(int curX, int curY){ for (int x = 0; x < getWidth(); x++){ for (int y = 0; y < getHeight(); y++){ getTile(x, y)->resetPasses(); } } getTile(curX, curY)->incrementPasses(); } void Maze::randomize(){ // Declare width and height locally to reduce function calls int width = getWidth(); int height = getHeight(); // The probability of any one wall appearing is 1/probDenom int probDenom = 2; for (int x = 0; x < width; x++){ for (int y = 0; y < height; y++){ bool walls[4]; // Make a walls array for tile (x, y) for (int k = 0; k < 4; k++){ walls[k] = rand() / (RAND_MAX / 2 + 1); //std::cout << randn << std::endl; //walls[k] = rand() % probDenom == 0; switch (k){ case NORTH: if (y + 1 < height){ getTile(x, y+1)->setWall(SOUTH, walls[k]); getTile(x, y)->setWall(NORTH, walls[k]); } else { getTile(x, y)->setWall(NORTH, true); } break; case EAST: if (x + 1 < width){ getTile(x+1, y)->setWall(WEST, walls[k]); getTile(x, y)->setWall(EAST, walls[k]); } else { getTile(x, y)->setWall(EAST, true); } break; case SOUTH: if (y > 0){ getTile(x, y-1)->setWall(NORTH, walls[k]); getTile(x, y)->setWall(SOUTH, walls[k]); } else { getTile(x, y)->setWall(SOUTH, true); } break; case WEST: if (x > 0){ getTile(x-1, y)->setWall(EAST, walls[k]); getTile(x, y)->setWall(WEST, walls[k]); } else { getTile(x, y)->setWall(WEST, true); } break; } } } } // Ensures that the middle is hallowed out if (width % 2 == 0){ if (height % 2 == 0){ getTile(width/2-1, height/2-1)->setWall(NORTH, false); getTile(width/2-1, height/2)->setWall(SOUTH, false); getTile(width/2, height/2-1)->setWall(NORTH, false); getTile(width/2, height/2)->setWall(SOUTH, false); getTile(width/2-1, height/2-1)->setWall(EAST, false); getTile(width/2, height/2-1)->setWall(WEST, false); } getTile(width/2-1, height/2)->setWall(EAST, false); getTile(width/2, height/2)->setWall(WEST, false); } if (height % 2 == 0){ getTile(width/2, height/2-1)->setWall(NORTH, false); getTile(width/2, height/2)->setWall(SOUTH, false); } // Once the walls are assigned, we can assign neighbors assignNeighbors(); } void Maze::saveMaze(std::string mazeFile){ // Create the stream std::ofstream file(mazeFile.c_str()); if (file.is_open()){ // Very primitive, but will work for (int x = 0; x < getWidth(); x++){ for (int y = 0; y < getHeight(); y++){ file << x << " " << y; for (int k = 0; k < 4; k++){ file << " " << (getTile(x, y)->isWall(k) ? 1 : 0); } file << std::endl; } } file.close(); } } void Maze::loadMaze(std::string mazeFile){ // Create the stream std::ifstream file(mazeFile.c_str()); // Initialize a string variable std::string line(""); if (file.is_open()){ // Very primitive, but will work while (getline(file, line)){ std::istringstream iss(line); std::vector<std::string> tokens; copy(std::istream_iterator<std::string>(iss), std::istream_iterator<std::string>(), std::back_inserter<std::vector<std::string> >(tokens)); for (int i = 0; i < 4; i++){ // Set the values of all of the walls getTile(atoi(tokens.at(0).c_str()), atoi(tokens.at(1).c_str())) ->setWall(i, atoi(tokens.at(2+i).c_str())); } } file.close(); // Once the walls are assigned, we can assign neighbors assignNeighbors(); } } void Maze::assignNeighbors(){ for (int x = 0; x < getWidth(); x++){ for (int y = 0; y < getHeight(); y++){ Tile* tile = getTile(x, y); // First we ensure that we have a fresh (empty) list tile->resetNeighbors(); // Then we assign new neighbors if (!tile->isWall(NORTH)){ tile->addNeighbor(getTile(x, y+1)); } if (!tile->isWall(EAST)){ tile->addNeighbor(getTile(x+1, y)); } if (!tile->isWall(SOUTH)){ tile->addNeighbor(getTile(x, y-1)); } if (!tile->isWall(WEST)){ tile->addNeighbor(getTile(x-1, y)); } } } } void Maze::printDistances(){ std::cout << std::endl; for (int y = getHeight()-1; y >= 0; y--){ for (int x = 0; x < getWidth(); x++){ if (getTile(x, y)->getDistance() < 100){ std::cout << " "; if (getTile(x, y)->getDistance() < 10){ std::cout << " "; } } std::cout << getTile(x, y)->getDistance() << " "; } std::cout << std::endl; } } std::vector<bool> Maze::solveShortestPath(){ // Solves the maze, assigns tiles that are part of the shortest path std::vector<Tile*> sp = findPathToCenter(); for (int i = 0; i < sp.size(); i++){ getTile(sp.at(i)->getX(), sp.at(i)->getY())->setPosp(true); } // Returns whether or not the maze is solvable and whether or not // it satisfies the minimum number of steps std::vector<bool> conditions; conditions.push_back(getClosestCenterTile()->getDistance() < MAX_DISTANCE); conditions.push_back(getClosestCenterTile()->getDistance() > MIN_MAZE_STEPS); return conditions; } std::vector<Tile*> Maze::findPath(int x1, int y1, int x2, int y2){ setDistancesFrom(x1, x2); return backtrace(getTile(x2, y2)); } std::vector<Tile*> Maze::findPathToCenter(){ setDistancesFrom(0, 0); return backtrace(getClosestCenterTile()); } std::vector<Tile*> Maze::backtrace(Tile* end){ // The vector to hold the solution nodes std::vector<Tile*> path; // Start at the ending node and simply trace back through the values std::queue<Tile*> queue; queue.push(end); path.push_back(end); while (!queue.empty()){ Tile* node = queue.front(); queue.pop(); // Removes the element std::vector<Tile*> neighbors = node->getNeighbors(); for (int i = 0; i < neighbors.size(); i++){ if (neighbors.at(i)->getDistance() == node->getDistance() - 1){ path.push_back(neighbors.at(i)); queue.push(neighbors.at(i)); } } } return path; } void Maze::setDistancesFrom(int x, int y){ // Ensure that the nodes are fresh every time this function is called for (int x = 0; x < getWidth(); x++){ for (int y = 0; y < getHeight(); y++){ Tile* tile = getTile(x, y); tile->setDistance(MAX_DISTANCE); tile->setExplored(false); tile->setPosp(false); } } // Queue for BFS std::queue<Tile*> queue; queue.push(getTile(x, y)); getTile(x, y)->setDistance(0); getTile(x, y)->setExplored(true); while (!queue.empty()){ Tile* node = queue.front(); queue.pop(); // Removes the element std::vector<Tile*> neighbors = node->getNeighbors(); for (int i = 0; i < neighbors.size(); i++){ if (!neighbors.at(i)->getExplored()){ neighbors.at(i)->setDistance(node->getDistance() + 1); queue.push(neighbors.at(i)); neighbors.at(i)->setExplored(true); } } } } Tile* Maze::getClosestCenterTile(){ if (getWidth() > 0 && getHeight() > 0){ int midWidth = getWidth()/2; int midHeight = getHeight()/2; Tile* closest = getTile(midWidth, midHeight); if (getWidth() % 2 == 0){ if (getTile(midWidth-1, midHeight)->getDistance() < closest->getDistance()){ closest = getTile(midWidth-1, midHeight); } } if (getHeight() % 2 == 0){ if (getTile(midWidth, midHeight-1)->getDistance() < closest->getDistance()){ closest = getTile(midWidth, midHeight-1); } } if (getWidth() % 2 == 0 && getHeight() % 2 == 0){ if (getTile(midWidth-1, midHeight-1)->getDistance() < closest->getDistance()){ closest = getTile(midWidth-1, midHeight-1); } } return closest; } // If either the width or the height is zero return NULL return NULL; } } // namespace sim <|endoftext|>
<commit_before>// Simple example effect: // Draws a noise pattern modulated by an expanding sine wave. #include <math.h> #include <termios.h> #include "lib/color.h" #include "tensegrity_effect.h" #include "lib/effect_runner.h" #include "lib/noise.h" #define NUM_LAYERS 4 #define NUM_HUES 2 Effect** effects; int hues[NUM_HUES][NUM_LAYERS] = { { 0, 60, 120, 280 }, { 210, 240, 250, 260 } }; class MyEffect : public TEffect { public: MyEffect(int channel) : TEffect(channel), cycle (0), hue(0.2){} virtual ~MyEffect() {} float cycle; float hue; virtual void beginFrame(const FrameInfo &f) { TEffect::beginFrame(f); const float speed = 10.0; cycle = fmodf(cycle + f.timeDelta * speed, 2 * M_PI); } virtual void shader(Vec3& rgb, const PixelInfo &p) const { float distance = len(p.point); float wave = sinf(3.0 * distance - cycle) + noise3(p.point); int spoke = spokeNumberForIndex(p.index); hsv2rgb(rgb, hue, 1.0 - (0.2 * (spoke+1)), wave); } virtual void nextColor() { hue += 0.1f; if (hue >= 1.0f) { hue = 0.0f; } } }; class ProcessingEffect: public TEffect { public: ProcessingEffect(int channel) : TEffect(channel), hue(0){} int hue; float t; float M_2PI; float time_divider; virtual void beginFrame(const FrameInfo &f) { TEffect::beginFrame(f); t += f.timeDelta; M_2PI = 2*M_PI; time_divider = M_2PI; } virtual void shader(Vec3& rgb, const PixelInfo &p) const { //const float speed = 10.0; int spoke = spokeNumberForIndex(p.index); bool reverse = false; if (channel % 2 != 0) { reverse = true; } int i = spoke; float ai = i * angleDelta; float k = p.index - strutOffsets[spoke]; hsv2rgb(rgb, fmodf((t/time_divider) * ai, M_2PI) / M_2PI, float(channel) / NUM_LAYERS * 0.80f, fmodf(k * t/0.5, 100) / 100.0f ); } virtual void nextColor() { hue += 1; if (hue > 1) hue = 0; } }; class FireEffect : public TEffect { public: FireEffect(int channel) : TEffect(channel), hue(0){} int hue; float t; float minz, maxz; virtual void beginFrame(const FrameInfo &f) { TEffect::beginFrame(f); t += f.timeDelta; minz = f.modelMin[2]; maxz = f.modelMax[2]; } virtual void shader(Vec3& rgb, const PixelInfo &p) const { const float speed = 10.0; //float distance = len(p.point); float mahHue = hues[hue][0] / 360.0f; float height = (p.point[2] - minz) / (maxz - minz); float v = fbm_noise2(height, t, 4); hsv2rgb(rgb, mahHue, v - height, 0.4 + (v * 0.6)); } virtual void nextColor() { hue += 1; if (hue > 1) hue = 0; } }; class PerlinEffect : public TEffect { public: PerlinEffect(int channel) : TEffect(channel), hue(0){} int hue; float t; virtual void beginFrame(const FrameInfo &f) { TEffect::beginFrame(f); t += f.timeDelta; } virtual void shader(Vec3& rgb, const PixelInfo &p) const { const float speed = 10.0; //float distance = len(p.point); float mahHue = hues[hue][channel] / 360.0f; float v = fbm_noise4(p.point[0], p.point[1], p.point[2], t, 2); hsv2rgb(rgb, mahHue, 0.7, 0.4 + v); } virtual void nextColor() { hue += 1; if (hue > 1) hue = 0; } }; class PythonEffect : public TEffect { public: PythonEffect(int channel) : TEffect(channel), hue(0){} int hue; float t; virtual void beginFrame(const FrameInfo &f) { TEffect::beginFrame(f); t += f.timeDelta; } virtual void shader(Vec3& rgb, const PixelInfo &p) const { const float speed = 10.0; //float distance = len(p.point); float mahHue = hues[hue][channel] / 360.0f; float v = fmodf((t * speed + p.index), 50.0f) / 50.0f; hsv2rgb(rgb, mahHue, 0.4, v); } virtual void nextColor() { hue += 1; if (hue > 1) hue = 0; } }; void argumentUsage() { fprintf(stderr, "[-v] [-fps LIMIT] [-speed MULTIPLIER] [-server HOST[:port]]"); } void usage(const char *name) { fprintf(stderr, "usage: %s ", name); argumentUsage(); fprintf(stderr, "\n"); } bool parseArgument(int &i, int &argc, char **argv, std::vector<EffectRunner*> er) { std::vector<EffectRunner*>::const_iterator it; if (!strcmp(argv[i], "-v")) { for (it = er.begin(); it != er.end(); ++it) { (*it)->setVerbose(true); } return true; } if (!strcmp(argv[i], "-fps") && (i+1 < argc)) { float rate = atof(argv[++i]); if (rate <= 0) { fprintf(stderr, "Invalid frame rate\n"); return false; } for (it = er.begin(); it != er.end(); ++it) { (*it)->setMaxFrameRate(rate); } return true; } if (!strcmp(argv[i], "-speed") && (i+1 < argc)) { float speed = atof(argv[++i]); if (speed <= 0) { fprintf(stderr, "Invalid speed\n"); return false; } for (it = er.begin(); it != er.end(); ++it) { (*it)->setSpeed(speed); } return true; } if (!strcmp(argv[i], "-server") && (i+1 < argc)) { ++i; for (it = er.begin(); it != er.end(); ++it) { if (!(*it)->setServer(argv[i])) { fprintf(stderr, "Can't resolve server name %s\n", argv[i]); return false; } } return true; } return false; } bool parseArguments(int argc, char **argv, std::vector<EffectRunner*> er) { for (int i = 1; i < argc; i++) { if (!parseArgument(i, argc, argv, er)) { usage(argv[0]); return false; } } return true; } #define NB_ENABLE 1 #define NB_DISABLE 0 int kbhit() { struct timeval tv; fd_set fds; tv.tv_sec = 0; tv.tv_usec = 0; FD_ZERO(&fds); FD_SET(STDIN_FILENO, &fds); //STDIN_FILENO is 0 select(STDIN_FILENO+1, &fds, NULL, NULL, &tv); return FD_ISSET(STDIN_FILENO, &fds); } void nonblock(int state) { struct termios ttystate; //get the terminal state tcgetattr(STDIN_FILENO, &ttystate); if (state==NB_ENABLE) { //turn off canonical mode ttystate.c_lflag &= ~ICANON; //minimum of number input read. ttystate.c_cc[VMIN] = 1; } else if (state==NB_DISABLE) { //turn on canonical mode ttystate.c_lflag |= ICANON; } //set the terminal attributes. tcsetattr(STDIN_FILENO, TCSANOW, &ttystate); } void changeEffect(int channel, const char* effectName, std::vector<EffectRunner*> er) { Effect *oldEffect = effects[channel]; fprintf(stderr, "\neffectName %s\n", effectName); if (strcmp(effectName, "falling") == 0) { fprintf(stderr, "\nchanged effect to MyEffect\n"); effects[channel] = new MyEffect(channel); } else if (strcmp(effectName, "python") == 0) { fprintf(stderr, "\nchanged effect to PythonEffect\n"); effects[channel] = new PythonEffect(channel); } else if (strcmp(effectName, "processing") == 0) { fprintf(stderr, "\nchanged effect to ProcessingEffect\n"); effects[channel] = new ProcessingEffect(channel); } else if (strcmp(effectName, "perlin") == 0) { fprintf(stderr, "\nchanged effect to PerlinEffect\n"); effects[channel] = new PerlinEffect(channel); } else if (strcmp(effectName, "fire") == 0) { fprintf(stderr, "\nchanged effect to FireEffect\n"); effects[channel] = new FireEffect(channel); } er[channel]->setEffect(effects[channel]); delete oldEffect; } void checkController(std::vector<EffectRunner*> er) { /* * This currently just listens for keypresses on the console. * Eventually it should read data from the raspberry pi gpio pins. * */ char c; static int effect = 0; std::vector<EffectRunner*>::const_iterator it; int i=kbhit(); if (i!=0) { c=fgetc(stdin); if (c == 's') { float speed = 0.0f; for (it = er.begin(); it != er.end(); ++it) { speed = (*it)->getSpeed(); if (speed < 0.1) { speed = 5.0; } else { speed *= 0.8; } (*it)->setSpeed(speed); } fprintf(stderr, "\nspeed set to %.2f. \n", speed); } else if (c == 'c') { // Change colour palette for (it = er.begin(); it != er.end(); ++it) { TEffect* e = (TEffect*) (*it)->getEffect(); e->nextColor(); } fprintf(stderr, "\nchanged color palette\n"); } else if (c == 'e') { // Change effect int j=0; int NUM_EFFECTS=5; effect++; int e_index = effect % NUM_EFFECTS; fprintf(stderr, "\ne_index is %d\n", e_index); for (it = er.begin(); it != er.end(); ++it, ++j) { if (e_index == 0) { changeEffect(j, "falling", er); } else if (e_index == 1) { changeEffect(j, "processing", er); } else if (e_index == 2) { changeEffect(j, "python", er); } else if (e_index == 3) { changeEffect(j, "perlin", er); } else if (e_index == 4) { changeEffect(j, "fire", er); } } } else { fprintf(stderr, "\nunknown command %c. \n", c); } } } int main(int argc, char **argv) { std::vector<EffectRunner*> effect_runners; const int layers = NUM_LAYERS; char buffer[1000]; effects = new Effect* [layers]; for (int i = 0; i < layers; i++) { Effect *e = new MyEffect(i); effects[i] = e; EffectRunner* r = new EffectRunner(); r->setEffect(e); r->setMaxFrameRate(50); r->setChannel(i); snprintf(buffer, 1000, "../Processing/tensegrity/opc_layout_%d.json", i); r->setLayout(buffer); effect_runners.push_back(r); } parseArguments(argc, argv, effect_runners); nonblock(NB_ENABLE); while (true) { for (int i=0 ; i < layers; i++) { effect_runners[i]->doFrame(); } checkController(effect_runners); } nonblock(NB_DISABLE); return 0; } <commit_msg>add reversal effect<commit_after>// Simple example effect: // Draws a noise pattern modulated by an expanding sine wave. #include <math.h> #include <termios.h> #include "lib/color.h" #include "tensegrity_effect.h" #include "lib/effect_runner.h" #include "lib/noise.h" #define NUM_LAYERS 4 #define NUM_HUES 2 Effect** effects; int hues[NUM_HUES][NUM_LAYERS] = { { 0, 60, 120, 280 }, { 210, 240, 250, 260 } }; #define PIV2 (M_PI+M_PI) #define C360 360.0000000000000000000 double difangrad(double x, double y) { double arg; arg = fmod(y-x, PIV2); if (arg < 0 ) arg = arg + PIV2; if (arg > M_PI) arg = arg - PIV2; return (-arg); } class MyEffect : public TEffect { public: MyEffect(int channel) : TEffect(channel), cycle (0), hue(0.2){} virtual ~MyEffect() {} float cycle; float hue; virtual void beginFrame(const FrameInfo &f) { TEffect::beginFrame(f); const float speed = 10.0; cycle = fmodf(cycle + f.timeDelta * speed, 2 * M_PI); } virtual void shader(Vec3& rgb, const PixelInfo &p) const { float distance = len(p.point); float wave = sinf(3.0 * distance - cycle) + noise3(p.point); int spoke = spokeNumberForIndex(p.index); hsv2rgb(rgb, hue, 1.0 - (0.2 * (spoke+1)), wave); } virtual void nextColor() { hue += 0.1f; if (hue >= 1.0f) { hue = 0.0f; } } }; class ProcessingEffect: public TEffect { public: ProcessingEffect(int channel) : TEffect(channel), hue(0), t(0.0f) {} int hue; float t; float M_2PI; float time_divider; virtual void beginFrame(const FrameInfo &f) { TEffect::beginFrame(f); t += f.timeDelta; M_2PI = 2*M_PI; time_divider = M_2PI; } virtual void shader(Vec3& rgb, const PixelInfo &p) const { //const float speed = 10.0; int spoke = spokeNumberForIndex(p.index); bool reverse = false; if (channel % 2 != 0) { reverse = true; } int i = spoke; float ai = i * angleDelta; float k = p.index - strutOffsets[spoke]; hsv2rgb(rgb, fmodf((t/time_divider) * ai, M_2PI) / M_2PI, float(channel) / NUM_LAYERS * 0.80f, fmodf(k * t/0.5, 100) / 100.0f ); } virtual void nextColor() { hue += 1; if (hue > 1) hue = 0; } }; class FireEffect : public TEffect { public: FireEffect(int channel) : TEffect(channel), hue(0), t(0.0f) {} int hue; float t; float minz, maxz; virtual void beginFrame(const FrameInfo &f) { TEffect::beginFrame(f); t += f.timeDelta; minz = f.modelMin[2]; maxz = f.modelMax[2]; } virtual void shader(Vec3& rgb, const PixelInfo &p) const { const float speed = 10.0; //float distance = len(p.point); float mahHue = hues[hue][0] / 360.0f; float height = (p.point[2] - minz) / (maxz - minz); float v = fbm_noise2(height, t, 4); hsv2rgb(rgb, mahHue, v - height, 0.4 + (v * 0.6)); } virtual void nextColor() { hue += 1; if (hue > 1) hue = 0; } }; class PerlinEffect : public TEffect { public: PerlinEffect(int channel) : TEffect(channel), hue(0), t(0.0f) {} int hue; float t; virtual void beginFrame(const FrameInfo &f) { TEffect::beginFrame(f); t += f.timeDelta; } virtual void shader(Vec3& rgb, const PixelInfo &p) const { const float speed = 10.0; //float distance = len(p.point); float mahHue = hues[hue][channel] / 360.0f; float v = fbm_noise4(p.point[0], p.point[1], p.point[2], t, 2); hsv2rgb(rgb, mahHue, 0.7, 0.4 + v); } virtual void nextColor() { hue += 1; if (hue > 1) hue = 0; } }; class PythonEffect : public TEffect { public: PythonEffect(int channel) : TEffect(channel), hue(0), t(0.0f) {} int hue; float t; virtual void beginFrame(const FrameInfo &f) { TEffect::beginFrame(f); t += f.timeDelta; } virtual void shader(Vec3& rgb, const PixelInfo &p) const { const float speed = 10.0; //float distance = len(p.point); float mahHue = hues[hue][channel] / 360.0f; float v = fmodf((t * speed + p.index), 50.0f) / 50.0f; hsv2rgb(rgb, mahHue, 0.4, v); } virtual void nextColor() { hue += 1; if (hue > 1) hue = 0; } }; class ReverseEffect : public TEffect { public: ReverseEffect(int channel) : TEffect(channel), hue(0), t(0.0f), revPerSecond(0.0f), currentAngle(0.0f) {} int hue; float t; float revPerSecond; float currentAngle; virtual void beginFrame(const FrameInfo &f) { revPerSecond = 1.0f; TEffect::beginFrame(f); currentAngle -= (f.timeDelta * ( 2*M_PI * (revPerSecond + 1.0))); if (currentAngle < 0) { currentAngle += M_PI * 2.0f; } } virtual void shader(Vec3& rgb, const PixelInfo &p) const { int spoke = spokeNumberForIndex(p.index); float spokeAngle = (angleDelta * spoke) - M_PI; //float d = currentAngle - spokeAngle; float angleDiff = difangrad(currentAngle - M_PI, spokeAngle); //atan2(fast_sin(d), fast_cos(d)); float v = 1.0 - (2*(fabs(angleDiff) / (M_PI))); //fprintf(stderr, "currentAngle %.2f spoke %d angleDiff %.2f v %.2f\n", currentAngle, spoke, angleDiff, v); float mahHue = hues[hue][channel] / 360.0f; hsv2rgb(rgb, mahHue, 0.4, v); } virtual void nextColor() { hue += 1; if (hue > 1) hue = 0; } }; void argumentUsage() { fprintf(stderr, "[-v] [-fps LIMIT] [-speed MULTIPLIER] [-server HOST[:port]]"); } void usage(const char *name) { fprintf(stderr, "usage: %s ", name); argumentUsage(); fprintf(stderr, "\n"); } bool parseArgument(int &i, int &argc, char **argv, std::vector<EffectRunner*> er) { std::vector<EffectRunner*>::const_iterator it; if (!strcmp(argv[i], "-v")) { for (it = er.begin(); it != er.end(); ++it) { (*it)->setVerbose(true); } return true; } if (!strcmp(argv[i], "-fps") && (i+1 < argc)) { float rate = atof(argv[++i]); if (rate <= 0) { fprintf(stderr, "Invalid frame rate\n"); return false; } for (it = er.begin(); it != er.end(); ++it) { (*it)->setMaxFrameRate(rate); } return true; } if (!strcmp(argv[i], "-speed") && (i+1 < argc)) { float speed = atof(argv[++i]); if (speed <= 0) { fprintf(stderr, "Invalid speed\n"); return false; } for (it = er.begin(); it != er.end(); ++it) { (*it)->setSpeed(speed); } return true; } if (!strcmp(argv[i], "-server") && (i+1 < argc)) { ++i; for (it = er.begin(); it != er.end(); ++it) { if (!(*it)->setServer(argv[i])) { fprintf(stderr, "Can't resolve server name %s\n", argv[i]); return false; } } return true; } return false; } bool parseArguments(int argc, char **argv, std::vector<EffectRunner*> er) { for (int i = 1; i < argc; i++) { if (!parseArgument(i, argc, argv, er)) { usage(argv[0]); return false; } } return true; } #define NB_ENABLE 1 #define NB_DISABLE 0 int kbhit() { struct timeval tv; fd_set fds; tv.tv_sec = 0; tv.tv_usec = 0; FD_ZERO(&fds); FD_SET(STDIN_FILENO, &fds); //STDIN_FILENO is 0 select(STDIN_FILENO+1, &fds, NULL, NULL, &tv); return FD_ISSET(STDIN_FILENO, &fds); } void nonblock(int state) { struct termios ttystate; //get the terminal state tcgetattr(STDIN_FILENO, &ttystate); if (state==NB_ENABLE) { //turn off canonical mode ttystate.c_lflag &= ~ICANON; //minimum of number input read. ttystate.c_cc[VMIN] = 1; } else if (state==NB_DISABLE) { //turn on canonical mode ttystate.c_lflag |= ICANON; } //set the terminal attributes. tcsetattr(STDIN_FILENO, TCSANOW, &ttystate); } void changeEffect(int channel, const char* effectName, std::vector<EffectRunner*> er) { Effect *oldEffect = effects[channel]; fprintf(stderr, "\neffectName %s\n", effectName); if (strcmp(effectName, "falling") == 0) { fprintf(stderr, "\nchanged effect to MyEffect\n"); effects[channel] = new MyEffect(channel); } else if (strcmp(effectName, "python") == 0) { fprintf(stderr, "\nchanged effect to PythonEffect\n"); effects[channel] = new PythonEffect(channel); } else if (strcmp(effectName, "processing") == 0) { fprintf(stderr, "\nchanged effect to ProcessingEffect\n"); effects[channel] = new ProcessingEffect(channel); } else if (strcmp(effectName, "perlin") == 0) { fprintf(stderr, "\nchanged effect to PerlinEffect\n"); effects[channel] = new PerlinEffect(channel); } else if (strcmp(effectName, "fire") == 0) { fprintf(stderr, "\nchanged effect to FireEffect\n"); effects[channel] = new FireEffect(channel); } else if (strcmp(effectName, "reverse") == 0) { fprintf(stderr, "\nchanged effect to ReverseEffect\n"); effects[channel] = new ReverseEffect(channel); } er[channel]->setEffect(effects[channel]); delete oldEffect; } void checkController(std::vector<EffectRunner*> er) { /* * This currently just listens for keypresses on the console. * Eventually it should read data from the raspberry pi gpio pins. * */ char c; static int effect = 0; std::vector<EffectRunner*>::const_iterator it; int i=kbhit(); if (i!=0) { c=fgetc(stdin); if (c == 's') { float speed = 0.0f; for (it = er.begin(); it != er.end(); ++it) { speed = (*it)->getSpeed(); if (speed < 0.1) { speed = 5.0; } else { speed *= 0.8; } (*it)->setSpeed(speed); } fprintf(stderr, "\nspeed set to %.2f. \n", speed); } else if (c == 'c') { // Change colour palette for (it = er.begin(); it != er.end(); ++it) { TEffect* e = (TEffect*) (*it)->getEffect(); e->nextColor(); } fprintf(stderr, "\nchanged color palette\n"); } else if (c == 'e') { // Change effect int j=0; int NUM_EFFECTS=6; effect++; int e_index = effect % NUM_EFFECTS; fprintf(stderr, "\ne_index is %d\n", e_index); for (it = er.begin(); it != er.end(); ++it, ++j) { if (e_index == 0) { changeEffect(j, "falling", er); } else if (e_index == 1) { changeEffect(j, "processing", er); } else if (e_index == 2) { changeEffect(j, "python", er); } else if (e_index == 3) { changeEffect(j, "perlin", er); } else if (e_index == 4) { changeEffect(j, "fire", er); } else if (e_index == 5) { changeEffect(j, "reverse", er); } } } else { fprintf(stderr, "\nunknown command %c. \n", c); } } } int main(int argc, char **argv) { std::vector<EffectRunner*> effect_runners; const int layers = NUM_LAYERS; char buffer[1000]; effects = new Effect* [layers]; for (int i = 0; i < layers; i++) { Effect *e = new ReverseEffect(i); effects[i] = e; EffectRunner* r = new EffectRunner(); r->setEffect(e); r->setMaxFrameRate(50); r->setChannel(i); snprintf(buffer, 1000, "../Processing/tensegrity/opc_layout_%d.json", i); r->setLayout(buffer); effect_runners.push_back(r); } parseArguments(argc, argv, effect_runners); nonblock(NB_ENABLE); while (true) { for (int i=0 ; i < layers; i++) { effect_runners[i]->doFrame(); } checkController(effect_runners); } nonblock(NB_DISABLE); return 0; } <|endoftext|>
<commit_before>#ifndef _SDD_DD_SUM_HH_ #define _SDD_DD_SUM_HH_ #include <initializer_list> #include <type_traits> // enable_if, is_same #include <unordered_map> #include <vector> #include "sdd/internal_manager_fwd.hh" #include "sdd/dd/context_fwd.hh" #include "sdd/dd/definition.hh" #include "sdd/dd/nary.hh" #include "sdd/dd/operations_fwd.hh" #include "sdd/dd/square_union.hh" #include "sdd/util/hash.hh" #include "sdd/util/boost_flat_map_no_warnings.hh" #include "sdd/util/boost_flat_set_no_warnings.hh" #include "sdd/values/empty.hh" #include "sdd/values/values_traits.hh" namespace sdd { namespace dd { /*------------------------------------------------------------------------------------------------*/ /// @internal /// @brief The sum operation in the cache. template <typename C> struct LIBSDD_ATTRIBUTE_PACKED sum_op_impl { /// @brief The textual representation of the union operator. static constexpr char symbol = '+'; /// @brief Perform the SDD union algorithm. /// /// It's a so-called 'n-ary' union in the sense that we don't create intermediary SDD. /// Also, a lot of tests permit to break loops as soon as possible. template <typename InputIterator, typename NodeType> static typename std::enable_if< std::is_same<NodeType, hierarchical_node<C>>::value or not values::values_traits<typename C::Values>::fast_iterable , SDD<C>>::type work(InputIterator begin, InputIterator end, context<C>& cxt) { using node_type = NodeType; using valuation_type = typename node_type::valuation_type; auto operands_cit = begin; const auto operands_end = end; // Get the first operand as a node, we need it to initialize the algorithm. const node_type& head = mem::variant_cast<node_type>(**operands_cit); // Type of the list of successors for a valuation, to be merged with the union operation // right before calling the square union. using sum_builder_type = sum_builder<C, SDD<C>>; /// @todo Use Boost.Intrusive to save on memory allocations? // List all the successors for each valuation in the final alpha. std::unordered_map<valuation_type, sum_builder_type> res(head.size()); // Needed to temporarily store arcs erased from res and arcs from the alpha visited in // the loop (B). std::vector<std::pair<valuation_type, sum_builder_type>> save; save.reserve(head.size()); // Used in test (F). std::vector<std::pair<valuation_type, sum_builder_type>> remainder; remainder.reserve(head.size()); // Initialize res with the alpha of the first operand. for (auto& arc : head) { sum_builder_type succs; succs.add(arc.successor()); res.emplace(arc.valuation(), std::move(succs)); } // (A). for (++operands_cit; operands_cit != operands_end; ++operands_cit) { // Throw a Top if operands are incompatible (different types or different variables). check_compatibility(*begin, *operands_cit); const auto res_end = res.end(); const node_type& node = mem::variant_cast<node_type>(**operands_cit); const auto alpha_end = node.end(); // (B). For each arc of the current operand. for (auto alpha_cit = node.begin(); alpha_cit != alpha_end; ++alpha_cit) { // The current valuation may be modified, we need a copy. valuation_type current_val = alpha_cit->valuation(); const SDD<C> current_succ = alpha_cit->successor(); // Initialize the start of the next search. auto res_cit = res.begin(); // (C). While the current valuation is not empty, test it against arcs in res. while (not values::empty_values(current_val) and res_cit != res_end) { const valuation_type& res_val = res_cit->first; sum_builder_type& res_succs = res_cit->second; // (D). if (current_val == res_val) // Same valuations. { save.emplace_back(res_val, std::move(res_succs)); save.back().second.add(current_succ); const auto to_erase = res_cit; ++res_cit; res.erase(to_erase); // Avoid useless insertion or temporary variables. goto equality; } intersection_builder<C, valuation_type> inter_builder; inter_builder.add(current_val); inter_builder.add(res_val); const valuation_type inter = intersection(cxt, std::move(inter_builder)); // (E). The current valuation and the current arc from res have a common part. if (not values::empty_values(inter)) { save.emplace_back(inter, res_succs); save.back().second.add(current_succ); // (F). valuation_type diff = difference(cxt, res_val, inter); if (not values::empty_values(diff)) { // (res_val - inter) can't be in intersection, but we need to keep it // for the next arcs of the current alpha. So we put in a temporary storage. // It will be added back in res when we have finished with the current valuation. remainder.emplace_back(std::move(diff), std::move(res_succs)); } // We won't need the current arc of res for the current val, we already have the // common part. Now, the current valuation has to be tested against the next arcs // of res. const auto to_erase = res_cit; ++res_cit; res.erase(to_erase); // (G). The current valuation is completely included in the current arc of res. if (current_val == inter) { // We can move to the next arc of the current operand. break; } // Continue with what remains of val. if val is empy, the loop will stop at the // next iteration. current_val = difference(cxt, current_val, inter); } else // (H). Empty intersection, lookup for next possible common parts. { ++res_cit; } } // While we're not at the end of res and val is not empty. // (I). For val or a part of val (it could have been modified during the previous // loop), we didn't find an intersection with any arc of res. if (not values::empty_values(current_val)) { sum_builder_type succs; succs.add(current_succ); save.emplace_back(std::move(current_val), std::move(succs)); } // Both arcs had the same valuation. equality:; // Reinject all parts that were removed in (F). for (auto& rem : remainder) { res.emplace(std::move(rem.first), std::move(rem.second)); } remainder.clear(); } // For each arc of the current operand. // Reinject all parts that were removed from res (all parts that have a non-empty // intersection with the current alpha) and all parts of the current alpha that have an // empty intersection with all the parts of res. res.insert(save.begin(), save.end()); // We still need save. save.clear(); } // End of iteration on operands. square_union<C, valuation_type> su; su.reserve(res.size()); for (auto& arc : res) { // construct an operand for the square union: (successors union) --> valuation su.add(sum(cxt, std::move(arc.second)), arc.first); } return SDD<C>(head.variable(), su(cxt)); } /// @brief Linear union of flat SDDs whose valuation are "fast iterable". template <typename InputIterator, typename NodeType> static typename std::enable_if< std::is_same<NodeType, flat_node<C>>::value and values::values_traits<typename C::Values>::fast_iterable , SDD<C>>::type work(InputIterator begin, InputIterator end, context<C>& cxt) { const auto& variable = mem::variant_cast<flat_node<C>>(**begin).variable(); using values_type = typename C::Values; using value_type = typename values_type::value_type; using sum_builder_type = sum_builder<C, SDD<C>>; boost::container::flat_map<value_type, sum_builder_type> value_to_succ; value_to_succ.reserve(std::distance(begin, end) * 2); auto cit = begin; for (; cit != end; ++cit) { check_compatibility(*begin, *cit); const auto& node = mem::variant_cast<flat_node<C>>(**cit); for (const auto& arc : node) { const SDD<C> succ = arc.successor(); for (const auto& value : arc.valuation()) { const auto search = value_to_succ.find(value); if (search == value_to_succ.end()) { value_to_succ.emplace_hint(search, value, sum_builder_type({succ})); } else { search->second.add(succ); } } } } boost::container::flat_map<SDD<C>, values_type> succ_to_value; succ_to_value.reserve(value_to_succ.size()); for (auto& value_succs : value_to_succ) { const SDD<C> succ = sum(cxt, std::move(value_succs.second)); const auto search = succ_to_value.find(succ); if (search == succ_to_value.end()) { succ_to_value.emplace_hint(search, succ, values_type({value_succs.first})); } else { search->second.insert(value_succs.first); } } alpha_builder<C, values_type> alpha; alpha.reserve(succ_to_value.size()); for (auto& succ_values : succ_to_value) { alpha.add(std::move(succ_values.second), succ_values.first); } return SDD<C>(variable, std::move(alpha)); } }; /*------------------------------------------------------------------------------------------------*/ /// @internal /// @brief Add an arc to the operands of the sum operation. /// /// This implementation is meant to be used as a policy by nary_builder which doesn't know how /// to add an arc. template <typename C, typename Valuation> struct LIBSDD_ATTRIBUTE_PACKED sum_builder_impl { void add(boost::container::flat_set<Valuation>& set, Valuation&& operand) { if (not values::empty_values(operand)) { set.insert(std::move(operand)); } } void add(boost::container::flat_set<Valuation>& set, const Valuation& operand) { if (not values::empty_values(operand)) { set.insert(operand); } } }; /*------------------------------------------------------------------------------------------------*/ /// @internal /// @brief The sum operation of a set of SDD. /// @related sdd::SDD template <typename C> inline SDD<C> sum(context<C>& cxt, sum_builder<C, SDD<C>>&& builder) { if (builder.empty()) { return zero<C>(); } else if (builder.size() == 1) { return *builder.begin(); } return cxt.sum_cache()(sum_op<C>(builder)); } /*------------------------------------------------------------------------------------------------*/ /// @internal /// @brief The sum operation of a set of values. /// @details A wrapper around the implementation of sum provided by Values. template <typename C, typename Values> inline Values sum(context<C>&, sum_builder<C, Values>&& builder) { if (builder.empty()) { return Values(); } else if (builder.size() == 1) { return *builder.begin(); } else { auto cit = builder.begin(); const auto end = builder.end(); Values result = *cit; for (++cit; cit != end; ++cit) { typename C::Values tmp = sum(result, *cit); using std::swap; swap(tmp, result); } return result; } } } // namespace dd /*------------------------------------------------------------------------------------------------*/ /// @brief Perform the union of two SDD. /// @related SDD template <typename C> inline SDD<C> operator+(const SDD<C>& lhs, const SDD<C>& rhs) { return dd::sum(global<C>().sdd_context, {lhs, rhs}); } /// @brief Perform the union of two SDD. /// @related SDD template <typename C> inline SDD<C>& operator+=(SDD<C>& lhs, const SDD<C>& rhs) { SDD<C> tmp = dd::sum(global<C>().sdd_context, {lhs, rhs}); using std::swap; swap(tmp, lhs); return lhs; } /// @brief Perform the union of an iterable container of SDD. /// @related SDD template <typename C, typename InputIterator> SDD<C> inline sum(InputIterator begin, InputIterator end) { dd::sum_builder<C, SDD<C>> builder; for (; begin != end; ++begin) { builder.add(*begin); } return dd::sum(global<C>().sdd_context, std::move(builder)); } /// @brief Perform the union of an initializer list of SDD. /// @related SDD template <typename C> SDD<C> inline sum(std::initializer_list<SDD<C>> operands) { return sum<C>(std::begin(operands), std::end(operands)); } /*------------------------------------------------------------------------------------------------*/ } // namespace sdd #endif // _SDD_DD_SUM_HH_ <commit_msg>Use custom allocator for standard containers used in dd::sum.<commit_after>#ifndef _SDD_DD_SUM_HH_ #define _SDD_DD_SUM_HH_ #include <initializer_list> #include <type_traits> // enable_if, is_same #include <unordered_map> #include <vector> #include "sdd/internal_manager_fwd.hh" #include "sdd/dd/context_fwd.hh" #include "sdd/dd/definition.hh" #include "sdd/dd/nary.hh" #include "sdd/dd/operations_fwd.hh" #include "sdd/dd/square_union.hh" #include "sdd/mem/linear_alloc.hh" #include "sdd/util/hash.hh" #include "sdd/util/boost_flat_map_no_warnings.hh" #include "sdd/util/boost_flat_set_no_warnings.hh" #include "sdd/values/empty.hh" #include "sdd/values/values_traits.hh" namespace sdd { namespace dd { /*------------------------------------------------------------------------------------------------*/ /// @internal /// @brief The sum operation in the cache. template <typename C> struct LIBSDD_ATTRIBUTE_PACKED sum_op_impl { /// @brief The textual representation of the union operator. static constexpr char symbol = '+'; /// @brief Perform the SDD union algorithm. /// /// It's a so-called 'n-ary' union in the sense that we don't create intermediary SDD. /// Also, a lot of tests permit to break loops as soon as possible. template <typename InputIterator, typename NodeType> static typename std::enable_if< std::is_same<NodeType, hierarchical_node<C>>::value or not values::values_traits<typename C::Values>::fast_iterable , SDD<C>>::type work(InputIterator begin, InputIterator end, context<C>& cxt) { using node_type = NodeType; using valuation_type = typename node_type::valuation_type; // Automatic reinitialisation of the memory arena. mem::rewinder _(cxt.arena()); auto operands_cit = begin; const auto operands_end = end; // Get the first operand as a node, we need it to initialize the algorithm. const node_type& head = mem::variant_cast<node_type>(**operands_cit); // Type of the list of successors for a valuation, to be merged with the union operation // right before calling the square union. using sum_builder_type = sum_builder<C, SDD<C>>; /// @todo Use intrusive hash map to save on memory allocations? // List all the successors for each valuation in the final alpha. std::unordered_map< valuation_type, sum_builder_type , std::hash<valuation_type>, std::equal_to<valuation_type> , mem::linear_alloc<std::pair<const valuation_type, sum_builder_type>> > res( head.size(), std::hash<valuation_type>(), std::equal_to<valuation_type>() , mem::linear_alloc<std::pair<const valuation_type, sum_builder_type>>(cxt.arena())); using pair_type = std::pair<valuation_type, sum_builder_type>; // Needed to temporarily store arcs erased from res and arcs from the alpha visited in // the loop (B). std::vector<pair_type, mem::linear_alloc<pair_type>> save(mem::linear_alloc<pair_type>(cxt.arena())); save.reserve(head.size()); // Used in test (F). std::vector<pair_type, mem::linear_alloc<pair_type>> remainder(mem::linear_alloc<pair_type>(cxt.arena())); remainder.reserve(head.size()); // Initialize res with the alpha of the first operand. for (auto& arc : head) { sum_builder_type succs; succs.add(arc.successor()); res.emplace(arc.valuation(), std::move(succs)); } // (A). for (++operands_cit; operands_cit != operands_end; ++operands_cit) { // Throw a Top if operands are incompatible (different types or different variables). check_compatibility(*begin, *operands_cit); const auto res_end = res.end(); const node_type& node = mem::variant_cast<node_type>(**operands_cit); const auto alpha_end = node.end(); // (B). For each arc of the current operand. for (auto alpha_cit = node.begin(); alpha_cit != alpha_end; ++alpha_cit) { // The current valuation may be modified, we need a copy. valuation_type current_val = alpha_cit->valuation(); const SDD<C> current_succ = alpha_cit->successor(); // Initialize the start of the next search. auto res_cit = res.begin(); // (C). While the current valuation is not empty, test it against arcs in res. while (not values::empty_values(current_val) and res_cit != res_end) { const valuation_type& res_val = res_cit->first; sum_builder_type& res_succs = res_cit->second; // (D). if (current_val == res_val) // Same valuations. { save.emplace_back(res_val, std::move(res_succs)); save.back().second.add(current_succ); const auto to_erase = res_cit; ++res_cit; res.erase(to_erase); // Avoid useless insertion or temporary variables. goto equality; } intersection_builder<C, valuation_type> inter_builder; inter_builder.add(current_val); inter_builder.add(res_val); const valuation_type inter = intersection(cxt, std::move(inter_builder)); // (E). The current valuation and the current arc from res have a common part. if (not values::empty_values(inter)) { save.emplace_back(inter, res_succs); save.back().second.add(current_succ); // (F). valuation_type diff = difference(cxt, res_val, inter); if (not values::empty_values(diff)) { // (res_val - inter) can't be in intersection, but we need to keep it // for the next arcs of the current alpha. So we put in a temporary storage. // It will be added back in res when we have finished with the current valuation. remainder.emplace_back(std::move(diff), std::move(res_succs)); } // We won't need the current arc of res for the current val, we already have the // common part. Now, the current valuation has to be tested against the next arcs // of res. const auto to_erase = res_cit; ++res_cit; res.erase(to_erase); // (G). The current valuation is completely included in the current arc of res. if (current_val == inter) { // We can move to the next arc of the current operand. break; } // Continue with what remains of val. if val is empy, the loop will stop at the // next iteration. current_val = difference(cxt, current_val, inter); } else // (H). Empty intersection, lookup for next possible common parts. { ++res_cit; } } // While we're not at the end of res and val is not empty. // (I). For val or a part of val (it could have been modified during the previous // loop), we didn't find an intersection with any arc of res. if (not values::empty_values(current_val)) { sum_builder_type succs; succs.add(current_succ); save.emplace_back(std::move(current_val), std::move(succs)); } // Both arcs had the same valuation. equality:; // Reinject all parts that were removed in (F). for (auto& rem : remainder) { res.emplace(std::move(rem.first), std::move(rem.second)); } remainder.clear(); } // For each arc of the current operand. // Reinject all parts that were removed from res (all parts that have a non-empty // intersection with the current alpha) and all parts of the current alpha that have an // empty intersection with all the parts of res. res.insert(save.begin(), save.end()); // We still need save. save.clear(); } // End of iteration on operands. square_union<C, valuation_type> su; su.reserve(res.size()); for (auto& arc : res) { // construct an operand for the square union: (successors union) --> valuation su.add(sum(cxt, std::move(arc.second)), arc.first); } return SDD<C>(head.variable(), su(cxt)); } /// @brief Linear union of flat SDDs whose valuation are "fast iterable". template <typename InputIterator, typename NodeType> static typename std::enable_if< std::is_same<NodeType, flat_node<C>>::value and values::values_traits<typename C::Values>::fast_iterable , SDD<C>>::type work(InputIterator begin, InputIterator end, context<C>& cxt) { const auto& variable = mem::variant_cast<flat_node<C>>(**begin).variable(); using values_type = typename C::Values; using value_type = typename values_type::value_type; using sum_builder_type = sum_builder<C, SDD<C>>; boost::container::flat_map<value_type, sum_builder_type> value_to_succ; value_to_succ.reserve(std::distance(begin, end) * 2); auto cit = begin; for (; cit != end; ++cit) { check_compatibility(*begin, *cit); const auto& node = mem::variant_cast<flat_node<C>>(**cit); for (const auto& arc : node) { const SDD<C> succ = arc.successor(); for (const auto& value : arc.valuation()) { const auto search = value_to_succ.find(value); if (search == value_to_succ.end()) { value_to_succ.emplace_hint(search, value, sum_builder_type({succ})); } else { search->second.add(succ); } } } } boost::container::flat_map<SDD<C>, values_type> succ_to_value; succ_to_value.reserve(value_to_succ.size()); for (auto& value_succs : value_to_succ) { const SDD<C> succ = sum(cxt, std::move(value_succs.second)); const auto search = succ_to_value.find(succ); if (search == succ_to_value.end()) { succ_to_value.emplace_hint(search, succ, values_type({value_succs.first})); } else { search->second.insert(value_succs.first); } } alpha_builder<C, values_type> alpha; alpha.reserve(succ_to_value.size()); for (auto& succ_values : succ_to_value) { alpha.add(std::move(succ_values.second), succ_values.first); } return SDD<C>(variable, std::move(alpha)); } }; /*------------------------------------------------------------------------------------------------*/ /// @internal /// @brief Add an arc to the operands of the sum operation. /// /// This implementation is meant to be used as a policy by nary_builder which doesn't know how /// to add an arc. template <typename C, typename Valuation> struct LIBSDD_ATTRIBUTE_PACKED sum_builder_impl { void add(boost::container::flat_set<Valuation>& set, Valuation&& operand) { if (not values::empty_values(operand)) { set.insert(std::move(operand)); } } void add(boost::container::flat_set<Valuation>& set, const Valuation& operand) { if (not values::empty_values(operand)) { set.insert(operand); } } }; /*------------------------------------------------------------------------------------------------*/ /// @internal /// @brief The sum operation of a set of SDD. /// @related sdd::SDD template <typename C> inline SDD<C> sum(context<C>& cxt, sum_builder<C, SDD<C>>&& builder) { if (builder.empty()) { return zero<C>(); } else if (builder.size() == 1) { return *builder.begin(); } return cxt.sum_cache()(sum_op<C>(builder)); } /*------------------------------------------------------------------------------------------------*/ /// @internal /// @brief The sum operation of a set of values. /// @details A wrapper around the implementation of sum provided by Values. template <typename C, typename Values> inline Values sum(context<C>&, sum_builder<C, Values>&& builder) { if (builder.empty()) { return Values(); } else if (builder.size() == 1) { return *builder.begin(); } else { auto cit = builder.begin(); const auto end = builder.end(); Values result = *cit; for (++cit; cit != end; ++cit) { typename C::Values tmp = sum(result, *cit); using std::swap; swap(tmp, result); } return result; } } } // namespace dd /*------------------------------------------------------------------------------------------------*/ /// @brief Perform the union of two SDD. /// @related SDD template <typename C> inline SDD<C> operator+(const SDD<C>& lhs, const SDD<C>& rhs) { return dd::sum(global<C>().sdd_context, {lhs, rhs}); } /// @brief Perform the union of two SDD. /// @related SDD template <typename C> inline SDD<C>& operator+=(SDD<C>& lhs, const SDD<C>& rhs) { SDD<C> tmp = dd::sum(global<C>().sdd_context, {lhs, rhs}); using std::swap; swap(tmp, lhs); return lhs; } /// @brief Perform the union of an iterable container of SDD. /// @related SDD template <typename C, typename InputIterator> SDD<C> inline sum(InputIterator begin, InputIterator end) { dd::sum_builder<C, SDD<C>> builder; for (; begin != end; ++begin) { builder.add(*begin); } return dd::sum(global<C>().sdd_context, std::move(builder)); } /// @brief Perform the union of an initializer list of SDD. /// @related SDD template <typename C> SDD<C> inline sum(std::initializer_list<SDD<C>> operands) { return sum<C>(std::begin(operands), std::end(operands)); } /*------------------------------------------------------------------------------------------------*/ } // namespace sdd #endif // _SDD_DD_SUM_HH_ <|endoftext|>
<commit_before>/** @file serialun.cpp * @brief Testing and debugging script */ //#define DEBUG #include <FMM_plan.hpp> //#include <LaplaceSphericalModified.hpp> #include <LaplaceSpherical.hpp> //#include <UnitKernel.hpp> //#include <KernelSkeleton.hpp> //#include <KernelSkeletonMixed.hpp> //#include <LaplaceCartesian.hpp> //#include <YukawaCartesian.hpp> //#include <YukawaSpherical.hpp> #include "StokesSpherical.hpp" #include <cstring> // modify error checking for counting kernel // TODO: Do this much better... //#define SKELETON_KERNEL //#define UNIT_KERNEL //#define SPH_KERNEL //#define CART_KERNEL //#define YUKAWA_KERNEL //#define YUKAWA_SPH #define STOKES_SPH // Random number in [0,1) inline double drand() { return ::drand48(); } // Random number in [A,B) inline double drand(double A, double B) { return A + (B-A) * drand(); } int main(int argc, char **argv) { //std::vector<std::string> args(argv+1, argv+argc); //std::cout << args[0] << '\n' << args[1] << '\n' << args[2] << std::endl; int numBodies = 1000, p=5; bool checkErrors = true; double beta = 0.125; FMMOptions opts = get_options(argc, argv); opts.local_evaluation = true; opts.sparse_local = true; // parse custom command line args for (int i = 1; i < argc; ++i) { if (strcmp(argv[i],"-N") == 0) { i++; numBodies = atoi(argv[i]); } else if (strcmp(argv[i],"-p") == 0) { i++; p = atoi(argv[i]); } else if (strcmp(argv[i],"-beta") == 0) { i++; beta = atof(argv[i]); } else if (strcmp(argv[i],"-nocheck") == 0) { checkErrors = false; } } // Init the FMM Kernel #ifdef SKELETON_KERNEL typedef KernelSkeleton kernel_type; kernel_type K; #endif #ifdef SPH_KERNEL typedef LaplaceSpherical kernel_type; kernel_type K(p); #endif #ifdef CART_KERNEL typedef LaplaceCartesian<5> kernel_type; kernel_type K; #endif #ifdef YUKAWA_KERNEL typedef YukawaCartesian kernel_type; kernel_type K(p,beta); #endif #ifdef YUKAWA_SPH typedef YukawaSpherical kernel_type; kernel_type K(p,beta); #endif #ifdef UNIT_KERNEL typedef UnitKernel kernel_type; kernel_type K; #endif #ifdef STOKES_SPH typedef StokesSpherical kernel_type; kernel_type K(p); #endif // if not using a Yukawa kernel, quiet warnings #if !defined(YUKAWA_KERNEL) && !defined(YUKAWA_SPH) (void) beta; #endif typedef kernel_type::point_type point_type; typedef kernel_type::source_type source_type; typedef kernel_type::target_type target_type; typedef kernel_type::charge_type charge_type; typedef kernel_type::result_type result_type; // Init points and charges std::vector<source_type> points(numBodies); for (int k = 0; k < numBodies; ++k) points[k] = source_type(drand(), drand(), drand()); //std::vector<point_type> target_points = points; std::vector<charge_type> charges(numBodies); for (int k = 0; k < numBodies; ++k) { #if defined(STOKES_SPH) charges[k] = charge_type(1,1,1); // charge_type(drand(),drand(),drand()); #else charges[k] = drand(); #endif } // Build the FMM //fmm_plan plan = fmm_plan(K, bodies, opts); FMM_plan<kernel_type> plan = FMM_plan<kernel_type>(K, points, opts); // Execute the FMM //fmm_execute(plan, charges, target_points); std::vector<result_type> result = plan.execute(charges); // Check the result // TODO: More elegant if (checkErrors) { // choose a number of samples to use int numSamples = std::min(numBodies, 1000); std::vector<int> sample_map(numSamples); std::vector<point_type> sample_targets(numSamples); std::vector<result_type> exact(numSamples); // sample the space (needs to be done better) for (int i=0; i<numSamples; i++) { int sample = i >> 15 % numBodies; sample_map[i] = sample; sample_targets[i] = points[sample]; } // Compute the result with a direct matrix-vector multiplication Direct::matvec(K, points.begin(), points.end(), charges.begin(), sample_targets.begin(), sample_targets.end(), exact.begin()); #if defined(SPH_KERNEL) || defined(CART_KERNEL) || defined(YUKAWA_KERNEL) result_type rdiff, rnorm; for (unsigned k = 0; k < exact.size(); ++k) { auto exact_val = exact[k]; auto fmm_val = result[sample_map[k]]; // printf("[%03d] exact: %lg, FMM: %lg\n", k, exact_val[0], fmm_val[0]); rdiff += (fmm_val - exact_val) * (fmm_val - exact_val); rnorm += exact_val * exact_val; } printf("Error (pot) : %.4e\n", sqrt(rdiff[0] / rnorm[0])); printf("Error (acc) : %.4e\n", sqrt((rdiff[1]+rdiff[2]+rdiff[3]) / (rnorm[1]+rnorm[2]+rnorm[3]))); #endif #if defined(YUKAWA_SPH) result_type rdiff = 0., rnorm = 0.; for (unsigned k = 0; k < exact.size(); ++k) { // printf("[%03d] exact: %lg, FMM: %lg\n", k, exact[k], result[k]); auto exact_val = exact[k]; auto fmm_val = result[sample_map[k]]; rdiff = (fmm_val - exact_val) * (fmm_val - exact_val); rnorm = exact_val * exact_val; } printf("Error (pot) : %.4e\n", sqrt(rdiff / rnorm)); #endif #if defined(STOKES_SPH) result_type rdiff = result_type(0.), rnorm = result_type(0.); for (unsigned k = 0; k < exact.size(); ++k) { auto exact_val = exact[k]; auto fmm_val = result[sample_map[k]]; for (unsigned i=0; i < 3; i++) { rdiff[i] += (fmm_val[i]-exact_val[i])*(fmm_val[i]-exact_val[i]); rnorm[i] += exact_val[i]*exact_val[i]; } } auto div = rdiff/rnorm; printf("Error (u) : %.4e, (v) : %.4e, (w) : %.4e\n",sqrt(div[0]),sqrt(div[1]),sqrt(div[2])); #endif #ifdef UNIT_KERNEL int wrong_results = 0; for (unsigned k = 0; k < exact.size(); ++k) { auto exact_val = exact[k]; auto fmm_val = result[sample_map[k]]; // printf("[%03d] exact: %lg, FMM: %lg\n", k, exact[k], result[k]); if ((exact_val - fmm_val) / exact_val > 1e-13) ++wrong_results; } printf("Wrong counts: %d\n", wrong_results); #endif } } <commit_msg>Turn off new local evaluation<commit_after>/** @file serialun.cpp * @brief Testing and debugging script */ //#define DEBUG #include <FMM_plan.hpp> //#include <LaplaceSphericalModified.hpp> #include <LaplaceSpherical.hpp> //#include <UnitKernel.hpp> //#include <KernelSkeleton.hpp> //#include <KernelSkeletonMixed.hpp> //#include <LaplaceCartesian.hpp> //#include <YukawaCartesian.hpp> //#include <YukawaSpherical.hpp> #include "StokesSpherical.hpp" #include <cstring> // modify error checking for counting kernel // TODO: Do this much better... //#define SKELETON_KERNEL //#define UNIT_KERNEL //#define SPH_KERNEL //#define CART_KERNEL //#define YUKAWA_KERNEL //#define YUKAWA_SPH #define STOKES_SPH // Random number in [0,1) inline double drand() { return ::drand48(); } // Random number in [A,B) inline double drand(double A, double B) { return A + (B-A) * drand(); } int main(int argc, char **argv) { //std::vector<std::string> args(argv+1, argv+argc); //std::cout << args[0] << '\n' << args[1] << '\n' << args[2] << std::endl; int numBodies = 1000, p=5; bool checkErrors = true; double beta = 0.125; FMMOptions opts = get_options(argc, argv); opts.local_evaluation = false; opts.sparse_local = false; // parse custom command line args for (int i = 1; i < argc; ++i) { if (strcmp(argv[i],"-N") == 0) { i++; numBodies = atoi(argv[i]); } else if (strcmp(argv[i],"-p") == 0) { i++; p = atoi(argv[i]); } else if (strcmp(argv[i],"-beta") == 0) { i++; beta = atof(argv[i]); } else if (strcmp(argv[i],"-nocheck") == 0) { checkErrors = false; } } // Init the FMM Kernel #ifdef SKELETON_KERNEL typedef KernelSkeleton kernel_type; kernel_type K; #endif #ifdef SPH_KERNEL typedef LaplaceSpherical kernel_type; kernel_type K(p); #endif #ifdef CART_KERNEL typedef LaplaceCartesian<5> kernel_type; kernel_type K; #endif #ifdef YUKAWA_KERNEL typedef YukawaCartesian kernel_type; kernel_type K(p,beta); #endif #ifdef YUKAWA_SPH typedef YukawaSpherical kernel_type; kernel_type K(p,beta); #endif #ifdef UNIT_KERNEL typedef UnitKernel kernel_type; kernel_type K; #endif #ifdef STOKES_SPH typedef StokesSpherical kernel_type; kernel_type K(p); #endif // if not using a Yukawa kernel, quiet warnings #if !defined(YUKAWA_KERNEL) && !defined(YUKAWA_SPH) (void) beta; #endif typedef kernel_type::point_type point_type; typedef kernel_type::source_type source_type; typedef kernel_type::target_type target_type; typedef kernel_type::charge_type charge_type; typedef kernel_type::result_type result_type; // Init points and charges std::vector<source_type> points(numBodies); for (int k = 0; k < numBodies; ++k) points[k] = source_type(drand(), drand(), drand()); //std::vector<point_type> target_points = points; std::vector<charge_type> charges(numBodies); for (int k = 0; k < numBodies; ++k) { #if defined(STOKES_SPH) charges[k] = charge_type(1,1,1); // charge_type(drand(),drand(),drand()); #else charges[k] = drand(); #endif } // Build the FMM //fmm_plan plan = fmm_plan(K, bodies, opts); FMM_plan<kernel_type> plan = FMM_plan<kernel_type>(K, points, opts); // Execute the FMM //fmm_execute(plan, charges, target_points); std::vector<result_type> result = plan.execute(charges); // Check the result // TODO: More elegant if (checkErrors) { // choose a number of samples to use int numSamples = std::min(numBodies, 1000); std::vector<int> sample_map(numSamples); std::vector<point_type> sample_targets(numSamples); std::vector<result_type> exact(numSamples); // sample the space (needs to be done better) for (int i=0; i<numSamples; i++) { int sample = i >> 15 % numBodies; sample_map[i] = sample; sample_targets[i] = points[sample]; } // Compute the result with a direct matrix-vector multiplication Direct::matvec(K, points.begin(), points.end(), charges.begin(), sample_targets.begin(), sample_targets.end(), exact.begin()); #if defined(SPH_KERNEL) || defined(CART_KERNEL) || defined(YUKAWA_KERNEL) result_type rdiff, rnorm; for (unsigned k = 0; k < exact.size(); ++k) { auto exact_val = exact[k]; auto fmm_val = result[sample_map[k]]; // printf("[%03d] exact: %lg, FMM: %lg\n", k, exact_val[0], fmm_val[0]); rdiff += (fmm_val - exact_val) * (fmm_val - exact_val); rnorm += exact_val * exact_val; } printf("Error (pot) : %.4e\n", sqrt(rdiff[0] / rnorm[0])); printf("Error (acc) : %.4e\n", sqrt((rdiff[1]+rdiff[2]+rdiff[3]) / (rnorm[1]+rnorm[2]+rnorm[3]))); #endif #if defined(YUKAWA_SPH) result_type rdiff = 0., rnorm = 0.; for (unsigned k = 0; k < exact.size(); ++k) { // printf("[%03d] exact: %lg, FMM: %lg\n", k, exact[k], result[k]); auto exact_val = exact[k]; auto fmm_val = result[sample_map[k]]; rdiff = (fmm_val - exact_val) * (fmm_val - exact_val); rnorm = exact_val * exact_val; } printf("Error (pot) : %.4e\n", sqrt(rdiff / rnorm)); #endif #if defined(STOKES_SPH) result_type rdiff = result_type(0.), rnorm = result_type(0.); for (unsigned k = 0; k < exact.size(); ++k) { auto exact_val = exact[k]; auto fmm_val = result[sample_map[k]]; for (unsigned i=0; i < 3; i++) { rdiff[i] += (fmm_val[i]-exact_val[i])*(fmm_val[i]-exact_val[i]); rnorm[i] += exact_val[i]*exact_val[i]; } } auto div = rdiff/rnorm; printf("Error (u) : %.4e, (v) : %.4e, (w) : %.4e\n",sqrt(div[0]),sqrt(div[1]),sqrt(div[2])); #endif #ifdef UNIT_KERNEL int wrong_results = 0; for (unsigned k = 0; k < exact.size(); ++k) { auto exact_val = exact[k]; auto fmm_val = result[sample_map[k]]; // printf("[%03d] exact: %lg, FMM: %lg\n", k, exact[k], result[k]); if ((exact_val - fmm_val) / exact_val > 1e-13) ++wrong_results; } printf("Wrong counts: %d\n", wrong_results); #endif } } <|endoftext|>
<commit_before>/** * Self-Organizing Maps on a cluster * Copyright (C) 2013 Peter Wittek * * 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 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 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 <cmath> #include <cstdlib> #ifdef CLI #include <iostream> #include <iomanip> #include <sstream> #else #include <stdexcept> #endif // CLI #ifdef HAVE_R #include <R.h> #endif // HAVE_R #include "somoclu.h" using namespace std; void my_abort(string err) { #ifdef CLI #ifdef HAVE_MPI int rank = 0; MPI_Comm_rank(MPI_COMM_WORLD, &rank); if (rank == 0) { cerr << "Error: " << err << endl; } MPI_Abort(MPI_COMM_WORLD, 1); #else cerr << "Error: " << err << endl; exit(1); #endif // HAVE_MPI #else throw std::runtime_error(err); #endif // CLI } void train(float *data, int data_length, unsigned int nEpoch, unsigned int nSomX, unsigned int nSomY, unsigned int nDimensions, unsigned int nVectors, unsigned int radius0, unsigned int radiusN, string radiusCooling, float scale0, float scaleN, string scaleCooling, unsigned int kernelType, string mapType, string gridType, bool compact_support, bool gaussian, float *codebook, int codebook_size, int *globalBmus, int globalBmus_size, float *uMatrix, int uMatrix_size) { #ifdef HAVE_R #ifndef CUDA if(kernelType == DENSE_GPU){ Rprintf("Error: CUDA kernel not compiled \n"); return; } #endif // CUDA #endif // HAVE_R train(0, data, NULL, codebook, globalBmus, uMatrix, nSomX, nSomY, nDimensions, nVectors, nVectors, nEpoch, radius0, radiusN, radiusCooling, scale0, scaleN, scaleCooling, kernelType, mapType, gridType, compact_support, gaussian #ifdef CLI , "", 0); #else ); #endif calculateUMatrix(uMatrix, codebook, nSomX, nSomY, nDimensions, mapType, gridType); } void julia_train(float *data, int data_length, unsigned int nEpoch, unsigned int nSomX, unsigned int nSomY, unsigned int nDimensions, unsigned int nVectors, unsigned int radius0, unsigned int radiusN, unsigned int _radiusCooling, float scale0, float scaleN, unsigned int _scaleCooling, unsigned int kernelType, unsigned int _mapType, unsigned int _gridType, bool compact_support, bool gaussian, float *codebook, int codebook_size, int *globalBmus, int globalBmus_size, float *uMatrix, int uMatrix_size) { string radiusCooling; string scaleCooling; string mapType; string gridType; if (_radiusCooling == 0) { radiusCooling = "linear"; } else { radiusCooling = "exponential"; } if (_scaleCooling == 0) { scaleCooling = "linear"; } else { scaleCooling = "exponential"; } if (_mapType == 0) { mapType = "planar"; } else { mapType = "toroid"; } if (_gridType == 0) { gridType = "square"; } else { gridType = "hexagonal"; } train(0, data, NULL, codebook, globalBmus, uMatrix, nSomX, nSomY, nDimensions, nVectors, nVectors, nEpoch, radius0, radiusN, radiusCooling, scale0, scaleN, scaleCooling, kernelType, mapType, gridType, compact_support, gaussian #ifdef CLI , "", 0); #else ); #endif calculateUMatrix(uMatrix, codebook, nSomX, nSomY, nDimensions, mapType, gridType); } void train(int itask, float *data, svm_node **sparseData, float *codebook, int *globalBmus, float *uMatrix, unsigned int nSomX, unsigned int nSomY, unsigned int nDimensions, unsigned int nVectors, unsigned int nVectorsPerRank, unsigned int nEpoch, unsigned int radius0, unsigned int radiusN, string radiusCooling, float scale0, float scaleN, string scaleCooling, unsigned int kernelType, string mapType, string gridType, bool compact_support, bool gaussian #ifdef CLI , string outPrefix, unsigned int snapshots) #else ) #endif { int nProcs = 1; #ifdef HAVE_MPI MPI_Comm_size(MPI_COMM_WORLD, &nProcs); #endif #ifdef CUDA if (kernelType == DENSE_GPU) { setDevice(itask, nProcs); initializeGpu(data, nVectorsPerRank, nDimensions, nSomX, nSomY); } #endif // (Re-)Initialize codebook with random values only if requested through // the passed codebook -- meaning that the user did not have an initial // codebook if (codebook[0] == 1000 && codebook[1] == 2000) { initializeCodebook(0, codebook, nSomX, nSomY, nDimensions); } /// /// Parameters for SOM /// if (radius0 == 0) { unsigned int minDim = min(nSomX, nSomY); radius0 = minDim / 2.0f; /// init radius for updating neighbors } if (radiusN == 0) { radiusN = 1; } if (scale0 == 0) { scale0 = 0.1; } /// /// Training /// unsigned int currentEpoch = 0; /// 0...nEpoch-1 while ( currentEpoch < nEpoch ) { #ifdef HAVE_MPI double epoch_time = MPI_Wtime(); #endif trainOneEpoch(itask, data, sparseData, codebook, globalBmus, nEpoch, currentEpoch, nSomX, nSomY, nDimensions, nVectors, nVectorsPerRank, radius0, radiusN, radiusCooling, scale0, scaleN, scaleCooling, kernelType, mapType, gridType, compact_support, gaussian); #ifdef CLI if (snapshots > 0 && itask == 0) { calculateUMatrix(uMatrix, codebook, nSomX, nSomY, nDimensions, mapType, gridType); stringstream sstm; sstm << outPrefix << "." << currentEpoch + 1; saveUMatrix(sstm.str() + string(".umx"), uMatrix, nSomX, nSomY); if (snapshots == 2) { saveBmus(sstm.str() + string(".bm"), globalBmus, nSomX, nSomY, nVectors); saveCodebook(sstm.str() + string(".wts"), codebook, nSomX, nSomY, nDimensions); } } #endif ++currentEpoch; #ifdef CLI #ifdef HAVE_MPI if (itask == 0) { epoch_time = MPI_Wtime() - epoch_time; cerr << "Epoch Time: " << epoch_time << endl; if ( (currentEpoch != nEpoch) && (currentEpoch % (nEpoch / 100 + 1) != 0) ) {} else { float ratio = currentEpoch / (float)nEpoch; int c = ratio * 50 + 1; cout << std::setw(7) << (int)(ratio * 100) << "% ["; for (int x = 0; x < c; x++) cout << "="; for (int x = c; x < 50; x++) cout << " "; cout << "]\n" << flush; } } #endif #endif } trainOneEpoch(itask, data, sparseData, codebook, globalBmus, nEpoch, currentEpoch, nSomX, nSomY, nDimensions, nVectors, nVectorsPerRank, radius0, radiusN, radiusCooling, scale0, scaleN, scaleCooling, kernelType, mapType, gridType, compact_support, gaussian, true); #ifdef CUDA if (kernelType == DENSE_GPU) { freeGpu(); } #endif } float linearCooling(float start, float end, float nEpoch, float epoch) { float diff = (start - end) / nEpoch; return start - (epoch * diff); } float exponentialCooling(float start, float end, float nEpoch, float epoch) { float diff = 0; if (end == 0.0) { diff = -log(0.1) / nEpoch; } else { diff = -log(end / start) / nEpoch; } return start * exp(-epoch * diff); } /** Initialize SOM codebook with random values * @param seed - random seed * @param codebook - the codebook to fill in * @param nSomX - dimensions of SOM map in the currentEpoch direction * @param nSomY - dimensions of SOM map in the y direction * @param nDimensions - dimensions of a data instance */ void initializeCodebook(unsigned int seed, float *codebook, unsigned int nSomX, unsigned int nSomY, unsigned int nDimensions) { /// /// Fill initial random weights /// #ifdef HAVE_R GetRNGstate(); #else srand(seed); #endif #pragma omp parallel for #ifdef _WIN32 for (int som_y = 0; som_y < nSomY; som_y++) { #else for (unsigned int som_y = 0; som_y < nSomY; som_y++) { #endif for (unsigned int som_x = 0; som_x < nSomX; som_x++) { for (unsigned int d = 0; d < nDimensions; d++) { #ifdef HAVE_R int w = 0xFFF & (int) (RAND_MAX * unif_rand()); #else int w = 0xFFF & rand(); #endif w -= 0x800; codebook[som_y * nSomX * nDimensions + som_x * nDimensions + d] = (float)w / 4096.0f; } } } #ifdef HAVE_R PutRNGstate(); #endif } void trainOneEpoch(int itask, float *data, svm_node **sparseData, float *codebook, int *globalBmus, unsigned int nEpoch, unsigned int currentEpoch, unsigned int nSomX, unsigned int nSomY, unsigned int nDimensions, unsigned int nVectors, unsigned int nVectorsPerRank, unsigned int radius0, unsigned int radiusN, string radiusCooling, float scale0, float scaleN, string scaleCooling, unsigned int kernelType, string mapType, string gridType, bool compact_support, bool gaussian, bool only_bmus) { float N = (float)nEpoch; float *numerator; float *denominator; float scale = scale0; float radius = radius0; if (itask == 0 && !only_bmus) { #ifdef HAVE_MPI numerator = new float[nSomY * nSomX * nDimensions]; denominator = new float[nSomY * nSomX]; for (unsigned int som_y = 0; som_y < nSomY; som_y++) { for (unsigned int som_x = 0; som_x < nSomX; som_x++) { denominator[som_y * nSomX + som_x] = 0.0; for (unsigned int d = 0; d < nDimensions; d++) { numerator[som_y * nSomX * nDimensions + som_x * nDimensions + d] = 0.0; } } } #endif if (radiusCooling == "linear") { radius = linearCooling(float(radius0), radiusN, N, currentEpoch); } else { radius = exponentialCooling(radius0, radiusN, N, currentEpoch); } if (scaleCooling == "linear") { scale = linearCooling(scale0, scaleN, N, currentEpoch); } else { scale = exponentialCooling(scale0, scaleN, N, currentEpoch); } // cout << "Epoch: " << currentEpoch << " Radius: " << radius << endl; } #ifdef HAVE_MPI if (!only_bmus) { MPI_Bcast(&radius, 1, MPI_FLOAT, 0, MPI_COMM_WORLD); MPI_Bcast(&scale, 1, MPI_FLOAT, 0, MPI_COMM_WORLD); MPI_Bcast(codebook, nSomY * nSomX * nDimensions, MPI_FLOAT, 0, MPI_COMM_WORLD); } #endif /// 1. Each task fills localNumerator and localDenominator /// 2. MPI_reduce sums up each tasks localNumerator and localDenominator to the root's /// numerator and denominator. switch (kernelType) { default: case DENSE_CPU: trainOneEpochDenseCPU(itask, data, numerator, denominator, codebook, nSomX, nSomY, nDimensions, nVectors, nVectorsPerRank, radius, scale, mapType, gridType, compact_support, gaussian, globalBmus, only_bmus); break; case DENSE_GPU: #ifdef CUDA trainOneEpochDenseGPU(itask, data, numerator, denominator, codebook, nSomX, nSomY, nDimensions, nVectors, nVectorsPerRank, radius, scale, mapType, gridType, compact_support, gaussian, globalBmus, only_bmus); #else my_abort("Compiled without CUDA!"); #endif break; case SPARSE_CPU: trainOneEpochSparseCPU(itask, sparseData, numerator, denominator, codebook, nSomX, nSomY, nDimensions, nVectors, nVectorsPerRank, radius, scale, mapType, gridType, compact_support, gaussian, globalBmus, only_bmus); break; } /// 3. Update codebook using numerator and denominator #ifdef HAVE_MPI MPI_Barrier(MPI_COMM_WORLD); if (itask == 0 && !only_bmus) { #pragma omp parallel for #ifdef _WIN32 for (int som_y = 0; som_y < nSomY; som_y++) { #else for (unsigned int som_y = 0; som_y < nSomY; som_y++) { #endif for (unsigned int som_x = 0; som_x < nSomX; som_x++) { float denom = denominator[som_y * nSomX + som_x]; for (unsigned int d = 0; d < nDimensions; d++) { float newWeight = numerator[som_y * nSomX * nDimensions + som_x * nDimensions + d] / denom; if (newWeight > 0.0) { codebook[som_y * nSomX * nDimensions + som_x * nDimensions + d] = newWeight; } } } } delete [] numerator; delete [] denominator; } #endif // HAVE_MPI } <commit_msg>Linear scaling was correct after all<commit_after>/** * Self-Organizing Maps on a cluster * Copyright (C) 2013 Peter Wittek * * 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 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 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 <cmath> #include <cstdlib> #ifdef CLI #include <iostream> #include <iomanip> #include <sstream> #else #include <stdexcept> #endif // CLI #ifdef HAVE_R #include <R.h> #endif // HAVE_R #include "somoclu.h" using namespace std; void my_abort(string err) { #ifdef CLI #ifdef HAVE_MPI int rank = 0; MPI_Comm_rank(MPI_COMM_WORLD, &rank); if (rank == 0) { cerr << "Error: " << err << endl; } MPI_Abort(MPI_COMM_WORLD, 1); #else cerr << "Error: " << err << endl; exit(1); #endif // HAVE_MPI #else throw std::runtime_error(err); #endif // CLI } void train(float *data, int data_length, unsigned int nEpoch, unsigned int nSomX, unsigned int nSomY, unsigned int nDimensions, unsigned int nVectors, unsigned int radius0, unsigned int radiusN, string radiusCooling, float scale0, float scaleN, string scaleCooling, unsigned int kernelType, string mapType, string gridType, bool compact_support, bool gaussian, float *codebook, int codebook_size, int *globalBmus, int globalBmus_size, float *uMatrix, int uMatrix_size) { #ifdef HAVE_R #ifndef CUDA if(kernelType == DENSE_GPU){ Rprintf("Error: CUDA kernel not compiled \n"); return; } #endif // CUDA #endif // HAVE_R train(0, data, NULL, codebook, globalBmus, uMatrix, nSomX, nSomY, nDimensions, nVectors, nVectors, nEpoch, radius0, radiusN, radiusCooling, scale0, scaleN, scaleCooling, kernelType, mapType, gridType, compact_support, gaussian #ifdef CLI , "", 0); #else ); #endif calculateUMatrix(uMatrix, codebook, nSomX, nSomY, nDimensions, mapType, gridType); } void julia_train(float *data, int data_length, unsigned int nEpoch, unsigned int nSomX, unsigned int nSomY, unsigned int nDimensions, unsigned int nVectors, unsigned int radius0, unsigned int radiusN, unsigned int _radiusCooling, float scale0, float scaleN, unsigned int _scaleCooling, unsigned int kernelType, unsigned int _mapType, unsigned int _gridType, bool compact_support, bool gaussian, float *codebook, int codebook_size, int *globalBmus, int globalBmus_size, float *uMatrix, int uMatrix_size) { string radiusCooling; string scaleCooling; string mapType; string gridType; if (_radiusCooling == 0) { radiusCooling = "linear"; } else { radiusCooling = "exponential"; } if (_scaleCooling == 0) { scaleCooling = "linear"; } else { scaleCooling = "exponential"; } if (_mapType == 0) { mapType = "planar"; } else { mapType = "toroid"; } if (_gridType == 0) { gridType = "square"; } else { gridType = "hexagonal"; } train(0, data, NULL, codebook, globalBmus, uMatrix, nSomX, nSomY, nDimensions, nVectors, nVectors, nEpoch, radius0, radiusN, radiusCooling, scale0, scaleN, scaleCooling, kernelType, mapType, gridType, compact_support, gaussian #ifdef CLI , "", 0); #else ); #endif calculateUMatrix(uMatrix, codebook, nSomX, nSomY, nDimensions, mapType, gridType); } void train(int itask, float *data, svm_node **sparseData, float *codebook, int *globalBmus, float *uMatrix, unsigned int nSomX, unsigned int nSomY, unsigned int nDimensions, unsigned int nVectors, unsigned int nVectorsPerRank, unsigned int nEpoch, unsigned int radius0, unsigned int radiusN, string radiusCooling, float scale0, float scaleN, string scaleCooling, unsigned int kernelType, string mapType, string gridType, bool compact_support, bool gaussian #ifdef CLI , string outPrefix, unsigned int snapshots) #else ) #endif { int nProcs = 1; #ifdef HAVE_MPI MPI_Comm_size(MPI_COMM_WORLD, &nProcs); #endif #ifdef CUDA if (kernelType == DENSE_GPU) { setDevice(itask, nProcs); initializeGpu(data, nVectorsPerRank, nDimensions, nSomX, nSomY); } #endif // (Re-)Initialize codebook with random values only if requested through // the passed codebook -- meaning that the user did not have an initial // codebook if (codebook[0] == 1000 && codebook[1] == 2000) { initializeCodebook(0, codebook, nSomX, nSomY, nDimensions); } /// /// Parameters for SOM /// if (radius0 == 0) { unsigned int minDim = min(nSomX, nSomY); radius0 = minDim / 2.0f; /// init radius for updating neighbors } if (radiusN == 0) { radiusN = 1; } if (scale0 == 0) { scale0 = 0.1; } /// /// Training /// unsigned int currentEpoch = 0; /// 0...nEpoch-1 while ( currentEpoch < nEpoch ) { #ifdef HAVE_MPI double epoch_time = MPI_Wtime(); #endif trainOneEpoch(itask, data, sparseData, codebook, globalBmus, nEpoch, currentEpoch, nSomX, nSomY, nDimensions, nVectors, nVectorsPerRank, radius0, radiusN, radiusCooling, scale0, scaleN, scaleCooling, kernelType, mapType, gridType, compact_support, gaussian); #ifdef CLI if (snapshots > 0 && itask == 0) { calculateUMatrix(uMatrix, codebook, nSomX, nSomY, nDimensions, mapType, gridType); stringstream sstm; sstm << outPrefix << "." << currentEpoch + 1; saveUMatrix(sstm.str() + string(".umx"), uMatrix, nSomX, nSomY); if (snapshots == 2) { saveBmus(sstm.str() + string(".bm"), globalBmus, nSomX, nSomY, nVectors); saveCodebook(sstm.str() + string(".wts"), codebook, nSomX, nSomY, nDimensions); } } #endif ++currentEpoch; #ifdef CLI #ifdef HAVE_MPI if (itask == 0) { epoch_time = MPI_Wtime() - epoch_time; cerr << "Epoch Time: " << epoch_time << endl; if ( (currentEpoch != nEpoch) && (currentEpoch % (nEpoch / 100 + 1) != 0) ) {} else { float ratio = currentEpoch / (float)nEpoch; int c = ratio * 50 + 1; cout << std::setw(7) << (int)(ratio * 100) << "% ["; for (int x = 0; x < c; x++) cout << "="; for (int x = c; x < 50; x++) cout << " "; cout << "]\n" << flush; } } #endif #endif } trainOneEpoch(itask, data, sparseData, codebook, globalBmus, nEpoch, currentEpoch, nSomX, nSomY, nDimensions, nVectors, nVectorsPerRank, radius0, radiusN, radiusCooling, scale0, scaleN, scaleCooling, kernelType, mapType, gridType, compact_support, gaussian, true); #ifdef CUDA if (kernelType == DENSE_GPU) { freeGpu(); } #endif } float linearCooling(float start, float end, float nEpoch, float epoch) { float diff = (start - end) / (nEpoch-1); return start - (epoch * diff); } float exponentialCooling(float start, float end, float nEpoch, float epoch) { float diff = 0; if (end == 0.0) { diff = -log(0.1) / nEpoch; } else { diff = -log(end / start) / nEpoch; } return start * exp(-epoch * diff); } /** Initialize SOM codebook with random values * @param seed - random seed * @param codebook - the codebook to fill in * @param nSomX - dimensions of SOM map in the currentEpoch direction * @param nSomY - dimensions of SOM map in the y direction * @param nDimensions - dimensions of a data instance */ void initializeCodebook(unsigned int seed, float *codebook, unsigned int nSomX, unsigned int nSomY, unsigned int nDimensions) { /// /// Fill initial random weights /// #ifdef HAVE_R GetRNGstate(); #else srand(seed); #endif #pragma omp parallel for #ifdef _WIN32 for (int som_y = 0; som_y < nSomY; som_y++) { #else for (unsigned int som_y = 0; som_y < nSomY; som_y++) { #endif for (unsigned int som_x = 0; som_x < nSomX; som_x++) { for (unsigned int d = 0; d < nDimensions; d++) { #ifdef HAVE_R int w = 0xFFF & (int) (RAND_MAX * unif_rand()); #else int w = 0xFFF & rand(); #endif w -= 0x800; codebook[som_y * nSomX * nDimensions + som_x * nDimensions + d] = (float)w / 4096.0f; } } } #ifdef HAVE_R PutRNGstate(); #endif } void trainOneEpoch(int itask, float *data, svm_node **sparseData, float *codebook, int *globalBmus, unsigned int nEpoch, unsigned int currentEpoch, unsigned int nSomX, unsigned int nSomY, unsigned int nDimensions, unsigned int nVectors, unsigned int nVectorsPerRank, unsigned int radius0, unsigned int radiusN, string radiusCooling, float scale0, float scaleN, string scaleCooling, unsigned int kernelType, string mapType, string gridType, bool compact_support, bool gaussian, bool only_bmus) { float N = (float)nEpoch; float *numerator; float *denominator; float scale = scale0; float radius = radius0; if (itask == 0 && !only_bmus) { #ifdef HAVE_MPI numerator = new float[nSomY * nSomX * nDimensions]; denominator = new float[nSomY * nSomX]; for (unsigned int som_y = 0; som_y < nSomY; som_y++) { for (unsigned int som_x = 0; som_x < nSomX; som_x++) { denominator[som_y * nSomX + som_x] = 0.0; for (unsigned int d = 0; d < nDimensions; d++) { numerator[som_y * nSomX * nDimensions + som_x * nDimensions + d] = 0.0; } } } #endif if (radiusCooling == "linear") { radius = linearCooling(float(radius0), radiusN, N, currentEpoch); } else { radius = exponentialCooling(radius0, radiusN, N, currentEpoch); } if (scaleCooling == "linear") { scale = linearCooling(scale0, scaleN, N, currentEpoch); } else { scale = exponentialCooling(scale0, scaleN, N, currentEpoch); } // cout << "Epoch: " << currentEpoch << " Radius: " << radius << endl; } #ifdef HAVE_MPI if (!only_bmus) { MPI_Bcast(&radius, 1, MPI_FLOAT, 0, MPI_COMM_WORLD); MPI_Bcast(&scale, 1, MPI_FLOAT, 0, MPI_COMM_WORLD); MPI_Bcast(codebook, nSomY * nSomX * nDimensions, MPI_FLOAT, 0, MPI_COMM_WORLD); } #endif /// 1. Each task fills localNumerator and localDenominator /// 2. MPI_reduce sums up each tasks localNumerator and localDenominator to the root's /// numerator and denominator. switch (kernelType) { default: case DENSE_CPU: trainOneEpochDenseCPU(itask, data, numerator, denominator, codebook, nSomX, nSomY, nDimensions, nVectors, nVectorsPerRank, radius, scale, mapType, gridType, compact_support, gaussian, globalBmus, only_bmus); break; case DENSE_GPU: #ifdef CUDA trainOneEpochDenseGPU(itask, data, numerator, denominator, codebook, nSomX, nSomY, nDimensions, nVectors, nVectorsPerRank, radius, scale, mapType, gridType, compact_support, gaussian, globalBmus, only_bmus); #else my_abort("Compiled without CUDA!"); #endif break; case SPARSE_CPU: trainOneEpochSparseCPU(itask, sparseData, numerator, denominator, codebook, nSomX, nSomY, nDimensions, nVectors, nVectorsPerRank, radius, scale, mapType, gridType, compact_support, gaussian, globalBmus, only_bmus); break; } /// 3. Update codebook using numerator and denominator #ifdef HAVE_MPI MPI_Barrier(MPI_COMM_WORLD); if (itask == 0 && !only_bmus) { #pragma omp parallel for #ifdef _WIN32 for (int som_y = 0; som_y < nSomY; som_y++) { #else for (unsigned int som_y = 0; som_y < nSomY; som_y++) { #endif for (unsigned int som_x = 0; som_x < nSomX; som_x++) { float denom = denominator[som_y * nSomX + som_x]; for (unsigned int d = 0; d < nDimensions; d++) { float newWeight = numerator[som_y * nSomX * nDimensions + som_x * nDimensions + d] / denom; if (newWeight > 0.0) { codebook[som_y * nSomX * nDimensions + som_x * nDimensions + d] = newWeight; } } } } delete [] numerator; delete [] denominator; } #endif // HAVE_MPI } <|endoftext|>
<commit_before>#include "valuedlg.h" #include "ui_valuedlg.h" #include "logtab.h" #include "themeutils.h" #include "tokenizer.h" #include <QDebug> #include <QDesktopServices> #include <QFile> #include <QFontDatabase> #include <QHttpMultiPart> #include <QNetworkAccessManager> #include <QNetworkReply> #include <QNetworkRequest> #include <QShortcut> #include <QString> #include <QTextDocument> #include <QTextStream> #include <QWebEngineView> QByteArray ValueDlg::sm_savedGeometry { QByteArray() }; qreal ValueDlg::sm_savedFontPointSize { 0 }; bool ValueDlg::sm_savedWrapText { true }; QJsonUtils::Notation ValueDlg::sm_notation { QJsonUtils::Notation::YAML }; ValueDlg::ValueDlg(QWidget *parent) : QDialog(parent), ui(new Ui::ValueDlg) { ui->setupUi(this); setWindowFlags(windowFlags() & ~Qt::WindowContextHelpButtonHint); restoreGeometry(sm_savedGeometry); // Set a monospaced font. QFont fixedFont = QFontDatabase::systemFont(QFontDatabase::FixedFont); fixedFont.setPointSizeF(sm_savedFontPointSize); ui->textEdit->setFont(fixedFont); auto prevKey = QKeySequence(Qt::CTRL + Qt::Key_Up); ui->prevButton->setShortcut(prevKey); ui->prevButton->setToolTip(QString("Go to previous event (%1)").arg(prevKey.toString(QKeySequence::NativeText))); auto nextKey = QKeySequence(Qt::CTRL + Qt::Key_Down); ui->nextButton->setShortcut(nextKey); ui->nextButton->setToolTip(QString("Go to next event (%1)").arg(nextKey.toString(QKeySequence::NativeText))); QShortcut *shortcutPlus = new QShortcut(QKeySequence(Qt::CTRL + Qt::Key_Plus), this); connect(shortcutPlus, &QShortcut::activated, this, &ValueDlg::on_zoomIn); QShortcut *shortcutEqual = new QShortcut(QKeySequence(Qt::CTRL + Qt::Key_Equal), this); connect(shortcutEqual, &QShortcut::activated, this, &ValueDlg::on_zoomIn); QShortcut *shortcutMinus = new QShortcut(QKeySequence(Qt::CTRL + Qt::Key_Minus), this); connect(shortcutMinus, &QShortcut::activated, this, &ValueDlg::on_zoomOut); m_id = QString(""); m_key = QString(""); m_queryPlan = QString(""); Options& options = Options::GetInstance(); m_visualizationServiceEnable = options.getVisualizationServiceEnable(); m_visualizationServiceURL = options.getVisualizationServiceURL(); ui->prevButton->setIcon(QIcon(ThemeUtils::GetThemedIcon(":/value-previous.png"))); ui->nextButton->setIcon(QIcon(ThemeUtils::GetThemedIcon(":/value-next.png"))); ui->wrapTextCheck->setChecked(sm_savedWrapText); SetWrapping(sm_savedWrapText); { const QSignalBlocker blocker(ui->notationComboBox); ui->notationComboBox->addItems(QJsonUtils::GetNotationNames()); ui->notationComboBox->setCurrentText(QJsonUtils::GetNameForNotation(sm_notation)); } QFile sqlsyntaxcss(":/sqlsyntax.css"); sqlsyntaxcss.open(QIODevice::ReadOnly); QTextStream textStream(&sqlsyntaxcss); QString styleSheet = textStream.readAll(); sqlsyntaxcss.close(); QTextDocument * textDoc = new QTextDocument(ui->textEdit); textDoc->setDefaultStyleSheet(styleSheet); textDoc->setDefaultFont(fixedFont); ui->textEdit->setDocument(textDoc); } ValueDlg::~ValueDlg() { delete ui; } void ValueDlg::on_zoomIn() { ui->textEdit->zoomIn(1); } void ValueDlg::on_zoomOut() { ui->textEdit->zoomOut(1); } static QString HighlightSyntax(QString in) { in = in.replace("; ", "\n"); Tokenizer sqlLexer; sqlLexer.SetSQL(); QList<Tokenizer::Token> tokens = sqlLexer.Tokenize(in); if (tokens.size() == 0) return in; QString out; QHash<Tokenizer::TokenType, QString> TokenTypeToCSSClass = { {Tokenizer::TokenType::Keyword, "k"}, {Tokenizer::TokenType::String, "s"}, {Tokenizer::TokenType::Tag, "t"}, {Tokenizer::TokenType::Whitespace, "w"}, {Tokenizer::TokenType::Identifier, "i"}, {Tokenizer::TokenType::Symbol, "sy"}, {Tokenizer::TokenType::OpenParan, "op"}, {Tokenizer::TokenType::CloseParan, "cp"}, {Tokenizer::TokenType::Operator, "o"}, {Tokenizer::TokenType::NoMatch, "n"}, {Tokenizer::TokenType::Integer, "in"}, {Tokenizer::TokenType::Float, "f"} }; // Build the html, grouping concurrent same token items in the same span. Tokenizer::TokenType prevType = tokens[0].type; out += "<span class=\"" + TokenTypeToCSSClass[prevType] + "\">"; for (Tokenizer::Token token : tokens) { QString word = in.mid(token.start, token.length); word = word.toHtmlEscaped(); // Use HTML safe spacing word.replace(" ", "&nbsp;"); word.replace("\t", "&nbsp;&nbsp;&nbsp;&nbsp;"); word.replace("\n", "<br>"); if(token.type != prevType) { out += "</span><span class=\"" + TokenTypeToCSSClass[token.type] + "\">"; prevType = token.type; } out += word; } out += "</span>"; return out; } void ValueDlg::SetContent(QString id, QString key, QJsonValue value) { m_id = id; m_key = key; m_value = value; setWindowTitle(QString("ID: %1 - Key: %2").arg(m_id, m_key)); UpdateValueBox(); // Recognize query plans m_queryPlan = ""; if (value.isObject()) { if (m_key.startsWith("logical-query") || m_key == "federate-query" || m_key == "remote-query-planning" || m_key == "begin-query" || m_key == "end-query") { // Assume that queries starting with < have query function trees or logical-query. // They normally start with "<?xml ...>", "<sqlproxy>" or "<query-function ...>" auto queryText = value.toObject()["query"].toString(); if (queryText.startsWith("<")) { m_queryPlan = queryText; } } else if (m_key.startsWith("query-plan") || m_key == "optimizer-step") { auto plan = value.toObject()["plan"]; if (plan.isObject()) { QJsonDocument doc(plan.toObject()); m_queryPlan = doc.toJson(QJsonDocument::Compact); } } } // Setup UI for query plan if (!m_queryPlan.isEmpty()) { ui->visualizeButton->setEnabled(true); ui->visualizeLabel->setText(""); } else { ui->visualizeButton->setEnabled(false); ui->visualizeLabel->setText("Nothing to visualize"); } ui->notationComboBox->setEnabled(QJsonUtils::IsStructured(value)); ui->notationComboBox->repaint(); } void ValueDlg::UpdateValueBox() { QString value = QJsonUtils::Format(m_value, sm_notation); int syntaxHighlightLimit = Options::GetInstance().getSyntaxHighlightLimit(); bool syntaxHighlight = (m_key != "msg" && !m_key.isEmpty() && QJsonUtils::IsStructured(m_value) && syntaxHighlightLimit && value.size() <= syntaxHighlightLimit); if (syntaxHighlight) { QString htmlText(QString("<body>") + HighlightSyntax(value) + QString("</body>")); ui->textEdit->setHtml(htmlText); } else { // Toggling between "setHtml" and "setPlainText" still winds up formatting // the "plain text" based on the previous HTML contents. The simplest way // to keep it "plain" appears to be to just keep it HTML and omit the styling. // (alternatively, we could explicitly use setTextColor to make it black.. // but that might not play well with themes?) QString htmlText(QString("<body><span>%1</span></body>").arg(value)); ui->textEdit->setHtml(htmlText); } ui->textEdit->moveCursor(QTextCursor::Start); ui->textEdit->ensureCursorVisible(); ui->textEdit->repaint(); } void ValueDlg::on_nextButton_clicked() { emit next(); } void ValueDlg::on_prevButton_clicked() { emit prev(); } void ValueDlg::on_wrapTextCheck_clicked() { SetWrapping(ui->wrapTextCheck->isChecked()); } void ValueDlg::on_notationComboBox_currentIndexChanged(const QString& newValue) { sm_notation = QJsonUtils::GetNotationFromName(newValue); UpdateValueBox(); } void ValueDlg::SetWrapping(const bool wrapText) { sm_savedWrapText = wrapText; if (sm_savedWrapText) { ui->textEdit->setLineWrapMode(QTextEdit::WidgetWidth); } else { ui->textEdit->setLineWrapMode(QTextEdit::NoWrap); } } QUrl ValueDlg::GetUploadURL() { return QUrl(m_visualizationServiceURL); } QUrl ValueDlg::GetVisualizeURL(QNetworkReply * const reply) { // The URL to visualize the query should be in the response. // // Sample response: //http://localhost:3000/d3/query-graphs.html?upload=y&file=31480681.xml auto response = QString(reply->readAll()); qDebug() << "Response from visualization service:\n" << response; return QUrl(response); } void ValueDlg::UploadQuery() { QHttpMultiPart *multipart = new QHttpMultiPart(QHttpMultiPart::FormDataType, this); QHttpPart filePart; filePart.setHeader(QNetworkRequest::ContentDispositionHeader, QVariant("form-data; name=\"queryfile\"; filename=\"yeah.xml\"")); filePart.setHeader(QNetworkRequest::ContentTypeHeader, QVariant("text/xml")); filePart.setBody(m_queryPlan.toUtf8()); multipart->append(filePart); QNetworkRequest request(GetUploadURL()); QNetworkAccessManager *networkManager = new QNetworkAccessManager(this); QNetworkReply *reply = networkManager->post(request, multipart); // Set the parent of the multipart to the reply, so that we delete the multiPart with the reply multipart->setParent(reply); connect(networkManager, SIGNAL(finished(QNetworkReply*)), this, SLOT(on_uploadFinished(QNetworkReply*))); } void ValueDlg::on_visualizeButton_clicked() { if (m_visualizationServiceEnable) { UploadQuery(); } else { VisualizeQuery(); } } void ValueDlg::on_uploadFinished(QNetworkReply* reply) { if (reply->error() == QNetworkReply::NetworkError::NoError) { ui->visualizeLabel->setText("Visualization uploaded, check your browser..."); QDesktopServices::openUrl(GetVisualizeURL(reply)); } else { ui->visualizeLabel->setText(QString("Failed to upload to URL '%1'").arg(reply->url().toString())); qDebug() << "Failed to upload query"; } ui->visualizeButton->setEnabled(false); } void ValueDlg::VisualizeQuery() { // Conditionally enable QtWebEngine debugging via Chromium-based browser at http://localhost:9000 #ifdef QT_DEBUG qputenv("QTWEBENGINE_REMOTE_DEBUGGING", "9000"); #endif m_view = new QWebEngineView(this); m_view->setAttribute(Qt::WA_DeleteOnClose); // Set Qt::Dialog rather than Qt::Window to disable zoom and avoid a Qt bug with unresponsive zoomed views on OSX m_view->setWindowFlags(Qt::Dialog | Qt::WindowMaximizeButtonHint | Qt::WindowCloseButtonHint); m_view->setWindowTitle(QString("Query Visualization - ID: %1 - Key: %2").arg(m_id, m_key)); QDesktopWidget widget; int screenId = widget.screenNumber(this); QRect screenRect = widget.availableGeometry(screenId); int width = screenRect.width() - 400; int height = screenRect.height() - 200; int x = screenRect.left() + 200; int y = screenRect.top() + 80; m_view->resize(width, height); m_view->move(x, y); // Add keyboard shortcut for reloading the view QShortcut *shortcut = new QShortcut(QKeySequence("Ctrl+r"), m_view); QObject::connect(shortcut, &QShortcut::activated, m_view, &QWebEngineView::reload); // Reload the view one time to work around a Qt bug causing left justified alignment m_reload = true; connect(m_view, &QWebEngineView::loadFinished, this, &ValueDlg::on_loadFinished); m_view->load(QUrl("qrc:///query-graphs/query-graphs.tlv.html?inline=" + QUrl::toPercentEncoding(m_queryPlan))); } void ValueDlg::on_loadFinished(bool loaded) { if (!loaded) { ui->visualizeLabel->setText(QString("Failed to load query visualization")); qDebug() << "Failed to load query visualization"; } if (m_reload) { m_reload = false; m_view->reload(); } m_view->show(); } void ValueDlg::reject() { sm_savedGeometry = saveGeometry(); sm_savedFontPointSize = ui->textEdit->document()->defaultFont().pointSize(); QDialog::reject(); } // Persist the dialog state into QSettings. // // WriteSettings and ReadSettings should only be called once during app start and close, // so the dialog state between multiple instances will not interfere each other. // void ValueDlg::WriteSettings(QSettings& settings) { settings.beginGroup("ValueDialog"); settings.setValue("geometry", sm_savedGeometry); settings.setValue("fontPointSize", sm_savedFontPointSize); settings.setValue("wrapText", sm_savedWrapText); settings.setValue("notation", QJsonUtils::GetNameForNotation(sm_notation)); settings.endGroup(); } void ValueDlg::ReadSettings(QSettings& settings) { settings.beginGroup("ValueDialog"); sm_savedGeometry = settings.value("geometry").toByteArray(); sm_savedFontPointSize = settings.value("fontPointSize").toReal(); sm_savedWrapText = settings.value("wrapText").toBool(); sm_notation = QJsonUtils::GetNotationFromName(settings.value("notation").toString()); settings.endGroup(); } <commit_msg>Escape HTML in raw strings before using setHtml to put them in the value dialog text box. (#97)<commit_after>#include "valuedlg.h" #include "ui_valuedlg.h" #include "logtab.h" #include "themeutils.h" #include "tokenizer.h" #include <QDebug> #include <QDesktopServices> #include <QFile> #include <QFontDatabase> #include <QHttpMultiPart> #include <QNetworkAccessManager> #include <QNetworkReply> #include <QNetworkRequest> #include <QShortcut> #include <QString> #include <QTextDocument> #include <QTextStream> #include <QWebEngineView> QByteArray ValueDlg::sm_savedGeometry { QByteArray() }; qreal ValueDlg::sm_savedFontPointSize { 0 }; bool ValueDlg::sm_savedWrapText { true }; QJsonUtils::Notation ValueDlg::sm_notation { QJsonUtils::Notation::YAML }; ValueDlg::ValueDlg(QWidget *parent) : QDialog(parent), ui(new Ui::ValueDlg) { ui->setupUi(this); setWindowFlags(windowFlags() & ~Qt::WindowContextHelpButtonHint); restoreGeometry(sm_savedGeometry); // Set a monospaced font. QFont fixedFont = QFontDatabase::systemFont(QFontDatabase::FixedFont); fixedFont.setPointSizeF(sm_savedFontPointSize); ui->textEdit->setFont(fixedFont); auto prevKey = QKeySequence(Qt::CTRL + Qt::Key_Up); ui->prevButton->setShortcut(prevKey); ui->prevButton->setToolTip(QString("Go to previous event (%1)").arg(prevKey.toString(QKeySequence::NativeText))); auto nextKey = QKeySequence(Qt::CTRL + Qt::Key_Down); ui->nextButton->setShortcut(nextKey); ui->nextButton->setToolTip(QString("Go to next event (%1)").arg(nextKey.toString(QKeySequence::NativeText))); QShortcut *shortcutPlus = new QShortcut(QKeySequence(Qt::CTRL + Qt::Key_Plus), this); connect(shortcutPlus, &QShortcut::activated, this, &ValueDlg::on_zoomIn); QShortcut *shortcutEqual = new QShortcut(QKeySequence(Qt::CTRL + Qt::Key_Equal), this); connect(shortcutEqual, &QShortcut::activated, this, &ValueDlg::on_zoomIn); QShortcut *shortcutMinus = new QShortcut(QKeySequence(Qt::CTRL + Qt::Key_Minus), this); connect(shortcutMinus, &QShortcut::activated, this, &ValueDlg::on_zoomOut); m_id = QString(""); m_key = QString(""); m_queryPlan = QString(""); Options& options = Options::GetInstance(); m_visualizationServiceEnable = options.getVisualizationServiceEnable(); m_visualizationServiceURL = options.getVisualizationServiceURL(); ui->prevButton->setIcon(QIcon(ThemeUtils::GetThemedIcon(":/value-previous.png"))); ui->nextButton->setIcon(QIcon(ThemeUtils::GetThemedIcon(":/value-next.png"))); ui->wrapTextCheck->setChecked(sm_savedWrapText); SetWrapping(sm_savedWrapText); { const QSignalBlocker blocker(ui->notationComboBox); ui->notationComboBox->addItems(QJsonUtils::GetNotationNames()); ui->notationComboBox->setCurrentText(QJsonUtils::GetNameForNotation(sm_notation)); } QFile sqlsyntaxcss(":/sqlsyntax.css"); sqlsyntaxcss.open(QIODevice::ReadOnly); QTextStream textStream(&sqlsyntaxcss); QString styleSheet = textStream.readAll(); sqlsyntaxcss.close(); QTextDocument * textDoc = new QTextDocument(ui->textEdit); textDoc->setDefaultStyleSheet(styleSheet); textDoc->setDefaultFont(fixedFont); ui->textEdit->setDocument(textDoc); } ValueDlg::~ValueDlg() { delete ui; } void ValueDlg::on_zoomIn() { ui->textEdit->zoomIn(1); } void ValueDlg::on_zoomOut() { ui->textEdit->zoomOut(1); } static QString MakeHTMLSafe(QString input) { auto output = input.toHtmlEscaped(); // Use HTML safe spacing output.replace(" ", "&nbsp;"); output.replace("\t", "&nbsp;&nbsp;&nbsp;&nbsp;"); output.replace("\n", "<br>"); return output; } static QString HighlightSyntax(QString in) { in = in.replace("; ", "\n"); Tokenizer sqlLexer; sqlLexer.SetSQL(); QList<Tokenizer::Token> tokens = sqlLexer.Tokenize(in); if (tokens.size() == 0) return in; QString out; QHash<Tokenizer::TokenType, QString> TokenTypeToCSSClass = { {Tokenizer::TokenType::Keyword, "k"}, {Tokenizer::TokenType::String, "s"}, {Tokenizer::TokenType::Tag, "t"}, {Tokenizer::TokenType::Whitespace, "w"}, {Tokenizer::TokenType::Identifier, "i"}, {Tokenizer::TokenType::Symbol, "sy"}, {Tokenizer::TokenType::OpenParan, "op"}, {Tokenizer::TokenType::CloseParan, "cp"}, {Tokenizer::TokenType::Operator, "o"}, {Tokenizer::TokenType::NoMatch, "n"}, {Tokenizer::TokenType::Integer, "in"}, {Tokenizer::TokenType::Float, "f"} }; // Build the html, grouping concurrent same token items in the same span. Tokenizer::TokenType prevType = tokens[0].type; out += "<span class=\"" + TokenTypeToCSSClass[prevType] + "\">"; for (Tokenizer::Token token : tokens) { QString word = in.mid(token.start, token.length); word = MakeHTMLSafe(word); if(token.type != prevType) { out += "</span><span class=\"" + TokenTypeToCSSClass[token.type] + "\">"; prevType = token.type; } out += word; } out += "</span>"; return out; } void ValueDlg::SetContent(QString id, QString key, QJsonValue value) { m_id = id; m_key = key; m_value = value; setWindowTitle(QString("ID: %1 - Key: %2").arg(m_id, m_key)); UpdateValueBox(); // Recognize query plans m_queryPlan = ""; if (value.isObject()) { if (m_key.startsWith("logical-query") || m_key == "federate-query" || m_key == "remote-query-planning" || m_key == "begin-query" || m_key == "end-query") { // Assume that queries starting with < have query function trees or logical-query. // They normally start with "<?xml ...>", "<sqlproxy>" or "<query-function ...>" auto queryText = value.toObject()["query"].toString(); if (queryText.startsWith("<")) { m_queryPlan = queryText; } } else if (m_key.startsWith("query-plan") || m_key == "optimizer-step") { auto plan = value.toObject()["plan"]; if (plan.isObject()) { QJsonDocument doc(plan.toObject()); m_queryPlan = doc.toJson(QJsonDocument::Compact); } } } // Setup UI for query plan if (!m_queryPlan.isEmpty()) { ui->visualizeButton->setEnabled(true); ui->visualizeLabel->setText(""); } else { ui->visualizeButton->setEnabled(false); ui->visualizeLabel->setText("Nothing to visualize"); } ui->notationComboBox->setEnabled(QJsonUtils::IsStructured(value)); ui->notationComboBox->repaint(); } void ValueDlg::UpdateValueBox() { QString value = QJsonUtils::Format(m_value, sm_notation); int syntaxHighlightLimit = Options::GetInstance().getSyntaxHighlightLimit(); bool syntaxHighlight = (m_key != "msg" && !m_key.isEmpty() && QJsonUtils::IsStructured(m_value) && syntaxHighlightLimit && value.size() <= syntaxHighlightLimit); if (syntaxHighlight) { QString htmlText(QString("<body>") + HighlightSyntax(value) + QString("</body>")); ui->textEdit->setHtml(htmlText); } else { // Toggling between "setHtml" and "setPlainText" still winds up formatting // the "plain text" based on the previous HTML contents. The simplest way // to keep it "plain" appears to be to just keep it HTML and omit the styling. // (alternatively, we could explicitly use setTextColor to make it black.. // but that might not play well with themes?) QString htmlText(QString("<body><span>%1</span></body>").arg(MakeHTMLSafe(value))); ui->textEdit->setHtml(htmlText); } ui->textEdit->moveCursor(QTextCursor::Start); ui->textEdit->ensureCursorVisible(); ui->textEdit->repaint(); } void ValueDlg::on_nextButton_clicked() { emit next(); } void ValueDlg::on_prevButton_clicked() { emit prev(); } void ValueDlg::on_wrapTextCheck_clicked() { SetWrapping(ui->wrapTextCheck->isChecked()); } void ValueDlg::on_notationComboBox_currentIndexChanged(const QString& newValue) { sm_notation = QJsonUtils::GetNotationFromName(newValue); UpdateValueBox(); } void ValueDlg::SetWrapping(const bool wrapText) { sm_savedWrapText = wrapText; if (sm_savedWrapText) { ui->textEdit->setLineWrapMode(QTextEdit::WidgetWidth); } else { ui->textEdit->setLineWrapMode(QTextEdit::NoWrap); } } QUrl ValueDlg::GetUploadURL() { return QUrl(m_visualizationServiceURL); } QUrl ValueDlg::GetVisualizeURL(QNetworkReply * const reply) { // The URL to visualize the query should be in the response. // // Sample response: //http://localhost:3000/d3/query-graphs.html?upload=y&file=31480681.xml auto response = QString(reply->readAll()); qDebug() << "Response from visualization service:\n" << response; return QUrl(response); } void ValueDlg::UploadQuery() { QHttpMultiPart *multipart = new QHttpMultiPart(QHttpMultiPart::FormDataType, this); QHttpPart filePart; filePart.setHeader(QNetworkRequest::ContentDispositionHeader, QVariant("form-data; name=\"queryfile\"; filename=\"yeah.xml\"")); filePart.setHeader(QNetworkRequest::ContentTypeHeader, QVariant("text/xml")); filePart.setBody(m_queryPlan.toUtf8()); multipart->append(filePart); QNetworkRequest request(GetUploadURL()); QNetworkAccessManager *networkManager = new QNetworkAccessManager(this); QNetworkReply *reply = networkManager->post(request, multipart); // Set the parent of the multipart to the reply, so that we delete the multiPart with the reply multipart->setParent(reply); connect(networkManager, SIGNAL(finished(QNetworkReply*)), this, SLOT(on_uploadFinished(QNetworkReply*))); } void ValueDlg::on_visualizeButton_clicked() { if (m_visualizationServiceEnable) { UploadQuery(); } else { VisualizeQuery(); } } void ValueDlg::on_uploadFinished(QNetworkReply* reply) { if (reply->error() == QNetworkReply::NetworkError::NoError) { ui->visualizeLabel->setText("Visualization uploaded, check your browser..."); QDesktopServices::openUrl(GetVisualizeURL(reply)); } else { ui->visualizeLabel->setText(QString("Failed to upload to URL '%1'").arg(reply->url().toString())); qDebug() << "Failed to upload query"; } ui->visualizeButton->setEnabled(false); } void ValueDlg::VisualizeQuery() { // Conditionally enable QtWebEngine debugging via Chromium-based browser at http://localhost:9000 #ifdef QT_DEBUG qputenv("QTWEBENGINE_REMOTE_DEBUGGING", "9000"); #endif m_view = new QWebEngineView(this); m_view->setAttribute(Qt::WA_DeleteOnClose); // Set Qt::Dialog rather than Qt::Window to disable zoom and avoid a Qt bug with unresponsive zoomed views on OSX m_view->setWindowFlags(Qt::Dialog | Qt::WindowMaximizeButtonHint | Qt::WindowCloseButtonHint); m_view->setWindowTitle(QString("Query Visualization - ID: %1 - Key: %2").arg(m_id, m_key)); QDesktopWidget widget; int screenId = widget.screenNumber(this); QRect screenRect = widget.availableGeometry(screenId); int width = screenRect.width() - 400; int height = screenRect.height() - 200; int x = screenRect.left() + 200; int y = screenRect.top() + 80; m_view->resize(width, height); m_view->move(x, y); // Add keyboard shortcut for reloading the view QShortcut *shortcut = new QShortcut(QKeySequence("Ctrl+r"), m_view); QObject::connect(shortcut, &QShortcut::activated, m_view, &QWebEngineView::reload); // Reload the view one time to work around a Qt bug causing left justified alignment m_reload = true; connect(m_view, &QWebEngineView::loadFinished, this, &ValueDlg::on_loadFinished); m_view->load(QUrl("qrc:///query-graphs/query-graphs.tlv.html?inline=" + QUrl::toPercentEncoding(m_queryPlan))); } void ValueDlg::on_loadFinished(bool loaded) { if (!loaded) { ui->visualizeLabel->setText(QString("Failed to load query visualization")); qDebug() << "Failed to load query visualization"; } if (m_reload) { m_reload = false; m_view->reload(); } m_view->show(); } void ValueDlg::reject() { sm_savedGeometry = saveGeometry(); sm_savedFontPointSize = ui->textEdit->document()->defaultFont().pointSize(); QDialog::reject(); } // Persist the dialog state into QSettings. // // WriteSettings and ReadSettings should only be called once during app start and close, // so the dialog state between multiple instances will not interfere each other. // void ValueDlg::WriteSettings(QSettings& settings) { settings.beginGroup("ValueDialog"); settings.setValue("geometry", sm_savedGeometry); settings.setValue("fontPointSize", sm_savedFontPointSize); settings.setValue("wrapText", sm_savedWrapText); settings.setValue("notation", QJsonUtils::GetNameForNotation(sm_notation)); settings.endGroup(); } void ValueDlg::ReadSettings(QSettings& settings) { settings.beginGroup("ValueDialog"); sm_savedGeometry = settings.value("geometry").toByteArray(); sm_savedFontPointSize = settings.value("fontPointSize").toReal(); sm_savedWrapText = settings.value("wrapText").toBool(); sm_notation = QJsonUtils::GetNotationFromName(settings.value("notation").toString()); settings.endGroup(); } <|endoftext|>
<commit_before>/* * Copyright (c) 2003 The Regents of The University of Michigan * 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 the copyright holders 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. */ #ifndef __SYSTEM_HH__ #define __SYSTEM_HH__ #include <string> #include <vector> #include "base/loader/symtab.hh" #include "base/statistics.hh" #include "cpu/pc_event.hh" #include "sim/sim_object.hh" #include "sim/sw_context.hh" class MemoryController; class PhysicalMemory; class RemoteGDB; class GDBListener; class ExecContext; class System : public SimObject { // lisa's binning stuff protected: std::map<const std::string, Statistics::MainBin *> fnBins; std::map<const Addr, SWContext *> swCtxMap; public: Statistics::Scalar<Counter> fnCalls; Statistics::MainBin *Kernel; Statistics::MainBin * getBin(const std::string &name); virtual bool findCaller(std::string, std::string) const = 0; SWContext *findContext(Addr pcb); bool addContext(Addr pcb, SWContext *ctx) { return (swCtxMap.insert(make_pair(pcb, ctx))).second; } void remContext(Addr pcb) { swCtxMap.erase(pcb); return; } virtual void dumpState(ExecContext *xc) const = 0; virtual void serialize(std::ostream &os); virtual void unserialize(Checkpoint *cp, const std::string &section); // public: const uint64_t init_param; MemoryController *memCtrl; PhysicalMemory *physmem; bool bin; PCEventQueue pcEventQueue; std::vector<ExecContext *> execContexts; virtual int registerExecContext(ExecContext *xc); virtual void replaceExecContext(int xcIndex, ExecContext *xc); public: System(const std::string _name, const uint64_t _init_param, MemoryController *, PhysicalMemory *, const bool); ~System(); virtual Addr getKernelStart() const = 0; virtual Addr getKernelEnd() const = 0; virtual Addr getKernelEntry() const = 0; virtual bool breakpoint() = 0; public: //////////////////////////////////////////// // // STATIC GLOBAL SYSTEM LIST // //////////////////////////////////////////// static std::vector<System *> systemList; static int numSystemsRunning; static void printSystems(); }; #endif // __SYSTEM_HH__ <commit_msg>forgot to check this in<commit_after>/* * Copyright (c) 2003 The Regents of The University of Michigan * 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 the copyright holders 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. */ #ifndef __SYSTEM_HH__ #define __SYSTEM_HH__ #include <string> #include <vector> #include "base/loader/symtab.hh" #include "base/statistics.hh" #include "cpu/pc_event.hh" #include "sim/sim_object.hh" #include "sim/sw_context.hh" class MemoryController; class PhysicalMemory; class RemoteGDB; class GDBListener; class ExecContext; class System : public SimObject { // lisa's binning stuff protected: std::map<const std::string, Statistics::MainBin *> fnBins; std::map<const Addr, SWContext *> swCtxMap; public: Statistics::Scalar<Counter> fnCalls; Statistics::MainBin *Kernel; Statistics::MainBin *User; Statistics::MainBin * getBin(const std::string &name); virtual bool findCaller(std::string, std::string) const = 0; SWContext *findContext(Addr pcb); bool addContext(Addr pcb, SWContext *ctx) { return (swCtxMap.insert(make_pair(pcb, ctx))).second; } void remContext(Addr pcb) { swCtxMap.erase(pcb); return; } virtual void dumpState(ExecContext *xc) const = 0; virtual void serialize(std::ostream &os); virtual void unserialize(Checkpoint *cp, const std::string &section); // public: const uint64_t init_param; MemoryController *memCtrl; PhysicalMemory *physmem; bool bin; PCEventQueue pcEventQueue; std::vector<ExecContext *> execContexts; virtual int registerExecContext(ExecContext *xc); virtual void replaceExecContext(int xcIndex, ExecContext *xc); public: System(const std::string _name, const uint64_t _init_param, MemoryController *, PhysicalMemory *, const bool); ~System(); virtual Addr getKernelStart() const = 0; virtual Addr getKernelEnd() const = 0; virtual Addr getKernelEntry() const = 0; virtual bool breakpoint() = 0; public: //////////////////////////////////////////// // // STATIC GLOBAL SYSTEM LIST // //////////////////////////////////////////// static std::vector<System *> systemList; static int numSystemsRunning; static void printSystems(); }; #endif // __SYSTEM_HH__ <|endoftext|>
<commit_before>/*========================================================================= Program: Visualization Toolkit Module: vtkPicker.cc Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) 1993-1995 Ken Martin, Will Schroeder, Bill Lorensen. This software is copyrighted by Ken Martin, Will Schroeder and Bill Lorensen. The following terms apply to all files associated with the software unless explicitly disclaimed in individual files. This copyright specifically does not apply to the related textbook "The Visualization Toolkit" ISBN 013199837-4 published by Prentice Hall which is covered by its own copyright. The authors hereby grant permission to use, copy, and distribute this software and its documentation for any purpose, provided that existing copyright notices are retained in all copies and that this notice is included verbatim in any distributions. Additionally, the authors grant permission to modify this software and its documentation for any purpose, provided that such modifications are not distributed without the explicit consent of the authors and that existing copyright notices are retained in all copies. Some of the algorithms implemented by this software are patented, observe all applicable patent law. IN NO EVENT SHALL THE AUTHORS OR DISTRIBUTORS BE LIABLE TO ANY PARTY FOR DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OF THIS SOFTWARE, ITS DOCUMENTATION, OR ANY DERIVATIVES THEREOF, EVEN IF THE AUTHORS HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. THE AUTHORS AND DISTRIBUTORS SPECIFICALLY DISCLAIM ANY WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, AND NON-INFRINGEMENT. THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, AND THE AUTHORS AND DISTRIBUTORS HAVE NO OBLIGATION TO PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS. =========================================================================*/ #include "vtkPicker.hh" #include "vtkCamera.hh" #include "vtkMath.hh" #include "vtkVertex.hh" #include "vtkRenderWindow.hh" static vtkMath math; // Description: // Construct object with initial tolerance of 1/40th of window. vtkPicker::vtkPicker() { this->Renderer = NULL; this->SelectionPoint[0] = 0.0; this->SelectionPoint[1] = 0.0; this->SelectionPoint[2] = 0.0; this->Tolerance = 0.025; // 1/40th of the renderer window this->PickPosition[0] = 0.0; this->PickPosition[1] = 0.0; this->PickPosition[2] = 0.0; this->MapperPosition[0] = 0.0; this->MapperPosition[1] = 0.0; this->MapperPosition[2] = 0.0; this->Actor = NULL; this->Mapper = NULL; this->DataSet = NULL; this->GlobalTMin = LARGE_FLOAT; } // Update state when actor is picked. void vtkPicker::MarkPicked(vtkActor *actor, vtkMapper *mapper, float tMin, float mapperPos[3]) { int i; float mapperHPosition[4]; float *worldHPosition; this->Actor = actor; this->Mapper = mapper; this->DataSet = mapper->GetInput(); this->GlobalTMin = tMin; for (i=0; i < 3; i++) { this->MapperPosition[i] = mapperPos[i]; mapperHPosition[i] = mapperPos[i]; } mapperHPosition[3] = 1.0; // // The point has to be transformed back into world coordinates. // Note: it is assumed that the transform is in the correct state. // this->Transform.SetPoint(mapperHPosition); worldHPosition = this->Transform.GetPoint(); for (i=0; i < 3; i++) this->PickPosition[i] = worldHPosition[i]; } // Description: // Perform pick operation with selection point provided. Normally the // first two values for the selection point are x-y pixel coordinate, and // the third value is =0. Return non-zero if something was successfully picked. int vtkPicker::Pick(float selectionX, float selectionY, float selectionZ, vtkRenderer *renderer) { int i; vtkActorCollection *actors; vtkActor *actor; vtkCamera *camera; vtkMapper *mapper; float p1World[4], p2World[4], p1Mapper[4], p2Mapper[4]; static vtkVertex cell; // use to take advantage of Hitbbox() method int picked=0; int *winSize; float x, y, t; float *viewport; float cameraPos[4], cameraFP[4]; float *displayCoords, *worldCoords; float *clipRange; float ray[3], rayLength; float transparency; int visible, pickable; float windowLowerLeft[4], windowUpperRight[4]; float *bounds, tol; float tF, tB; float hitPosition[3]; // // Initialize picking process // this->Renderer = renderer; this->SelectionPoint[0] = selectionX; this->SelectionPoint[1] = selectionY; this->SelectionPoint[2] = selectionZ; this->Initialize(); if ( renderer == NULL ) { vtkErrorMacro(<<"Must specify renderer!"); return 0; } // // Get camera focal point and position. Convert to display (screen) // coordinates. We need a depth value for z-buffer. // camera = renderer->GetActiveCamera(); camera->GetPosition(cameraPos); cameraPos[3] = 1.0; camera->GetFocalPoint(cameraFP); cameraFP[3] = 1.0; renderer->SetWorldPoint(cameraFP); renderer->WorldToDisplay(); displayCoords = renderer->GetDisplayPoint(); selectionZ = displayCoords[2]; // // Convert the selection point into world coordinates. // renderer->SetDisplayPoint(selectionX, selectionY, selectionZ); renderer->DisplayToWorld(); worldCoords = renderer->GetWorldPoint(); if ( worldCoords[3] == 0.0 ) { vtkErrorMacro(<<"Bad homogeneous coordinates"); return 0; } for (i=0; i < 3; i++) this->PickPosition[i] = worldCoords[i] / worldCoords[3]; // // Compute the ray endpoints. The ray is along the line running from // the camera position to the selection point, starting where this line // intersects the front clipping plane, and terminating where this // line intersects the back clipping plane. // for (i=0; i<3; i++) ray[i] = this->PickPosition[i] - cameraPos[i]; if (( rayLength = math.Dot(ray,ray)) == 0.0 ) { vtkWarningMacro("Cannot process points"); return 0; } else rayLength = sqrt (rayLength); clipRange = camera->GetClippingRange(); tF = clipRange[0] / rayLength; tB = clipRange[1] / rayLength; for (i=0; i<3; i++) { p1World[i] = cameraPos[i] + tF*ray[i]; p2World[i] = cameraPos[i] + tB*ray[i]; } p1World[3] = p2World[3] = 1.0; // // Compute the tolerance in world coordinates. Do this by // determining the world coordinates of the diagonal points of the // window, computing the width of the window in world coordinates, and // multiplying by the tolerance. // viewport = renderer->GetViewport(); winSize = renderer->GetRenderWindow()->GetSize(); x = winSize[0] * viewport[0]; y = winSize[1] * viewport[1]; renderer->SetDisplayPoint(x, y, selectionZ); renderer->DisplayToWorld(); renderer->GetWorldPoint(windowLowerLeft); x = winSize[0] * viewport[2]; y = winSize[1] * viewport[3]; renderer->SetDisplayPoint(x, y, selectionZ); renderer->DisplayToWorld(); renderer->GetWorldPoint(windowUpperRight); for (tol=0.0,i=0; i<3; i++) tol += (windowUpperRight[i] - windowLowerLeft[i])*(windowUpperRight[i] - windowLowerLeft[i]); tol = sqrt (tol) * this->Tolerance; // // Loop over all actors. Transform ray (defined from position of // camera to selection point) into coordinates of mapper (not // transformed to actors coordinates! Reduces overall computation!!!). // actors = renderer->GetActors(); for ( actors->InitTraversal(); actor=actors->GetNextItem(); ) { visible = actor->GetVisibility(); pickable = actor->GetPickable(); transparency = actor->GetProperty()->GetOpacity(); // // If actor can be picked, get its composite matrix, invert it, and // use the inverted matrix to transform the ray points into mapper // coordinates. // if (visible && pickable && transparency != 0.0) { this->Transform.SetMatrix(actor->GetMatrix()); this->Transform.Push(); this->Transform.Inverse(); this->Transform.SetPoint(p1World); this->Transform.GetPoint(p1Mapper); this->Transform.SetPoint(p2World); this->Transform.GetPoint(p2Mapper); for (i=0; i<3; i++) ray[i] = p2Mapper[i] - p1Mapper[i]; this->Transform.Pop(); // // Have the ray endpoints in mapper space, now need to compare this // with the mapper bounds to see whether intersection is possible. // if ( (mapper = actor->GetMapper()) != NULL ) { // // Get the bounding box of the modeller. Note that the tolerance is // added to the bounding box to make sure things on the edge of the // bounding box are picked correctly. // bounds = mapper->GetBounds(); if ( cell.HitBBox(bounds, p1Mapper, ray, hitPosition, t) ) { picked = 1; this->IntersectWithLine(p1Mapper,p2Mapper,tol,actor,mapper); this->Actors.AddItem(actor); } } } } return picked; } // Intersect data with specified ray. void vtkPicker::IntersectWithLine(float p1[3], float p2[3], float tol, vtkActor *actor, vtkMapper *mapper) { int i; float *center, t, ray[3], rayFactor; // // Get the data from the modeller // center = mapper->GetCenter(); for (i=0; i<3; i++) ray[i] = p2[i] - p1[i]; if (( rayFactor = math.Dot(ray,ray)) == 0.0 ) return; // // Project the center point onto the ray and determine its parametric value // t = (ray[0]*(center[0]-p1[0]) + ray[1]*(center[1]-p1[1]) + ray[2]*(center[2]-p1[2])) / rayFactor; if ( t >= 0.0 && t <= 1.0 && t < this->GlobalTMin ) { this->MarkPicked(actor, mapper, t, center); } } // Initialize the picking process. void vtkPicker::Initialize() { this->Actors.RemoveAllItems(); this->PickPosition[0] = 0.0; this->PickPosition[1] = 0.0; this->PickPosition[2] = 0.0; this->MapperPosition[0] = 0.0; this->MapperPosition[1] = 0.0; this->MapperPosition[2] = 0.0; this->Actor = NULL; this->Mapper = NULL; this->GlobalTMin = LARGE_FLOAT; } void vtkPicker::PrintSelf(ostream& os, vtkIndent indent) { this->vtkObject::PrintSelf(os,indent); os << indent << "Renderer: " << this->Renderer << "\n"; os << indent << "Selection Point: (" << this->SelectionPoint[0] << "," << this->SelectionPoint[1] << "," << this->SelectionPoint[2] << ")\n"; os << indent << "Tolerance: " << this->Tolerance << "\n"; os << indent << "Pick Position: (" << this->PickPosition[0] << "," << this->PickPosition[1] << "," << this->PickPosition[2] << ")\n"; os << indent << "Mapper Position: (" << this->MapperPosition[0] << "," << this->MapperPosition[1] << "," << this->MapperPosition[2] << ")\n"; os << indent << "Actor: " << this->Actor << "\n"; os << indent << "Mapper: " << this->Mapper << "\n"; } <commit_msg>pc fixes<commit_after>/*========================================================================= Program: Visualization Toolkit Module: vtkPicker.cc Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) 1993-1995 Ken Martin, Will Schroeder, Bill Lorensen. This software is copyrighted by Ken Martin, Will Schroeder and Bill Lorensen. The following terms apply to all files associated with the software unless explicitly disclaimed in individual files. This copyright specifically does not apply to the related textbook "The Visualization Toolkit" ISBN 013199837-4 published by Prentice Hall which is covered by its own copyright. The authors hereby grant permission to use, copy, and distribute this software and its documentation for any purpose, provided that existing copyright notices are retained in all copies and that this notice is included verbatim in any distributions. Additionally, the authors grant permission to modify this software and its documentation for any purpose, provided that such modifications are not distributed without the explicit consent of the authors and that existing copyright notices are retained in all copies. Some of the algorithms implemented by this software are patented, observe all applicable patent law. IN NO EVENT SHALL THE AUTHORS OR DISTRIBUTORS BE LIABLE TO ANY PARTY FOR DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OF THIS SOFTWARE, ITS DOCUMENTATION, OR ANY DERIVATIVES THEREOF, EVEN IF THE AUTHORS HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. THE AUTHORS AND DISTRIBUTORS SPECIFICALLY DISCLAIM ANY WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, AND NON-INFRINGEMENT. THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, AND THE AUTHORS AND DISTRIBUTORS HAVE NO OBLIGATION TO PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS. =========================================================================*/ #include "vtkPicker.hh" #include "vtkCamera.hh" #include "vtkMath.hh" #include "vtkVertex.hh" #include "vtkRenderWindow.hh" static vtkMath math; // Description: // Construct object with initial tolerance of 1/40th of window. vtkPicker::vtkPicker() { this->Renderer = NULL; this->SelectionPoint[0] = 0.0; this->SelectionPoint[1] = 0.0; this->SelectionPoint[2] = 0.0; this->Tolerance = 0.025; // 1/40th of the renderer window this->PickPosition[0] = 0.0; this->PickPosition[1] = 0.0; this->PickPosition[2] = 0.0; this->MapperPosition[0] = 0.0; this->MapperPosition[1] = 0.0; this->MapperPosition[2] = 0.0; this->Actor = NULL; this->Mapper = NULL; this->DataSet = NULL; this->GlobalTMin = LARGE_FLOAT; } // Update state when actor is picked. void vtkPicker::MarkPicked(vtkActor *actor, vtkMapper *mapper, float tMin, float mapperPos[3]) { int i; float mapperHPosition[4]; float *worldHPosition; this->Actor = actor; this->Mapper = mapper; this->DataSet = mapper->GetInput(); this->GlobalTMin = tMin; for (i=0; i < 3; i++) { this->MapperPosition[i] = mapperPos[i]; mapperHPosition[i] = mapperPos[i]; } mapperHPosition[3] = 1.0; // // The point has to be transformed back into world coordinates. // Note: it is assumed that the transform is in the correct state. // this->Transform.SetPoint(mapperHPosition); worldHPosition = this->Transform.GetPoint(); for (i=0; i < 3; i++) this->PickPosition[i] = worldHPosition[i]; } // Description: // Perform pick operation with selection point provided. Normally the // first two values for the selection point are x-y pixel coordinate, and // the third value is =0. Return non-zero if something was successfully picked. int vtkPicker::Pick(float selectionX, float selectionY, float selectionZ, vtkRenderer *renderer) { int i; vtkActorCollection *actors; vtkActor *actor; vtkCamera *camera; vtkMapper *mapper; float p1World[4], p2World[4], p1Mapper[3], p2Mapper[3]; static vtkVertex cell; // use to take advantage of Hitbbox() method int picked=0; int *winSize; float x, y, t; float *viewport; float cameraPos[4], cameraFP[4]; float *displayCoords, *worldCoords; float *clipRange; float ray[3], rayLength; float transparency; int visible, pickable; float windowLowerLeft[4], windowUpperRight[4]; float *bounds, tol; float tF, tB; float hitPosition[3]; // // Initialize picking process // this->Renderer = renderer; this->SelectionPoint[0] = selectionX; this->SelectionPoint[1] = selectionY; this->SelectionPoint[2] = selectionZ; this->Initialize(); if ( renderer == NULL ) { vtkErrorMacro(<<"Must specify renderer!"); return 0; } // // Get camera focal point and position. Convert to display (screen) // coordinates. We need a depth value for z-buffer. // camera = renderer->GetActiveCamera(); camera->GetPosition((float *)cameraPos); cameraPos[3] = 1.0; camera->GetFocalPoint((float *)cameraFP); cameraFP[3] = 1.0; renderer->SetWorldPoint(cameraFP); renderer->WorldToDisplay(); displayCoords = renderer->GetDisplayPoint(); selectionZ = displayCoords[2]; // // Convert the selection point into world coordinates. // renderer->SetDisplayPoint(selectionX, selectionY, selectionZ); renderer->DisplayToWorld(); worldCoords = renderer->GetWorldPoint(); if ( worldCoords[3] == 0.0 ) { vtkErrorMacro(<<"Bad homogeneous coordinates"); return 0; } for (i=0; i < 3; i++) this->PickPosition[i] = worldCoords[i] / worldCoords[3]; // // Compute the ray endpoints. The ray is along the line running from // the camera position to the selection point, starting where this line // intersects the front clipping plane, and terminating where this // line intersects the back clipping plane. // for (i=0; i<3; i++) ray[i] = this->PickPosition[i] - cameraPos[i]; if (( rayLength = math.Dot(ray,ray)) == 0.0 ) { vtkWarningMacro("Cannot process points"); return 0; } else rayLength = sqrt (rayLength); clipRange = camera->GetClippingRange(); tF = clipRange[0] / rayLength; tB = clipRange[1] / rayLength; for (i=0; i<3; i++) { p1World[i] = cameraPos[i] + tF*ray[i]; p2World[i] = cameraPos[i] + tB*ray[i]; } p1World[3] = p2World[3] = 1.0; // // Compute the tolerance in world coordinates. Do this by // determining the world coordinates of the diagonal points of the // window, computing the width of the window in world coordinates, and // multiplying by the tolerance. // viewport = renderer->GetViewport(); winSize = renderer->GetRenderWindow()->GetSize(); x = winSize[0] * viewport[0]; y = winSize[1] * viewport[1]; renderer->SetDisplayPoint(x, y, selectionZ); renderer->DisplayToWorld(); renderer->GetWorldPoint(windowLowerLeft); x = winSize[0] * viewport[2]; y = winSize[1] * viewport[3]; renderer->SetDisplayPoint(x, y, selectionZ); renderer->DisplayToWorld(); renderer->GetWorldPoint(windowUpperRight); for (tol=0.0,i=0; i<3; i++) tol += (windowUpperRight[i] - windowLowerLeft[i])*(windowUpperRight[i] - windowLowerLeft[i]); tol = sqrt (tol) * this->Tolerance; // // Loop over all actors. Transform ray (defined from position of // camera to selection point) into coordinates of mapper (not // transformed to actors coordinates! Reduces overall computation!!!). // actors = renderer->GetActors(); for ( actors->InitTraversal(); actor=actors->GetNextItem(); ) { visible = actor->GetVisibility(); pickable = actor->GetPickable(); transparency = actor->GetProperty()->GetOpacity(); // // If actor can be picked, get its composite matrix, invert it, and // use the inverted matrix to transform the ray points into mapper // coordinates. // if (visible && pickable && transparency != 0.0) { this->Transform.SetMatrix(actor->GetMatrix()); this->Transform.Push(); this->Transform.Inverse(); this->Transform.SetPoint(p1World); this->Transform.GetPoint(p1Mapper); this->Transform.SetPoint(p2World); this->Transform.GetPoint(p2Mapper); for (i=0; i<3; i++) ray[i] = p2Mapper[i] - p1Mapper[i]; this->Transform.Pop(); // // Have the ray endpoints in mapper space, now need to compare this // with the mapper bounds to see whether intersection is possible. // if ( (mapper = actor->GetMapper()) != NULL ) { // // Get the bounding box of the modeller. Note that the tolerance is // added to the bounding box to make sure things on the edge of the // bounding box are picked correctly. // bounds = mapper->GetBounds(); if ( cell.HitBBox(bounds, p1Mapper, ray, hitPosition, t) ) { picked = 1; this->IntersectWithLine(p1Mapper,p2Mapper,tol,actor,mapper); this->Actors.AddItem(actor); } } } } return picked; } // Intersect data with specified ray. void vtkPicker::IntersectWithLine(float p1[3], float p2[3], float tol, vtkActor *actor, vtkMapper *mapper) { int i; float *center, t, ray[3], rayFactor; // // Get the data from the modeller // center = mapper->GetCenter(); for (i=0; i<3; i++) ray[i] = p2[i] - p1[i]; if (( rayFactor = math.Dot(ray,ray)) == 0.0 ) return; // // Project the center point onto the ray and determine its parametric value // t = (ray[0]*(center[0]-p1[0]) + ray[1]*(center[1]-p1[1]) + ray[2]*(center[2]-p1[2])) / rayFactor; if ( t >= 0.0 && t <= 1.0 && t < this->GlobalTMin ) { this->MarkPicked(actor, mapper, t, center); } } // Initialize the picking process. void vtkPicker::Initialize() { this->Actors.RemoveAllItems(); this->PickPosition[0] = 0.0; this->PickPosition[1] = 0.0; this->PickPosition[2] = 0.0; this->MapperPosition[0] = 0.0; this->MapperPosition[1] = 0.0; this->MapperPosition[2] = 0.0; this->Actor = NULL; this->Mapper = NULL; this->GlobalTMin = LARGE_FLOAT; } void vtkPicker::PrintSelf(ostream& os, vtkIndent indent) { this->vtkObject::PrintSelf(os,indent); os << indent << "Renderer: " << this->Renderer << "\n"; os << indent << "Selection Point: (" << this->SelectionPoint[0] << "," << this->SelectionPoint[1] << "," << this->SelectionPoint[2] << ")\n"; os << indent << "Tolerance: " << this->Tolerance << "\n"; os << indent << "Pick Position: (" << this->PickPosition[0] << "," << this->PickPosition[1] << "," << this->PickPosition[2] << ")\n"; os << indent << "Mapper Position: (" << this->MapperPosition[0] << "," << this->MapperPosition[1] << "," << this->MapperPosition[2] << ")\n"; os << indent << "Actor: " << this->Actor << "\n"; os << indent << "Mapper: " << this->Mapper << "\n"; } <|endoftext|>
<commit_before>/* * IceWM * * Copyright (C) 1997-2003 Marko Macek * * Window list */ #include "config.h" #include "ykey.h" #include "ypaint.h" #include "wmwinlist.h" #include "ymenuitem.h" #include "yaction.h" #include "prefs.h" #include "wmaction.h" #include "wmclient.h" #include "wmframe.h" #include "wmmgr.h" #include "wmapp.h" #include "sysdep.h" #include "yrect.h" #include "intl.h" WindowList *windowList = 0; WindowListItem::WindowListItem(ClientData *frame, int workspace): YListItem() { fFrame = frame; fWorkspace = workspace; } WindowListItem::~WindowListItem() { if (fFrame) { fFrame->setWinListItem(0); fFrame = 0; } } int WindowListItem::getOffset() { int ofs = -20; ClientData *w = getFrame(); if (w) { ofs += 40; while (w->owner()) { ofs += 20; w = w->owner(); } } return ofs; } ustring WindowListItem::getText() { if (fFrame) return getFrame()->getTitle(); else if (fWorkspace < 0) return _("All Workspaces"); else return workspaceNames[fWorkspace]; } ref<YIcon> WindowListItem::getIcon() { if (fFrame) return getFrame()->getIcon(); return null; } WindowListBox::WindowListBox(YScrollView *view, YWindow *aParent): YListBox(view, aParent) { } WindowListBox::~WindowListBox() { } void WindowListBox::activateItem(YListItem *item) { WindowListItem *i = (WindowListItem *)item; ClientData *f = i->getFrame(); if (f) { f->activateWindow(true); windowList->getFrame()->wmHide(); } else { int w = i->getWorkspace(); if (w != -1) { manager->activateWorkspace(w); windowList->getFrame()->wmHide(); } } } void WindowListBox::getSelectedWindows(YArray<YFrameWindow *> &frames) { if (hasSelection()) { for (YListItem *i = getFirst(); i; i = i->getNext()) { if (isSelected(i)) { WindowListItem *item = (WindowListItem *)i; ClientData *f = item->getFrame(); if (f) frames.append((YFrameWindow *)f); } } } } void WindowListBox::actionPerformed(YAction action, unsigned int modifiers) { YArray<YFrameWindow *> frameList; getSelectedWindows(frameList); if (action == actionTileVertical || action == actionTileHorizontal) { if (frameList.getCount() > 0) manager->tileWindows(frameList.getItemPtr(0), frameList.getCount(), (action == actionTileVertical) ? true : false); } else if (action == actionCascade || action == actionArrange) { if (frameList.getCount() > 0) { if (action == actionCascade) { manager->cascadePlace(frameList.getItemPtr(0), frameList.getCount()); } else if (action == actionArrange) { manager->smartPlace(frameList.getItemPtr(0), frameList.getCount()); } } } else { for (int i = 0; i < frameList.getCount(); i++) { if (action == actionHide) if (frameList[i]->isHidden()) continue; if (action == actionMinimize) if (frameList[i]->isMinimized()) continue; frameList[i]->actionPerformed(action, modifiers); } } } bool WindowListBox::handleKey(const XKeyEvent &key) { if (key.type == KeyPress) { KeySym k = keyCodeToKeySym(key.keycode); int m = KEY_MODMASK(key.state); switch (k) { case XK_Escape: windowList->getFrame()->wmHide(); return true; case XK_F10: case XK_Menu: if (k != XK_F10 || m == ShiftMask) { if (hasSelection()) { enableCommands(windowListPopup); windowListPopup->popup(0, 0, 0, key.x_root, key.y_root, YPopupWindow::pfCanFlipVertical | YPopupWindow::pfCanFlipHorizontal | YPopupWindow::pfPopupMenu); } else { windowListAllPopup->popup(0, 0, 0, key.x_root, key.y_root, YPopupWindow::pfCanFlipVertical | YPopupWindow::pfCanFlipHorizontal | YPopupWindow::pfPopupMenu); } } break; case XK_Delete: { if (m & ShiftMask) actionPerformed(actionKill, key.state); else actionPerformed(actionClose, key.state); } break; } } return YListBox::handleKey(key); } void WindowListBox::handleClick(const XButtonEvent &up, int count) { if (up.button == 3 && count == 1 && IS_BUTTON(up.state, Button3Mask)) { int no = findItemByPoint(up.x, up.y); if (no != -1) { YListItem *i = getItem(no); if (!isSelected(i)) { focusSelectItem(no); } else { //fFocusedItem = -1; } enableCommands(windowListPopup); windowListPopup->popup(0, 0, 0, up.x_root, up.y_root, YPopupWindow::pfCanFlipVertical | YPopupWindow::pfCanFlipHorizontal | YPopupWindow::pfPopupMenu); } else { windowListAllPopup->popup(0, 0, 0, up.x_root, up.y_root, YPopupWindow::pfCanFlipVertical | YPopupWindow::pfCanFlipHorizontal | YPopupWindow::pfPopupMenu); } return ; } YListBox::handleClick(up, count); } void WindowListBox::enableCommands(YMenu *popup) { bool noItems = true; long workspace = -1; bool sameWorkspace = false; bool notHidden = false; bool notMinimized = false; // enable minimize,hide if appropriate // enable workspace selections if appropriate popup->enableCommand(actionNull); for (YListItem *i = getFirst(); i; i = i->getNext()) { if (isSelected(i)) { WindowListItem *item = (WindowListItem *)i; if (!item->getFrame()) { continue; } noItems = false; if (!item->getFrame()->isHidden()) notHidden = true; if (!item->getFrame()->isMinimized()) notMinimized = true; long ws = item->getFrame()->getWorkspace(); if (workspace == -1) { workspace = ws; sameWorkspace = true; } else if (workspace != ws) { sameWorkspace = false; } if (item->getFrame()->isAllWorkspaces()) sameWorkspace = false; } } if (!notHidden) popup->disableCommand(actionHide); if (!notMinimized) popup->disableCommand(actionMinimize); moveMenu->enableCommand(actionNull); if (sameWorkspace && workspace != -1) { for (int i = 0; i < moveMenu->itemCount(); i++) { YMenuItem *item = moveMenu->getItem(i); for (int w = 0; w < workspaceCount; w++) if (item && item->getAction() == workspaceActionMoveTo[w]) item->setEnabled(w != workspace); } } if (noItems) { moveMenu->disableCommand(actionNull); popup->disableCommand(actionNull); } } WindowList::WindowList(YWindow *aParent, YActionListener *wmActionListener): YFrameClient(aParent, 0) { this->wmActionListener = wmActionListener; scroll = new YScrollView(this); list = new WindowListBox(scroll, scroll); scroll->setView(list); list->show(); scroll->show(); fWorkspaceCount = workspaceCount; workspaceItem = new WindowListItem *[fWorkspaceCount + 1]; for (int ws = 0; ws < fWorkspaceCount; ws++) { workspaceItem[ws] = new WindowListItem(0, ws); list->addItem(workspaceItem[ws]); } workspaceItem[fWorkspaceCount] = new WindowListItem(0, -1); list->addItem(workspaceItem[fWorkspaceCount]); YMenu *closeSubmenu = new YMenu(); assert(closeSubmenu != 0); closeSubmenu->addItem(_("_Close"), -2, _("Del"), actionClose); closeSubmenu->addSeparator(); closeSubmenu->addItem(_("_Kill Client"), -2, null, actionKill); #if 0 closeSubmenu->addItem(_("_Terminate Process"), -2, 0, actionTermProcess)->setEnabled(false); closeSubmenu->addItem(_("Kill _Process"), -2, 0, actionKillProcess)->setEnabled(false); #endif windowListPopup = new YMenu(); windowListPopup->setActionListener(list); windowListPopup->addItem(_("_Show"), -2, null, actionShow); windowListPopup->addItem(_("_Hide"), -2, null, actionHide); windowListPopup->addItem(_("_Minimize"), -2, null, actionMinimize); windowListPopup->addSubmenu(_("Move _To"), -2, moveMenu); windowListPopup->addSeparator(); windowListPopup->addItem(_("Tile _Vertically"), -2, KEY_NAME(gKeySysTileVertical), actionTileVertical); windowListPopup->addItem(_("T_ile Horizontally"), -2, KEY_NAME(gKeySysTileHorizontal), actionTileHorizontal); windowListPopup->addItem(_("Ca_scade"), -2, KEY_NAME(gKeySysCascade), actionCascade); windowListPopup->addItem(_("_Arrange"), -2, KEY_NAME(gKeySysArrange), actionArrange); windowListPopup->addSeparator(); windowListPopup->addItem(_("_Minimize All"), -2, KEY_NAME(gKeySysMinimizeAll), actionMinimizeAll); windowListPopup->addItem(_("_Hide All"), -2, KEY_NAME(gKeySysHideAll), actionHideAll); windowListPopup->addItem(_("_Undo"), -2, KEY_NAME(gKeySysUndoArrange), actionUndoArrange); windowListPopup->addSeparator(); windowListPopup->addItem(_("_Close"), -2, actionClose, closeSubmenu); windowListAllPopup = new YMenu(); windowListAllPopup->setActionListener(wmActionListener); windowListAllPopup->addItem(_("Tile _Vertically"), -2, KEY_NAME(gKeySysTileVertical), actionTileVertical); windowListAllPopup->addItem(_("T_ile Horizontally"), -2, KEY_NAME(gKeySysTileHorizontal), actionTileHorizontal); windowListAllPopup->addItem(_("Ca_scade"), -2, KEY_NAME(gKeySysCascade), actionCascade); windowListAllPopup->addItem(_("_Arrange"), -2, KEY_NAME(gKeySysArrange), actionArrange); windowListAllPopup->addItem(_("_Minimize All"), -2, KEY_NAME(gKeySysMinimizeAll), actionMinimizeAll); windowListAllPopup->addItem(_("_Hide All"), -2, KEY_NAME(gKeySysHideAll), actionHideAll); windowListAllPopup->addItem(_("_Undo"), -2, KEY_NAME(gKeySysUndoArrange), actionUndoArrange); int dx, dy; unsigned dw, dh; manager->getScreenGeometry(&dx, &dy, &dw, &dh, 0); unsigned w = dw; unsigned h = dh; setGeometry(YRect(w / 4, h / 4, w / 2, h / 2)); windowList = this; setWindowTitle(_("Window list")); setIconTitle(_("Window list")); setWinWorkspaceHint(-1); setWinLayerHint(WinLayerAboveDock); } WindowList::~WindowList() { delete list; list = 0; delete scroll; scroll = 0; windowList = 0; delete windowListAllPopup; windowListAllPopup = 0; for (int ws = 0; ws <= fWorkspaceCount; ws++) { delete workspaceItem[ws]; } delete[] workspaceItem; } void WindowList::updateWorkspaces() { long fOldWorkspaceCount = fWorkspaceCount; fWorkspaceCount = workspaceCount; if (fWorkspaceCount != fOldWorkspaceCount) { WindowListItem **oldWorkspaceItem = workspaceItem; workspaceItem = new WindowListItem *[fWorkspaceCount + 1]; workspaceItem[fWorkspaceCount] = oldWorkspaceItem[fOldWorkspaceCount]; list->removeItem(workspaceItem[fWorkspaceCount]); if (fWorkspaceCount > fOldWorkspaceCount) { for (long w = 0; w < fOldWorkspaceCount; w++) workspaceItem[w] = oldWorkspaceItem[w]; for (long w = fOldWorkspaceCount; w < fWorkspaceCount; w++) { workspaceItem[w] = new WindowListItem(0, w); list->addItem(workspaceItem[w]); } } else if (fWorkspaceCount < fOldWorkspaceCount) { for (long w = 0; w < fWorkspaceCount; w++) workspaceItem[w] = oldWorkspaceItem[w]; for (long w = fWorkspaceCount; w < fOldWorkspaceCount; w++) { list->removeItem(oldWorkspaceItem[w]); delete oldWorkspaceItem[w]; } } list->addItem(workspaceItem[fWorkspaceCount]); delete[] oldWorkspaceItem; } } void WindowList::handleFocus(const XFocusChangeEvent &focus) { if (focus.type == FocusIn && focus.mode != NotifyUngrab) { list->setWindowFocus(); } else if (focus.type == FocusOut) { } } void WindowList::relayout() { list->repaint(); } WindowListItem *WindowList::addWindowListApp(YFrameWindow *frame) { if (!frame->client()->adopted()) return 0; WindowListItem *item = new WindowListItem(frame); if (item) { insertApp(item); } return item; } void WindowList::insertApp(WindowListItem *item) { ClientData *frame = item->getFrame(); if (frame->owner() && frame->owner()->winListItem()) { list->addAfter(frame->owner()->winListItem(), item); } else { int nw = frame->getWorkspace(); if (!frame->isAllWorkspaces()) list->addAfter(workspaceItem[nw], item); else list->addItem(item); } } void WindowList::removeWindowListApp(WindowListItem *item) { if (item) { list->removeItem(item); delete item; } } void WindowList::updateWindowListApp(WindowListItem *item) { if (item) { list->removeItem(item); insertApp(item); } } void WindowList::configure(const YRect &r) { YFrameClient::configure(r); scroll->setGeometry(YRect(0, 0, r.width(), r.height())); } void WindowList::handleClose() { if (!getFrame()->isHidden()) getFrame()->wmHide(); } void WindowList::showFocused(int x, int y) { YFrameWindow *f = manager->getFocus(); if (f != getFrame()) { if (f) list->focusSelectItem(list->findItem(f->winListItem())); else list->focusSelectItem(0); } if (getFrame() == 0) manager->manageClient(handle(), false); if (getFrame() != 0) { if (x != -1 && y != -1) { int px, py; int xiscreen = manager->getScreenForRect(x, y, 1, 1); int dx, dy; unsigned dw, dh; manager->getScreenGeometry(&dx, &dy, &dw, &dh, xiscreen); px = x - getFrame()->width() / 2; py = y - getFrame()->height() / 2; if (px + getFrame()->width() > dx + dw) px = dx + dw - getFrame()->width(); if (py + getFrame()->height() > dy + dh) py = dx + dh - getFrame()->height(); if (px < dx) px = dx; if (py < dy) py = dy; getFrame()->setNormalPositionOuter(px, py); } getFrame()->setRequestedLayer(WinLayerAboveDock); getFrame()->setAllWorkspaces(); getFrame()->activateWindow(true); } } // vim: set sw=4 ts=4 et: <commit_msg>Window list skip taskbar.<commit_after>/* * IceWM * * Copyright (C) 1997-2003 Marko Macek * * Window list */ #include "config.h" #include "ykey.h" #include "ypaint.h" #include "wmwinlist.h" #include "ymenuitem.h" #include "yaction.h" #include "prefs.h" #include "wmaction.h" #include "wmclient.h" #include "wmframe.h" #include "wmmgr.h" #include "wmapp.h" #include "sysdep.h" #include "yrect.h" #include "intl.h" WindowList *windowList = 0; WindowListItem::WindowListItem(ClientData *frame, int workspace): YListItem() { fFrame = frame; fWorkspace = workspace; } WindowListItem::~WindowListItem() { if (fFrame) { fFrame->setWinListItem(0); fFrame = 0; } } int WindowListItem::getOffset() { int ofs = -20; ClientData *w = getFrame(); if (w) { ofs += 40; while (w->owner()) { ofs += 20; w = w->owner(); } } return ofs; } ustring WindowListItem::getText() { if (fFrame) return getFrame()->getTitle(); else if (fWorkspace < 0) return _("All Workspaces"); else return workspaceNames[fWorkspace]; } ref<YIcon> WindowListItem::getIcon() { if (fFrame) return getFrame()->getIcon(); return null; } WindowListBox::WindowListBox(YScrollView *view, YWindow *aParent): YListBox(view, aParent) { } WindowListBox::~WindowListBox() { } void WindowListBox::activateItem(YListItem *item) { WindowListItem *i = (WindowListItem *)item; ClientData *f = i->getFrame(); if (f) { f->activateWindow(true); windowList->getFrame()->wmHide(); } else { int w = i->getWorkspace(); if (w != -1) { manager->activateWorkspace(w); windowList->getFrame()->wmHide(); } } } void WindowListBox::getSelectedWindows(YArray<YFrameWindow *> &frames) { if (hasSelection()) { for (YListItem *i = getFirst(); i; i = i->getNext()) { if (isSelected(i)) { WindowListItem *item = (WindowListItem *)i; ClientData *f = item->getFrame(); if (f) frames.append((YFrameWindow *)f); } } } } void WindowListBox::actionPerformed(YAction action, unsigned int modifiers) { YArray<YFrameWindow *> frameList; getSelectedWindows(frameList); if (action == actionTileVertical || action == actionTileHorizontal) { if (frameList.getCount() > 0) manager->tileWindows(frameList.getItemPtr(0), frameList.getCount(), (action == actionTileVertical) ? true : false); } else if (action == actionCascade || action == actionArrange) { if (frameList.getCount() > 0) { if (action == actionCascade) { manager->cascadePlace(frameList.getItemPtr(0), frameList.getCount()); } else if (action == actionArrange) { manager->smartPlace(frameList.getItemPtr(0), frameList.getCount()); } } } else { for (int i = 0; i < frameList.getCount(); i++) { if (action == actionHide) if (frameList[i]->isHidden()) continue; if (action == actionMinimize) if (frameList[i]->isMinimized()) continue; frameList[i]->actionPerformed(action, modifiers); } } } bool WindowListBox::handleKey(const XKeyEvent &key) { if (key.type == KeyPress) { KeySym k = keyCodeToKeySym(key.keycode); int m = KEY_MODMASK(key.state); switch (k) { case XK_Escape: windowList->getFrame()->wmHide(); return true; case XK_F10: case XK_Menu: if (k != XK_F10 || m == ShiftMask) { if (hasSelection()) { enableCommands(windowListPopup); windowListPopup->popup(0, 0, 0, key.x_root, key.y_root, YPopupWindow::pfCanFlipVertical | YPopupWindow::pfCanFlipHorizontal | YPopupWindow::pfPopupMenu); } else { windowListAllPopup->popup(0, 0, 0, key.x_root, key.y_root, YPopupWindow::pfCanFlipVertical | YPopupWindow::pfCanFlipHorizontal | YPopupWindow::pfPopupMenu); } } break; case XK_Delete: { if (m & ShiftMask) actionPerformed(actionKill, key.state); else actionPerformed(actionClose, key.state); } break; } } return YListBox::handleKey(key); } void WindowListBox::handleClick(const XButtonEvent &up, int count) { if (up.button == 3 && count == 1 && IS_BUTTON(up.state, Button3Mask)) { int no = findItemByPoint(up.x, up.y); if (no != -1) { YListItem *i = getItem(no); if (!isSelected(i)) { focusSelectItem(no); } else { //fFocusedItem = -1; } enableCommands(windowListPopup); windowListPopup->popup(0, 0, 0, up.x_root, up.y_root, YPopupWindow::pfCanFlipVertical | YPopupWindow::pfCanFlipHorizontal | YPopupWindow::pfPopupMenu); } else { windowListAllPopup->popup(0, 0, 0, up.x_root, up.y_root, YPopupWindow::pfCanFlipVertical | YPopupWindow::pfCanFlipHorizontal | YPopupWindow::pfPopupMenu); } return ; } YListBox::handleClick(up, count); } void WindowListBox::enableCommands(YMenu *popup) { bool noItems = true; long workspace = -1; bool sameWorkspace = false; bool notHidden = false; bool notMinimized = false; // enable minimize,hide if appropriate // enable workspace selections if appropriate popup->enableCommand(actionNull); for (YListItem *i = getFirst(); i; i = i->getNext()) { if (isSelected(i)) { WindowListItem *item = (WindowListItem *)i; if (!item->getFrame()) { continue; } noItems = false; if (!item->getFrame()->isHidden()) notHidden = true; if (!item->getFrame()->isMinimized()) notMinimized = true; long ws = item->getFrame()->getWorkspace(); if (workspace == -1) { workspace = ws; sameWorkspace = true; } else if (workspace != ws) { sameWorkspace = false; } if (item->getFrame()->isAllWorkspaces()) sameWorkspace = false; } } if (!notHidden) popup->disableCommand(actionHide); if (!notMinimized) popup->disableCommand(actionMinimize); moveMenu->enableCommand(actionNull); if (sameWorkspace && workspace != -1) { for (int i = 0; i < moveMenu->itemCount(); i++) { YMenuItem *item = moveMenu->getItem(i); for (int w = 0; w < workspaceCount; w++) if (item && item->getAction() == workspaceActionMoveTo[w]) item->setEnabled(w != workspace); } } if (noItems) { moveMenu->disableCommand(actionNull); popup->disableCommand(actionNull); } } WindowList::WindowList(YWindow *aParent, YActionListener *wmActionListener): YFrameClient(aParent, 0) { this->wmActionListener = wmActionListener; scroll = new YScrollView(this); list = new WindowListBox(scroll, scroll); scroll->setView(list); list->show(); scroll->show(); fWorkspaceCount = workspaceCount; workspaceItem = new WindowListItem *[fWorkspaceCount + 1]; for (int ws = 0; ws < fWorkspaceCount; ws++) { workspaceItem[ws] = new WindowListItem(0, ws); list->addItem(workspaceItem[ws]); } workspaceItem[fWorkspaceCount] = new WindowListItem(0, -1); list->addItem(workspaceItem[fWorkspaceCount]); YMenu *closeSubmenu = new YMenu(); assert(closeSubmenu != 0); closeSubmenu->addItem(_("_Close"), -2, _("Del"), actionClose); closeSubmenu->addSeparator(); closeSubmenu->addItem(_("_Kill Client"), -2, null, actionKill); #if 0 closeSubmenu->addItem(_("_Terminate Process"), -2, 0, actionTermProcess)->setEnabled(false); closeSubmenu->addItem(_("Kill _Process"), -2, 0, actionKillProcess)->setEnabled(false); #endif windowListPopup = new YMenu(); windowListPopup->setActionListener(list); windowListPopup->addItem(_("_Show"), -2, null, actionShow); windowListPopup->addItem(_("_Hide"), -2, null, actionHide); windowListPopup->addItem(_("_Minimize"), -2, null, actionMinimize); windowListPopup->addSubmenu(_("Move _To"), -2, moveMenu); windowListPopup->addSeparator(); windowListPopup->addItem(_("Tile _Vertically"), -2, KEY_NAME(gKeySysTileVertical), actionTileVertical); windowListPopup->addItem(_("T_ile Horizontally"), -2, KEY_NAME(gKeySysTileHorizontal), actionTileHorizontal); windowListPopup->addItem(_("Ca_scade"), -2, KEY_NAME(gKeySysCascade), actionCascade); windowListPopup->addItem(_("_Arrange"), -2, KEY_NAME(gKeySysArrange), actionArrange); windowListPopup->addSeparator(); windowListPopup->addItem(_("_Minimize All"), -2, KEY_NAME(gKeySysMinimizeAll), actionMinimizeAll); windowListPopup->addItem(_("_Hide All"), -2, KEY_NAME(gKeySysHideAll), actionHideAll); windowListPopup->addItem(_("_Undo"), -2, KEY_NAME(gKeySysUndoArrange), actionUndoArrange); windowListPopup->addSeparator(); windowListPopup->addItem(_("_Close"), -2, actionClose, closeSubmenu); windowListAllPopup = new YMenu(); windowListAllPopup->setActionListener(wmActionListener); windowListAllPopup->addItem(_("Tile _Vertically"), -2, KEY_NAME(gKeySysTileVertical), actionTileVertical); windowListAllPopup->addItem(_("T_ile Horizontally"), -2, KEY_NAME(gKeySysTileHorizontal), actionTileHorizontal); windowListAllPopup->addItem(_("Ca_scade"), -2, KEY_NAME(gKeySysCascade), actionCascade); windowListAllPopup->addItem(_("_Arrange"), -2, KEY_NAME(gKeySysArrange), actionArrange); windowListAllPopup->addItem(_("_Minimize All"), -2, KEY_NAME(gKeySysMinimizeAll), actionMinimizeAll); windowListAllPopup->addItem(_("_Hide All"), -2, KEY_NAME(gKeySysHideAll), actionHideAll); windowListAllPopup->addItem(_("_Undo"), -2, KEY_NAME(gKeySysUndoArrange), actionUndoArrange); int dx, dy; unsigned dw, dh; manager->getScreenGeometry(&dx, &dy, &dw, &dh, 0); unsigned w = dw; unsigned h = dh; setGeometry(YRect(w / 4, h / 4, w / 2, h / 2)); windowList = this; setWindowTitle(_("Window list")); setIconTitle(_("Window list")); setWinHintsHint(WinHintsSkipTaskBar); setWinWorkspaceHint(-1); setWinLayerHint(WinLayerAboveDock); } WindowList::~WindowList() { delete list; list = 0; delete scroll; scroll = 0; windowList = 0; delete windowListAllPopup; windowListAllPopup = 0; for (int ws = 0; ws <= fWorkspaceCount; ws++) { delete workspaceItem[ws]; } delete[] workspaceItem; } void WindowList::updateWorkspaces() { long fOldWorkspaceCount = fWorkspaceCount; fWorkspaceCount = workspaceCount; if (fWorkspaceCount != fOldWorkspaceCount) { WindowListItem **oldWorkspaceItem = workspaceItem; workspaceItem = new WindowListItem *[fWorkspaceCount + 1]; workspaceItem[fWorkspaceCount] = oldWorkspaceItem[fOldWorkspaceCount]; list->removeItem(workspaceItem[fWorkspaceCount]); if (fWorkspaceCount > fOldWorkspaceCount) { for (long w = 0; w < fOldWorkspaceCount; w++) workspaceItem[w] = oldWorkspaceItem[w]; for (long w = fOldWorkspaceCount; w < fWorkspaceCount; w++) { workspaceItem[w] = new WindowListItem(0, w); list->addItem(workspaceItem[w]); } } else if (fWorkspaceCount < fOldWorkspaceCount) { for (long w = 0; w < fWorkspaceCount; w++) workspaceItem[w] = oldWorkspaceItem[w]; for (long w = fWorkspaceCount; w < fOldWorkspaceCount; w++) { list->removeItem(oldWorkspaceItem[w]); delete oldWorkspaceItem[w]; } } list->addItem(workspaceItem[fWorkspaceCount]); delete[] oldWorkspaceItem; } } void WindowList::handleFocus(const XFocusChangeEvent &focus) { if (focus.type == FocusIn && focus.mode != NotifyUngrab) { list->setWindowFocus(); } else if (focus.type == FocusOut) { } } void WindowList::relayout() { list->repaint(); } WindowListItem *WindowList::addWindowListApp(YFrameWindow *frame) { if (!frame->client()->adopted()) return 0; WindowListItem *item = new WindowListItem(frame); if (item) { insertApp(item); } return item; } void WindowList::insertApp(WindowListItem *item) { ClientData *frame = item->getFrame(); if (frame->owner() && frame->owner()->winListItem()) { list->addAfter(frame->owner()->winListItem(), item); } else { int nw = frame->getWorkspace(); if (!frame->isAllWorkspaces()) list->addAfter(workspaceItem[nw], item); else list->addItem(item); } } void WindowList::removeWindowListApp(WindowListItem *item) { if (item) { list->removeItem(item); delete item; } } void WindowList::updateWindowListApp(WindowListItem *item) { if (item) { list->removeItem(item); insertApp(item); } } void WindowList::configure(const YRect &r) { YFrameClient::configure(r); scroll->setGeometry(YRect(0, 0, r.width(), r.height())); } void WindowList::handleClose() { if (!getFrame()->isHidden()) getFrame()->wmHide(); } void WindowList::showFocused(int x, int y) { YFrameWindow *f = manager->getFocus(); if (f != getFrame()) { if (f) list->focusSelectItem(list->findItem(f->winListItem())); else list->focusSelectItem(0); } if (getFrame() == 0) manager->manageClient(handle(), false); if (getFrame() != 0) { if (x != -1 && y != -1) { int px, py; int xiscreen = manager->getScreenForRect(x, y, 1, 1); int dx, dy; unsigned dw, dh; manager->getScreenGeometry(&dx, &dy, &dw, &dh, xiscreen); px = x - getFrame()->width() / 2; py = y - getFrame()->height() / 2; if (px + getFrame()->width() > dx + dw) px = dx + dw - getFrame()->width(); if (py + getFrame()->height() > dy + dh) py = dx + dh - getFrame()->height(); if (px < dx) px = dx; if (py < dy) py = dy; getFrame()->setNormalPositionOuter(px, py); } getFrame()->setRequestedLayer(WinLayerAboveDock); getFrame()->setAllWorkspaces(); getFrame()->activateWindow(true); } } // vim: set sw=4 ts=4 et: <|endoftext|>
<commit_before>/* * test.cpp * * Created on: Dec 5, 2014 * Author: ryung */ #include <iostream.> void main() { return; } <commit_msg>Committed by angelbc1999<commit_after>/* * test.cpp * * Created on: Dec 5, 2014 * Author: ryung */ #include <iostream.> void main() { //Roger is here return; } <|endoftext|>
<commit_before>/* This is both a sort of unit test, and a demonstration of how to use deadlock * prevention. * * Suggested compilation command: * c++ -Wall -pedantic -std=c++11 test.cpp -o test -lpthread */ #include <time.h> #include <errno.h> #include <stdio.h> #include <unistd.h> #include <assert.h> #include <string.h> #include <stdarg.h> #include <pthread.h> #include "locking-container.hpp" //use this definition if you want the simple test #define THREAD_TYPE thread //use this definition if you want the multi-lock test //#define THREAD_TYPE thread_multi //(probably better as arguments, but I'm too lazy right now) #define THREADS 10 #define TIME 30 //(if you set either of these to 'false', the threads will gradually die off) #define READ_BLOCK true #define WRITE_BLOCK true //the data being protected (initialize the 'int' to 'THREADS') typedef locking_container <int> protected_int; static protected_int my_data(THREADS); //(used by 'thread_multi') static protected_int my_data2; static null_container multi_lock; static void send_output(const char *format, ...); static void *thread(void *nv); static void *thread_multi(void *nv); int main() { //create some threads pthread_t threads[THREADS]; for (long i = 0; (unsigned) i < sizeof threads / sizeof(pthread_t); i++) { send_output("start %li\n", i); threads[i] = pthread_t(); if (pthread_create(threads + i, NULL, &THREAD_TYPE, (void*) i) != 0) { send_output("error: %s\n", strerror(errno)); } } //wait for them to do some stuff sleep(TIME); //the threads exit when the value goes below 0 { protected_int::write_proxy write = my_data.get_write(); //(no clean way to exit if the container can't be locked) assert(write); *write = -1; } //<-- proxy goes out of scope and unlocks 'my_data' here (you can also 'write.clear()') for (long i = 0; (unsigned) i < sizeof threads / sizeof(pthread_t); i++) { send_output("?join %li\n", i); pthread_join(threads[i], NULL); send_output("+join %li\n", i); } } //a print function that ensures we have exclusive access to the output static void send_output(const char *format, ...) { //(there is no reasonable reason to allow multiple locks at once.) typedef locking_container <FILE*, w_lock> protected_out; //(this is local so that it can't be involved in a deadlock) static protected_out stdout2(stdout); va_list ap; va_start(ap, format); //NOTE: authorization isn't important here because it's not possible for the //caller to lock another container while it holds a lock on 'stdout2'; //deadlocks aren't an issue with respect to 'stdout2' protected_out::write_proxy write = stdout2.get_write(); if (!write) return; vfprintf(*write, format, ap); } //a simple thread for repeatedly accessing the data static void *thread(void *nv) { //(cancelation can be messy...) if (pthread_setcancelstate(PTHREAD_CANCEL_DISABLE, NULL) != 0) return NULL; //get an authorization object, to prevent deadlocks //NOTE: for the most part you should be able to use any authorization type //with any lock type, but the behavior will be the stricter of the two lock_auth_base::auth_type auth(protected_int::new_auth()); long n = (long) nv, counter = 0; struct timespec wait = { 0, (10 + n) * 10 * 1000 * 1000 }; nanosleep(&wait, NULL); //loop through reading and writing forever while (true) { //read a bunch of times for (int i = 0; i < THREADS + n; i++) { send_output("?read %li\n", n); protected_int::read_proxy read = my_data.get_read_auth(auth, READ_BLOCK); if (!read) { send_output("!read %li\n", n); return NULL; } send_output("+read %li (%i) -> %i\n", n, read.last_lock_count(), *read); send_output("@read %li %i\n", n, !!my_data.get_read_auth(auth, READ_BLOCK)); if (*read < 0) { send_output("counter %li %i\n", n, counter); return NULL; } //(sort of like a contest, to see how many times each thread reads its own number) if (*read == n) ++counter; nanosleep(&wait, NULL); read.clear(); send_output("-read %li\n", n); nanosleep(&wait, NULL); } //write once send_output("?write %li\n", n); protected_int::write_proxy write = my_data.get_write_auth(auth, WRITE_BLOCK); if (!write) { send_output("!write %li\n", n); return NULL; } send_output("+write %li (%i)\n", n, write.last_lock_count()); send_output("@write %li %i\n", n, !!my_data.get_write_auth(auth, WRITE_BLOCK)); if (*write < 0) { send_output("counter %li %i\n", n, counter); return NULL; } *write = n; nanosleep(&wait, NULL); write.clear(); send_output("-write %li\n", n); nanosleep(&wait, NULL); } } //a more complicated thread that requires deadlock prevention, but multiple write locks at once static void *thread_multi(void *nv) { //NOTE: blocking system calls are still cancelation points, so threads could //exit while waiting for a lock! if (pthread_setcancelstate(PTHREAD_CANCEL_DISABLE, NULL) != 0) return NULL; //NOTE: multi-locking will work with either 'lock_auth <w_lock>' or //'lock_auth <rw_lock>'; however, 'lock_auth <w_lock>' will prevent a thread //from holding mutiple read locks at a time when that thread doesn't hold the //multi-lock. protected_int::auth_type auth(new lock_auth <rw_lock>); long n = (long) nv, success = 0, failure = 0; struct timespec wait = { 0, (10 + n) * 1 * 1000 * 1000 }; nanosleep(&wait, NULL); while (true) { for (int i = 0; i < THREADS + n; i++) { send_output("?read0 %li\n", n); protected_int::read_proxy read0 = my_data.get_read_multi(multi_lock, auth); if (!read0) { send_output("!read0 %li\n", n); return NULL; } send_output("+read0 %li (%i) -> %i\n", n, read0.last_lock_count(), *read0); if (*read0 < 0) { send_output("diff %li %i %i\n", n, success, -failure); return NULL; } nanosleep(&wait, NULL); //NOTE: if the auth. type is 'lock_auth <w_lock>', this second read lock //will always fail because 'multi_lock' is already in use! (this is because //'lock_auth <w_lock>' records the lock above as a write lock; when an //auth. object holds a write lock, it can only obtain new read or write //locks if the container to be locked has no other locks.) send_output("?read1 %li\n", n); protected_int::read_proxy read1 = my_data2.get_read_multi(multi_lock, auth); if (!read1) { //(track the number of successes vs. failures for 'read1') ++failure; send_output("!read1 %li\n", n); //NOTE: due to deadlock prevention, 'auth' will reject a lock if another //thread is waiting for a write lock for 'multi_lock' because this //thread already holds a read lock (on 'my_data'). (this could easily //lead to a deadlock if 'get_read_auth' above blocked.) this isn't a //catastrophic error, so we just skip the operation here. } else { ++success; send_output("+read1 %li (%i) -> %i\n", n, read1.last_lock_count(), *read1); nanosleep(&wait, NULL); read1.clear(); send_output("-read1 %li\n", n); } read0.clear(); send_output("-read0 %li\n", n); nanosleep(&wait, NULL); send_output("?write %li\n", n); protected_int::write_proxy write = my_data.get_write_multi(multi_lock, auth); if (!write) { send_output("!write %li\n", n); //(this thread has no locks at this point, so 'get_write_auth' above //should simply block if another thread is waiting for (or has) a write //lock on 'multi_lock'. a NULL return is therefore an error.) return NULL; } send_output("+write %li (%i)\n", n, write.last_lock_count()); if (*write < 0) { send_output("diff %li %i %i\n", n, success, -failure); return NULL; } *write = n; nanosleep(&wait, NULL); write.clear(); send_output("-write %li\n", n); nanosleep(&wait, NULL); } //get a write lock on 'multi_lock'. this blocks until all other locks have //been released (provided they were obtained with 'get_write_auth' or //'get_read_auth' using 'multi_lock'). this is mostly a way to appease //'auth', because 'auth' rejects a lock when a deadlock is possible. //NOTE: the lock will be rejected without blocking if this thread holds a //lock on another object, because a deadlock could otherwise happen! send_output("?multi0 %li\n", n); null_container::write_proxy multi = multi_lock.get_write_auth(auth); if (!multi) { send_output("!multi0 %li\n", n); return NULL; } send_output("+multi0 %li\n", n); //NOTE: even though this thread holds a write lock on 'multi_lock', it will //still allow new read locks from this thread. this is why 'get_write_multi' //can be used below. //NOTE: even if the auth. type is 'lock_auth <w_lock>', this thread should //be able to obtain multiple write locks, since the containers aren't being //used by any other threads (thanks to 'multi_lock'). send_output("?multi1 %li\n", n); protected_int::write_proxy write1 = my_data.get_write_multi(multi_lock, auth); if (!write1) { send_output("!multi1 %li\n", n); return NULL; } send_output("+multi1 %li\n", n); if (*write1 < 0) return NULL; //NOTE: this second write lock is only possible because this thread's write //lock on 'multi_lock' ensures that nothing else currently holds a lock on //'my_data2'. in fact, that's the only purpose of using 'multi_lock'! send_output("?multi2 %li\n", n); protected_int::write_proxy write2 = my_data2.get_write_multi(multi_lock, auth); if (!write2) { send_output("!multi2 %li\n", n); return NULL; } send_output("+multi2 %li\n", n); //NOTE: since 'get_write_multi' keeps track of new locks on 'my_data' and //'my_data2', the write lock on 'multi_lock' can be cleared. this allows //other threads to access those objects as they become free again. multi.clear(); send_output("-multi0 %li\n", n); *write1 = *write2 = 100 + n; nanosleep(&wait, NULL); write2.clear(); send_output("-multi2 %li\n", n); write1.clear(); send_output("-multi1 %li\n", n); } } <commit_msg>changed output lock type to dumb_lock for test program<commit_after>/* This is both a sort of unit test, and a demonstration of how to use deadlock * prevention. * * Suggested compilation command: * c++ -Wall -pedantic -std=c++11 test.cpp -o test -lpthread */ #include <time.h> #include <errno.h> #include <stdio.h> #include <unistd.h> #include <assert.h> #include <string.h> #include <stdarg.h> #include <pthread.h> #include "locking-container.hpp" //use this definition if you want the simple test #define THREAD_TYPE thread //use this definition if you want the multi-lock test //#define THREAD_TYPE thread_multi //(probably better as arguments, but I'm too lazy right now) #define THREADS 10 #define TIME 30 //(if you set either of these to 'false', the threads will gradually die off) #define READ_BLOCK true #define WRITE_BLOCK true //the data being protected (initialize the 'int' to 'THREADS') typedef locking_container <int> protected_int; static protected_int my_data(THREADS); //(used by 'thread_multi') static protected_int my_data2; static null_container multi_lock; static void send_output(const char *format, ...); static void *thread(void *nv); static void *thread_multi(void *nv); int main() { //create some threads pthread_t threads[THREADS]; for (long i = 0; (unsigned) i < sizeof threads / sizeof(pthread_t); i++) { send_output("start %li\n", i); threads[i] = pthread_t(); if (pthread_create(threads + i, NULL, &THREAD_TYPE, (void*) i) != 0) { send_output("error: %s\n", strerror(errno)); } } //wait for them to do some stuff sleep(TIME); //the threads exit when the value goes below 0 { protected_int::write_proxy write = my_data.get_write(); //(no clean way to exit if the container can't be locked) assert(write); *write = -1; } //<-- proxy goes out of scope and unlocks 'my_data' here (you can also 'write.clear()') for (long i = 0; (unsigned) i < sizeof threads / sizeof(pthread_t); i++) { send_output("?join %li\n", i); pthread_join(threads[i], NULL); send_output("+join %li\n", i); } } //a print function that ensures we have exclusive access to the output static void send_output(const char *format, ...) { //(there is no reasonable reason to allow multiple locks at once.) typedef locking_container <FILE*, dumb_lock> protected_out; //(this is local so that it can't be involved in a deadlock) static protected_out stdout2(stdout); va_list ap; va_start(ap, format); //NOTE: authorization isn't important here because it's not possible for the //caller to lock another container while it holds a lock on 'stdout2'; //deadlocks aren't an issue with respect to 'stdout2' protected_out::write_proxy write = stdout2.get_write(); if (!write) return; vfprintf(*write, format, ap); } //a simple thread for repeatedly accessing the data static void *thread(void *nv) { //(cancelation can be messy...) if (pthread_setcancelstate(PTHREAD_CANCEL_DISABLE, NULL) != 0) return NULL; //get an authorization object, to prevent deadlocks //NOTE: for the most part you should be able to use any authorization type //with any lock type, but the behavior will be the stricter of the two lock_auth_base::auth_type auth(protected_int::new_auth()); long n = (long) nv, counter = 0; struct timespec wait = { 0, (10 + n) * 10 * 1000 * 1000 }; nanosleep(&wait, NULL); //loop through reading and writing forever while (true) { //read a bunch of times for (int i = 0; i < THREADS + n; i++) { send_output("?read %li\n", n); protected_int::read_proxy read = my_data.get_read_auth(auth, READ_BLOCK); if (!read) { send_output("!read %li\n", n); return NULL; } send_output("+read %li (%i) -> %i\n", n, read.last_lock_count(), *read); send_output("@read %li %i\n", n, !!my_data.get_read_auth(auth, READ_BLOCK)); if (*read < 0) { send_output("counter %li %i\n", n, counter); return NULL; } //(sort of like a contest, to see how many times each thread reads its own number) if (*read == n) ++counter; nanosleep(&wait, NULL); read.clear(); send_output("-read %li\n", n); nanosleep(&wait, NULL); } //write once send_output("?write %li\n", n); protected_int::write_proxy write = my_data.get_write_auth(auth, WRITE_BLOCK); if (!write) { send_output("!write %li\n", n); return NULL; } send_output("+write %li (%i)\n", n, write.last_lock_count()); send_output("@write %li %i\n", n, !!my_data.get_write_auth(auth, WRITE_BLOCK)); if (*write < 0) { send_output("counter %li %i\n", n, counter); return NULL; } *write = n; nanosleep(&wait, NULL); write.clear(); send_output("-write %li\n", n); nanosleep(&wait, NULL); } } //a more complicated thread that requires deadlock prevention, but multiple write locks at once static void *thread_multi(void *nv) { //NOTE: blocking system calls are still cancelation points, so threads could //exit while waiting for a lock! if (pthread_setcancelstate(PTHREAD_CANCEL_DISABLE, NULL) != 0) return NULL; //NOTE: multi-locking will work with either 'lock_auth <w_lock>' or //'lock_auth <rw_lock>'; however, 'lock_auth <w_lock>' will prevent a thread //from holding mutiple read locks at a time when that thread doesn't hold the //multi-lock. protected_int::auth_type auth(new lock_auth <rw_lock>); long n = (long) nv, success = 0, failure = 0; struct timespec wait = { 0, (10 + n) * 1 * 1000 * 1000 }; nanosleep(&wait, NULL); while (true) { for (int i = 0; i < THREADS + n; i++) { send_output("?read0 %li\n", n); protected_int::read_proxy read0 = my_data.get_read_multi(multi_lock, auth); if (!read0) { send_output("!read0 %li\n", n); return NULL; } send_output("+read0 %li (%i) -> %i\n", n, read0.last_lock_count(), *read0); if (*read0 < 0) { send_output("diff %li %i %i\n", n, success, -failure); return NULL; } nanosleep(&wait, NULL); //NOTE: if the auth. type is 'lock_auth <w_lock>', this second read lock //will always fail because 'multi_lock' is already in use! (this is because //'lock_auth <w_lock>' records the lock above as a write lock; when an //auth. object holds a write lock, it can only obtain new read or write //locks if the container to be locked has no other locks.) send_output("?read1 %li\n", n); protected_int::read_proxy read1 = my_data2.get_read_multi(multi_lock, auth); if (!read1) { //(track the number of successes vs. failures for 'read1') ++failure; send_output("!read1 %li\n", n); //NOTE: due to deadlock prevention, 'auth' will reject a lock if another //thread is waiting for a write lock for 'multi_lock' because this //thread already holds a read lock (on 'my_data'). (this could easily //lead to a deadlock if 'get_read_auth' above blocked.) this isn't a //catastrophic error, so we just skip the operation here. } else { ++success; send_output("+read1 %li (%i) -> %i\n", n, read1.last_lock_count(), *read1); nanosleep(&wait, NULL); read1.clear(); send_output("-read1 %li\n", n); } read0.clear(); send_output("-read0 %li\n", n); nanosleep(&wait, NULL); send_output("?write %li\n", n); protected_int::write_proxy write = my_data.get_write_multi(multi_lock, auth); if (!write) { send_output("!write %li\n", n); //(this thread has no locks at this point, so 'get_write_auth' above //should simply block if another thread is waiting for (or has) a write //lock on 'multi_lock'. a NULL return is therefore an error.) return NULL; } send_output("+write %li (%i)\n", n, write.last_lock_count()); if (*write < 0) { send_output("diff %li %i %i\n", n, success, -failure); return NULL; } *write = n; nanosleep(&wait, NULL); write.clear(); send_output("-write %li\n", n); nanosleep(&wait, NULL); } //get a write lock on 'multi_lock'. this blocks until all other locks have //been released (provided they were obtained with 'get_write_auth' or //'get_read_auth' using 'multi_lock'). this is mostly a way to appease //'auth', because 'auth' rejects a lock when a deadlock is possible. //NOTE: the lock will be rejected without blocking if this thread holds a //lock on another object, because a deadlock could otherwise happen! send_output("?multi0 %li\n", n); null_container::write_proxy multi = multi_lock.get_write_auth(auth); if (!multi) { send_output("!multi0 %li\n", n); return NULL; } send_output("+multi0 %li\n", n); //NOTE: even though this thread holds a write lock on 'multi_lock', it will //still allow new read locks from this thread. this is why 'get_write_multi' //can be used below. //NOTE: even if the auth. type is 'lock_auth <w_lock>', this thread should //be able to obtain multiple write locks, since the containers aren't being //used by any other threads (thanks to 'multi_lock'). send_output("?multi1 %li\n", n); protected_int::write_proxy write1 = my_data.get_write_multi(multi_lock, auth); if (!write1) { send_output("!multi1 %li\n", n); return NULL; } send_output("+multi1 %li\n", n); if (*write1 < 0) return NULL; //NOTE: this second write lock is only possible because this thread's write //lock on 'multi_lock' ensures that nothing else currently holds a lock on //'my_data2'. in fact, that's the only purpose of using 'multi_lock'! send_output("?multi2 %li\n", n); protected_int::write_proxy write2 = my_data2.get_write_multi(multi_lock, auth); if (!write2) { send_output("!multi2 %li\n", n); return NULL; } send_output("+multi2 %li\n", n); //NOTE: since 'get_write_multi' keeps track of new locks on 'my_data' and //'my_data2', the write lock on 'multi_lock' can be cleared. this allows //other threads to access those objects as they become free again. multi.clear(); send_output("-multi0 %li\n", n); *write1 = *write2 = 100 + n; nanosleep(&wait, NULL); write2.clear(); send_output("-multi2 %li\n", n); write1.clear(); send_output("-multi1 %li\n", n); } } <|endoftext|>
<commit_before>#include <locale> #include <string.h> #include <unistd.h> #include <assert.h> #include "ctext.h" int8_t my_event(ctext *context, ctext_event event) { /* switch(event) { case CTEXT_SCROLL: printf("< Scroll >"); break; case CTEXT_CLEAR: printf("< Clear >"); break; case CTEXT_DATA: printf("< Data >"); break; } */ return 0; } int main(int argc, char **argv ){ FILE *pDebug; int speed = 450000; int16_t x = 0; int16_t y = 0; int amount = 0; float perc; locale::global(locale("en_US.utf8")); initscr(); cbreak(); curs_set(0); WINDOW *local_win; ctext_config config; pDebug = fopen("debug1.txt", "a"); local_win = newwin(9, 100, 5, 5); start_color(); ctext ct(local_win); // get the default config ct.get_config(&config); // add my handler config.m_on_event = my_event; //config.m_bounding_box = true; config.m_buffer_size = 20; config.m_scroll_on_append = true; config.m_do_wrap = true; //config.m_append_top = true; // set the config back ct.set_config(&config); attr_t attrs; short color_pair_number; for(x = 0; x < 200; x++) { init_pair(x, x, 0); /* wattr_on(local_win, COLOR_PAIR(x), 0); wattr_get(local_win, &attrs, &color_pair_number, 0); //printf("%x %x ", attrs,color_pair_number); wattr_off(local_win, COLOR_PAIR(x), 0); //wattr_on(local_win, COLOR_PAIR(x), 0); wattr_on(local_win, COLOR_PAIR(color_pair_number), 0); wattr_get(local_win, &attrs, &color_pair_number, 0); printf("%x %x\r\n", attrs,color_pair_number); wattr_off(local_win, COLOR_PAIR(x), 0); mvwaddwstr(local_win, 0, x, L"h"); wattr_off(local_win, COLOR_PAIR(x), 0); wrefresh(local_win); usleep(speed / 200); */ } char buffer[32], *ptr; int color = 0, round; ct.ob_start(); for(y = 0; y < 150; y++) { x = y % 50; for(round = 0; round < 9; round++) { wattr_on(local_win, COLOR_PAIR(color % 200), 0); ct.printf("%c....", (color % 26) + 'A' ); wstandend(local_win); //wattr_off(local_win, COLOR_PAIR(color % 200), 0); color++; } wattr_on(local_win, COLOR_PAIR(x * 3 + 1), 0); ct.printf("%c%c%c\n", x + 'A', x + 'A', x + 'A'); wstandend(local_win); //usleep(speed / 50); /* for(ptr = buffer; *ptr; ptr++) { ct.putchar((char)*ptr); usleep(speed / 15); } */ } ct.ob_end(); ct.redraw(); for(x = 0; x < 50; x++) { //ct.right(); ct.up(); usleep(speed); } for(x = 0; x < 20; x++) { ct.get_offset_percent(&perc); fprintf(pDebug, "%f\n", perc); fflush(pDebug); ct.left(); ct.down(); usleep(speed); } fclose(pDebug); /* for(x = 0; x < 18; x++) { amount = ct.clear(1); if(x < 15) { assert(amount == 1); } else { assert(amount == 0); } usleep(speed); } */ endwin(); return 0; } <commit_msg>page_up/page_down test<commit_after>#include <locale> #include <string.h> #include <unistd.h> #include <assert.h> #include "ctext.h" int8_t my_event(ctext *context, ctext_event event) { /* switch(event) { case CTEXT_SCROLL: printf("< Scroll >"); break; case CTEXT_CLEAR: printf("< Clear >"); break; case CTEXT_DATA: printf("< Data >"); break; } */ return 0; } int main(int argc, char **argv ){ FILE *pDebug; int speed = 450000; int16_t x = 0; int16_t y = 0; int amount = 0; float perc; locale::global(locale("en_US.utf8")); initscr(); cbreak(); curs_set(0); WINDOW *local_win; ctext_config config; pDebug = fopen("debug1.txt", "a"); local_win = newwin(9, 100, 5, 5); start_color(); ctext ct(local_win); // get the default config ct.get_config(&config); // add my handler config.m_on_event = my_event; //config.m_bounding_box = true; config.m_buffer_size = 20; config.m_scroll_on_append = true; config.m_do_wrap = true; //config.m_append_top = true; // set the config back ct.set_config(&config); attr_t attrs; short color_pair_number; for(x = 0; x < 200; x++) { init_pair(x, x, 0); /* wattr_on(local_win, COLOR_PAIR(x), 0); wattr_get(local_win, &attrs, &color_pair_number, 0); //printf("%x %x ", attrs,color_pair_number); wattr_off(local_win, COLOR_PAIR(x), 0); //wattr_on(local_win, COLOR_PAIR(x), 0); wattr_on(local_win, COLOR_PAIR(color_pair_number), 0); wattr_get(local_win, &attrs, &color_pair_number, 0); printf("%x %x\r\n", attrs,color_pair_number); wattr_off(local_win, COLOR_PAIR(x), 0); mvwaddwstr(local_win, 0, x, L"h"); wattr_off(local_win, COLOR_PAIR(x), 0); wrefresh(local_win); usleep(speed / 200); */ } char buffer[32], *ptr; int color = 0, round; ct.ob_start(); for(y = 0; y < 150; y++) { x = y % 50; ct.printf("%4d", y); for(round = 0; round < 9; round++) { wattr_on(local_win, COLOR_PAIR(color % 200), 0); ct.printf("%c....", (color % 26) + 'A' ); wstandend(local_win); //wattr_off(local_win, COLOR_PAIR(color % 200), 0); color++; } wattr_on(local_win, COLOR_PAIR(x * 3 + 1), 0); ct.printf("%c%c%c\n", x + 'A', x + 'A', x + 'A'); wstandend(local_win); //usleep(speed / 50); /* for(ptr = buffer; *ptr; ptr++) { ct.putchar((char)*ptr); usleep(speed / 15); } */ } ct.ob_end(); for(x = 0; x < 50; x++) { //ct.right(); ct.page_up(); usleep(speed * 1); ct.page_down(); usleep(speed * 1); } for(x = 0; x < 20; x++) { ct.get_offset_percent(&perc); fprintf(pDebug, "%f\n", perc); fflush(pDebug); ct.left(); ct.page_down(); usleep(speed); } fclose(pDebug); /* for(x = 0; x < 18; x++) { amount = ct.clear(1); if(x < 15) { assert(amount == 1); } else { assert(amount == 0); } usleep(speed); } */ endwin(); return 0; } <|endoftext|>
<commit_before>// Copyright (C) 2012, Luis Pedro Coelho <luis@luispedro.org> // License: MIT #include <iostream> #include <memory> #include <cmath> #include <random> #include <cassert> #include <eigen3/Eigen/Dense> using namespace Eigen; extern "C" { #include <Python.h> #include <numpy/ndarrayobject.h> } namespace { template <typename T> int random_int(T& random, const int max) { std::uniform_int_distribution<int> dist(0, max - 1); return dist(random); } inline float soft(float val, float lam) { return copysign(fdim(fabs(val), lam), val); } typedef Map<Matrix<float, Dynamic, Dynamic, RowMajor>, Aligned> MapXAf; struct lasso_solver { lasso_solver(const MapXAf& X, const MapXAf& Y, const MapXAf& W, MapXAf& B, const int max_iter, const float lam, int maxnops=-1, const float eps=1e-15) :X(X) ,Y(Y) ,W(W) ,B(B) ,max_iter(max_iter) ,maxnops(maxnops == -1 ? 2*B.size() : maxnops) ,lam(lam) ,eps(eps) { } void next_coords(int& i, int& j) { ++j; if (j == B.cols()) { j = 0; ++i; if (i == B.rows()) i = 0; } } int solve() { MatrixXf residuals; int nops = 0; int i = 0; int j = -1; for (int it = 0; it != max_iter; ++it) { // This resets the residuals matrix to the real values to avoid drift due to approximations if (!(it % 512)) residuals = Y - B*X; this->next_coords(i, j); // We now set βᵢⱼ holding everything else fixed. This comes down // to a very simple 1-dimensional problem. // We remember the current value in order to compute update below const float prev = B(i,j); float x2 = 0.0; float xy = 0.0; for (int k = 0, cols = Y.cols(); k != cols; ++k) { x2 += W(i,k)*X(j,k)*X(j,k); xy += W(i,k)*X(j,k)*residuals(i,k); } const float raw_step = (x2 == 0. ? 0. : (xy/x2)); const float best = soft(prev + raw_step, lam); if (fabs(best - prev) < eps) { ++nops; if (nops > maxnops) return it; } else { const float step = best - prev; assert(!std::isnan(best)); nops = 0; B(i,j) = best; residuals.row(i) -= step*X.row(j); } } return max_iter; } std::mt19937 r; const MapXAf& X; const MapXAf& Y; const MapXAf& W; MapXAf& B; const int max_iter; const int maxnops; const float lam; const float eps; }; MapXAf as_eigen(PyArrayObject* arr) { assert(PyArray_EquivTypenums(PyArray_TYPE(arr), NPY_FLOAT32)); return MapXAf( static_cast<float*>(PyArray_DATA(arr)), PyArray_DIM(arr, 0), PyArray_DIM(arr, 1)); } const char* errmsg = "INTERNAL ERROR"; PyObject* py_lasso(PyObject* self, PyObject* args) { PyArrayObject* X; PyArrayObject* Y; PyArrayObject* W; PyArrayObject* B; int max_iter; float lam; float eps; if (!PyArg_ParseTuple(args, "OOOOiff", &X, &Y, &W, &B, &max_iter, &lam, &eps)) return NULL; if (!PyArray_Check(X) || !PyArray_ISCARRAY_RO(X) || !PyArray_Check(Y) || !PyArray_ISCARRAY_RO(Y) || !PyArray_Check(W) || !PyArray_ISCARRAY_RO(W) || !PyArray_Check(B) || !PyArray_ISCARRAY(B) || !PyArray_EquivTypenums(PyArray_TYPE(X), NPY_FLOAT32) || !PyArray_EquivTypenums(PyArray_TYPE(Y), NPY_FLOAT32) || !PyArray_EquivTypenums(PyArray_TYPE(W), NPY_FLOAT32) || !PyArray_EquivTypenums(PyArray_TYPE(B), NPY_FLOAT32)) { PyErr_SetString(PyExc_RuntimeError,errmsg); return 0; } MapXAf mX = as_eigen(X); MapXAf mY = as_eigen(Y); MapXAf mW = as_eigen(W); MapXAf mB = as_eigen(B); max_iter *= mB.size(); lasso_solver solver(mX, mY, mW, mB, max_iter, lam, -1, eps); const int iters = solver.solve(); return Py_BuildValue("i", iters); } PyMethodDef methods[] = { {"lasso", py_lasso, METH_VARARGS , "Do NOT call directly.\n" }, {NULL, NULL,0,NULL}, }; const char * module_doc = "Internal Module.\n" "\n" "Do NOT use directly!\n"; } // namespace extern "C" void init_lasso() { import_array(); (void)Py_InitModule3("_lasso", methods, module_doc); } <commit_msg>ENH Accelaration<commit_after>// Copyright (C) 2012, Luis Pedro Coelho <luis@luispedro.org> // License: MIT #include <iostream> #include <memory> #include <cmath> #include <random> #include <cassert> #include <eigen3/Eigen/Dense> using namespace Eigen; extern "C" { #include <Python.h> #include <numpy/ndarrayobject.h> } namespace { template <typename T> int random_int(T& random, const int max) { std::uniform_int_distribution<int> dist(0, max - 1); return dist(random); } inline float soft(const float val, const float lam) { return std::copysign(std::fdim(std::fabs(val), lam), val); } typedef Map<Matrix<float, Dynamic, Dynamic, RowMajor>, Aligned> MapXAf; struct lasso_solver { lasso_solver(const MapXAf& X, const MapXAf& Y, const MapXAf& W, MapXAf& B, const int max_iter, const float lam, int maxnops=-1, const float eps=1e-15) :X(X) ,Y(Y) ,W(W) ,B(B) ,max_iter(max_iter) ,maxnops(maxnops == -1 ? 2*B.size() : maxnops) ,lam(lam) ,eps(eps) { } void next_coords(int& i, int& j) { ++j; if (j == B.cols()) { j = 0; ++i; if (i == B.rows()) i = 0; } } int solve() { MatrixXf residuals; int nops = 0; int i = 0; int j = -1; for (int it = 0; it != max_iter; ++it) { // This resets the residuals matrix to the real values to avoid drift due to approximations if (!(it % 512)) residuals = Y - B*X; this->next_coords(i, j); // We now set βᵢⱼ holding everything else fixed. This comes down // to a very simple 1-dimensional problem. // We remember the current value in order to compute update below const float prev = B(i,j); float x2 = 0.0; float xy = 0.0; for (int k = 0, cols = Y.cols(); k != cols; ++k) { x2 += W(i,k)*X(j,k)*X(j,k); xy += W(i,k)*X(j,k)*residuals(i,k); } const float raw_step = (x2 == 0. ? 0. : (xy/x2)); const float best = soft(prev + raw_step, lam); if (fabs(best - prev) < eps) { ++nops; if (nops > maxnops) return it; } else { const float step = best - prev; assert(!std::isnan(best)); nops = 0; B(i,j) = best; residuals.row(i) -= step*X.row(j); } } return max_iter; } std::mt19937 r; const MapXAf& X; const MapXAf& Y; const MapXAf& W; MapXAf& B; const int max_iter; const int maxnops; const float lam; const float eps; }; MapXAf as_eigen(PyArrayObject* arr) { assert(PyArray_EquivTypenums(PyArray_TYPE(arr), NPY_FLOAT32)); return MapXAf( static_cast<float*>(PyArray_DATA(arr)), PyArray_DIM(arr, 0), PyArray_DIM(arr, 1)); } const char* errmsg = "INTERNAL ERROR"; PyObject* py_lasso(PyObject* self, PyObject* args) { PyArrayObject* X; PyArrayObject* Y; PyArrayObject* W; PyArrayObject* B; int max_iter; float lam; float eps; if (!PyArg_ParseTuple(args, "OOOOiff", &X, &Y, &W, &B, &max_iter, &lam, &eps)) return NULL; if (!PyArray_Check(X) || !PyArray_ISCARRAY_RO(X) || !PyArray_Check(Y) || !PyArray_ISCARRAY_RO(Y) || !PyArray_Check(W) || !PyArray_ISCARRAY_RO(W) || !PyArray_Check(B) || !PyArray_ISCARRAY(B) || !PyArray_EquivTypenums(PyArray_TYPE(X), NPY_FLOAT32) || !PyArray_EquivTypenums(PyArray_TYPE(Y), NPY_FLOAT32) || !PyArray_EquivTypenums(PyArray_TYPE(W), NPY_FLOAT32) || !PyArray_EquivTypenums(PyArray_TYPE(B), NPY_FLOAT32)) { PyErr_SetString(PyExc_RuntimeError,errmsg); return 0; } MapXAf mX = as_eigen(X); MapXAf mY = as_eigen(Y); MapXAf mW = as_eigen(W); MapXAf mB = as_eigen(B); max_iter *= mB.size(); lasso_solver solver(mX, mY, mW, mB, max_iter, lam, -1, eps); const int iters = solver.solve(); return Py_BuildValue("i", iters); } PyMethodDef methods[] = { {"lasso", py_lasso, METH_VARARGS , "Do NOT call directly.\n" }, {NULL, NULL,0,NULL}, }; const char * module_doc = "Internal Module.\n" "\n" "Do NOT use directly!\n"; } // namespace extern "C" void init_lasso() { import_array(); (void)Py_InitModule3("_lasso", methods, module_doc); } <|endoftext|>
<commit_before>// $Id$ /* Copyright (c) 2007, Trustees of Leland Stanford Junior University 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 the Stanford University 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 <string> #include <sstream> #include <iostream> #include <iomanip> #include <stdlib.h> #include <assert.h> #include "random_utils.hpp" #include "iq_router_combined.hpp" IQRouterCombined::IQRouterCombined( const Configuration& config, Module *parent, string name, int id, int inputs, int outputs ) : IQRouterBase( config, parent, name, id, inputs, outputs ) { string alloc_type; string arb_type; int iters; // Allocate the allocators config.GetStr( "sw_allocator", alloc_type ); config.GetStr( "sw_alloc_arb_type", arb_type ); iters = config.GetInt("sw_alloc_iters"); if(iters == 0) iters = config.GetInt("alloc_iters"); _sw_allocator = Allocator::NewAllocator( this, "sw_allocator", alloc_type, _inputs*_input_speedup, _outputs*_output_speedup, iters, arb_type ); _vc_rr_offset = new int [_inputs*_input_speedup*_vcs]; for ( int i = 0; i < _inputs*_input_speedup*_vcs; ++i ) { _vc_rr_offset[i] = 0; } _sw_rr_offset = new int [_inputs*_input_speedup]; for ( int i = 0; i < _inputs*_input_speedup; ++i ) { _sw_rr_offset[i] = 0; } } IQRouterCombined::~IQRouterCombined( ) { delete _sw_allocator; delete [] _vc_rr_offset; delete [] _sw_rr_offset; } void IQRouterCombined::InternalStep( ) { _InputQueuing( ); _Route( ); _Alloc( ); for ( int input = 0; input < _inputs; ++input ) { for ( int vc = 0; vc < _vcs; ++vc ) { _vc[input][vc].AdvanceTime( ); } } _crossbar_pipe->Advance( ); _credit_pipe->Advance( ); _OutputQueuing( ); } void IQRouterCombined::_Alloc( ) { _sw_allocator->Clear( ); for(int input = 0; input < _inputs; ++input) { for(int s = 0; s < _input_speedup; ++s) { int expanded_input = s*_inputs + input; // Arbitrate (round-robin) between multiple requesting VCs at the same // input (handles the case when multiple VC's are requesting the same // output port) int vc = _sw_rr_offset[expanded_input]; for(int v = 0; v < _vcs; ++v) { // This continue acounts for the interleaving of VCs when input speedup // is used. // dub: Essentially, this skips loop iterations corresponding to those // VCs not in the current speedup set. The skipped iterations will be // handled in a different iteration of the enclosing loop over 's'. if((vc % _input_speedup) != s) { vc = (vc + 1) % _vcs; continue; } VC * cur_vc = &_vc[input][vc]; if(!cur_vc->Empty()) { switch(cur_vc->GetState()) { case VC::vc_alloc: { const OutputSet * route_set = cur_vc->GetRouteSet(); int output = _vc_rr_offset[expanded_input*_vcs+vc]; for(int output_index = 0; output_index < _outputs; ++output_index) { // When input_speedup > 1, the virtual channel buffers are // interleaved to create multiple input ports to the switch. // Similarily, the output ports are interleaved based on their // originating input when output_speedup > 1. assert(expanded_input == (vc%_input_speedup)*_inputs+input); int expanded_output = (input%_output_speedup)*_outputs + output; if((_switch_hold_in[expanded_input] == -1) && (_switch_hold_out[expanded_output] == -1)) { int vc_cnt = route_set->NumVCs(output); BufferState * dest_vc = &_next_vcs[output]; for(int vc_index = 0; vc_index < vc_cnt; ++vc_index) { int out_vc = route_set->GetVC(output, vc_index, NULL); if(dest_vc->IsAvailableFor(out_vc) && !dest_vc->IsFullFor(out_vc)) { // We could have requested this same input-output pair in // a previous iteration; only replace the previous request // if the current request has a higher priority (this is // default behavior of the allocators). Switch allocation // priorities are strictly determined by the packet // priorities. _sw_allocator->AddRequest(expanded_input, expanded_output, vc, cur_vc->GetPriority(), cur_vc->GetPriority()); Flit * f = cur_vc->FrontFlit(); if(f->watch) { cout << "VC requesting allocation at " << _fullname << " (input: " << input << ", vc: " << vc << ")" << endl << *f; } // we're done once we have found at least one suitable VC break; } } } output = (output + 1) % _outputs; } break; } case VC::active: { int output = cur_vc->GetOutputPort(); BufferState * dest_vc = &_next_vcs[output]; if(!dest_vc->IsFullFor(cur_vc->GetOutputVC())) { // When input_speedup > 1, the virtual channel buffers are // interleaved to create multiple input ports to the switch. // Similarily, the output ports are interleaved based on their // originating input when output_speedup > 1. assert(expanded_input == (vc%_input_speedup)*_inputs + input); int expanded_output = (input%_output_speedup)*_outputs + output; if((_switch_hold_in[expanded_input] == -1) && (_switch_hold_out[expanded_output] == -1)) { // We could have requested this same input-output pair in a // previous iteration; only replace the previous request if // the current request has a higher priority (this is default // behavior of the allocators). Switch allocation priorities // are strictly determined by the packet priorities. _sw_allocator->AddRequest(expanded_input, expanded_output, vc, cur_vc->GetPriority(), cur_vc->GetPriority()); } } break; } } } vc = (vc + 1) % _vcs; } } } _sw_allocator->Allocate(); // Winning flits cross the switch _crossbar_pipe->WriteAll(NULL); ////////////////////////////// // Switch Power Modelling // - Record Total Cycles // switchMonitor.cycle() ; for(int input = 0; input < _inputs; ++input) { Credit * c = NULL; for(int s = 0; s < _input_speedup; ++s) { int expanded_input = s*_inputs + input; int expanded_output; VC * cur_vc; int vc; if(_switch_hold_in[expanded_input] != -1) { assert(_switch_hold_in[expanded_input] >= 0); expanded_output = _switch_hold_in[expanded_input]; vc = _switch_hold_vc[expanded_input]; cur_vc = &_vc[input][vc]; if (cur_vc->Empty()) { // Cancel held match if VC is empty expanded_output = -1; } } else { expanded_output = _sw_allocator->OutputAssigned(expanded_input); if(expanded_output >= 0) { vc = _sw_allocator->ReadRequest(expanded_input, expanded_output); cur_vc = &_vc[input][vc]; } } if(expanded_output >= 0) { int output = expanded_output % _outputs; BufferState * dest_vc = &_next_vcs[output]; Flit * f = cur_vc->FrontFlit(); switch(cur_vc->GetState()) { case VC::vc_alloc: { const OutputSet * route_set = cur_vc->GetRouteSet(); int sel_prio = -1; int sel_vc = -1; int vc_cnt = route_set->NumVCs(output); for(int vc_index = 0; vc_index < vc_cnt; ++vc_index) { int out_prio; int out_vc = route_set->GetVC(output, vc_index, &out_prio); if(dest_vc->IsAvailableFor(out_vc) && !dest_vc->IsFullFor(out_vc) && (out_prio > sel_prio)) { sel_vc = out_vc; sel_prio = out_prio; } } // we should only get to this point if some VC requested allocation assert(sel_vc > -1); cur_vc->SetState(VC::active); cur_vc->SetOutput(output, sel_vc); dest_vc->TakeBuffer(sel_vc); _vc_rr_offset[expanded_input*_vcs+vc] = (output + 1) % _outputs; if ( f->watch ) { cout << "Granted VC allocation at " << _fullname << " (input: " << input << ", vc: " << vc << " )" << endl << *f; } } // NOTE: from here, we just fall through to the code for VC::active! case VC::active: if(_hold_switch_for_packet) { _switch_hold_in[expanded_input] = expanded_output; _switch_hold_vc[expanded_input] = vc; _switch_hold_out[expanded_output] = expanded_input; } assert(cur_vc->GetState() == VC::active); assert(!cur_vc->Empty()); assert(cur_vc->GetOutputPort() == output); dest_vc = &_next_vcs[output]; assert(!dest_vc->IsFullFor(cur_vc->GetOutputVC())); // Forward flit to crossbar and send credit back f = cur_vc->RemoveFlit(); f->hops++; // // Switch Power Modelling // switchMonitor.traversal(input, output, f); bufferMonitor.read(input, f); if(f->watch) { cout << "Forwarding flit through crossbar at " << _fullname << ":" << endl << *f << " input: " << expanded_input << " output: " << expanded_output << endl; } if (c == NULL) { c = _NewCredit(_vcs); } c->vc[c->vc_cnt] = f->vc; c->vc_cnt++; c->dest_router = f->from_router; f->vc = cur_vc->GetOutputVC(); dest_vc->SendingFlit(f); _crossbar_pipe->Write(f, expanded_output); if(f->tail) { cur_vc->SetState(VC::idle); _switch_hold_in[expanded_input] = -1; _switch_hold_vc[expanded_input] = -1; _switch_hold_out[expanded_output] = -1; } _sw_rr_offset[expanded_input] = (f->vc + 1) % _vcs; } } } _credit_pipe->Write(c, input); } } <commit_msg>beautify flit watch output for combined allocation router<commit_after>// $Id$ /* Copyright (c) 2007, Trustees of Leland Stanford Junior University 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 the Stanford University 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 <string> #include <sstream> #include <iostream> #include <iomanip> #include <stdlib.h> #include <assert.h> #include "random_utils.hpp" #include "iq_router_combined.hpp" IQRouterCombined::IQRouterCombined( const Configuration& config, Module *parent, string name, int id, int inputs, int outputs ) : IQRouterBase( config, parent, name, id, inputs, outputs ) { string alloc_type; string arb_type; int iters; // Allocate the allocators config.GetStr( "sw_allocator", alloc_type ); config.GetStr( "sw_alloc_arb_type", arb_type ); iters = config.GetInt("sw_alloc_iters"); if(iters == 0) iters = config.GetInt("alloc_iters"); _sw_allocator = Allocator::NewAllocator( this, "sw_allocator", alloc_type, _inputs*_input_speedup, _outputs*_output_speedup, iters, arb_type ); _vc_rr_offset = new int [_inputs*_input_speedup*_vcs]; for ( int i = 0; i < _inputs*_input_speedup*_vcs; ++i ) { _vc_rr_offset[i] = 0; } _sw_rr_offset = new int [_inputs*_input_speedup]; for ( int i = 0; i < _inputs*_input_speedup; ++i ) { _sw_rr_offset[i] = 0; } } IQRouterCombined::~IQRouterCombined( ) { delete _sw_allocator; delete [] _vc_rr_offset; delete [] _sw_rr_offset; } void IQRouterCombined::InternalStep( ) { _InputQueuing( ); _Route( ); _Alloc( ); for ( int input = 0; input < _inputs; ++input ) { for ( int vc = 0; vc < _vcs; ++vc ) { _vc[input][vc].AdvanceTime( ); } } _crossbar_pipe->Advance( ); _credit_pipe->Advance( ); _OutputQueuing( ); } void IQRouterCombined::_Alloc( ) { _sw_allocator->Clear( ); for(int input = 0; input < _inputs; ++input) { for(int s = 0; s < _input_speedup; ++s) { int expanded_input = s*_inputs + input; // Arbitrate (round-robin) between multiple requesting VCs at the same // input (handles the case when multiple VC's are requesting the same // output port) int vc = _sw_rr_offset[expanded_input]; for(int v = 0; v < _vcs; ++v) { // This continue acounts for the interleaving of VCs when input speedup // is used. // dub: Essentially, this skips loop iterations corresponding to those // VCs not in the current speedup set. The skipped iterations will be // handled in a different iteration of the enclosing loop over 's'. if((vc % _input_speedup) != s) { vc = (vc + 1) % _vcs; continue; } VC * cur_vc = &_vc[input][vc]; if(!cur_vc->Empty()) { switch(cur_vc->GetState()) { case VC::vc_alloc: { const OutputSet * route_set = cur_vc->GetRouteSet(); int output = _vc_rr_offset[expanded_input*_vcs+vc]; for(int output_index = 0; output_index < _outputs; ++output_index) { // When input_speedup > 1, the virtual channel buffers are // interleaved to create multiple input ports to the switch. // Similarily, the output ports are interleaved based on their // originating input when output_speedup > 1. assert(expanded_input == (vc%_input_speedup)*_inputs+input); int expanded_output = (input%_output_speedup)*_outputs + output; if((_switch_hold_in[expanded_input] == -1) && (_switch_hold_out[expanded_output] == -1)) { int vc_cnt = route_set->NumVCs(output); BufferState * dest_vc = &_next_vcs[output]; for(int vc_index = 0; vc_index < vc_cnt; ++vc_index) { int out_vc = route_set->GetVC(output, vc_index, NULL); if(dest_vc->IsAvailableFor(out_vc) && !dest_vc->IsFullFor(out_vc)) { // We could have requested this same input-output pair in // a previous iteration; only replace the previous request // if the current request has a higher priority (this is // default behavior of the allocators). Switch allocation // priorities are strictly determined by the packet // priorities. _sw_allocator->AddRequest(expanded_input, expanded_output, vc, cur_vc->GetPriority(), cur_vc->GetPriority()); Flit * f = cur_vc->FrontFlit(); if(f->watch) { cout << "VC requesting allocation at " << _fullname << " (input: " << input << ", vc: " << vc << ")" << endl << *f; } // we're done once we have found at least one suitable VC break; } } } output = (output + 1) % _outputs; } break; } case VC::active: { int output = cur_vc->GetOutputPort(); BufferState * dest_vc = &_next_vcs[output]; if(!dest_vc->IsFullFor(cur_vc->GetOutputVC())) { // When input_speedup > 1, the virtual channel buffers are // interleaved to create multiple input ports to the switch. // Similarily, the output ports are interleaved based on their // originating input when output_speedup > 1. assert(expanded_input == (vc%_input_speedup)*_inputs + input); int expanded_output = (input%_output_speedup)*_outputs + output; if((_switch_hold_in[expanded_input] == -1) && (_switch_hold_out[expanded_output] == -1)) { // We could have requested this same input-output pair in a // previous iteration; only replace the previous request if // the current request has a higher priority (this is default // behavior of the allocators). Switch allocation priorities // are strictly determined by the packet priorities. _sw_allocator->AddRequest(expanded_input, expanded_output, vc, cur_vc->GetPriority(), cur_vc->GetPriority()); } } break; } } } vc = (vc + 1) % _vcs; } } } _sw_allocator->Allocate(); // Winning flits cross the switch _crossbar_pipe->WriteAll(NULL); ////////////////////////////// // Switch Power Modelling // - Record Total Cycles // switchMonitor.cycle() ; for(int input = 0; input < _inputs; ++input) { Credit * c = NULL; for(int s = 0; s < _input_speedup; ++s) { int expanded_input = s*_inputs + input; int expanded_output; VC * cur_vc; int vc; if(_switch_hold_in[expanded_input] != -1) { assert(_switch_hold_in[expanded_input] >= 0); expanded_output = _switch_hold_in[expanded_input]; vc = _switch_hold_vc[expanded_input]; cur_vc = &_vc[input][vc]; if (cur_vc->Empty()) { // Cancel held match if VC is empty expanded_output = -1; } } else { expanded_output = _sw_allocator->OutputAssigned(expanded_input); if(expanded_output >= 0) { vc = _sw_allocator->ReadRequest(expanded_input, expanded_output); cur_vc = &_vc[input][vc]; } } if(expanded_output >= 0) { int output = expanded_output % _outputs; BufferState * dest_vc = &_next_vcs[output]; Flit * f = cur_vc->FrontFlit(); switch(cur_vc->GetState()) { case VC::vc_alloc: { const OutputSet * route_set = cur_vc->GetRouteSet(); int sel_prio = -1; int sel_vc = -1; int vc_cnt = route_set->NumVCs(output); for(int vc_index = 0; vc_index < vc_cnt; ++vc_index) { int out_prio; int out_vc = route_set->GetVC(output, vc_index, &out_prio); if(dest_vc->IsAvailableFor(out_vc) && !dest_vc->IsFullFor(out_vc) && (out_prio > sel_prio)) { sel_vc = out_vc; sel_prio = out_prio; } } // we should only get to this point if some VC requested allocation assert(sel_vc > -1); cur_vc->SetState(VC::active); cur_vc->SetOutput(output, sel_vc); dest_vc->TakeBuffer(sel_vc); _vc_rr_offset[expanded_input*_vcs+vc] = (output + 1) % _outputs; if ( f->watch ) { cout << "Granted VC allocation at " << _fullname << " (input: " << input << ", vc: " << vc << ")" << endl << *f; } } // NOTE: from here, we just fall through to the code for VC::active! case VC::active: if(_hold_switch_for_packet) { _switch_hold_in[expanded_input] = expanded_output; _switch_hold_vc[expanded_input] = vc; _switch_hold_out[expanded_output] = expanded_input; } assert(cur_vc->GetState() == VC::active); assert(!cur_vc->Empty()); assert(cur_vc->GetOutputPort() == output); dest_vc = &_next_vcs[output]; assert(!dest_vc->IsFullFor(cur_vc->GetOutputVC())); // Forward flit to crossbar and send credit back f = cur_vc->RemoveFlit(); f->hops++; // // Switch Power Modelling // switchMonitor.traversal(input, output, f); bufferMonitor.read(input, f); if(f->watch) { cout << "Forwarding flit through crossbar at " << _fullname << ":" << endl << *f << " input: " << expanded_input << " output: " << expanded_output << endl; } if (c == NULL) { c = _NewCredit(_vcs); } c->vc[c->vc_cnt] = f->vc; c->vc_cnt++; c->dest_router = f->from_router; f->vc = cur_vc->GetOutputVC(); dest_vc->SendingFlit(f); _crossbar_pipe->Write(f, expanded_output); if(f->tail) { cur_vc->SetState(VC::idle); _switch_hold_in[expanded_input] = -1; _switch_hold_vc[expanded_input] = -1; _switch_hold_out[expanded_output] = -1; } _sw_rr_offset[expanded_input] = (f->vc + 1) % _vcs; } } } _credit_pipe->Write(c, input); } } <|endoftext|>
<commit_before>/* * Copyright (c) 2016 Joseph Thomson * * 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. */ #pragma once #ifndef VIEW_HPP #define VIEW_HPP #include <functional> #include <iosfwd> #include <stdexcept> #include <utility> struct nullopt_t { constexpr explicit nullopt_t(int) {} }; constexpr nullopt_t nullopt{0}; class bad_optional_access : public std::logic_error { public: bad_optional_access() : std::logic_error( "Attempted to access the value of an uninitialized optional.") { } }; template <typename> class view; template <typename> class optional_view; template <typename T> constexpr T* get_pointer(view<T> const&) noexcept; template <typename T> constexpr T* get_pointer(optional_view<T> const&) noexcept; template <typename T> class view { public: using value_type = T; using const_type = view<T const>; private: T* target; template <typename U> static constexpr U* throw_if_null(U* p) { if (!p) { throw std::invalid_argument("Cannot convert null pointer to view."); } return p; } public: constexpr view(T& r) noexcept : target(&r) { } constexpr explicit view(T* p) : target(throw_if_null(p)) { } template <typename U, typename = std::enable_if_t<std::is_convertible<U*, T*>::value>> constexpr view(view<U> const& v) noexcept : target(get_pointer(v)) { } template <typename U, typename = std::enable_if_t<std::is_convertible<U*, T*>::value>> constexpr explicit view(optional_view<U> const& v) : target(throw_if_null(get_pointer(v))) { } constexpr T& operator*() const noexcept { return *target; } constexpr T* operator->() const noexcept { return target; } constexpr operator T&() const noexcept { return *target; } constexpr explicit operator T*() const noexcept { return target; } void swap(view& other) noexcept { using std::swap; swap(target, other.target); } }; template <typename T> void swap(view<T>& lhs, view<T>& rhs) { lhs.swap(rhs); } template <typename T1, typename T2> constexpr bool operator==(view<T1> const& lhs, view<T2> const& rhs) noexcept { return get_pointer(lhs) == get_pointer(rhs); } template <typename T1, typename T2> constexpr bool operator==(view<T1> const& lhs, T2 const& rhs) noexcept { return get_pointer(lhs) == &rhs; } template <typename T1, typename T2> constexpr bool operator==(T1 const& lhs, view<T2> const& rhs) noexcept { return &lhs == get_pointer(rhs); } template <typename T1, typename T2> constexpr bool operator!=(view<T1> const& lhs, view<T2> const& rhs) noexcept { return !(lhs == rhs); } template <typename T1, typename T2> constexpr bool operator!=(view<T1> const& lhs, T2 const& rhs) noexcept { return !(lhs == rhs); } template <typename T1, typename T2> constexpr bool operator!=(T1 const& lhs, view<T2> const& rhs) noexcept { return !(lhs == rhs); } template <typename T1, typename T2> constexpr bool operator<(view<T1> const& lhs, view<T2> const& rhs) noexcept { return std::less<std::common_type_t<T1*, T2*>>()(get_pointer(lhs), get_pointer(rhs)); } template <typename T1, typename T2> constexpr bool operator>(view<T1> const& lhs, view<T2> const& rhs) noexcept { return rhs < lhs; } template <typename T1, typename T2> constexpr bool operator<=(view<T1> const& lhs, view<T2> const& rhs) noexcept { return !(rhs < lhs); } template <typename T1, typename T2> constexpr bool operator>=(view<T1> const& lhs, view<T2> const& rhs) noexcept { return !(lhs < rhs); } template <typename T> class optional_view { public: using value_type = T; using const_type = optional_view<T const>; private: T* target; public: constexpr optional_view() noexcept : target() { } constexpr optional_view(nullopt_t) noexcept : target() { } constexpr optional_view(T& r) noexcept : target(&r) { } constexpr explicit optional_view(std::nullptr_t) noexcept : target(nullptr) { } constexpr explicit optional_view(T* p) noexcept : target(p) { } template <typename U, typename = std::enable_if_t<std::is_convertible<U*, T*>::value>> constexpr optional_view(optional_view<U> const& v) noexcept : target(get_pointer(v)) { } template <typename U, typename = std::enable_if_t<std::is_convertible<U*, T*>::value>> constexpr optional_view(view<U> const& v) noexcept : target(get_pointer(v)) { } constexpr explicit operator bool() const noexcept { return target != nullptr; } constexpr T& operator*() const noexcept { return *target; } constexpr T* operator->() const noexcept { return target; } constexpr explicit operator T&() const { return value(); } constexpr explicit operator T*() const noexcept { return target; } constexpr T& value() const { if (!target) { throw bad_optional_access(); } return *target; } template <typename U, typename T_ = T, std::enable_if_t<std::is_copy_constructible<T_>::value, int> = 0> constexpr T value_or(U&& default_value) const noexcept { return target ? *target : static_cast<T>(std::forward<U>(default_value)); } void swap(optional_view& other) noexcept { using std::swap; swap(target, other.target); } }; template <typename T> void swap(optional_view<T>& lhs, optional_view<T>& rhs) noexcept { lhs.swap(rhs); } template <typename T1, typename T2> constexpr bool operator==(optional_view<T1> const& lhs, optional_view<T2> const& rhs) noexcept { return get_pointer(lhs) == get_pointer(rhs); } template <typename T1, typename T2> constexpr bool operator==(optional_view<T1> const& lhs, view<T2> const& rhs) noexcept { return get_pointer(lhs) == get_pointer(rhs); } template <typename T1, typename T2> constexpr bool operator==(view<T1> const& lhs, optional_view<T2> const& rhs) noexcept { return get_pointer(lhs) == get_pointer(rhs); } template <typename T1, typename T2> constexpr bool operator==(optional_view<T1> const& lhs, T2 const& rhs) noexcept { return get_pointer(lhs) == &rhs; } template <typename T1, typename T2> constexpr bool operator==(T1 const& lhs, optional_view<T2> const& rhs) noexcept { return &lhs == get_pointer(rhs); } template <typename T> constexpr bool operator==(optional_view<T> const& lhs, nullopt_t) noexcept { return !lhs; } template <typename T> constexpr bool operator==(nullopt_t, optional_view<T> const& rhs) noexcept { return !rhs; } template <typename T1, typename T2> constexpr bool operator!=(optional_view<T1> const& lhs, optional_view<T2> const& rhs) noexcept { return !(lhs == rhs); } template <typename T1, typename T2> constexpr bool operator!=(optional_view<T1> const& lhs, view<T2> const& rhs) noexcept { return !(lhs == rhs); } template <typename T1, typename T2> constexpr bool operator!=(view<T1> const& lhs, optional_view<T2> const& rhs) noexcept { return !(lhs == rhs); } template <typename T1, typename T2> constexpr bool operator!=(optional_view<T1> const& lhs, T2 const& rhs) noexcept { return !(lhs == rhs); } template <typename T1, typename T2> constexpr bool operator!=(T1 const& lhs, optional_view<T2> const& rhs) noexcept { return !(lhs == rhs); } template <typename T> constexpr bool operator!=(optional_view<T> const& lhs, nullopt_t) noexcept { return !(lhs == nullopt); } template <typename T> constexpr bool operator!=(nullopt_t, optional_view<T> const& rhs) noexcept { return !(nullopt == rhs); } template <typename T1, typename T2> constexpr bool operator<(optional_view<T1> const& lhs, optional_view<T2> const& rhs) noexcept { return std::less<std::common_type_t<T1*, T2*>>()(get_pointer(lhs), get_pointer(rhs)); } template <typename T1, typename T2> constexpr bool operator>(optional_view<T1> const& lhs, optional_view<T2> const& rhs) noexcept { return rhs < lhs; } template <typename T1, typename T2> constexpr bool operator<=(optional_view<T1> const& lhs, optional_view<T2> const& rhs) noexcept { return !(rhs < lhs); } template <typename T1, typename T2> constexpr bool operator>=(optional_view<T1> const& lhs, optional_view<T2> const& rhs) noexcept { return !(lhs < rhs); } template <typename T> constexpr view<T> make_view(T& r) noexcept { return r; } template <typename T> constexpr optional_view<T> make_optional_view(T& r) noexcept { return r; } template <typename T, typename U> constexpr view<T> static_view_cast(view<U> const& v) noexcept { return static_cast<T&>(*v); } template <typename T, typename U> constexpr view<T> dynamic_view_cast(view<U> const& v) { return dynamic_cast<T&>(*v); } template <typename T, typename U> constexpr view<T> const_view_cast(view<U> const& v) noexcept { return const_cast<T&>(*v); } template <typename T, typename U> constexpr optional_view<T> static_view_cast(optional_view<U> const& v) noexcept { return optional_view<T>(static_cast<T*>(get_pointer(v))); } template <typename T, typename U> constexpr optional_view<T> dynamic_view_cast(optional_view<U> const& v) noexcept { return optional_view<T>(dynamic_cast<T*>(get_pointer(v))); } template <typename T, typename U> constexpr optional_view<T> const_view_cast(optional_view<U> const& v) noexcept { return optional_view<T>(const_cast<T*>(get_pointer(v))); } template <typename T> std::ostream& operator<<(std::ostream& s, view<T> const& v) { return s << get_pointer(v); } template <typename T> std::istream& operator>>(std::istream& s, view<T> const& v) { return get_pointer(v) >> s; } template <typename T> std::ostream& operator<<(std::ostream& s, optional_view<T> const& v) { return s << get_pointer(v); } template <typename T> std::istream& operator>>(std::istream& s, optional_view<T> const& v) { return get_pointer(v) >> s; } template <typename T> constexpr T* get_pointer(view<T> const& v) noexcept { return static_cast<T*>(v); } template <typename T> constexpr T* get_pointer(optional_view<T> const& v) noexcept { return static_cast<T*>(v); } namespace std { template <typename T> struct hash<view<T>> { constexpr std::size_t operator()(view<T> const& v) const noexcept { return hash<T*>()(get_pointer(v)); } }; template <typename T> struct hash<optional_view<T>> { constexpr std::size_t operator()(optional_view<T> const& v) const noexcept { return hash<T*>()(get_pointer(v)); } }; } // namespace std #endif // VIEW_HPP <commit_msg>Remove `optional_view(nullptr_t)` and rearrange functions.<commit_after>/* * Copyright (c) 2016 Joseph Thomson * * 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. */ #pragma once #ifndef VIEW_HPP #define VIEW_HPP #include <functional> #include <iosfwd> #include <stdexcept> #include <utility> //====================== // forward declarations //====================== template <typename> class view; template <typename> class optional_view; template <typename T> constexpr T* get_pointer(view<T> const&) noexcept; template <typename T> constexpr T* get_pointer(optional_view<T> const&) noexcept; //========= // nullopt //========= struct nullopt_t { constexpr explicit nullopt_t(int) noexcept {} }; constexpr nullopt_t nullopt{0}; //===================== // bad_optional_access //===================== class bad_optional_access : public std::logic_error { public: bad_optional_access() : std::logic_error( "Attempted to access the value of an uninitialized optional.") { } }; //====== // view //====== template <typename T> class view { public: using value_type = T; using const_type = view<T const>; private: T* target; template <typename U> static constexpr U* throw_if_null(U* p) { if (!p) { throw std::invalid_argument("Cannot convert null pointer to view."); } return p; } public: constexpr view(T& r) noexcept : target(&r) { } constexpr explicit view(T* p) : target(throw_if_null(p)) { } template <typename U, typename = std::enable_if_t<std::is_convertible<U*, T*>::value>> constexpr view(view<U> const& v) noexcept : target(get_pointer(v)) { } template <typename U, typename = std::enable_if_t<std::is_convertible<U*, T*>::value>> constexpr explicit view(optional_view<U> const& v) : target(throw_if_null(get_pointer(v))) { } constexpr T& operator*() const noexcept { return *target; } constexpr T* operator->() const noexcept { return target; } constexpr operator T&() const noexcept { return *target; } constexpr explicit operator T*() const noexcept { return target; } void swap(view& other) noexcept { using std::swap; swap(target, other.target); } }; template <typename T> constexpr view<T> make_view(T& r) noexcept { return r; } template <typename T, typename U> constexpr view<T> static_view_cast(view<U> const& v) noexcept { return static_cast<T&>(*v); } template <typename T, typename U> constexpr view<T> dynamic_view_cast(view<U> const& v) { return dynamic_cast<T&>(*v); } template <typename T, typename U> constexpr view<T> const_view_cast(view<U> const& v) noexcept { return const_cast<T&>(*v); } template <typename T> constexpr T* get_pointer(view<T> const& v) noexcept { return static_cast<T*>(v); } template <typename T> void swap(view<T>& lhs, view<T>& rhs) { lhs.swap(rhs); } template <typename T1, typename T2> constexpr bool operator==(view<T1> const& lhs, view<T2> const& rhs) noexcept { return get_pointer(lhs) == get_pointer(rhs); } template <typename T1, typename T2> constexpr bool operator==(view<T1> const& lhs, T2 const& rhs) noexcept { return get_pointer(lhs) == &rhs; } template <typename T1, typename T2> constexpr bool operator==(T1 const& lhs, view<T2> const& rhs) noexcept { return &lhs == get_pointer(rhs); } template <typename T1, typename T2> constexpr bool operator!=(view<T1> const& lhs, view<T2> const& rhs) noexcept { return !(lhs == rhs); } template <typename T1, typename T2> constexpr bool operator!=(view<T1> const& lhs, T2 const& rhs) noexcept { return !(lhs == rhs); } template <typename T1, typename T2> constexpr bool operator!=(T1 const& lhs, view<T2> const& rhs) noexcept { return !(lhs == rhs); } template <typename T1, typename T2> constexpr bool operator<(view<T1> const& lhs, view<T2> const& rhs) noexcept { return std::less<std::common_type_t<T1*, T2*>>()(get_pointer(lhs), get_pointer(rhs)); } template <typename T1, typename T2> constexpr bool operator>(view<T1> const& lhs, view<T2> const& rhs) noexcept { return rhs < lhs; } template <typename T1, typename T2> constexpr bool operator<=(view<T1> const& lhs, view<T2> const& rhs) noexcept { return !(rhs < lhs); } template <typename T1, typename T2> constexpr bool operator>=(view<T1> const& lhs, view<T2> const& rhs) noexcept { return !(lhs < rhs); } template <typename T> std::ostream& operator<<(std::ostream& s, view<T> const& v) { return s << get_pointer(v); } template <typename T> std::istream& operator>>(std::istream& s, view<T> const& v) { return get_pointer(v) >> s; } namespace std { template <typename T> struct hash<view<T>> { constexpr std::size_t operator()(view<T> const& v) const noexcept { return hash<T*>()(get_pointer(v)); } }; } // namespace std //=============== // optional_view //=============== template <typename T> class optional_view { public: using value_type = T; using const_type = optional_view<T const>; private: T* target; public: constexpr optional_view() noexcept : target() { } constexpr optional_view(nullopt_t) noexcept : target() { } constexpr optional_view(T& r) noexcept : target(&r) { } constexpr explicit optional_view(T* p) noexcept : target(p) { } template <typename U, typename = std::enable_if_t<std::is_convertible<U*, T*>::value>> constexpr optional_view(optional_view<U> const& v) noexcept : target(get_pointer(v)) { } template <typename U, typename = std::enable_if_t<std::is_convertible<U*, T*>::value>> constexpr optional_view(view<U> const& v) noexcept : target(get_pointer(v)) { } constexpr explicit operator bool() const noexcept { return target != nullptr; } constexpr T& operator*() const noexcept { return *target; } constexpr T* operator->() const noexcept { return target; } constexpr explicit operator T&() const { return value(); } constexpr explicit operator T*() const noexcept { return target; } constexpr T& value() const { if (!target) { throw bad_optional_access(); } return *target; } template <typename U, typename T_ = T, std::enable_if_t<std::is_copy_constructible<T_>::value, int> = 0> constexpr T value_or(U&& default_value) const noexcept { return target ? *target : static_cast<T>(std::forward<U>(default_value)); } void swap(optional_view& other) noexcept { using std::swap; swap(target, other.target); } }; template <typename T> constexpr optional_view<T> make_optional_view(T& r) noexcept { return r; } template <typename T, typename U> constexpr optional_view<T> static_view_cast(optional_view<U> const& v) noexcept { return optional_view<T>(static_cast<T*>(get_pointer(v))); } template <typename T, typename U> constexpr optional_view<T> dynamic_view_cast(optional_view<U> const& v) noexcept { return optional_view<T>(dynamic_cast<T*>(get_pointer(v))); } template <typename T, typename U> constexpr optional_view<T> const_view_cast(optional_view<U> const& v) noexcept { return optional_view<T>(const_cast<T*>(get_pointer(v))); } template <typename T> constexpr T* get_pointer(optional_view<T> const& v) noexcept { return static_cast<T*>(v); } template <typename T> void swap(optional_view<T>& lhs, optional_view<T>& rhs) noexcept { lhs.swap(rhs); } template <typename T1, typename T2> constexpr bool operator==(optional_view<T1> const& lhs, optional_view<T2> const& rhs) noexcept { return get_pointer(lhs) == get_pointer(rhs); } template <typename T1, typename T2> constexpr bool operator==(optional_view<T1> const& lhs, view<T2> const& rhs) noexcept { return get_pointer(lhs) == get_pointer(rhs); } template <typename T1, typename T2> constexpr bool operator==(view<T1> const& lhs, optional_view<T2> const& rhs) noexcept { return get_pointer(lhs) == get_pointer(rhs); } template <typename T1, typename T2> constexpr bool operator==(optional_view<T1> const& lhs, T2 const& rhs) noexcept { return get_pointer(lhs) == &rhs; } template <typename T1, typename T2> constexpr bool operator==(T1 const& lhs, optional_view<T2> const& rhs) noexcept { return &lhs == get_pointer(rhs); } template <typename T> constexpr bool operator==(optional_view<T> const& lhs, nullopt_t) noexcept { return !lhs; } template <typename T> constexpr bool operator==(nullopt_t, optional_view<T> const& rhs) noexcept { return !rhs; } template <typename T1, typename T2> constexpr bool operator!=(optional_view<T1> const& lhs, optional_view<T2> const& rhs) noexcept { return !(lhs == rhs); } template <typename T1, typename T2> constexpr bool operator!=(optional_view<T1> const& lhs, view<T2> const& rhs) noexcept { return !(lhs == rhs); } template <typename T1, typename T2> constexpr bool operator!=(view<T1> const& lhs, optional_view<T2> const& rhs) noexcept { return !(lhs == rhs); } template <typename T1, typename T2> constexpr bool operator!=(optional_view<T1> const& lhs, T2 const& rhs) noexcept { return !(lhs == rhs); } template <typename T1, typename T2> constexpr bool operator!=(T1 const& lhs, optional_view<T2> const& rhs) noexcept { return !(lhs == rhs); } template <typename T> constexpr bool operator!=(optional_view<T> const& lhs, nullopt_t) noexcept { return !(lhs == nullopt); } template <typename T> constexpr bool operator!=(nullopt_t, optional_view<T> const& rhs) noexcept { return !(nullopt == rhs); } template <typename T1, typename T2> constexpr bool operator<(optional_view<T1> const& lhs, optional_view<T2> const& rhs) noexcept { return std::less<std::common_type_t<T1*, T2*>>()(get_pointer(lhs), get_pointer(rhs)); } template <typename T1, typename T2> constexpr bool operator>(optional_view<T1> const& lhs, optional_view<T2> const& rhs) noexcept { return rhs < lhs; } template <typename T1, typename T2> constexpr bool operator<=(optional_view<T1> const& lhs, optional_view<T2> const& rhs) noexcept { return !(rhs < lhs); } template <typename T1, typename T2> constexpr bool operator>=(optional_view<T1> const& lhs, optional_view<T2> const& rhs) noexcept { return !(lhs < rhs); } template <typename T> std::ostream& operator<<(std::ostream& s, optional_view<T> const& v) { return s << get_pointer(v); } template <typename T> std::istream& operator>>(std::istream& s, optional_view<T> const& v) { return get_pointer(v) >> s; } namespace std { template <typename T> struct hash<optional_view<T>> { constexpr std::size_t operator()(optional_view<T> const& v) const noexcept { return hash<T*>()(get_pointer(v)); } }; } // namespace std #endif // VIEW_HPP <|endoftext|>
<commit_before>#include "InputItemWidget.hpp" #include <Wt/WLineEdit> #include <iostream> #include <boost/foreach.hpp> #include <Wt/Utils> #include <Wt/WIntValidator> #include <Wt/WPushButton> #include <Wt/Http/Client> #include <Wt/Http/Message> #include <Wt/WApplication> #include <boost/log/trivial.hpp> #include <fstream> #include <limits> #include "../application.hpp" /* class ShopParseException : public std::exception { public: ShopParseException };*/ InputItemWidget::InputItemWidget(ShopList shops, Wt::WContainerWidget *parent) :Wt::WContainerWidget(parent), shops(shops) { edit=new Wt::WLineEdit(this); edit->setPlaceholderText("Paste URL here"); countEdit=new Wt::WLineEdit(this); Wt::WIntValidator *val = new Wt::WIntValidator(); val->setBottom(0); val->setMandatory(true); countEdit->setValidator(val); countEdit->setPlaceholderText("count"); btn = new Wt::WPushButton("Add", this); btn->setStyleClass("btn-primary"); btn->clicked().connect(this,&InputItemWidget::changed); } void InputItemWidget::changed() { if(countEdit->validate()!=Wt::WValidator::Valid) { std::cout<<"invalid!\n"; return; } int count = boost::lexical_cast<int>(countEdit->text()); string newText = Wt::Utils::urlDecode(edit->text().toUTF8()); std::cout<<"changed to "<<newText<<"\n"; boost::smatch url_match; //boost::regex_search(edit->text().toUTF8(),m,shop->inputURLRegex); //boost::regex r{"ARTICLEID=(?<id>\\d+)"}; //boost::regex r{re->text().toUTF8()}; //for(auto shop=shops->begin();shop!=shops->end();shop++) bool found=false; BOOST_FOREACH(auto tuple, *shops) { auto shop=tuple.second; if(boost::regex_search(newText,url_match, shop->inputURLRegex)) { found=true; std::cout<<"match for shop "<<shop->name<<"\n"; std::cout<<"number: "<<url_match["number"]<<"\n"; std::cout<<"number2: "<<url_match["number2"]<<"\n"; std::map<string, string> urlMatches; if(url_match["number"].matched) urlMatches["number"]=url_match["number"]; if(url_match["number2"].matched) urlMatches["number2"]=url_match["number2"]; if(url_match["title"].matched) urlMatches["title"]=url_match["title"]; // get data from page Wt::Http::Client *client = new Wt::Http::Client(Wt::WApplication::instance()); client->setTimeout(10); client->setMaximumResponseSize(1024*1024); client->done().connect([ this, newText, url_match, shop, count, urlMatches ](boost::system::error_code err, const Wt::Http::Message& response, Wt::NoClass, Wt::NoClass, Wt::NoClass, Wt::NoClass) { std::cout<<"done()\n"; if(!err) { if(response.status() == 200) { std::cout<<"shop regexes:\n"; boost::smatch pageMatch; if(boost::regex_search(response.body(), pageMatch, shop->pageRegex)) { std::map<string, string> matches = urlMatches; // number if(pageMatch["number"].matched) { matches["number"]=pageMatch["number"]; } // number2 if(pageMatch["number2"].matched) { matches["number2"]=pageMatch["number2"]; } // price if(pageMatch["price"].matched) { matches["price"]=pageMatch["price"]; } // title if(pageMatch["title"].matched) { matches["title"]=pageMatch["title"]; } double price=std::numeric_limits<double>::quiet_NaN(); try { price = boost::lexical_cast<double>(matches["price"]); } catch(boost::bad_lexical_cast &) { std::cerr<<"unable to convert \""<<matches["price"]<<"\" to float\n"; try // try to fix "," as a comma separator { matches["price"].replace(matches["price"].find(','),1,{'.'}); std::cerr<<"trying with \""<<matches["price"]<<"\"\n"; price = boost::lexical_cast<double>(matches["price"]); } catch(boost::bad_lexical_cast &) {} } BOOST_FOREACH(auto m, matches) std::cout<<"matches[\""<<m.first<<"\"]=\""<<m.second<<"\"\n"; Session& dbSession = static_cast<ShareBuy*>(Wt::WApplication::instance())->dbSession; dbo::Transaction transaction(dbSession); PItem item = dbSession.add(new Item( shop->name, matches["number"], matches["number2"], matches["title"], newText, price, count)); item.modify()->user = dbSession.user(); transaction.commit(); _itemEntered.emit(); edit->setText(""); countEdit->setText(""); } else { BOOST_LOG_TRIVIAL(fatal)<<"unable to match page regex to shop response for shop "<<shop->name; std::ofstream responseFile("unmatched_response"); responseFile<<response.body(); } } else std::cout<<"response statuscode: "<<response.status()<<"\n"; } else std::cout<<"error: "<<err.message()<<"\n"; btn->setEnabled(true); btn->setText("Add"); edit->setPlaceholderText("Paste URL here"); Wt::WApplication::instance()->triggerUpdate(); }); if(client->get(edit->text().toUTF8())) { btn->setEnabled(false); btn->setText("adding..."); std::cout<<"loading info from page...\n"; } } } if(!found) { edit->setText(""); edit->setPlaceholderText("invalid URL!"); } } Wt::Signal<void>& InputItemWidget::itemEntered() { return _itemEntered; } <commit_msg>Delete Http::Client on done()<commit_after>#include "InputItemWidget.hpp" #include <Wt/WLineEdit> #include <iostream> #include <boost/foreach.hpp> #include <Wt/Utils> #include <Wt/WIntValidator> #include <Wt/WPushButton> #include <Wt/Http/Client> #include <Wt/Http/Message> #include <Wt/WApplication> #include <boost/log/trivial.hpp> #include <fstream> #include <limits> #include "../application.hpp" /* class ShopParseException : public std::exception { public: ShopParseException };*/ InputItemWidget::InputItemWidget(ShopList shops, Wt::WContainerWidget *parent) :Wt::WContainerWidget(parent), shops(shops) { edit=new Wt::WLineEdit(this); edit->setPlaceholderText("Paste URL here"); countEdit=new Wt::WLineEdit(this); Wt::WIntValidator *val = new Wt::WIntValidator(); val->setBottom(0); val->setMandatory(true); countEdit->setValidator(val); countEdit->setPlaceholderText("count"); btn = new Wt::WPushButton("Add", this); btn->setStyleClass("btn-primary"); btn->clicked().connect(this,&InputItemWidget::changed); } void InputItemWidget::changed() { if(countEdit->validate()!=Wt::WValidator::Valid) { std::cout<<"invalid!\n"; return; } int count = boost::lexical_cast<int>(countEdit->text()); string newText = Wt::Utils::urlDecode(edit->text().toUTF8()); std::cout<<"changed to "<<newText<<"\n"; boost::smatch url_match; //boost::regex_search(edit->text().toUTF8(),m,shop->inputURLRegex); //boost::regex r{"ARTICLEID=(?<id>\\d+)"}; //boost::regex r{re->text().toUTF8()}; //for(auto shop=shops->begin();shop!=shops->end();shop++) bool found=false; BOOST_FOREACH(auto tuple, *shops) { auto shop=tuple.second; if(boost::regex_search(newText,url_match, shop->inputURLRegex)) { found=true; std::cout<<"match for shop "<<shop->name<<"\n"; std::cout<<"number: "<<url_match["number"]<<"\n"; std::cout<<"number2: "<<url_match["number2"]<<"\n"; std::map<string, string> urlMatches; if(url_match["number"].matched) urlMatches["number"]=url_match["number"]; if(url_match["number2"].matched) urlMatches["number2"]=url_match["number2"]; if(url_match["title"].matched) urlMatches["title"]=url_match["title"]; // get data from page Wt::Http::Client *client = new Wt::Http::Client(Wt::WApplication::instance()); client->setTimeout(10); client->setMaximumResponseSize(1024*1024); client->done().connect([ this, client, newText, url_match, shop, count, urlMatches ](boost::system::error_code err, const Wt::Http::Message& response, Wt::NoClass, Wt::NoClass, Wt::NoClass, Wt::NoClass) { std::cout<<"done()\n"; if(!err) { if(response.status() == 200) { std::cout<<"shop regexes:\n"; boost::smatch pageMatch; if(boost::regex_search(response.body(), pageMatch, shop->pageRegex)) { std::map<string, string> matches = urlMatches; // number if(pageMatch["number"].matched) { matches["number"]=pageMatch["number"]; } // number2 if(pageMatch["number2"].matched) { matches["number2"]=pageMatch["number2"]; } // price if(pageMatch["price"].matched) { matches["price"]=pageMatch["price"]; } // title if(pageMatch["title"].matched) { matches["title"]=pageMatch["title"]; } double price=std::numeric_limits<double>::quiet_NaN(); try { price = boost::lexical_cast<double>(matches["price"]); } catch(boost::bad_lexical_cast &) { std::cerr<<"unable to convert \""<<matches["price"]<<"\" to float\n"; try // try to fix "," as a comma separator { matches["price"].replace(matches["price"].find(','),1,{'.'}); std::cerr<<"trying with \""<<matches["price"]<<"\"\n"; price = boost::lexical_cast<double>(matches["price"]); } catch(boost::bad_lexical_cast &) {} } BOOST_FOREACH(auto m, matches) std::cout<<"matches[\""<<m.first<<"\"]=\""<<m.second<<"\"\n"; Session& dbSession = static_cast<ShareBuy*>(Wt::WApplication::instance())->dbSession; dbo::Transaction transaction(dbSession); PItem item = dbSession.add(new Item( shop->name, matches["number"], matches["number2"], matches["title"], newText, price, count)); item.modify()->user = dbSession.user(); transaction.commit(); _itemEntered.emit(); edit->setText(""); countEdit->setText(""); } else { BOOST_LOG_TRIVIAL(fatal)<<"unable to match page regex to shop response for shop "<<shop->name; std::ofstream responseFile("unmatched_response"); responseFile<<response.body(); } } else std::cout<<"response statuscode: "<<response.status()<<"\n"; } else std::cout<<"error: "<<err.message()<<"\n"; delete client; btn->setEnabled(true); btn->setText("Add"); edit->setPlaceholderText("Paste URL here"); Wt::WApplication::instance()->triggerUpdate(); }); if(client->get(edit->text().toUTF8())) { btn->setEnabled(false); btn->setText("adding..."); std::cout<<"loading info from page...\n"; } } } if(!found) { edit->setText(""); edit->setPlaceholderText("invalid URL!"); } } Wt::Signal<void>& InputItemWidget::itemEntered() { return _itemEntered; } <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: dbwiz.hxx,v $ * * $Revision: 1.2 $ * * last change: $Author: hr $ $Date: 2004-08-02 15:58:40 $ * * 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 EXPRESS 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 DBAUI_DBWIZ_HXX #define DBAUI_DBWIZ_HXX #ifndef _SFXTABDLG_HXX #include <sfx2/tabdlg.hxx> #endif #ifndef _DBAUI_DSNTYPES_HXX_ #include "dsntypes.hxx" #endif #ifndef DBAUI_ITEMSETHELPER_HXX #include "IItemSetHelper.hxx" #endif #ifndef _COMPHELPER_UNO3_HXX_ #include <comphelper/uno3.hxx> #endif #ifndef _SVTOOLS_WIZARDMACHINE_HXX_ #include <svtools/wizardmachine.hxx> #endif #ifndef _DBAUI_MODULE_DBU_HXX_ #include "moduledbu.hxx" #endif #include <memory> FORWARD_DECLARE_INTERFACE(beans,XPropertySet) FORWARD_DECLARE_INTERFACE(sdbc,XConnection) FORWARD_DECLARE_INTERFACE(lang,XMultiServiceFactory) //......................................................................... namespace dbaui { //......................................................................... class ODsnTypeCollection; //========================================================================= //= ODbTypeWizDialog //========================================================================= class OGeneralPage; struct OPageSettings; class ODbDataSourceAdministrationHelper; /** tab dialog for administrating the office wide registered data sources */ class ODbTypeWizDialog : public svt::OWizardMachine , public IItemSetHelper, public IAdminHelper,public dbaui::OModuleClient { private: ::std::auto_ptr<ODbDataSourceAdministrationHelper> m_pImpl; SfxItemSet* m_pOutSet; DATASOURCE_TYPE m_eType; sal_Bool m_bResetting : 1; /// sal_True while we're resetting the pages sal_Bool m_bApplied : 1; /// sal_True if any changes have been applied while the dialog was executing sal_Bool m_bUIEnabled : 1; /// <TRUE/> if the UI is enabled, false otherwise. Cannot be switched back to <TRUE/>, once it is <FALSE/> public: /** ctor. The itemset given should have been created by <method>createItemSet</method> and should be destroyed after the dialog has been destroyed */ ODbTypeWizDialog(Window* pParent ,SfxItemSet* _pItems ,const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& _rxORB ,const ::com::sun::star::uno::Any& _aDataSourceName ); virtual ~ODbTypeWizDialog(); virtual const SfxItemSet* getOutputSet() const; virtual SfxItemSet* getWriteOutputSet(); // forwards to ODbDataSourceAdministrationHelper virtual ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory > getORB(); virtual ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XConnection > createConnection(); virtual ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XDriver > getDriver(); virtual DATASOURCE_TYPE getDatasourceType(const SfxItemSet& _rSet) const; virtual void clearPassword(); virtual sal_Bool saveDatasource(); virtual void setTitle(const ::rtl::OUString& _sTitle); protected: /// to override to create new pages virtual TabPage* createPage(WizardState _nState); virtual WizardState determineNextState(WizardState _nCurrentState); virtual sal_Bool leaveState(WizardState _nState); virtual ::svt::IWizardPage* getWizardPage(TabPage* _pCurrentPage) const; virtual sal_Bool onFinish(sal_Int32 _nResult); protected: inline sal_Bool isUIEnabled() const { return m_bUIEnabled; } inline void disabledUI() { m_bUIEnabled = sal_False; } /// select a datasource with a given name, adjust the item set accordingly, and everything like that .. void implSelectDatasource(const ::rtl::OUString& _rRegisteredName); void resetPages(const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet >& _rxDatasource); enum ApplyResult { AR_LEAVE_MODIFIED, // somthing was modified and has successfully been committed AR_LEAVE_UNCHANGED, // no changes were made AR_KEEP // don't leave the page (e.g. because an error occured) }; /** apply all changes made */ ApplyResult implApplyChanges(); private: DECL_LINK(OnTypeSelected, OGeneralPage*); }; //......................................................................... } // namespace dbaui //......................................................................... #endif // DBAUI_DBWIZ_HXX <commit_msg>INTEGRATION: CWS dba22 (1.2.62); FILE MERGED 2005/01/06 12:43:58 oj 1.2.62.1: #i39321# extend createConnection to return a pair now<commit_after>/************************************************************************* * * $RCSfile: dbwiz.hxx,v $ * * $Revision: 1.3 $ * * last change: $Author: kz $ $Date: 2005-01-21 17:18:44 $ * * 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 EXPRESS 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 DBAUI_DBWIZ_HXX #define DBAUI_DBWIZ_HXX #ifndef _SFXTABDLG_HXX #include <sfx2/tabdlg.hxx> #endif #ifndef _DBAUI_DSNTYPES_HXX_ #include "dsntypes.hxx" #endif #ifndef DBAUI_ITEMSETHELPER_HXX #include "IItemSetHelper.hxx" #endif #ifndef _COMPHELPER_UNO3_HXX_ #include <comphelper/uno3.hxx> #endif #ifndef _SVTOOLS_WIZARDMACHINE_HXX_ #include <svtools/wizardmachine.hxx> #endif #ifndef _DBAUI_MODULE_DBU_HXX_ #include "moduledbu.hxx" #endif #include <memory> FORWARD_DECLARE_INTERFACE(beans,XPropertySet) FORWARD_DECLARE_INTERFACE(sdbc,XConnection) FORWARD_DECLARE_INTERFACE(lang,XMultiServiceFactory) //......................................................................... namespace dbaui { //......................................................................... class ODsnTypeCollection; //========================================================================= //= ODbTypeWizDialog //========================================================================= class OGeneralPage; struct OPageSettings; class ODbDataSourceAdministrationHelper; /** tab dialog for administrating the office wide registered data sources */ class ODbTypeWizDialog : public svt::OWizardMachine , public IItemSetHelper, public IAdminHelper,public dbaui::OModuleClient { private: ::std::auto_ptr<ODbDataSourceAdministrationHelper> m_pImpl; SfxItemSet* m_pOutSet; DATASOURCE_TYPE m_eType; sal_Bool m_bResetting : 1; /// sal_True while we're resetting the pages sal_Bool m_bApplied : 1; /// sal_True if any changes have been applied while the dialog was executing sal_Bool m_bUIEnabled : 1; /// <TRUE/> if the UI is enabled, false otherwise. Cannot be switched back to <TRUE/>, once it is <FALSE/> public: /** ctor. The itemset given should have been created by <method>createItemSet</method> and should be destroyed after the dialog has been destroyed */ ODbTypeWizDialog(Window* pParent ,SfxItemSet* _pItems ,const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& _rxORB ,const ::com::sun::star::uno::Any& _aDataSourceName ); virtual ~ODbTypeWizDialog(); virtual const SfxItemSet* getOutputSet() const; virtual SfxItemSet* getWriteOutputSet(); // forwards to ODbDataSourceAdministrationHelper virtual ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory > getORB(); virtual ::std::pair< ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XConnection >,sal_Bool> createConnection(); virtual ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XDriver > getDriver(); virtual DATASOURCE_TYPE getDatasourceType(const SfxItemSet& _rSet) const; virtual void clearPassword(); virtual sal_Bool saveDatasource(); virtual void setTitle(const ::rtl::OUString& _sTitle); protected: /// to override to create new pages virtual TabPage* createPage(WizardState _nState); virtual WizardState determineNextState(WizardState _nCurrentState); virtual sal_Bool leaveState(WizardState _nState); virtual ::svt::IWizardPage* getWizardPage(TabPage* _pCurrentPage) const; virtual sal_Bool onFinish(sal_Int32 _nResult); protected: inline sal_Bool isUIEnabled() const { return m_bUIEnabled; } inline void disabledUI() { m_bUIEnabled = sal_False; } /// select a datasource with a given name, adjust the item set accordingly, and everything like that .. void implSelectDatasource(const ::rtl::OUString& _rRegisteredName); void resetPages(const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet >& _rxDatasource); enum ApplyResult { AR_LEAVE_MODIFIED, // somthing was modified and has successfully been committed AR_LEAVE_UNCHANGED, // no changes were made AR_KEEP // don't leave the page (e.g. because an error occured) }; /** apply all changes made */ ApplyResult implApplyChanges(); private: DECL_LINK(OnTypeSelected, OGeneralPage*); }; //......................................................................... } // namespace dbaui //......................................................................... #endif // DBAUI_DBWIZ_HXX <|endoftext|>
<commit_before>#ifndef STAN__MATH__MATRIX__EXP_HPP #define STAN__MATH__MATRIX__EXP_HPP #include <stan/math/matrix/Eigen.hpp> #include <boost/math/special_functions/fpclassify.hpp> namespace stan { namespace math { /** * Return the element-wise exponentiation of the matrix or vector. * * @param m The matrix or vector. * @return ret(i,j) = exp(m(i,j)) */ template<typename T, int Rows, int Cols> inline Eigen::Matrix<T,Rows,Cols> exp(const Eigen::Matrix<T,Rows,Cols> & m) { return m.array().exp().matrix(); } template<int Rows, int Cols> inline Eigen::Matrix<double,Rows,Cols> exp(const Eigen::Matrix<double,Rows,Cols> & m) { for (const double * it = m.data(), * end_ = it + m.size(); it != end_; it++) if (boost::math::isnan(*it)) { Eigen::Matrix<double,Rows,Cols> mat = m; for (double * it = mat.data(), * end_ = it + mat.size(); it != end_; it++) *it = std::exp(*it); return mat; } return m.array().exp().matrix(); } } } #endif <commit_msg>even simpler and better solution<commit_after>#ifndef STAN__MATH__MATRIX__EXP_HPP #define STAN__MATH__MATRIX__EXP_HPP #include <stan/math/matrix/Eigen.hpp> #include <boost/math/special_functions/fpclassify.hpp> #include <limits> namespace stan { namespace math { /** * Return the element-wise exponentiation of the matrix or vector. * * @param m The matrix or vector. * @return ret(i,j) = exp(m(i,j)) */ template<typename T, int Rows, int Cols> inline Eigen::Matrix<T,Rows,Cols> exp(const Eigen::Matrix<T,Rows,Cols>& m) { return m.array().exp().matrix(); } //FIXME: //specialization not needed once Eigen fixes issue: //http://eigen.tuxfamily.org/bz/show_bug.cgi?id=859 template<int Rows, int Cols> inline Eigen::Matrix<double,Rows,Cols> exp(const Eigen::Matrix<double,Rows,Cols>& m) { Eigen::Matrix<double,Rows,Cols> mat = m.array().exp().matrix(); for (int i = 0, size_ = mat.size(); i < size_; i++) if (boost::math::isnan(m(i))) mat(i) = std::numeric_limits<double>::quiet_NaN(); return mat; } } } #endif <|endoftext|>
<commit_before>#include <GL/glew.h> #include <SDL2/SDL.h> #include <stdio.h> typedef int32_t bool32; #include "platform_code.cpp" #include "GL.cpp" #include "file_formats.cpp" void HandleKeyDown(SDL_Keysym key); bool32 quit=0; bool32 SetupSDLWindow(); void Render(); void Setup(); void Teardown(); SDL_Window * MainSDLWindow; int ScreenWidth=800,ScreenHeight=600; int main(int argc, char * argv[]) { if(!SetupSDLWindow()) return 1; Setup(); SDL_Event e; while( !quit ) { while( SDL_PollEvent( &e ) != 0 ) { if( e.type == SDL_QUIT ) { quit = true; } else if( e.type == SDL_KEYDOWN) { HandleKeyDown(e.key.keysym); } } Render(); SDL_GL_SwapWindow( MainSDLWindow ); } Teardown(); SDL_DestroyWindow(MainSDLWindow); SDL_Quit(); return 0; } void HandleKeyDown(SDL_Keysym key) { switch(key.sym) { case SDLK_ESCAPE: quit=true; break; } } void PrintHPIDirectory(HPIDirectoryEntry dir, int Tabs=0) { char printf_format[Tabs+2+3+2+1+1]; for(int i=0;i<Tabs;i++) printf_format[i]='\t'; printf_format[Tabs]='%'; printf_format[Tabs+1]='s'; printf_format[Tabs+2]=' '; printf_format[Tabs+3]='-'; printf_format[Tabs+4]=' '; printf_format[Tabs+5]='%'; printf_format[Tabs+6]='d'; printf_format[Tabs+7]='\n'; printf_format[Tabs+8]=0; for(int EntryIndex=0;EntryIndex<dir.NumberOfEntries;EntryIndex++) { printf(printf_format,dir.Entries[EntryIndex].Name,dir.Entries[EntryIndex].IsDirectory?0:dir.Entries[EntryIndex].File.FileSize); if(dir.Entries[EntryIndex].IsDirectory) { PrintHPIDirectory(dir.Entries[EntryIndex].Directory,Tabs+1); } } } ShaderProgram UnitShader; ShaderProgram OrthoShader; #define STB_TRUETYPE_IMPLEMENTATION // force following include to generate implementation #include "stb_truetype.h" unsigned char temp_bitmap[512*512]; stbtt_bakedchar cdata[96]; // ASCII 32..126 is 95 glyphs GLuint ftex; void my_stbtt_initfont(void) { char ttf_buffer[1<<20]; fread(ttf_buffer, 1, 1<<20, fopen("data/times.ttf", "rb")); stbtt_BakeFontBitmap((const unsigned char*)ttf_buffer,0, 32.0, temp_bitmap,512,512, 32,96, cdata); // no guarantee this fits! // can free ttf_buffer at this point glGenTextures(1, &ftex); glBindTexture(GL_TEXTURE_2D, ftex); glTexImage2D(GL_TEXTURE_2D, 0, GL_ALPHA, 512,512, 0, GL_ALPHA, GL_UNSIGNED_BYTE, temp_bitmap); // can free temp_bitmap at this point glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); } void my_stbtt_print(float x, float y, char *text) { //TODO(Christof): actually make this work, // assume orthographic projection with units = screen pixels, origin at top left glBindTexture(GL_TEXTURE_2D, ftex); glBegin(GL_QUADS); while (*text) { if (*text >= 32 && *text >0) { stbtt_aligned_quad q; stbtt_GetBakedQuad(cdata, 512,512, *text-32, &x,&y,&q,1);//1=opengl & d3d10+,0=d3d9 glTexCoord2f(q.s0,q.t1); glVertex2f(q.x0,q.y0); glTexCoord2f(q.s1,q.t1); glVertex2f(q.x1,q.y0); glTexCoord2f(q.s1,q.t0); glVertex2f(q.x1,q.y1); glTexCoord2f(q.s0,q.t0); glVertex2f(q.x0,q.y1); } ++text; } glEnd(); } struct ScreenText { GLuint VertexArrayObject; GLuint FontTexture; int NumberOfVertices; float X,Y; }; ScreenText SetupOnScreenText(char * Text, float X, float Y) { int NumQuads=0; char * t=Text; while (*t) { if (*t >= 32 && *t >0) { NumQuads++; } t++; } const int NUM_FLOATS_PER_QUAD=2*3*2*2;//2 triangles per quad, 3 verts per triangle, 2 position and 2 texture coords per vert GLfloat VertexAndTexCoordData[NumQuads*NUM_FLOATS_PER_QUAD]; ScreenText result; result.X=X; result.Y=Y; result.FontTexture=ftex; result.NumberOfVertices=NumQuads * 6; glGenVertexArrays(1,&result.VertexArrayObject); for(int i=0;i<NumQuads;i++) { if (Text[i] >= 32 && Text[i] >0) { stbtt_aligned_quad q; //TODO(Christof): Make this position independant stbtt_GetBakedQuad(cdata, 512,512, Text[i]-32, &X,&Y,&q,1); VertexAndTexCoordData[i*NUM_FLOATS_PER_QUAD + 0]=q.x0; VertexAndTexCoordData[i*NUM_FLOATS_PER_QUAD + 1]=q.y0; VertexAndTexCoordData[i*NUM_FLOATS_PER_QUAD + 2]=q.s0; VertexAndTexCoordData[i*NUM_FLOATS_PER_QUAD + 3]=q.t0; VertexAndTexCoordData[i*NUM_FLOATS_PER_QUAD + 4]=q.x0; VertexAndTexCoordData[i*NUM_FLOATS_PER_QUAD + 5]=q.y1; VertexAndTexCoordData[i*NUM_FLOATS_PER_QUAD + 6]=q.s0; VertexAndTexCoordData[i*NUM_FLOATS_PER_QUAD + 7]=q.t1; VertexAndTexCoordData[i*NUM_FLOATS_PER_QUAD + 8]=q.x1; VertexAndTexCoordData[i*NUM_FLOATS_PER_QUAD + 9]=q.y1; VertexAndTexCoordData[i*NUM_FLOATS_PER_QUAD + 10]=q.s1; VertexAndTexCoordData[i*NUM_FLOATS_PER_QUAD + 11]=q.t1; VertexAndTexCoordData[i*NUM_FLOATS_PER_QUAD + 12]=q.x1; VertexAndTexCoordData[i*NUM_FLOATS_PER_QUAD + 13]=q.y1; VertexAndTexCoordData[i*NUM_FLOATS_PER_QUAD + 14]=q.s1; VertexAndTexCoordData[i*NUM_FLOATS_PER_QUAD + 15]=q.t1; VertexAndTexCoordData[i*NUM_FLOATS_PER_QUAD + 16]=q.x1; VertexAndTexCoordData[i*NUM_FLOATS_PER_QUAD + 17]=q.y0; VertexAndTexCoordData[i*NUM_FLOATS_PER_QUAD + 18]=q.s1; VertexAndTexCoordData[i*NUM_FLOATS_PER_QUAD + 19]=q.t0; VertexAndTexCoordData[i*NUM_FLOATS_PER_QUAD + 20]=q.x0; VertexAndTexCoordData[i*NUM_FLOATS_PER_QUAD + 21]=q.y0; VertexAndTexCoordData[i*NUM_FLOATS_PER_QUAD + 22]=q.s0; VertexAndTexCoordData[i*NUM_FLOATS_PER_QUAD + 23]=q.t0; } } glBindVertexArray(result.VertexArrayObject); GLuint VertexBuffer; glGenBuffers(1,&VertexBuffer); glBindBuffer(GL_ARRAY_BUFFER,VertexBuffer); glBufferData(GL_ARRAY_BUFFER,sizeof(GLfloat)*NumQuads*NUM_FLOATS_PER_QUAD,VertexAndTexCoordData,GL_STATIC_DRAW); glVertexAttribPointer(0,2,GL_FLOAT,GL_FALSE,sizeof(GLfloat)*4,0); glVertexAttribPointer(1,2,GL_FLOAT,GL_FALSE,sizeof(GLfloat)*4,(GLvoid*)(sizeof(GLfloat)*2)); glEnableVertexAttribArray(0); glEnableVertexAttribArray(1); glBindVertexArray(0); //glDeleteBuffers(1,&VertexBuffer); return result; } void RenderOnScreenText(ScreenText Text) { glBindVertexArray(Text.VertexArrayObject); glBindTexture(GL_TEXTURE_2D,Text.FontTexture); glDrawArrays(GL_TRIANGLES,0,Text.NumberOfVertices); } ScreenText TestText; void Setup() { my_stbtt_initfont(); UnitShader=LoadShaderProgram("shaders/unit3do.vs.glsl","shaders/unit3do.fs.glsl"); OrthoShader=LoadShaderProgram("shaders/ortho.vs.glsl","shaders/ortho.fs.glsl"); glUseProgram(OrthoShader.ProgramID); glUniform1i(GetUniformLocation(OrthoShader,"UnitTexture"),0); TestText=SetupOnScreenText("This is a test, now somewhat longer",0,30); //GL Setup: glClearColor( 0.f, 0.f,0.f, 0.f ); glEnable(GL_DEPTH_TEST); glDepthFunc(GL_LESS); //glEnable(GL_CULL_FACE); glDisable(GL_CULL_FACE); glCullFace(GL_BACK); //glFrontFace(GL_CW); GLint viewport[4]; glGetIntegerv(GL_VIEWPORT, viewport); glUseProgram(OrthoShader.ProgramID); glUniform2iv(GetUniformLocation(OrthoShader,"Viewport"),1,viewport+2); if(LoadHPIFile("data/totala1.hpi",&AllArchiveFiles[0])) { //PrintHPIDirectory(main.Root); LoadAllTextures(); HPIEntry Default = FindHPIEntry(&AllArchiveFiles[0],"objects3D/armsolar.3do"); //HPIEntry Default = FindHPIEntry(main,"units/ARMSOLAR.FBI"); if(Default.IsDirectory) { LogError("%s is unexpectedly a directory!",Default.Name); } else if(Default.Name) { char temp[Default.File.FileSize]; if(LoadHPIFileEntryData(Default,temp)) { Object3d temp_model; Load3DOFromBuffer(temp,&temp_model); FILE * file =fopen(Default.Name,"wb"); fwrite(temp,Default.File.FileSize,1,file); fclose(file); Unload3DO(&temp_model); } } else { LogError("failed to find %s",Default.Name); } } } void Render() { glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glDisable(GL_BLEND); // Turn Blending on glEnable(GL_DEPTH_TEST); //Turn Depth Testing off glUseProgram(UnitShader.ProgramID); //TODO(Christof): Unit Rendering here glBlendFunc(GL_SRC_ALPHA,GL_ONE_MINUS_SRC_ALPHA); glEnable(GL_BLEND); // Turn Blending on glDisable(GL_DEPTH_TEST); //Turn Depth Testing off glUseProgram(OrthoShader.ProgramID); RenderOnScreenText(TestText); //my_stbtt_print(0,0,"Another Test"); GLenum ErrorValue = glGetError(); if(ErrorValue!=GL_NO_ERROR) { LogError("failed to render : %s",gluErrorString(ErrorValue)); } } void Teardown() { UnloadShaderProgram(UnitShader); for(int i=0;i<5;i++) UnloadHPIFile(&AllArchiveFiles[i]); } bool32 SetupSDLWindow() { if (SDL_Init(SDL_INIT_EVERYTHING) != 0) { LogError("SDL_Init Error: %s", SDL_GetError()); return 0; } SDL_GL_SetAttribute( SDL_GL_CONTEXT_MAJOR_VERSION, 3 ); SDL_GL_SetAttribute( SDL_GL_CONTEXT_MINOR_VERSION, 0 ); SDL_GL_SetAttribute( SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_CORE ); MainSDLWindow = SDL_CreateWindow("Hello World!", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED,ScreenWidth, ScreenHeight, SDL_WINDOW_SHOWN|SDL_WINDOW_OPENGL); if (!MainSDLWindow) { LogError("SDL_CreateWindow Error: %s", SDL_GetError()); return 0; } GLint GLMajorVer, GLMinorVer; GLenum ErrorValue = glGetError(); if(ErrorValue!=GL_NO_ERROR) { LogError("failed before create context : %s", gluErrorString(ErrorValue)); } SDL_GLContext gContext = SDL_GL_CreateContext( MainSDLWindow); SDL_GL_MakeCurrent (MainSDLWindow,gContext); if( SDL_GL_SetSwapInterval( 1 ) < 0 ) { LogWarning("Warning: Unable to set VSync! SDL Error: %s",SDL_GetError()); } glGetIntegerv(GL_MAJOR_VERSION, &GLMajorVer); glGetIntegerv(GL_MINOR_VERSION, &GLMinorVer); LogDebug("OpenGL Version %d.%d",GLMajorVer,GLMinorVer); ErrorValue = glGetError(); if(ErrorValue!=GL_NO_ERROR) { LogError("failed before glewInit : %s",gluErrorString(ErrorValue)); } glewExperimental = GL_TRUE; GLenum glewError = glewInit(); if( glewError != GLEW_OK ) { LogError("Error initializing GLEW! %s", glewGetErrorString( glewError )); return 0; } //as we need to use glewExperimental - known issue (it segfaults otherwise!) - we encounter //another known issue, which is that while glewInit suceeds, it leaves opengl in an error state ErrorValue = glGetError(); return 1; } <commit_msg>handle missing font file slightly better.<commit_after>#include <GL/glew.h> #include <SDL2/SDL.h> #include <stdio.h> typedef int32_t bool32; #include "platform_code.cpp" #include "GL.cpp" #include "file_formats.cpp" void HandleKeyDown(SDL_Keysym key); bool32 quit=0; bool32 SetupSDLWindow(); void Render(); void Setup(); void Teardown(); SDL_Window * MainSDLWindow; int ScreenWidth=800,ScreenHeight=600; int main(int argc, char * argv[]) { if(!SetupSDLWindow()) return 1; Setup(); SDL_Event e; while( !quit ) { while( SDL_PollEvent( &e ) != 0 ) { if( e.type == SDL_QUIT ) { quit = true; } else if( e.type == SDL_KEYDOWN) { HandleKeyDown(e.key.keysym); } } Render(); SDL_GL_SwapWindow( MainSDLWindow ); } Teardown(); SDL_DestroyWindow(MainSDLWindow); SDL_Quit(); return 0; } void HandleKeyDown(SDL_Keysym key) { switch(key.sym) { case SDLK_ESCAPE: quit=true; break; } } void PrintHPIDirectory(HPIDirectoryEntry dir, int Tabs=0) { char printf_format[Tabs+2+3+2+1+1]; for(int i=0;i<Tabs;i++) printf_format[i]='\t'; printf_format[Tabs]='%'; printf_format[Tabs+1]='s'; printf_format[Tabs+2]=' '; printf_format[Tabs+3]='-'; printf_format[Tabs+4]=' '; printf_format[Tabs+5]='%'; printf_format[Tabs+6]='d'; printf_format[Tabs+7]='\n'; printf_format[Tabs+8]=0; for(int EntryIndex=0;EntryIndex<dir.NumberOfEntries;EntryIndex++) { printf(printf_format,dir.Entries[EntryIndex].Name,dir.Entries[EntryIndex].IsDirectory?0:dir.Entries[EntryIndex].File.FileSize); if(dir.Entries[EntryIndex].IsDirectory) { PrintHPIDirectory(dir.Entries[EntryIndex].Directory,Tabs+1); } } } ShaderProgram UnitShader; ShaderProgram OrthoShader; #define STB_TRUETYPE_IMPLEMENTATION // force following include to generate implementation #include "stb_truetype.h" unsigned char temp_bitmap[512*512]; stbtt_bakedchar cdata[96]; // ASCII 32..126 is 95 glyphs GLuint ftex; void my_stbtt_initfont(void) { char ttf_buffer[1<<20]; FILE * file=fopen("data/times.ttf", "rb"); if(!file) { LogError("Failed to load font file"); // return; } fread(ttf_buffer, 1, 1<<20, file); stbtt_BakeFontBitmap((const unsigned char*)ttf_buffer,0, 32.0, temp_bitmap,512,512, 32,96, cdata); // no guarantee this fits! // can free ttf_buffer at this point glGenTextures(1, &ftex); glBindTexture(GL_TEXTURE_2D, ftex); glTexImage2D(GL_TEXTURE_2D, 0, GL_ALPHA, 512,512, 0, GL_ALPHA, GL_UNSIGNED_BYTE, temp_bitmap); // can free temp_bitmap at this point glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); } void my_stbtt_print(float x, float y, char *text) { //TODO(Christof): actually make this work, // assume orthographic projection with units = screen pixels, origin at top left glBindTexture(GL_TEXTURE_2D, ftex); glBegin(GL_QUADS); while (*text) { if (*text >= 32 && *text >0) { stbtt_aligned_quad q; stbtt_GetBakedQuad(cdata, 512,512, *text-32, &x,&y,&q,1);//1=opengl & d3d10+,0=d3d9 glTexCoord2f(q.s0,q.t1); glVertex2f(q.x0,q.y0); glTexCoord2f(q.s1,q.t1); glVertex2f(q.x1,q.y0); glTexCoord2f(q.s1,q.t0); glVertex2f(q.x1,q.y1); glTexCoord2f(q.s0,q.t0); glVertex2f(q.x0,q.y1); } ++text; } glEnd(); } struct ScreenText { GLuint VertexArrayObject; GLuint FontTexture; int NumberOfVertices; float X,Y; }; ScreenText SetupOnScreenText(char * Text, float X, float Y) { int NumQuads=0; char * t=Text; while (*t) { if (*t >= 32 && *t >0) { NumQuads++; } t++; } const int NUM_FLOATS_PER_QUAD=2*3*2*2;//2 triangles per quad, 3 verts per triangle, 2 position and 2 texture coords per vert GLfloat VertexAndTexCoordData[NumQuads*NUM_FLOATS_PER_QUAD]; ScreenText result; result.X=X; result.Y=Y; result.FontTexture=ftex; result.NumberOfVertices=NumQuads * 6; glGenVertexArrays(1,&result.VertexArrayObject); for(int i=0;i<NumQuads;i++) { if (Text[i] >= 32 && Text[i] >0) { stbtt_aligned_quad q; //TODO(Christof): Make this position independant stbtt_GetBakedQuad(cdata, 512,512, Text[i]-32, &X,&Y,&q,1); VertexAndTexCoordData[i*NUM_FLOATS_PER_QUAD + 0]=q.x0; VertexAndTexCoordData[i*NUM_FLOATS_PER_QUAD + 1]=q.y0; VertexAndTexCoordData[i*NUM_FLOATS_PER_QUAD + 2]=q.s0; VertexAndTexCoordData[i*NUM_FLOATS_PER_QUAD + 3]=q.t0; VertexAndTexCoordData[i*NUM_FLOATS_PER_QUAD + 4]=q.x0; VertexAndTexCoordData[i*NUM_FLOATS_PER_QUAD + 5]=q.y1; VertexAndTexCoordData[i*NUM_FLOATS_PER_QUAD + 6]=q.s0; VertexAndTexCoordData[i*NUM_FLOATS_PER_QUAD + 7]=q.t1; VertexAndTexCoordData[i*NUM_FLOATS_PER_QUAD + 8]=q.x1; VertexAndTexCoordData[i*NUM_FLOATS_PER_QUAD + 9]=q.y1; VertexAndTexCoordData[i*NUM_FLOATS_PER_QUAD + 10]=q.s1; VertexAndTexCoordData[i*NUM_FLOATS_PER_QUAD + 11]=q.t1; VertexAndTexCoordData[i*NUM_FLOATS_PER_QUAD + 12]=q.x1; VertexAndTexCoordData[i*NUM_FLOATS_PER_QUAD + 13]=q.y1; VertexAndTexCoordData[i*NUM_FLOATS_PER_QUAD + 14]=q.s1; VertexAndTexCoordData[i*NUM_FLOATS_PER_QUAD + 15]=q.t1; VertexAndTexCoordData[i*NUM_FLOATS_PER_QUAD + 16]=q.x1; VertexAndTexCoordData[i*NUM_FLOATS_PER_QUAD + 17]=q.y0; VertexAndTexCoordData[i*NUM_FLOATS_PER_QUAD + 18]=q.s1; VertexAndTexCoordData[i*NUM_FLOATS_PER_QUAD + 19]=q.t0; VertexAndTexCoordData[i*NUM_FLOATS_PER_QUAD + 20]=q.x0; VertexAndTexCoordData[i*NUM_FLOATS_PER_QUAD + 21]=q.y0; VertexAndTexCoordData[i*NUM_FLOATS_PER_QUAD + 22]=q.s0; VertexAndTexCoordData[i*NUM_FLOATS_PER_QUAD + 23]=q.t0; } } glBindVertexArray(result.VertexArrayObject); GLuint VertexBuffer; glGenBuffers(1,&VertexBuffer); glBindBuffer(GL_ARRAY_BUFFER,VertexBuffer); glBufferData(GL_ARRAY_BUFFER,sizeof(GLfloat)*NumQuads*NUM_FLOATS_PER_QUAD,VertexAndTexCoordData,GL_STATIC_DRAW); glVertexAttribPointer(0,2,GL_FLOAT,GL_FALSE,sizeof(GLfloat)*4,0); glVertexAttribPointer(1,2,GL_FLOAT,GL_FALSE,sizeof(GLfloat)*4,(GLvoid*)(sizeof(GLfloat)*2)); glEnableVertexAttribArray(0); glEnableVertexAttribArray(1); glBindVertexArray(0); //glDeleteBuffers(1,&VertexBuffer); return result; } void RenderOnScreenText(ScreenText Text) { glBindVertexArray(Text.VertexArrayObject); glBindTexture(GL_TEXTURE_2D,Text.FontTexture); glDrawArrays(GL_TRIANGLES,0,Text.NumberOfVertices); } ScreenText TestText; void Setup() { my_stbtt_initfont(); UnitShader=LoadShaderProgram("shaders/unit3do.vs.glsl","shaders/unit3do.fs.glsl"); OrthoShader=LoadShaderProgram("shaders/ortho.vs.glsl","shaders/ortho.fs.glsl"); glUseProgram(OrthoShader.ProgramID); glUniform1i(GetUniformLocation(OrthoShader,"UnitTexture"),0); TestText=SetupOnScreenText("This is a test, now somewhat longer",0,30); //GL Setup: glClearColor( 0.f, 0.f,0.f, 0.f ); glEnable(GL_DEPTH_TEST); glDepthFunc(GL_LESS); //glEnable(GL_CULL_FACE); glDisable(GL_CULL_FACE); glCullFace(GL_BACK); //glFrontFace(GL_CW); GLint viewport[4]; glGetIntegerv(GL_VIEWPORT, viewport); glUseProgram(OrthoShader.ProgramID); glUniform2iv(GetUniformLocation(OrthoShader,"Viewport"),1,viewport+2); if(LoadHPIFile("data/totala1.hpi",&AllArchiveFiles[0])) { //PrintHPIDirectory(main.Root); LoadAllTextures(); HPIEntry Default = FindHPIEntry(&AllArchiveFiles[0],"objects3D/armsolar.3do"); //HPIEntry Default = FindHPIEntry(main,"units/ARMSOLAR.FBI"); if(Default.IsDirectory) { LogError("%s is unexpectedly a directory!",Default.Name); } else if(Default.Name) { char temp[Default.File.FileSize]; if(LoadHPIFileEntryData(Default,temp)) { Object3d temp_model; Load3DOFromBuffer(temp,&temp_model); FILE * file =fopen(Default.Name,"wb"); fwrite(temp,Default.File.FileSize,1,file); fclose(file); Unload3DO(&temp_model); } } else { LogError("failed to find %s",Default.Name); } } } void Render() { glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glDisable(GL_BLEND); // Turn Blending on glEnable(GL_DEPTH_TEST); //Turn Depth Testing off glUseProgram(UnitShader.ProgramID); //TODO(Christof): Unit Rendering here glBlendFunc(GL_SRC_ALPHA,GL_ONE_MINUS_SRC_ALPHA); glEnable(GL_BLEND); // Turn Blending on glDisable(GL_DEPTH_TEST); //Turn Depth Testing off glUseProgram(OrthoShader.ProgramID); RenderOnScreenText(TestText); //my_stbtt_print(0,0,"Another Test"); GLenum ErrorValue = glGetError(); if(ErrorValue!=GL_NO_ERROR) { LogError("failed to render : %s",gluErrorString(ErrorValue)); } } void Teardown() { UnloadShaderProgram(UnitShader); for(int i=0;i<5;i++) UnloadHPIFile(&AllArchiveFiles[i]); } bool32 SetupSDLWindow() { if (SDL_Init(SDL_INIT_EVERYTHING) != 0) { LogError("SDL_Init Error: %s", SDL_GetError()); return 0; } SDL_GL_SetAttribute( SDL_GL_CONTEXT_MAJOR_VERSION, 3 ); SDL_GL_SetAttribute( SDL_GL_CONTEXT_MINOR_VERSION, 0 ); SDL_GL_SetAttribute( SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_CORE ); MainSDLWindow = SDL_CreateWindow("Hello World!", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED,ScreenWidth, ScreenHeight, SDL_WINDOW_SHOWN|SDL_WINDOW_OPENGL); if (!MainSDLWindow) { LogError("SDL_CreateWindow Error: %s", SDL_GetError()); return 0; } GLint GLMajorVer, GLMinorVer; GLenum ErrorValue = glGetError(); if(ErrorValue!=GL_NO_ERROR) { LogError("failed before create context : %s", gluErrorString(ErrorValue)); } SDL_GLContext gContext = SDL_GL_CreateContext( MainSDLWindow); SDL_GL_MakeCurrent (MainSDLWindow,gContext); if( SDL_GL_SetSwapInterval( 1 ) < 0 ) { LogWarning("Warning: Unable to set VSync! SDL Error: %s",SDL_GetError()); } glGetIntegerv(GL_MAJOR_VERSION, &GLMajorVer); glGetIntegerv(GL_MINOR_VERSION, &GLMinorVer); LogDebug("OpenGL Version %d.%d",GLMajorVer,GLMinorVer); ErrorValue = glGetError(); if(ErrorValue!=GL_NO_ERROR) { LogError("failed before glewInit : %s",gluErrorString(ErrorValue)); } glewExperimental = GL_TRUE; GLenum glewError = glewInit(); if( glewError != GLEW_OK ) { LogError("Error initializing GLEW! %s", glewGetErrorString( glewError )); return 0; } //as we need to use glewExperimental - known issue (it segfaults otherwise!) - we encounter //another known issue, which is that while glewInit suceeds, it leaves opengl in an error state ErrorValue = glGetError(); return 1; } <|endoftext|>
<commit_before>//--------------------------------------------------------------------------- // $Id$ // Version: $Name$ // // Copyright (C) 1998, 1999, 2000, 2001, 2002, 2003, 2004, 2005, 2006, 2008, 2009, 2010, 2011, 2012 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. // //--------------------------------------------------------------------------- #include <deal.II/base/logstream.h> #include <deal.II/base/job_identifier.h> #include <deal.II/base/memory_consumption.h> #include <deal.II/base/thread_management.h> #ifdef HAVE_SYS_RESOURCE_H # include <sys/resource.h> #endif #ifdef HAVE_UNISTD_H # include <unistd.h> #endif #include <iostream> #include <iomanip> #include <fstream> #include <sstream> DEAL_II_NAMESPACE_OPEN namespace { Threads::Mutex log_lock; Threads::Mutex write_lock; } // The standard log object of deal.II: LogStream deallog; LogStream::LogStream() : std_out(&std::cerr), file(0), std_depth(10000), file_depth(10000), print_utime(false), diff_utime(false), last_time (0.), double_threshold(0.), float_threshold(0.), offset(0), old_cerr(0), at_newline(true), stream_flags(std::ios::showpoint | std::ios::left), stream_width(std::cout.width()), stream_precision(std::cout.precision()) { get_prefixes().push("DEAL:"); #if defined(HAVE_UNISTD_H) && defined(HAVE_TIMES) reference_time_val = 1./sysconf(_SC_CLK_TCK) * times(&reference_tms); #endif } LogStream::~LogStream() { // if there was anything left in the stream that is current to this // thread, make sure we flush it before it gets lost { if (get_stream().str().length() > 0) { // except the situation is not quite that simple. if this object is // the 'deallog' object, then it is destroyed upon exit of the // program. since it's defined in a shared library that depends on // libstdc++.so, destruction happens before destruction of // std::cout/cerr, but after all file variables defined in user // programs have been destroyed. in other words, if we get here and // the object being destroyed is 'deallog' and if 'deallog' is // associated with a file stream, then we're in trouble: we'll try // to write to a file that doesn't exist any more, and we're likely // going to crash (this is tested by base/log_crash_01). rather // than letting it come to this, print a message to the screen // (note that we can't issue an assertion here either since Assert // may want to write to 'deallog' itself, and AssertThrow will // throw an exception that can't be caught) if ((this == &deallog) && file) std::cerr << ("You still have content that was written to 'deallog' " "but not flushed to the screen or a file while the " "program is being terminated. This would lead to a " "segmentation fault. Make sure you flush the " "content of the 'deallog' object using 'std::endl' " "before the end of the program.") << std::endl; else *this << std::endl; } } if (old_cerr) std::cerr.rdbuf(old_cerr); } void LogStream::test_mode(bool on) { Threads::Mutex::ScopedLock lock(log_lock); if (on) { double_threshold = 1.e-10; float_threshold = 1.e-7; offset = 1.e-7; } else { double_threshold = 0.; float_threshold = 0.; offset = 0.; } } LogStream & LogStream::operator<< (std::ostream& (*p) (std::ostream &)) { std::ostringstream &stream = get_stream(); // save the state of out stream std::ios::fmtflags old_flags = stream.flags(stream_flags); unsigned int old_precision = stream.precision (stream_precision); unsigned int old_width = stream.width (stream_width); // Print to the internal stringstream: stream << p; // Next check whether this is the <tt>flush</tt> or <tt>endl</tt> // manipulator, and if so print out the message. std::ostream & (* const p_flush) (std::ostream &) = &std::flush; std::ostream & (* const p_endl) (std::ostream &) = &std::endl; if (p == p_flush || p == p_endl) { Threads::Mutex::ScopedLock lock(write_lock); // Print the line head in case of a newline: if (at_newline) print_line_head(); if(p == p_flush) at_newline = false; if(p == p_endl) at_newline = true; if (get_prefixes().size() <= std_depth) *std_out << stream.str(); if (file && (get_prefixes().size() <= file_depth)) *file << stream.str() << std::flush; // Start a new string stream.str(""); } // reset output format stream.flags (old_flags); stream.precision(old_precision); stream.width(old_width); return *this; } void LogStream::attach(std::ostream &o) { Threads::Mutex::ScopedLock lock(log_lock); file = &o; o.setf(std::ios::showpoint | std::ios::left); o << dealjobid(); } void LogStream::detach () { Threads::Mutex::ScopedLock lock(log_lock); file = 0; } void LogStream::log_cerr () { Threads::Mutex::ScopedLock lock(log_lock); if (old_cerr == 0) { old_cerr = std::cerr.rdbuf(file->rdbuf()); } else { std::cerr.rdbuf(old_cerr); old_cerr = 0; } } std::ostream & LogStream::get_console() { return *std_out; } std::ostream & LogStream::get_file_stream() { Assert(file, ExcNoFileStreamGiven()); return *file; } bool LogStream::has_file() const { return (file != 0); } const std::string & LogStream::get_prefix() const { return get_prefixes().top(); } void LogStream::push (const std::string &text) { std::string pre=get_prefixes().top(); pre += text; pre += std::string(":"); get_prefixes().push(pre); } void LogStream::pop () { if (get_prefixes().size() > 1) get_prefixes().pop(); } std::ios::fmtflags LogStream::flags(const std::ios::fmtflags f) { std::ios::fmtflags tmp = stream_flags; stream_flags = f; return tmp; } std::streamsize LogStream::precision (const std::streamsize prec) { std::streamsize tmp = stream_precision; stream_precision = prec; return tmp; } std::streamsize LogStream::width (const std::streamsize wide) { std::streamsize tmp = stream_width; stream_width = wide; return tmp; } unsigned int LogStream::depth_console (const unsigned int n) { Threads::Mutex::ScopedLock lock(log_lock); const unsigned int h = std_depth; std_depth = n; return h; } unsigned int LogStream::depth_file (const unsigned int n) { Threads::Mutex::ScopedLock lock(log_lock); const unsigned int h = file_depth; file_depth = n; return h; } void LogStream::threshold_double (const double t) { Threads::Mutex::ScopedLock lock(log_lock); double_threshold = t; } void LogStream::threshold_float (const float t) { Threads::Mutex::ScopedLock lock(log_lock); float_threshold = t; } bool LogStream::log_execution_time (const bool flag) { Threads::Mutex::ScopedLock lock(log_lock); const bool h = print_utime; print_utime = flag; return h; } bool LogStream::log_time_differences (const bool flag) { Threads::Mutex::ScopedLock lock(log_lock); const bool h = diff_utime; diff_utime = flag; return h; } bool LogStream::log_thread_id (const bool flag) { Threads::Mutex::ScopedLock lock(log_lock); const bool h = print_thread_id; print_thread_id = flag; return h; } std::stack<std::string> & LogStream::get_prefixes() const { #ifdef DEAL_II_WITH_THREADS bool exists = false; std::stack<std::string> &local_prefixes = prefixes.get(exists); // If this is a new locally stored stack, copy the "blessed" prefixes // from the initial thread that created logstream. if(! exists) { const tbb::enumerable_thread_specific<std::stack<std::string> > &impl = prefixes.get_implementation(); // The thread that created this LogStream object should be the first // in tbb's enumerable_thread_specific containter. const tbb::enumerable_thread_specific<std::stack<std::string> >::const_iterator first_elem = impl.begin(); if (first_elem != impl.end()) { local_prefixes = *first_elem; } } return local_prefixes; #else return prefixes.get(); #endif } void LogStream::print_line_head() { #ifdef HAVE_SYS_RESOURCE_H rusage usage; double utime = 0.; if (print_utime) { getrusage(RUSAGE_SELF, &usage); utime = usage.ru_utime.tv_sec + 1.e-6 * usage.ru_utime.tv_usec; if (diff_utime) { double diff = utime - last_time; last_time = utime; utime = diff; } } #else //TODO[BG]: Do something useful here double utime = 0.; #endif /* * The following lines were used for debugging a memory leak. * They work on Linux, not on Solaris, since the /proc filesystem * on Solaris is quite cryptic. For other systems, we don't know. * * Unfortunately, the information in /proc/pid/stat is updated slowly, * therefore, the information is quite unreliable. * * Furthermore, the constructor of ifstream caused another memory leak. * * Still, this code might be useful sometimes, so I kept it here. * When we have more information about the kernel, this should be * incorporated properly. Suggestions are welcome! */ #ifdef DEALII_MEMORY_DEBUG static const pid_t id = getpid(); std::ostringstream statname; statname << "/proc/" << id << "/stat"; static long size; static string dummy; ifstream stat(statname.str()); // ignore 22 values stat >> dummy >> dummy >> dummy >> dummy >> dummy >> dummy >> dummy >> dummy >> dummy >> dummy >> dummy >> dummy >> dummy >> dummy >> dummy >> dummy >> dummy >> dummy >> dummy >> dummy >> dummy >> dummy >> size; #endif const std::string &head = get_prefix(); const unsigned int thread = Threads::this_thread_id(); if (get_prefixes().size() <= std_depth) { if (print_utime) { int p = std_out->width(5); *std_out << utime << ':'; #ifdef DEALII_MEMORY_DEBUG *std_out << size << ':'; #endif std_out->width(p); } if (print_thread_id) *std_out << '[' << thread << ']'; *std_out << head << ':'; } if (file && (get_prefixes().size() <= file_depth)) { if (print_utime) { int p = file->width(6); *file << utime << ':'; #ifdef DEALII_MEMORY_DEBUG *file << size << ':'; #endif file->width(p); } if (print_thread_id) *file << '[' << thread << ']'; *file << head << ':'; } } void LogStream::timestamp () { struct tms current_tms; #if defined(HAVE_UNISTD_H) && defined(HAVE_TIMES) const clock_t tick = sysconf(_SC_CLK_TCK); const double time = 1./tick * times(&current_tms); #else const double time = 0.; const unsigned int tick = 100; #endif (*this) << "Wall: " << time - reference_time_val << " User: " << 1./tick * (current_tms.tms_utime - reference_tms.tms_utime) << " System: " << 1./tick * (current_tms.tms_stime - reference_tms.tms_stime) << " Child-User: " << 1./tick * (current_tms.tms_cutime - reference_tms.tms_cutime) << " Child-System: " << 1./tick * (current_tms.tms_cstime - reference_tms.tms_cstime) << std::endl; } std::size_t LogStream::memory_consumption () const { // TODO Assert(false, ExcNotImplemented()); std::size_t mem = sizeof(*this); // to determine size of stack // elements, we have to copy the // stack since we can't access // elements from further below // std::stack<std::string> tmp = prefixes; // while (tmp.empty() == false) // { // mem += MemoryConsumption::memory_consumption (tmp.top()); // tmp.pop (); // } return mem; } DEAL_II_NAMESPACE_CLOSE <commit_msg>Add the log_lock mutex to the three new method in LogStream that modify the stream<commit_after>//--------------------------------------------------------------------------- // $Id$ // Version: $Name$ // // Copyright (C) 1998, 1999, 2000, 2001, 2002, 2003, 2004, 2005, 2006, 2008, 2009, 2010, 2011, 2012 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. // //--------------------------------------------------------------------------- #include <deal.II/base/logstream.h> #include <deal.II/base/job_identifier.h> #include <deal.II/base/memory_consumption.h> #include <deal.II/base/thread_management.h> #ifdef HAVE_SYS_RESOURCE_H # include <sys/resource.h> #endif #ifdef HAVE_UNISTD_H # include <unistd.h> #endif #include <iostream> #include <iomanip> #include <fstream> #include <sstream> DEAL_II_NAMESPACE_OPEN namespace { Threads::Mutex log_lock; Threads::Mutex write_lock; } // The standard log object of deal.II: LogStream deallog; LogStream::LogStream() : std_out(&std::cerr), file(0), std_depth(10000), file_depth(10000), print_utime(false), diff_utime(false), last_time (0.), double_threshold(0.), float_threshold(0.), offset(0), old_cerr(0), at_newline(true), stream_flags(std::ios::showpoint | std::ios::left), stream_width(std::cout.width()), stream_precision(std::cout.precision()) { get_prefixes().push("DEAL:"); #if defined(HAVE_UNISTD_H) && defined(HAVE_TIMES) reference_time_val = 1./sysconf(_SC_CLK_TCK) * times(&reference_tms); #endif } LogStream::~LogStream() { // if there was anything left in the stream that is current to this // thread, make sure we flush it before it gets lost { if (get_stream().str().length() > 0) { // except the situation is not quite that simple. if this object is // the 'deallog' object, then it is destroyed upon exit of the // program. since it's defined in a shared library that depends on // libstdc++.so, destruction happens before destruction of // std::cout/cerr, but after all file variables defined in user // programs have been destroyed. in other words, if we get here and // the object being destroyed is 'deallog' and if 'deallog' is // associated with a file stream, then we're in trouble: we'll try // to write to a file that doesn't exist any more, and we're likely // going to crash (this is tested by base/log_crash_01). rather // than letting it come to this, print a message to the screen // (note that we can't issue an assertion here either since Assert // may want to write to 'deallog' itself, and AssertThrow will // throw an exception that can't be caught) if ((this == &deallog) && file) std::cerr << ("You still have content that was written to 'deallog' " "but not flushed to the screen or a file while the " "program is being terminated. This would lead to a " "segmentation fault. Make sure you flush the " "content of the 'deallog' object using 'std::endl' " "before the end of the program.") << std::endl; else *this << std::endl; } } if (old_cerr) std::cerr.rdbuf(old_cerr); } void LogStream::test_mode(bool on) { Threads::Mutex::ScopedLock lock(log_lock); if (on) { double_threshold = 1.e-10; float_threshold = 1.e-7; offset = 1.e-7; } else { double_threshold = 0.; float_threshold = 0.; offset = 0.; } } LogStream & LogStream::operator<< (std::ostream& (*p) (std::ostream &)) { std::ostringstream &stream = get_stream(); // save the state of out stream std::ios::fmtflags old_flags = stream.flags(stream_flags); unsigned int old_precision = stream.precision (stream_precision); unsigned int old_width = stream.width (stream_width); // Print to the internal stringstream: stream << p; // Next check whether this is the <tt>flush</tt> or <tt>endl</tt> // manipulator, and if so print out the message. std::ostream & (* const p_flush) (std::ostream &) = &std::flush; std::ostream & (* const p_endl) (std::ostream &) = &std::endl; if (p == p_flush || p == p_endl) { Threads::Mutex::ScopedLock lock(write_lock); // Print the line head in case of a newline: if (at_newline) print_line_head(); if(p == p_flush) at_newline = false; if(p == p_endl) at_newline = true; if (get_prefixes().size() <= std_depth) *std_out << stream.str(); if (file && (get_prefixes().size() <= file_depth)) *file << stream.str() << std::flush; // Start a new string stream.str(""); } // reset output format stream.flags (old_flags); stream.precision(old_precision); stream.width(old_width); return *this; } void LogStream::attach(std::ostream &o) { Threads::Mutex::ScopedLock lock(log_lock); file = &o; o.setf(std::ios::showpoint | std::ios::left); o << dealjobid(); } void LogStream::detach () { Threads::Mutex::ScopedLock lock(log_lock); file = 0; } void LogStream::log_cerr () { Threads::Mutex::ScopedLock lock(log_lock); if (old_cerr == 0) { old_cerr = std::cerr.rdbuf(file->rdbuf()); } else { std::cerr.rdbuf(old_cerr); old_cerr = 0; } } std::ostream & LogStream::get_console() { return *std_out; } std::ostream & LogStream::get_file_stream() { Assert(file, ExcNoFileStreamGiven()); return *file; } bool LogStream::has_file() const { return (file != 0); } const std::string & LogStream::get_prefix() const { return get_prefixes().top(); } void LogStream::push (const std::string &text) { std::string pre=get_prefixes().top(); pre += text; pre += std::string(":"); get_prefixes().push(pre); } void LogStream::pop () { if (get_prefixes().size() > 1) get_prefixes().pop(); } std::ios::fmtflags LogStream::flags(const std::ios::fmtflags f) { Threads::Mutex::ScopedLock lock(log_lock); std::ios::fmtflags tmp = stream_flags; stream_flags = f; return tmp; } std::streamsize LogStream::precision (const std::streamsize prec) { Threads::Mutex::ScopedLock lock(log_lock); std::streamsize tmp = stream_precision; stream_precision = prec; return tmp; } std::streamsize LogStream::width (const std::streamsize wide) { Threads::Mutex::ScopedLock lock(log_lock); std::streamsize tmp = stream_width; stream_width = wide; return tmp; } unsigned int LogStream::depth_console (const unsigned int n) { Threads::Mutex::ScopedLock lock(log_lock); const unsigned int h = std_depth; std_depth = n; return h; } unsigned int LogStream::depth_file (const unsigned int n) { Threads::Mutex::ScopedLock lock(log_lock); const unsigned int h = file_depth; file_depth = n; return h; } void LogStream::threshold_double (const double t) { Threads::Mutex::ScopedLock lock(log_lock); double_threshold = t; } void LogStream::threshold_float (const float t) { Threads::Mutex::ScopedLock lock(log_lock); float_threshold = t; } bool LogStream::log_execution_time (const bool flag) { Threads::Mutex::ScopedLock lock(log_lock); const bool h = print_utime; print_utime = flag; return h; } bool LogStream::log_time_differences (const bool flag) { Threads::Mutex::ScopedLock lock(log_lock); const bool h = diff_utime; diff_utime = flag; return h; } bool LogStream::log_thread_id (const bool flag) { Threads::Mutex::ScopedLock lock(log_lock); const bool h = print_thread_id; print_thread_id = flag; return h; } std::stack<std::string> & LogStream::get_prefixes() const { #ifdef DEAL_II_WITH_THREADS bool exists = false; std::stack<std::string> &local_prefixes = prefixes.get(exists); // If this is a new locally stored stack, copy the "blessed" prefixes // from the initial thread that created logstream. if(! exists) { const tbb::enumerable_thread_specific<std::stack<std::string> > &impl = prefixes.get_implementation(); // The thread that created this LogStream object should be the first // in tbb's enumerable_thread_specific containter. const tbb::enumerable_thread_specific<std::stack<std::string> >::const_iterator first_elem = impl.begin(); if (first_elem != impl.end()) { local_prefixes = *first_elem; } } return local_prefixes; #else return prefixes.get(); #endif } void LogStream::print_line_head() { #ifdef HAVE_SYS_RESOURCE_H rusage usage; double utime = 0.; if (print_utime) { getrusage(RUSAGE_SELF, &usage); utime = usage.ru_utime.tv_sec + 1.e-6 * usage.ru_utime.tv_usec; if (diff_utime) { double diff = utime - last_time; last_time = utime; utime = diff; } } #else //TODO[BG]: Do something useful here double utime = 0.; #endif /* * The following lines were used for debugging a memory leak. * They work on Linux, not on Solaris, since the /proc filesystem * on Solaris is quite cryptic. For other systems, we don't know. * * Unfortunately, the information in /proc/pid/stat is updated slowly, * therefore, the information is quite unreliable. * * Furthermore, the constructor of ifstream caused another memory leak. * * Still, this code might be useful sometimes, so I kept it here. * When we have more information about the kernel, this should be * incorporated properly. Suggestions are welcome! */ #ifdef DEALII_MEMORY_DEBUG static const pid_t id = getpid(); std::ostringstream statname; statname << "/proc/" << id << "/stat"; static long size; static string dummy; ifstream stat(statname.str()); // ignore 22 values stat >> dummy >> dummy >> dummy >> dummy >> dummy >> dummy >> dummy >> dummy >> dummy >> dummy >> dummy >> dummy >> dummy >> dummy >> dummy >> dummy >> dummy >> dummy >> dummy >> dummy >> dummy >> dummy >> size; #endif const std::string &head = get_prefix(); const unsigned int thread = Threads::this_thread_id(); if (get_prefixes().size() <= std_depth) { if (print_utime) { int p = std_out->width(5); *std_out << utime << ':'; #ifdef DEALII_MEMORY_DEBUG *std_out << size << ':'; #endif std_out->width(p); } if (print_thread_id) *std_out << '[' << thread << ']'; *std_out << head << ':'; } if (file && (get_prefixes().size() <= file_depth)) { if (print_utime) { int p = file->width(6); *file << utime << ':'; #ifdef DEALII_MEMORY_DEBUG *file << size << ':'; #endif file->width(p); } if (print_thread_id) *file << '[' << thread << ']'; *file << head << ':'; } } void LogStream::timestamp () { struct tms current_tms; #if defined(HAVE_UNISTD_H) && defined(HAVE_TIMES) const clock_t tick = sysconf(_SC_CLK_TCK); const double time = 1./tick * times(&current_tms); #else const double time = 0.; const unsigned int tick = 100; #endif (*this) << "Wall: " << time - reference_time_val << " User: " << 1./tick * (current_tms.tms_utime - reference_tms.tms_utime) << " System: " << 1./tick * (current_tms.tms_stime - reference_tms.tms_stime) << " Child-User: " << 1./tick * (current_tms.tms_cutime - reference_tms.tms_cutime) << " Child-System: " << 1./tick * (current_tms.tms_cstime - reference_tms.tms_cstime) << std::endl; } std::size_t LogStream::memory_consumption () const { // TODO Assert(false, ExcNotImplemented()); std::size_t mem = sizeof(*this); // to determine size of stack // elements, we have to copy the // stack since we can't access // elements from further below // std::stack<std::string> tmp = prefixes; // while (tmp.empty() == false) // { // mem += MemoryConsumption::memory_consumption (tmp.top()); // tmp.pop (); // } return mem; } DEAL_II_NAMESPACE_CLOSE <|endoftext|>
<commit_before>// Copyright (c) 2015, Ming Wen // // fys.hpp // // General header file of this software. #include <iostream> #include <fstream> #include <string> #include <vector> #include <cstdlib> #include <opencv2/core/core.hpp> #include <opencv2/highgui/highgui.hpp> #include <opencv2/features2d/features2d.hpp> #include <opencv2/nonfree/features2d.hpp> #include <unistd.h> // Declarations of classes namespace fys{ enum Features {null}; } // namespace fys <commit_msg>adapt header<commit_after>// Copyright (c) 2015, Ming Wen // // fys.hpp // // General header file of this software. #ifndef _H_FYS #define _H_FYS #include <iostream> #include <fstream> #include <string> #include <vector> #include <cstdlib> #include <opencv2/core/core.hpp> #include <opencv2/highgui/highgui.hpp> #include <opencv2/features2d/features2d.hpp> #include <opencv2/nonfree/features2d.hpp> #include <unistd.h> // Declarations of classes namespace fys{ enum Features {null}; } // namespace fys #endif // _H_FYS <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: translatechanges.hxx,v $ * * $Revision: 1.7 $ * * last change: $Author: hr $ $Date: 2004-06-18 15:47:14 $ * * 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 CONFIGMGR_API_TRANSLATECHANGES_HXX_ #define CONFIGMGR_API_TRANSLATECHANGES_HXX_ #include <com/sun/star/beans/XPropertyChangeListener.hpp> #include <com/sun/star/beans/XVetoableChangeListener.hpp> #include <com/sun/star/beans/XPropertiesChangeListener.hpp> #include <com/sun/star/container/XContainerListener.hpp> #include <com/sun/star/util/XChangesListener.hpp> namespace configmgr { // --------------------------------------------------------------------------------------------------- namespace css = ::com::sun::star; namespace uno = css::uno; namespace lang = css::lang; namespace util = css::util; namespace beans = css::beans; namespace container = css::container; // --------------------------------------------------------------------------------------------------- namespace memory { class Accessor; } namespace configuration { class NodeChangeInformation; class NodeChangeData; class NodeChangeLocation; //class NodeChange; //class NodeChanges; class Tree; class TreeRef; class NodeRef; class NodeID; class RelativePath; } // --------------------------------------------------------------------------------------------------- namespace configapi { class NotifierImpl; class Factory; struct UnoChange { uno::Any newValue, oldValue; }; //interpreting NodeChanges // resolve the relative path from a given base tree (root) to the changed node bool resolveChangeLocation( configuration::RelativePath& aPath, configuration::NodeChangeLocation const& aChange, configuration::Tree const& aBaseTree); // resolve the relative path from a given base node to the changed node bool resolveChangeLocation( configuration::RelativePath& aPath, configuration::NodeChangeLocation const& aChange, configuration::Tree const& aBaseTree, configuration::NodeRef const& aBaseNode); // change path and base settings to start from the given base tree (root) bool rebaseChange( memory::Accessor const& _aAccessor, configuration::NodeChangeLocation& aChange, configuration::TreeRef const& _aBaseTreeRef); // change path and base settings to start from the given base node bool rebaseChange( memory::Accessor const& _aAccessor, configuration::NodeChangeLocation& aChange, configuration::TreeRef const& _aBaseTreeRef, configuration::NodeRef const& aBaseNode); // resolve non-uno elements to Uno Objects bool resolveUnoObjects(UnoChange& aUnoChange, configuration::NodeChangeData const& aChange, const memory::Accessor& aAccessor, Factory& rFactory); // resolve non-uno elements to Uno Objects inplace bool resolveToUno(configuration::NodeChangeData& aChange, const memory::Accessor& aAccessor, Factory& rFactory); // building events /// find the sending api object void fillEventSource(lang::EventObject& rEvent, configuration::Tree const& aTree, configuration::NodeRef const& aNode, Factory& rFactory); /// fill a change info from a NodeChangeInfo void fillChange(util::ElementChange& rChange, configuration::NodeChangeInformation const& aInfo, configuration::Tree const& aBaseTree, Factory& rFactory); /// fill a change info from a NodeChangeInfo void fillChange(util::ElementChange& rChange, configuration::NodeChangeInformation const& aInfo, configuration::Tree const& aBaseTree, configuration::NodeRef const& aBaseNode, Factory& rFactory); /// fill a change info from a NodeChangeInfo (base,path and uno objects are assumed to be resolved already) void fillChangeFromResolved(util::ElementChange& rChange, configuration::NodeChangeInformation const& aInfo); /// fill a event from a NodeChangeInfo bool fillEventData(container::ContainerEvent& rEvent, configuration::NodeChangeInformation const& aInfo, Factory& rFactory); /// fill a event from a NodeChangeInfo (uno objects are assumed to be resolved already) bool fillEventDataFromResolved(container::ContainerEvent& rEvent, configuration::NodeChangeInformation const& aInfo); /// fill a event from a NodeChangeInfo(uno objects are assumed to be resolved already) - returns false if this isn't a property change bool fillEventData(beans::PropertyChangeEvent& rEvent, configuration::NodeChangeInformation const& aInfo, Factory& rFactory, bool bMore); /// fill a event from a NodeChangeInfo(uno objects are assumed to be resolved already) - returns false if this isn't a property change bool fillEventDataFromResolved(beans::PropertyChangeEvent& rEvent, configuration::NodeChangeInformation const& aInfo, bool bMore); } // --------------------------------------------------------------------------------------------------- } #endif // CONFIGMGR_API_TRANSLATECHANGES_HXX_ <commit_msg>INTEGRATION: CWS ooo19126 (1.7.74); FILE MERGED 2005/09/05 17:03:46 rt 1.7.74.1: #i54170# Change license header: remove SISSL<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: translatechanges.hxx,v $ * * $Revision: 1.8 $ * * last change: $Author: rt $ $Date: 2005-09-08 03:21:48 $ * * 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 * ************************************************************************/ #ifndef CONFIGMGR_API_TRANSLATECHANGES_HXX_ #define CONFIGMGR_API_TRANSLATECHANGES_HXX_ #include <com/sun/star/beans/XPropertyChangeListener.hpp> #include <com/sun/star/beans/XVetoableChangeListener.hpp> #include <com/sun/star/beans/XPropertiesChangeListener.hpp> #include <com/sun/star/container/XContainerListener.hpp> #include <com/sun/star/util/XChangesListener.hpp> namespace configmgr { // --------------------------------------------------------------------------------------------------- namespace css = ::com::sun::star; namespace uno = css::uno; namespace lang = css::lang; namespace util = css::util; namespace beans = css::beans; namespace container = css::container; // --------------------------------------------------------------------------------------------------- namespace memory { class Accessor; } namespace configuration { class NodeChangeInformation; class NodeChangeData; class NodeChangeLocation; //class NodeChange; //class NodeChanges; class Tree; class TreeRef; class NodeRef; class NodeID; class RelativePath; } // --------------------------------------------------------------------------------------------------- namespace configapi { class NotifierImpl; class Factory; struct UnoChange { uno::Any newValue, oldValue; }; //interpreting NodeChanges // resolve the relative path from a given base tree (root) to the changed node bool resolveChangeLocation( configuration::RelativePath& aPath, configuration::NodeChangeLocation const& aChange, configuration::Tree const& aBaseTree); // resolve the relative path from a given base node to the changed node bool resolveChangeLocation( configuration::RelativePath& aPath, configuration::NodeChangeLocation const& aChange, configuration::Tree const& aBaseTree, configuration::NodeRef const& aBaseNode); // change path and base settings to start from the given base tree (root) bool rebaseChange( memory::Accessor const& _aAccessor, configuration::NodeChangeLocation& aChange, configuration::TreeRef const& _aBaseTreeRef); // change path and base settings to start from the given base node bool rebaseChange( memory::Accessor const& _aAccessor, configuration::NodeChangeLocation& aChange, configuration::TreeRef const& _aBaseTreeRef, configuration::NodeRef const& aBaseNode); // resolve non-uno elements to Uno Objects bool resolveUnoObjects(UnoChange& aUnoChange, configuration::NodeChangeData const& aChange, const memory::Accessor& aAccessor, Factory& rFactory); // resolve non-uno elements to Uno Objects inplace bool resolveToUno(configuration::NodeChangeData& aChange, const memory::Accessor& aAccessor, Factory& rFactory); // building events /// find the sending api object void fillEventSource(lang::EventObject& rEvent, configuration::Tree const& aTree, configuration::NodeRef const& aNode, Factory& rFactory); /// fill a change info from a NodeChangeInfo void fillChange(util::ElementChange& rChange, configuration::NodeChangeInformation const& aInfo, configuration::Tree const& aBaseTree, Factory& rFactory); /// fill a change info from a NodeChangeInfo void fillChange(util::ElementChange& rChange, configuration::NodeChangeInformation const& aInfo, configuration::Tree const& aBaseTree, configuration::NodeRef const& aBaseNode, Factory& rFactory); /// fill a change info from a NodeChangeInfo (base,path and uno objects are assumed to be resolved already) void fillChangeFromResolved(util::ElementChange& rChange, configuration::NodeChangeInformation const& aInfo); /// fill a event from a NodeChangeInfo bool fillEventData(container::ContainerEvent& rEvent, configuration::NodeChangeInformation const& aInfo, Factory& rFactory); /// fill a event from a NodeChangeInfo (uno objects are assumed to be resolved already) bool fillEventDataFromResolved(container::ContainerEvent& rEvent, configuration::NodeChangeInformation const& aInfo); /// fill a event from a NodeChangeInfo(uno objects are assumed to be resolved already) - returns false if this isn't a property change bool fillEventData(beans::PropertyChangeEvent& rEvent, configuration::NodeChangeInformation const& aInfo, Factory& rFactory, bool bMore); /// fill a event from a NodeChangeInfo(uno objects are assumed to be resolved already) - returns false if this isn't a property change bool fillEventDataFromResolved(beans::PropertyChangeEvent& rEvent, configuration::NodeChangeInformation const& aInfo, bool bMore); } // --------------------------------------------------------------------------------------------------- } #endif // CONFIGMGR_API_TRANSLATECHANGES_HXX_ <|endoftext|>
<commit_before>/** * Copyright 2014-2015 Steven T Sell (ssell@ocularinteractive.com) * * 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 "Input/InputHandler.hpp" #include "OcularEngine.hpp" #include "Events/Events/KeyboardInputEvent.hpp" #include "Events/Events/MouseButtonInputEvent.hpp" #include "Events/Events/MouseMoveInputEvent.hpp" #include <algorithm> //------------------------------------------------------------------------------------------ namespace Ocular { namespace Core { //---------------------------------------------------------------------------------- // CONSTRUCTORS //---------------------------------------------------------------------------------- InputHandler::InputHandler() { m_KeyboardState.fill(false); m_MouseState.fill(false); } InputHandler::~InputHandler() { } //---------------------------------------------------------------------------------- // PUBLIC METHODS //---------------------------------------------------------------------------------- void InputHandler::triggerKeyboardKeyDown(KeyboardKeys key) { shiftConvertKey(key); if(!m_KeyboardState[static_cast<uint8_t>(key)]) { toggleKeyState(key); } } void InputHandler::triggerMouseButtonDown(MouseButtons const button) { if(!m_MouseState[static_cast<uint8_t>(button)]) { toggleButtonState(button); } } void InputHandler::triggerKeyboardKeyUp(KeyboardKeys key) { if((key == KeyboardKeys::ShiftLeft) || (key == KeyboardKeys::ShiftRight)) { swapShiftSpecialKeys(); } else { shiftConvertKey(key); } if(m_KeyboardState[static_cast<uint8_t>(key)]) { toggleKeyState(key); } } void InputHandler::triggerMouseButtonUp(MouseButtons const button) { if(m_MouseState[static_cast<uint8_t>(button)]) { toggleButtonState(button); } } void InputHandler::setMousePosition(Math::Vector2f const& position) { m_MousePositionCurrent = position; } Math::Vector2f const& InputHandler::getMousePosition() const { return m_MousePositionCurrent; } bool InputHandler::isKeyboardKeyDown(KeyboardKeys const key) const { return m_KeyboardState[static_cast<uint8_t>(key)]; } bool InputHandler::isMouseButtonDown(MouseButtons const button) const { return m_KeyboardState[static_cast<uint8_t>(button)]; } bool InputHandler::isLeftShiftDown() const { return m_KeyboardState[4]; } bool InputHandler::isRightShiftDown() const { return m_KeyboardState[5]; } bool InputHandler::isLeftCtrlDown() const { return m_KeyboardState[6]; } bool InputHandler::isRightCtrlDown() const { return m_KeyboardState[7]; } bool InputHandler::isLeftAltDown() const { return m_KeyboardState[8]; } bool InputHandler::isRightAltDown() const { return m_KeyboardState[9]; } bool InputHandler::isLeftMouseDown() const { return m_MouseState[0]; } bool InputHandler::isRightMouseDown() const { return m_MouseState[1]; } //---------------------------------------------------------------------------------- // PROTECTED METHODS //---------------------------------------------------------------------------------- void InputHandler::update() { } //---------------------------------------------------------------------------------- // PRIVATE METHODS //---------------------------------------------------------------------------------- void InputHandler::toggleKeyState(KeyboardKeys const key) { // Toggle the state and generate an event const uint8_t index = static_cast<uint8_t>(key); const KeyState state = (!m_KeyboardState[index] ? KeyState::Pressed : KeyState::Released); OcularEvents->queueEvent(std::make_shared<Events::KeyboardInputEvent>(key, state)); m_KeyboardState[index] = !m_KeyboardState[index]; } void InputHandler::toggleButtonState(MouseButtons const button) { // Toggle the state and generate an event const uint8_t index = static_cast<uint8_t>(button); const KeyState state = (!m_MouseState[index] ? KeyState::Pressed : KeyState::Released); OcularEvents->queueEvent(std::make_shared<Events::MouseButtonInputEvent>(button, state)); m_MouseState[index] = !m_MouseState[index]; } void InputHandler::shiftConvertKey(KeyboardKeys& key) { if(m_KeyboardState[static_cast<uint8_t>(KeyboardKeys::ShiftLeft)] || m_KeyboardState[static_cast<uint8_t>(KeyboardKeys::ShiftRight)]) { switch(key) { case KeyboardKeys::Apostrophe: key = KeyboardKeys::Tilde; break; case KeyboardKeys::Mainpad1: key = KeyboardKeys::ExclamationMark; break; case KeyboardKeys::Mainpad2: key = KeyboardKeys::Ampersat; break; case KeyboardKeys::Mainpad3: key = KeyboardKeys::Hash; break; case KeyboardKeys::Mainpad4: key = KeyboardKeys::DollarSign; break; case KeyboardKeys::Mainpad5: key = KeyboardKeys::PercentSign; break; case KeyboardKeys::Mainpad6: key = KeyboardKeys::Caret; break; case KeyboardKeys::Mainpad7: key = KeyboardKeys::Ampersand; break; case KeyboardKeys::Mainpad8: key = KeyboardKeys::Multiply; break; case KeyboardKeys::Mainpad9: key = KeyboardKeys::ParenthesisLeft; break; case KeyboardKeys::Mainpad0: key = KeyboardKeys::ParenthesisRight; break; case KeyboardKeys::Subtract: key = KeyboardKeys::Underscore; break; case KeyboardKeys::Equals: key = KeyboardKeys::Plus; break; case KeyboardKeys::BracketLeft: key = KeyboardKeys::CurlyBracketLeft; break; case KeyboardKeys::BracketRight: key = KeyboardKeys::CurlyBracketRight; break; case KeyboardKeys::Backslash: key = KeyboardKeys::Pipe; break; case KeyboardKeys::Semicolon: key = KeyboardKeys::Colon; break; case KeyboardKeys::QuotationSingle: key = KeyboardKeys::QuotationDouble; break; case KeyboardKeys::Comma: key = KeyboardKeys::AngleBracketLeft; break; case KeyboardKeys::Period: key = KeyboardKeys::AngleBracketRight; break; case KeyboardKeys::ForwardSlash: key = KeyboardKeys::QuestionMark; break; default: break; } } } void InputHandler::swapShiftSpecialKeys() { if(m_KeyboardState[static_cast<uint8_t>(KeyboardKeys::Tilde)]) { toggleKeyState(KeyboardKeys::Tilde); toggleKeyState(KeyboardKeys::Apostrophe); } if(m_KeyboardState[static_cast<uint8_t>(KeyboardKeys::ExclamationMark)]) { toggleKeyState(KeyboardKeys::ExclamationMark); toggleKeyState(KeyboardKeys::Mainpad1); } if(m_KeyboardState[static_cast<uint8_t>(KeyboardKeys::Ampersat)]) { toggleKeyState(KeyboardKeys::Ampersat); toggleKeyState(KeyboardKeys::Mainpad2); } if(m_KeyboardState[static_cast<uint8_t>(KeyboardKeys::Hash)]) { toggleKeyState(KeyboardKeys::Hash); toggleKeyState(KeyboardKeys::Mainpad3); } if(m_KeyboardState[static_cast<uint8_t>(KeyboardKeys::DollarSign)]) { toggleKeyState(KeyboardKeys::DollarSign); toggleKeyState(KeyboardKeys::Mainpad4); } if(m_KeyboardState[static_cast<uint8_t>(KeyboardKeys::PercentSign)]) { toggleKeyState(KeyboardKeys::PercentSign); toggleKeyState(KeyboardKeys::Mainpad5); } if(m_KeyboardState[static_cast<uint8_t>(KeyboardKeys::Caret)]) { toggleKeyState(KeyboardKeys::Caret); toggleKeyState(KeyboardKeys::Mainpad6); } if(m_KeyboardState[static_cast<uint8_t>(KeyboardKeys::Ampersand)]) { toggleKeyState(KeyboardKeys::Ampersand); toggleKeyState(KeyboardKeys::Mainpad7); } if(m_KeyboardState[static_cast<uint8_t>(KeyboardKeys::Multiply)]) { toggleKeyState(KeyboardKeys::Multiply); toggleKeyState(KeyboardKeys::Mainpad8); } if(m_KeyboardState[static_cast<uint8_t>(KeyboardKeys::ParenthesisLeft)]) { toggleKeyState(KeyboardKeys::ParenthesisLeft); toggleKeyState(KeyboardKeys::Mainpad9); } if(m_KeyboardState[static_cast<uint8_t>(KeyboardKeys::ParenthesisRight)]) { toggleKeyState(KeyboardKeys::ParenthesisRight); toggleKeyState(KeyboardKeys::Mainpad0); } if(m_KeyboardState[static_cast<uint8_t>(KeyboardKeys::Underscore)]) { toggleKeyState(KeyboardKeys::Underscore); toggleKeyState(KeyboardKeys::Subtract); } if(m_KeyboardState[static_cast<uint8_t>(KeyboardKeys::Multiply)]) { toggleKeyState(KeyboardKeys::Multiply); toggleKeyState(KeyboardKeys::Equals); } if(m_KeyboardState[static_cast<uint8_t>(KeyboardKeys::CurlyBracketLeft)]) { toggleKeyState(KeyboardKeys::CurlyBracketLeft); toggleKeyState(KeyboardKeys::BracketLeft); } if(m_KeyboardState[static_cast<uint8_t>(KeyboardKeys::CurlyBracketRight)]) { toggleKeyState(KeyboardKeys::CurlyBracketRight); toggleKeyState(KeyboardKeys::BracketRight); } if(m_KeyboardState[static_cast<uint8_t>(KeyboardKeys::Pipe)]) { toggleKeyState(KeyboardKeys::Pipe); toggleKeyState(KeyboardKeys::Backslash); } if(m_KeyboardState[static_cast<uint8_t>(KeyboardKeys::Colon)]) { toggleKeyState(KeyboardKeys::Colon); toggleKeyState(KeyboardKeys::Semicolon); } if(m_KeyboardState[static_cast<uint8_t>(KeyboardKeys::QuotationDouble)]) { toggleKeyState(KeyboardKeys::QuotationDouble); toggleKeyState(KeyboardKeys::QuotationSingle); } if(m_KeyboardState[static_cast<uint8_t>(KeyboardKeys::AngleBracketLeft)]) { toggleKeyState(KeyboardKeys::AngleBracketLeft); toggleKeyState(KeyboardKeys::Comma); } if(m_KeyboardState[static_cast<uint8_t>(KeyboardKeys::AngleBracketRight)]) { toggleKeyState(KeyboardKeys::AngleBracketRight); toggleKeyState(KeyboardKeys::Period); } if(m_KeyboardState[static_cast<uint8_t>(KeyboardKeys::QuestionMark)]) { toggleKeyState(KeyboardKeys::QuestionMark); toggleKeyState(KeyboardKeys::ForwardSlash); } } //---------------------------------------------------------------------------------- // STATIC METHODS //---------------------------------------------------------------------------------- std::string InputHandler::ToString(KeyState const state) { static std::string stringArray[2] = { "Released", "Pressed" }; return stringArray[static_cast<uint8_t>(state)]; } std::string InputHandler::ToString(MouseButtons const button) { static std::string stringArray[3] = { "Left", "Right", "Middle" }; return stringArray[static_cast<uint8_t>(button)]; } std::string InputHandler::ToString(KeyboardKeys const key) { static std::string stringArray[255] = { "Backspace", "Tab", "Clear", "Enter", "Left Shift", "Right Shift", "Left Ctrl", "Right Ctrl", "Left Alt", "Right Alt", "Pause", "Caps Lock", "Escape", "Space", "Page Up", "Page Down", "End", "Home", "Left Arrow", "Right Arrow", "Up Arrow", "Down Arrow", "Select", "Execute", "Print Screen", "Insert", "Delete", "Help", "OS Key", "-", "_", "+", "=", "[", "]", "{", "}", "\\", "|", ";", ":", "'", "\"", ",", ".", "<", ">", "/", "?", "`", "~", "!", "@", "#", "$", "%", "^", "&", "*", "(", ")", "Undefined", "Undefined", "Undefined", "Undefined", "Undefined", "Undefined", "Undefined", "Undefined", "Undefined", "Undefined", "Undefined", "Undefined", "Undefined", "Undefined", "Undefined", "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "+", "-", "*", "/", ".", "Separator", "Enter", "Undefined", "Undefined", "Undefined", "Undefined", "Undefined", "Undefined", "Undefined", "Undefined", "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z", "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "Enter", "Undefined", "Undefined", "Undefined", "Undefined", "Undefined", "Undefined", "Undefined", "Undefined", "Undefined", "Undefined", "Undefined", "Undefined", "Undefined", "F1", "F2", "F3", "F4", "F5", "F6", "F7", "F8", "F9", "F10", "F11", "F12", "F13", "F14", "F15", "F16", "F17", "F18", "F19", "F20", "F21", "F22", "F23", "F24", "Undefined", "Undefined", "Undefined", "Undefined", "Undefined", "Undefined", "Undefined", "Undefined", "Undefined", "Undefined", "Undefined", "Undefined", "Undefined", "Undefined", "Undefined", "Undefined", "Undefined", "Undefined", "Undefined", "Undefined", "Undefined", "Undefined", "Undefined", "Undefined", "Undefined", "Undefined", "Undefined", "Undefined", "Undefined", "Undefined", "Undefined", "Undefined", "Undefined", "Undefined", "Undefined", "Undefined", "Undefined", "Undefined", "Undefined", "Undefined", "Undefined", "Undefined", "Undefined", "Undefined", "Undefined", "Undefined", "Undefined", "Undefined", "Undefined", "Undefined", "Undefined", "Undefined", "Undefined", "Undefined", "Undefined", "Undefined", "Undefined", "Undefined", "Undefined", "Undefined", "Undefined", "Undefined", "Undefined", "Undefined", "Undefined", "Undefined", "Undefined", "Undefined", "Undefined", "Undefined", "Undefined", "Undefined", "Undefined", "Undefined", "Undefined", "Undefined", "Undefined", "Undefined", "Undefined", "Undefined" }; return stringArray[static_cast<uint8_t>(key)]; } } }<commit_msg>Fix to improper input state swaps<commit_after>/** * Copyright 2014-2015 Steven T Sell (ssell@ocularinteractive.com) * * 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 "Input/InputHandler.hpp" #include "OcularEngine.hpp" #include "Events/Events/KeyboardInputEvent.hpp" #include "Events/Events/MouseButtonInputEvent.hpp" #include "Events/Events/MouseMoveInputEvent.hpp" #include <algorithm> //------------------------------------------------------------------------------------------ namespace Ocular { namespace Core { //---------------------------------------------------------------------------------- // CONSTRUCTORS //---------------------------------------------------------------------------------- InputHandler::InputHandler() { m_KeyboardState.fill(false); m_MouseState.fill(false); } InputHandler::~InputHandler() { } //---------------------------------------------------------------------------------- // PUBLIC METHODS //---------------------------------------------------------------------------------- void InputHandler::triggerKeyboardKeyDown(KeyboardKeys key) { shiftConvertKey(key); if(!m_KeyboardState[static_cast<uint8_t>(key)]) { toggleKeyState(key); } } void InputHandler::triggerMouseButtonDown(MouseButtons const button) { if(!m_MouseState[static_cast<uint8_t>(button)]) { toggleButtonState(button); } } void InputHandler::triggerKeyboardKeyUp(KeyboardKeys key) { if((key == KeyboardKeys::ShiftLeft) || (key == KeyboardKeys::ShiftRight)) { swapShiftSpecialKeys(); } else { if(m_KeyboardState[static_cast<uint8_t>(key)]) { toggleKeyState(key); return; } else { shiftConvertKey(key); } } if(m_KeyboardState[static_cast<uint8_t>(key)]) { toggleKeyState(key); } } void InputHandler::triggerMouseButtonUp(MouseButtons const button) { if(m_MouseState[static_cast<uint8_t>(button)]) { toggleButtonState(button); } } void InputHandler::setMousePosition(Math::Vector2f const& position) { m_MousePositionCurrent = position; } Math::Vector2f const& InputHandler::getMousePosition() const { return m_MousePositionCurrent; } bool InputHandler::isKeyboardKeyDown(KeyboardKeys const key) const { return m_KeyboardState[static_cast<uint8_t>(key)]; } bool InputHandler::isMouseButtonDown(MouseButtons const button) const { return m_KeyboardState[static_cast<uint8_t>(button)]; } bool InputHandler::isLeftShiftDown() const { return m_KeyboardState[4]; } bool InputHandler::isRightShiftDown() const { return m_KeyboardState[5]; } bool InputHandler::isLeftCtrlDown() const { return m_KeyboardState[6]; } bool InputHandler::isRightCtrlDown() const { return m_KeyboardState[7]; } bool InputHandler::isLeftAltDown() const { return m_KeyboardState[8]; } bool InputHandler::isRightAltDown() const { return m_KeyboardState[9]; } bool InputHandler::isLeftMouseDown() const { return m_MouseState[0]; } bool InputHandler::isRightMouseDown() const { return m_MouseState[1]; } //---------------------------------------------------------------------------------- // PROTECTED METHODS //---------------------------------------------------------------------------------- void InputHandler::update() { } //---------------------------------------------------------------------------------- // PRIVATE METHODS //---------------------------------------------------------------------------------- void InputHandler::toggleKeyState(KeyboardKeys const key) { // Toggle the state and generate an event const uint8_t index = static_cast<uint8_t>(key); const KeyState state = (!m_KeyboardState[index] ? KeyState::Pressed : KeyState::Released); OcularEvents->queueEvent(std::make_shared<Events::KeyboardInputEvent>(key, state)); m_KeyboardState[index] = !m_KeyboardState[index]; } void InputHandler::toggleButtonState(MouseButtons const button) { // Toggle the state and generate an event const uint8_t index = static_cast<uint8_t>(button); const KeyState state = (!m_MouseState[index] ? KeyState::Pressed : KeyState::Released); OcularEvents->queueEvent(std::make_shared<Events::MouseButtonInputEvent>(button, state)); m_MouseState[index] = !m_MouseState[index]; } void InputHandler::shiftConvertKey(KeyboardKeys& key) { if(m_KeyboardState[static_cast<uint8_t>(KeyboardKeys::ShiftLeft)] || m_KeyboardState[static_cast<uint8_t>(KeyboardKeys::ShiftRight)]) { switch(key) { case KeyboardKeys::Apostrophe: key = KeyboardKeys::Tilde; break; case KeyboardKeys::Mainpad1: key = KeyboardKeys::ExclamationMark; break; case KeyboardKeys::Mainpad2: key = KeyboardKeys::Ampersat; break; case KeyboardKeys::Mainpad3: key = KeyboardKeys::Hash; break; case KeyboardKeys::Mainpad4: key = KeyboardKeys::DollarSign; break; case KeyboardKeys::Mainpad5: key = KeyboardKeys::PercentSign; break; case KeyboardKeys::Mainpad6: key = KeyboardKeys::Caret; break; case KeyboardKeys::Mainpad7: key = KeyboardKeys::Ampersand; break; case KeyboardKeys::Mainpad8: key = KeyboardKeys::Multiply; break; case KeyboardKeys::Mainpad9: key = KeyboardKeys::ParenthesisLeft; break; case KeyboardKeys::Mainpad0: key = KeyboardKeys::ParenthesisRight; break; case KeyboardKeys::Subtract: key = KeyboardKeys::Underscore; break; case KeyboardKeys::Equals: key = KeyboardKeys::Plus; break; case KeyboardKeys::BracketLeft: key = KeyboardKeys::CurlyBracketLeft; break; case KeyboardKeys::BracketRight: key = KeyboardKeys::CurlyBracketRight; break; case KeyboardKeys::Backslash: key = KeyboardKeys::Pipe; break; case KeyboardKeys::Semicolon: key = KeyboardKeys::Colon; break; case KeyboardKeys::QuotationSingle: key = KeyboardKeys::QuotationDouble; break; case KeyboardKeys::Comma: key = KeyboardKeys::AngleBracketLeft; break; case KeyboardKeys::Period: key = KeyboardKeys::AngleBracketRight; break; case KeyboardKeys::ForwardSlash: key = KeyboardKeys::QuestionMark; break; default: break; } } } void InputHandler::swapShiftSpecialKeys() { if(m_KeyboardState[static_cast<uint8_t>(KeyboardKeys::Tilde)]) { toggleKeyState(KeyboardKeys::Tilde); toggleKeyState(KeyboardKeys::Apostrophe); } if(m_KeyboardState[static_cast<uint8_t>(KeyboardKeys::ExclamationMark)]) { toggleKeyState(KeyboardKeys::ExclamationMark); toggleKeyState(KeyboardKeys::Mainpad1); } if(m_KeyboardState[static_cast<uint8_t>(KeyboardKeys::Ampersat)]) { toggleKeyState(KeyboardKeys::Ampersat); toggleKeyState(KeyboardKeys::Mainpad2); } if(m_KeyboardState[static_cast<uint8_t>(KeyboardKeys::Hash)]) { toggleKeyState(KeyboardKeys::Hash); toggleKeyState(KeyboardKeys::Mainpad3); } if(m_KeyboardState[static_cast<uint8_t>(KeyboardKeys::DollarSign)]) { toggleKeyState(KeyboardKeys::DollarSign); toggleKeyState(KeyboardKeys::Mainpad4); } if(m_KeyboardState[static_cast<uint8_t>(KeyboardKeys::PercentSign)]) { toggleKeyState(KeyboardKeys::PercentSign); toggleKeyState(KeyboardKeys::Mainpad5); } if(m_KeyboardState[static_cast<uint8_t>(KeyboardKeys::Caret)]) { toggleKeyState(KeyboardKeys::Caret); toggleKeyState(KeyboardKeys::Mainpad6); } if(m_KeyboardState[static_cast<uint8_t>(KeyboardKeys::Ampersand)]) { toggleKeyState(KeyboardKeys::Ampersand); toggleKeyState(KeyboardKeys::Mainpad7); } if(m_KeyboardState[static_cast<uint8_t>(KeyboardKeys::Multiply)]) { toggleKeyState(KeyboardKeys::Multiply); toggleKeyState(KeyboardKeys::Mainpad8); } if(m_KeyboardState[static_cast<uint8_t>(KeyboardKeys::ParenthesisLeft)]) { toggleKeyState(KeyboardKeys::ParenthesisLeft); toggleKeyState(KeyboardKeys::Mainpad9); } if(m_KeyboardState[static_cast<uint8_t>(KeyboardKeys::ParenthesisRight)]) { toggleKeyState(KeyboardKeys::ParenthesisRight); toggleKeyState(KeyboardKeys::Mainpad0); } if(m_KeyboardState[static_cast<uint8_t>(KeyboardKeys::Underscore)]) { toggleKeyState(KeyboardKeys::Underscore); toggleKeyState(KeyboardKeys::Subtract); } if(m_KeyboardState[static_cast<uint8_t>(KeyboardKeys::Multiply)]) { toggleKeyState(KeyboardKeys::Multiply); toggleKeyState(KeyboardKeys::Equals); } if(m_KeyboardState[static_cast<uint8_t>(KeyboardKeys::CurlyBracketLeft)]) { toggleKeyState(KeyboardKeys::CurlyBracketLeft); toggleKeyState(KeyboardKeys::BracketLeft); } if(m_KeyboardState[static_cast<uint8_t>(KeyboardKeys::CurlyBracketRight)]) { toggleKeyState(KeyboardKeys::CurlyBracketRight); toggleKeyState(KeyboardKeys::BracketRight); } if(m_KeyboardState[static_cast<uint8_t>(KeyboardKeys::Pipe)]) { toggleKeyState(KeyboardKeys::Pipe); toggleKeyState(KeyboardKeys::Backslash); } if(m_KeyboardState[static_cast<uint8_t>(KeyboardKeys::Colon)]) { toggleKeyState(KeyboardKeys::Colon); toggleKeyState(KeyboardKeys::Semicolon); } if(m_KeyboardState[static_cast<uint8_t>(KeyboardKeys::QuotationDouble)]) { toggleKeyState(KeyboardKeys::QuotationDouble); toggleKeyState(KeyboardKeys::QuotationSingle); } if(m_KeyboardState[static_cast<uint8_t>(KeyboardKeys::AngleBracketLeft)]) { toggleKeyState(KeyboardKeys::AngleBracketLeft); toggleKeyState(KeyboardKeys::Comma); } if(m_KeyboardState[static_cast<uint8_t>(KeyboardKeys::AngleBracketRight)]) { toggleKeyState(KeyboardKeys::AngleBracketRight); toggleKeyState(KeyboardKeys::Period); } if(m_KeyboardState[static_cast<uint8_t>(KeyboardKeys::QuestionMark)]) { toggleKeyState(KeyboardKeys::QuestionMark); toggleKeyState(KeyboardKeys::ForwardSlash); } } //---------------------------------------------------------------------------------- // STATIC METHODS //---------------------------------------------------------------------------------- std::string InputHandler::ToString(KeyState const state) { static std::string stringArray[2] = { "Released", "Pressed" }; return stringArray[static_cast<uint8_t>(state)]; } std::string InputHandler::ToString(MouseButtons const button) { static std::string stringArray[3] = { "Left", "Right", "Middle" }; return stringArray[static_cast<uint8_t>(button)]; } std::string InputHandler::ToString(KeyboardKeys const key) { static std::string stringArray[255] = { "Backspace", "Tab", "Clear", "Enter", "Left Shift", "Right Shift", "Left Ctrl", "Right Ctrl", "Left Alt", "Right Alt", "Pause", "Caps Lock", "Escape", "Space", "Page Up", "Page Down", "End", "Home", "Left Arrow", "Right Arrow", "Up Arrow", "Down Arrow", "Select", "Execute", "Print Screen", "Insert", "Delete", "Help", "OS Key", "-", "_", "+", "=", "[", "]", "{", "}", "\\", "|", ";", ":", "'", "\"", ",", ".", "<", ">", "/", "?", "`", "~", "!", "@", "#", "$", "%", "^", "&", "*", "(", ")", "Undefined", "Undefined", "Undefined", "Undefined", "Undefined", "Undefined", "Undefined", "Undefined", "Undefined", "Undefined", "Undefined", "Undefined", "Undefined", "Undefined", "Undefined", "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "+", "-", "*", "/", ".", "Separator", "Enter", "Undefined", "Undefined", "Undefined", "Undefined", "Undefined", "Undefined", "Undefined", "Undefined", "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z", "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "Enter", "Undefined", "Undefined", "Undefined", "Undefined", "Undefined", "Undefined", "Undefined", "Undefined", "Undefined", "Undefined", "Undefined", "Undefined", "Undefined", "F1", "F2", "F3", "F4", "F5", "F6", "F7", "F8", "F9", "F10", "F11", "F12", "F13", "F14", "F15", "F16", "F17", "F18", "F19", "F20", "F21", "F22", "F23", "F24", "Undefined", "Undefined", "Undefined", "Undefined", "Undefined", "Undefined", "Undefined", "Undefined", "Undefined", "Undefined", "Undefined", "Undefined", "Undefined", "Undefined", "Undefined", "Undefined", "Undefined", "Undefined", "Undefined", "Undefined", "Undefined", "Undefined", "Undefined", "Undefined", "Undefined", "Undefined", "Undefined", "Undefined", "Undefined", "Undefined", "Undefined", "Undefined", "Undefined", "Undefined", "Undefined", "Undefined", "Undefined", "Undefined", "Undefined", "Undefined", "Undefined", "Undefined", "Undefined", "Undefined", "Undefined", "Undefined", "Undefined", "Undefined", "Undefined", "Undefined", "Undefined", "Undefined", "Undefined", "Undefined", "Undefined", "Undefined", "Undefined", "Undefined", "Undefined", "Undefined", "Undefined", "Undefined", "Undefined", "Undefined", "Undefined", "Undefined", "Undefined", "Undefined", "Undefined", "Undefined", "Undefined", "Undefined", "Undefined", "Undefined", "Undefined", "Undefined", "Undefined", "Undefined", "Undefined", "Undefined" }; return stringArray[static_cast<uint8_t>(key)]; } } }<|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: backendaccess.hxx,v $ * * $Revision: 1.11 $ * * last change: $Author: kz $ $Date: 2005-01-18 13:28:06 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (the "License"); You may not use this file * except in compliance with the License. You may obtain a copy of the * License at http://www.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #ifndef CONFIGMGR_BACKEND_BACKENDACCESS_HXX_ #define CONFIGMGR_BACKEND_BACKENDACCESS_HXX_ #ifndef CONFIGMGR_BACKEND_BACKENDNOTIFIER_HXX #include "backendnotifier.hxx" #endif // CONFIGMGR_BACKEND_BACKENDNOTIFIER_HXX #ifndef CONFIGMGR_BACKEND_MERGEDDATAPROVIDER_HXX #include "mergeddataprovider.hxx" #endif // CONFIGMGR_BACKEND_MERGEDDATAPROVIDER_HXX #ifndef CONFIGMGR_BACKEND_MERGEDCOMPONENTDATA_HXX #include "mergedcomponentdata.hxx" #endif // CONFIGMGR_BACKEND_MERGEDCOMPONENTDATA_HXX #ifndef CONFIGMGR_MATCHLOCALE_HXX #include "matchlocale.hxx" #endif #ifndef _COM_SUN_STAR_CONFIGURATION_BACKEND_XLAYER_HPP_ #include <com/sun/star/configuration/backend/XLayer.hpp> #endif // _COM_SUN_STAR_CONFIGURATION_BACKEND_XLAYER_HPP_ #ifndef _COM_SUN_STAR_CONFIGURATION_BACKEND_XSCHEMA_HPP_ #include <com/sun/star/configuration/backend/XSchema.hpp> #endif // _COM_SUN_STAR_CONFIGURATION_BACKEND_XSCHEMA_HPP_ #ifndef _COM_SUN_STAR_CONFIGURATION_BACKEND_XBACKEND_HPP_ #include <com/sun/star/configuration/backend/XBackend.hpp> #endif // _COM_SUN_STAR_CONFIGURATION_BACKEND_XBACKEND_HPP_ #ifndef _COM_SUN_STAR_UNO_XCOMPONENTCONTEXT_HPP_ #include <com/sun/star/uno/XComponentContext.hpp> #endif #ifndef _COM_SUN_STAR_LANG_XMULTISERVICEFACTORY_HPP_ #include <com/sun/star/lang/XMultiServiceFactory.hpp> #endif #ifndef CONFIGMGR_BINARYCACHE_HXX #include "binarycache.hxx" #endif //CONFIGMGR_BINARYWRITER_HXX #ifndef _COM_SUN_STAR_CONFIGURATION_BACKEND_XBACKENDCHANGESNOTIFIER_HPP_ #include <com/sun/star/configuration/backend/XBackendChangesNotifier.hpp> #endif namespace configmgr { namespace backend { namespace css = com::sun::star ; namespace uno = css::uno ; namespace lang = css::lang ; namespace backenduno = css::configuration::backend ; /** Implementation of IMergedDataProvider handling the access to the configuration data. */ class BackendAccess : public IMergedDataProvider { public : /** Constructor using an XBackend implementation and a service factory. @param xBackend backend used for access to data @param xContext uno context for instantiation of services */ BackendAccess( const uno::Reference<backenduno::XBackend>& xBackend, const uno::Reference<uno::XComponentContext>& xContext) ; /** Destructor */ ~BackendAccess(void) ; // IMergedDataProvider virtual ComponentResult getNodeData(const ComponentRequest& aRequest, ITemplateDataProvider* aTemplateProvider, INodeDataListener *aListener = NULL) CFG_UNO_THROW_ALL() ; virtual void removeRequestListener(INodeDataListener *aListener, const ComponentRequest& aRequest) CFG_NOTHROW(); virtual void updateNodeData(const UpdateRequest& aUpdate) CFG_UNO_THROW_ALL() ; virtual NodeResult getDefaultData(const NodeRequest& aRequest) CFG_UNO_THROW_ALL() ; virtual TemplateResult getTemplateData(const TemplateRequest& aRequest) CFG_UNO_THROW_ALL() ; virtual bool isStrippingDefaults(void) CFG_NOTHROW() { return false ; } private : /** Retrieves the schema of a component. */ uno::Reference< backenduno::XSchema > getSchema(const OUString& aComponent) ; /** Retrieves the layers for a request. */ uno::Sequence< uno::Reference<backenduno::XLayer> > getLayers(const OUString& aComponent,const RequestOptions& aOptions) ; /** Reads merged default data with a given number of layers. */ bool readDefaultData( MergedComponentData & aComponentData, OUString const & aComponent, RequestOptions const & aOptions, bool bIncludeTemplates, const uno::Reference<backenduno::XLayer> * pLayers, sal_Int32 nNumLayers, ITemplateDataProvider *aTemplateProvider, sal_Int32 * pLayersMerged = 0) CFG_UNO_THROW_ALL(); /** Merges layers onto component data. */ void merge( MergedComponentData& aData, const uno::Reference<backenduno::XLayer> * pLayers, sal_Int32 aNumLayers, localehelper::Locale const & aRequestedLocale, localehelper::LocaleSequence & inoutMergedLocales, ITemplateDataProvider *aTemplateProvider, sal_Int32 * pLayersMerged = 0) CFG_UNO_THROW_ALL(); private : /** Decides if merging should be retried after an exception. @throws com::sun::star::uno::Exception if not approved */ bool approveRecovery( const uno::Any & aMergeException, const uno::Reference<backenduno::XLayer> & aBrokenLayer, bool bUserLayerData) CFG_UNO_THROW_ALL(); private : /** Get the factory used for service invocation */ uno::Reference<lang::XMultiServiceFactory> getServiceFactory() const; /** UNO context to which this backend belongs */ uno::Reference<uno::XComponentContext> mContext ; /** Backend being accessed */ uno::Reference<backenduno::XBackend> mBackend ; /** Binary cache of default data */ BinaryCache mBinaryCache; /** Manages Nofification from the Backends */ uno::Reference<backenduno::XBackendChangesListener> mXNotifier; BackendChangeNotifier * mNotifier; } ; } } // configmgr.backend #endif // CONFIGMGR_BACKEND_BACKENDACCESS_HXX_ <commit_msg>INTEGRATION: CWS nativefixer9 (1.11.28); FILE MERGED 2005/05/19 07:25:22 jb 1.11.28.1: #i49148# Store schema version in cache (in place of unused 'owner entity'). Invalidate cache on schema change.<commit_after>/************************************************************************* * * $RCSfile: backendaccess.hxx,v $ * * $Revision: 1.12 $ * * last change: $Author: rt $ $Date: 2005-05-20 15:41:41 $ * * 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 CONFIGMGR_BACKEND_BACKENDACCESS_HXX_ #define CONFIGMGR_BACKEND_BACKENDACCESS_HXX_ #ifndef CONFIGMGR_BACKEND_BACKENDNOTIFIER_HXX #include "backendnotifier.hxx" #endif // CONFIGMGR_BACKEND_BACKENDNOTIFIER_HXX #ifndef CONFIGMGR_BACKEND_MERGEDDATAPROVIDER_HXX #include "mergeddataprovider.hxx" #endif // CONFIGMGR_BACKEND_MERGEDDATAPROVIDER_HXX #ifndef CONFIGMGR_BACKEND_MERGEDCOMPONENTDATA_HXX #include "mergedcomponentdata.hxx" #endif // CONFIGMGR_BACKEND_MERGEDCOMPONENTDATA_HXX #ifndef CONFIGMGR_MATCHLOCALE_HXX #include "matchlocale.hxx" #endif #ifndef _COM_SUN_STAR_CONFIGURATION_BACKEND_XLAYER_HPP_ #include <com/sun/star/configuration/backend/XLayer.hpp> #endif // _COM_SUN_STAR_CONFIGURATION_BACKEND_XLAYER_HPP_ #ifndef _COM_SUN_STAR_CONFIGURATION_BACKEND_XSCHEMA_HPP_ #include <com/sun/star/configuration/backend/XSchema.hpp> #endif // _COM_SUN_STAR_CONFIGURATION_BACKEND_XSCHEMA_HPP_ #ifndef _COM_SUN_STAR_CONFIGURATION_BACKEND_XBACKEND_HPP_ #include <com/sun/star/configuration/backend/XBackend.hpp> #endif // _COM_SUN_STAR_CONFIGURATION_BACKEND_XBACKEND_HPP_ #ifndef _COM_SUN_STAR_UNO_XCOMPONENTCONTEXT_HPP_ #include <com/sun/star/uno/XComponentContext.hpp> #endif #ifndef _COM_SUN_STAR_LANG_XMULTISERVICEFACTORY_HPP_ #include <com/sun/star/lang/XMultiServiceFactory.hpp> #endif #ifndef CONFIGMGR_BINARYCACHE_HXX #include "binarycache.hxx" #endif //CONFIGMGR_BINARYWRITER_HXX #ifndef _COM_SUN_STAR_CONFIGURATION_BACKEND_XBACKENDCHANGESNOTIFIER_HPP_ #include <com/sun/star/configuration/backend/XBackendChangesNotifier.hpp> #endif namespace configmgr { namespace backend { namespace css = com::sun::star ; namespace uno = css::uno ; namespace lang = css::lang ; namespace backenduno = css::configuration::backend ; /** Implementation of IMergedDataProvider handling the access to the configuration data. */ class BackendAccess : public IMergedDataProvider { public : /** Constructor using an XBackend implementation and a service factory. @param xBackend backend used for access to data @param xContext uno context for instantiation of services */ BackendAccess( const uno::Reference<backenduno::XBackend>& xBackend, const uno::Reference<uno::XComponentContext>& xContext) ; /** Destructor */ ~BackendAccess(void) ; // IMergedDataProvider virtual ComponentResult getNodeData(const ComponentRequest& aRequest, ITemplateDataProvider* aTemplateProvider, INodeDataListener *aListener = NULL) CFG_UNO_THROW_ALL() ; virtual void removeRequestListener(INodeDataListener *aListener, const ComponentRequest& aRequest) CFG_NOTHROW(); virtual void updateNodeData(const UpdateRequest& aUpdate) CFG_UNO_THROW_ALL() ; virtual NodeResult getDefaultData(const NodeRequest& aRequest) CFG_UNO_THROW_ALL() ; virtual TemplateResult getTemplateData(const TemplateRequest& aRequest) CFG_UNO_THROW_ALL() ; virtual bool isStrippingDefaults(void) CFG_NOTHROW() { return false ; } private : /** Retrieves the schema of a component. */ uno::Reference< backenduno::XSchema > getSchema(const OUString& aComponent) ; /** Retrieves the schema version of a component. */ OUString getSchemaVersion(const OUString& aComponent) ; /** Retrieves the layers for a request. */ uno::Sequence< uno::Reference<backenduno::XLayer> > getLayers(const OUString& aComponent,const RequestOptions& aOptions) ; /** Reads merged default data with a given number of layers. */ bool readDefaultData( MergedComponentData & aComponentData, OUString const & aComponent, RequestOptions const & aOptions, bool bIncludeTemplates, const uno::Reference<backenduno::XLayer> * pLayers, sal_Int32 nNumLayers, ITemplateDataProvider *aTemplateProvider, sal_Int32 * pLayersMerged = 0) CFG_UNO_THROW_ALL(); /** Merges layers onto component data. */ void merge( MergedComponentData& aData, const uno::Reference<backenduno::XLayer> * pLayers, sal_Int32 aNumLayers, localehelper::Locale const & aRequestedLocale, localehelper::LocaleSequence & inoutMergedLocales, ITemplateDataProvider *aTemplateProvider, sal_Int32 * pLayersMerged = 0) CFG_UNO_THROW_ALL(); private : /** Decides if merging should be retried after an exception. @throws com::sun::star::uno::Exception if not approved */ bool approveRecovery( const uno::Any & aMergeException, const uno::Reference<backenduno::XLayer> & aBrokenLayer, bool bUserLayerData) CFG_UNO_THROW_ALL(); private : /** Get the factory used for service invocation */ uno::Reference<lang::XMultiServiceFactory> getServiceFactory() const; /** UNO context to which this backend belongs */ uno::Reference<uno::XComponentContext> mContext ; /** Backend being accessed */ uno::Reference<backenduno::XBackend> mBackend ; /** Binary cache of default data */ BinaryCache mBinaryCache; /** Manages Nofification from the Backends */ uno::Reference<backenduno::XBackendChangesListener> mXNotifier; BackendChangeNotifier * mNotifier; } ; } } // configmgr.backend #endif // CONFIGMGR_BACKEND_BACKENDACCESS_HXX_ <|endoftext|>
<commit_before>/********************************************************************************* * * Inviwo - Interactive Visualization Workshop * * Copyright (c) 2015 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/cimg/cimgutils.h> #include <inviwo/core/datastructures/image/layerramprecision.h> #include <inviwo/core/util/filesystem.h> #include <algorithm> #include <warn/push> #include <warn/ignore/all> #include <modules/cimg/ext/cimg/CImg.h> #include <warn/pop> #include <warn/push> #include <warn/ignore/switch-enum> #include <warn/ignore/conversion> #if (_MSC_VER) # pragma warning(disable: 4146) # pragma warning(disable: 4197) # pragma warning(disable: 4297) # pragma warning(disable: 4267) # pragma warning(disable: 4293) #endif // Added in Cimg.h below struct type<float>... /*#include <limits> #include <half/half.hpp> template<> struct type < half_float::half > { static const char* string() { static const char *const s = "half"; return s; } static bool is_float() { return true; } static bool is_inf(const half_float::half val) { #ifdef isinf return (bool)isinf(val); #else return !is_nan(val) && (val<cimg::type<half_float::half>::min() || val>cimg::type<half_float::half>::max()); #endif } static bool is_nan(const half_float::half val) { #ifdef isnan return (bool)isnan(val); #else return !(val == val); #endif } static half_float::half min() { return std::numeric_limits<half_float::half>::min(); } static half_float::half max() { return std::numeric_limits<half_float::half>::max(); } static half_float::half inf() { return (half_float::half)cimg::type<double>::inf(); } static half_float::half nan() { return (half_float::half)cimg::type<double>::nan(); } static half_float::half cut(const double val) { return val<(double)min() ? min() : val>(double)max() ? max() : (half_float::half)val; } static const char* format() { return "%.16g"; } static double format(const half_float::half val) { return (double)val; } }; */ using namespace cimg_library; namespace inviwo { std::unordered_map<std::string, DataFormatEnums::Id> extToBaseTypeMap_ = { { "png", DataFormatEnums::UINT8 } , { "jpg", DataFormatEnums::UINT8 } , { "jpeg", DataFormatEnums::UINT8 } , { "bmp", DataFormatEnums::UINT8 } , { "exr", DataFormatEnums::FLOAT32 } , { "hdr", DataFormatEnums::FLOAT32 } }; ////////////////////// Templates /////////////////////////////////////////////////// // Single channel images template <typename T> struct CImgToIvwConvert { static void* convert(void* dst, CImg<T>* img) { //Inviwo store pixels interleaved (RGBRGBRGB), CImg stores pixels in a planer format (RRRRGGGGBBBB). //Permute from planer to interleaved format, does we need to specify cxyz as input instead of xyzc if (img->spectrum() > 1){ img->permute_axes("cxyz"); } if (!dst) { T* dstAlloc = new T[img->size()]; dst = static_cast<void*>(dstAlloc); } const void* src = static_cast<const void*>(img->data()); std::memcpy(dst, src, img->size()*sizeof(T)); return dst; } }; // Single channel images template <typename T> struct LayerToCImg { static CImg<T>* convert(const LayerRAM* inputLayerRAM, bool permute = true) { //Single channel means we can do xyzc, as no permutation is needed CImg<T>* img = new CImg<T>(static_cast<const T*>(inputLayerRAM->getData()), inputLayerRAM->getDimensions().x, inputLayerRAM->getDimensions().y, 1, 1, false); return img; } }; // Multiple channel images template <typename T, template <typename, glm::precision> class G> struct LayerToCImg<G<T, glm::defaultp>> { static CImg<T>* convert(const LayerRAM* inputLayerRAM, bool permute = true) { const DataFormatBase* dataFormat = inputLayerRAM->getDataFormat(); const G<T, glm::defaultp>* typedDataPtr = static_cast<const G<T, glm::defaultp>*>(inputLayerRAM->getData()); //Inviwo store pixels interleaved (RGBRGBRGB), CImg stores pixels in a planer format (RRRRGGGGBBBB). //Permute from interleaved to planer format, does we need to specify yzcx as input instead of cxyz CImg<T>* img = new CImg<T>(glm::value_ptr(*typedDataPtr), dataFormat->getComponents(), inputLayerRAM->getDimensions().x, inputLayerRAM->getDimensions().y, 1, false); if (permute) img->permute_axes("yzcx"); return img; } }; struct CImgNormalizedLayerDispatcher { using type = std::vector<unsigned char>*; template <typename T> std::vector<unsigned char>* dispatch(const LayerRAM* inputLayer) { CImg<typename T::primitive>* img = LayerToCImg<typename T::type>::convert(inputLayer, false); CImg<unsigned char> normalizedImg = img->get_normalize(0, 255); normalizedImg.mirror('z'); std::vector<unsigned char>* data = new std::vector<unsigned char>(&normalizedImg[0], &normalizedImg[normalizedImg.size()]); delete img; return data; } }; struct CImgLoadLayerDispatcher { using type = void*; template <typename T> void* dispatch(void* dst, const char* filePath, uvec2& dimensions, DataFormatEnums::Id& formatId, const DataFormatBase* dataFormat, bool rescaleToDim) { CImg<typename T::primitive> img(filePath); size_t components = static_cast<size_t>(img.spectrum()); if (rescaleToDim) { img.resize(dimensions.x, dimensions.y, -100, -100, 3); } else{ dimensions = uvec2(img.width(), img.height()); } const DataFormatBase* loadedDataFormat = DataFormatBase::get(dataFormat->getNumericType(), components, sizeof(typename T::primitive)*8); if (loadedDataFormat) formatId = loadedDataFormat->getId(); else throw Exception("CImgLoadLayerDispatcher, could not find proper data type"); //Image is up-side-down img.mirror('y'); return CImgToIvwConvert<typename T::primitive>::convert(dst, &img); } }; struct CImgSaveLayerDispatcher { using type = void; template <typename T> void dispatch(const char* filePath, const LayerRAM* inputLayer) { CImg<typename T::primitive>* img = LayerToCImg<typename T::type>::convert(inputLayer); //Should rescale values based on output format i.e. PNG/JPG is 0-255, HDR different. const DataFormatBase* outFormat = DataFLOAT32::get(); std::string fileExtension = filesystem::getFileExtension(filePath); if (extToBaseTypeMap_.find(fileExtension) != extToBaseTypeMap_.end()) { outFormat = DataFormatBase::get(extToBaseTypeMap_[fileExtension]); } //Image is up-side-down img->mirror('y'); const DataFormatBase* inFormat = inputLayer->getDataFormat(); double inMin = inFormat->getMin(); double inMax = inFormat->getMax(); double outMin = outFormat->getMin(); double outMax = outFormat->getMax(); //Special treatment for float data types: // For float input images, we assume that the range is [0,1] (which is the same as rendered in a Canvas) // For float output images, we normalize to [0,1] // Note that no normalization is performed if both input and output are float images if (inFormat->getNumericType() == DataFormatEnums::FLOAT_TYPE) { inMin = 0.0; inMax = 1.0; } if (outFormat->getNumericType() == DataFormatEnums::FLOAT_TYPE) { outMin = 0.0; outMax = 1.0; } //The image values should be rescaled if the ranges of the input and output are different if (inMin != outMin || inMax != outMax) { typename T::primitive* data = img->data(); double scale = (outMax - outMin) / (inMax - inMin); for (size_t i = 0; i < img->size(); i++) data[i] = static_cast<typename T::primitive>((static_cast<double>(data[i]) - inMin)*scale + outMin); } img->save(filePath); delete img; } }; struct CImgRescaleLayerDispatcher { using type = void*; template <typename T> void* dispatch(const LayerRAM* inputLayerRAM, uvec2 dst_dim) { auto img = std::unique_ptr<CImg<typename T::primitive>>(LayerToCImg<typename T::type>::convert(inputLayerRAM)); img->resize(dst_dim.x, dst_dim.y, -100, -100, 3); return CImgToIvwConvert<typename T::primitive>::convert(nullptr, img.get()); } }; struct CImgLoadVolumeDispatcher { using type = void*; template <typename T> void* dispatch(void* dst, const char* filePath, size3_t& dimensions, DataFormatEnums::Id& formatId, const DataFormatBase* dataFormat) { CImg<typename T::primitive> img(filePath); size_t components = static_cast<size_t>(img.spectrum()); dimensions = size3_t(img.width(), img.height(), img.depth()); const DataFormatBase* loadedDataFormat = DataFormatBase::get(dataFormat->getNumericType(), components, sizeof(typename T::primitive) * 8); if (loadedDataFormat) formatId = loadedDataFormat->getId(); else throw Exception("CImgLoadVolumeDispatcher, could not find proper data type"); //Image is up-side-down img.mirror('y'); return CImgToIvwConvert<typename T::primitive>::convert(dst, &img); } }; ////////////////////// CImgUtils /////////////////////////////////////////////////// void* CImgUtils::loadLayerData(void* dst, const std::string& filePath, uvec2& dimensions, DataFormatEnums::Id& formatId, bool rescaleToDim) { std::string fileExtension = filesystem::getFileExtension(filePath); if (extToBaseTypeMap_.find(fileExtension) != extToBaseTypeMap_.end()) { formatId = extToBaseTypeMap_[fileExtension]; } else { formatId = DataFormatEnums::FLOAT32; } const DataFormatBase* dataFormat = DataFormatBase::get(formatId); CImgLoadLayerDispatcher disp; return dataFormat->dispatch(disp, dst, filePath.c_str(), dimensions, formatId, dataFormat, rescaleToDim); } void* CImgUtils::loadVolumeData(void* dst, const std::string& filePath, size3_t& dimensions, DataFormatEnums::Id& formatId) { std::string fileExtension = filesystem::getFileExtension(filePath); if (extToBaseTypeMap_.find(fileExtension) != extToBaseTypeMap_.end()) { formatId = extToBaseTypeMap_[fileExtension]; } else { formatId = DataFormatEnums::FLOAT32; } const DataFormatBase* dataFormat = DataFormatBase::get(formatId); CImgLoadVolumeDispatcher disp; return dataFormat->dispatch(disp, dst, filePath.c_str(), dimensions, formatId, dataFormat); } void CImgUtils::saveLayer(const std::string& filePath, const Layer* inputLayer) { CImgSaveLayerDispatcher disp; const LayerRAM* inputLayerRam = inputLayer->getRepresentation<LayerRAM>(); inputLayer->getDataFormat()->dispatch(disp, filePath.c_str(), inputLayerRam); } std::vector<unsigned char>* CImgUtils::saveLayerToBuffer(std::string& fileType, const Layer* inputLayer) { CImgNormalizedLayerDispatcher disp; const LayerRAM* inputLayerRam = inputLayer->getRepresentation<LayerRAM>(); // Can only produce raw output fileType = "raw"; return inputLayer->getDataFormat()->dispatch(disp, inputLayerRam); } void* CImgUtils::rescaleLayer(const Layer* inputLayer, uvec2 dst_dim) { const LayerRAM* layerRam = inputLayer->getRepresentation<LayerRAM>(); return rescaleLayerRAM(layerRam, dst_dim); } void* CImgUtils::rescaleLayerRAM(const LayerRAM* srcLayerRam, uvec2 dst_dim) { CImgRescaleLayerDispatcher disp; return srcLayerRam->getDataFormat()->dispatch(disp, srcLayerRam, dst_dim); } } // namespace #include <warn/pop> <commit_msg>CIMG: SaveLayer now clamps the out values to outMin and outMax<commit_after>/********************************************************************************* * * Inviwo - Interactive Visualization Workshop * * Copyright (c) 2015 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/cimg/cimgutils.h> #include <inviwo/core/datastructures/image/layerramprecision.h> #include <inviwo/core/util/filesystem.h> #include <algorithm> #include <warn/push> #include <warn/ignore/all> #include <modules/cimg/ext/cimg/CImg.h> #include <warn/pop> #include <warn/push> #include <warn/ignore/switch-enum> #include <warn/ignore/conversion> #if (_MSC_VER) # pragma warning(disable: 4146) # pragma warning(disable: 4197) # pragma warning(disable: 4297) # pragma warning(disable: 4267) # pragma warning(disable: 4293) #endif // Added in Cimg.h below struct type<float>... /*#include <limits> #include <half/half.hpp> template<> struct type < half_float::half > { static const char* string() { static const char *const s = "half"; return s; } static bool is_float() { return true; } static bool is_inf(const half_float::half val) { #ifdef isinf return (bool)isinf(val); #else return !is_nan(val) && (val<cimg::type<half_float::half>::min() || val>cimg::type<half_float::half>::max()); #endif } static bool is_nan(const half_float::half val) { #ifdef isnan return (bool)isnan(val); #else return !(val == val); #endif } static half_float::half min() { return std::numeric_limits<half_float::half>::min(); } static half_float::half max() { return std::numeric_limits<half_float::half>::max(); } static half_float::half inf() { return (half_float::half)cimg::type<double>::inf(); } static half_float::half nan() { return (half_float::half)cimg::type<double>::nan(); } static half_float::half cut(const double val) { return val<(double)min() ? min() : val>(double)max() ? max() : (half_float::half)val; } static const char* format() { return "%.16g"; } static double format(const half_float::half val) { return (double)val; } }; */ using namespace cimg_library; namespace inviwo { std::unordered_map<std::string, DataFormatEnums::Id> extToBaseTypeMap_ = { { "png", DataFormatEnums::UINT8 } , { "jpg", DataFormatEnums::UINT8 } , { "jpeg", DataFormatEnums::UINT8 } , { "bmp", DataFormatEnums::UINT8 } , { "exr", DataFormatEnums::FLOAT32 } , { "hdr", DataFormatEnums::FLOAT32 } }; ////////////////////// Templates /////////////////////////////////////////////////// // Single channel images template <typename T> struct CImgToIvwConvert { static void* convert(void* dst, CImg<T>* img) { //Inviwo store pixels interleaved (RGBRGBRGB), CImg stores pixels in a planer format (RRRRGGGGBBBB). //Permute from planer to interleaved format, does we need to specify cxyz as input instead of xyzc if (img->spectrum() > 1){ img->permute_axes("cxyz"); } if (!dst) { T* dstAlloc = new T[img->size()]; dst = static_cast<void*>(dstAlloc); } const void* src = static_cast<const void*>(img->data()); std::memcpy(dst, src, img->size()*sizeof(T)); return dst; } }; // Single channel images template <typename T> struct LayerToCImg { static CImg<T>* convert(const LayerRAM* inputLayerRAM, bool permute = true) { //Single channel means we can do xyzc, as no permutation is needed CImg<T>* img = new CImg<T>(static_cast<const T*>(inputLayerRAM->getData()), inputLayerRAM->getDimensions().x, inputLayerRAM->getDimensions().y, 1, 1, false); return img; } }; // Multiple channel images template <typename T, template <typename, glm::precision> class G> struct LayerToCImg<G<T, glm::defaultp>> { static CImg<T>* convert(const LayerRAM* inputLayerRAM, bool permute = true) { const DataFormatBase* dataFormat = inputLayerRAM->getDataFormat(); const G<T, glm::defaultp>* typedDataPtr = static_cast<const G<T, glm::defaultp>*>(inputLayerRAM->getData()); //Inviwo store pixels interleaved (RGBRGBRGB), CImg stores pixels in a planer format (RRRRGGGGBBBB). //Permute from interleaved to planer format, does we need to specify yzcx as input instead of cxyz CImg<T>* img = new CImg<T>(glm::value_ptr(*typedDataPtr), dataFormat->getComponents(), inputLayerRAM->getDimensions().x, inputLayerRAM->getDimensions().y, 1, false); if (permute) img->permute_axes("yzcx"); return img; } }; struct CImgNormalizedLayerDispatcher { using type = std::vector<unsigned char>*; template <typename T> std::vector<unsigned char>* dispatch(const LayerRAM* inputLayer) { CImg<typename T::primitive>* img = LayerToCImg<typename T::type>::convert(inputLayer, false); CImg<unsigned char> normalizedImg = img->get_normalize(0, 255); normalizedImg.mirror('z'); std::vector<unsigned char>* data = new std::vector<unsigned char>(&normalizedImg[0], &normalizedImg[normalizedImg.size()]); delete img; return data; } }; struct CImgLoadLayerDispatcher { using type = void*; template <typename T> void* dispatch(void* dst, const char* filePath, uvec2& dimensions, DataFormatEnums::Id& formatId, const DataFormatBase* dataFormat, bool rescaleToDim) { CImg<typename T::primitive> img(filePath); size_t components = static_cast<size_t>(img.spectrum()); if (rescaleToDim) { img.resize(dimensions.x, dimensions.y, -100, -100, 3); } else{ dimensions = uvec2(img.width(), img.height()); } const DataFormatBase* loadedDataFormat = DataFormatBase::get(dataFormat->getNumericType(), components, sizeof(typename T::primitive)*8); if (loadedDataFormat) formatId = loadedDataFormat->getId(); else throw Exception("CImgLoadLayerDispatcher, could not find proper data type"); //Image is up-side-down img.mirror('y'); return CImgToIvwConvert<typename T::primitive>::convert(dst, &img); } }; struct CImgSaveLayerDispatcher { using type = void; template <typename T> void dispatch(const char* filePath, const LayerRAM* inputLayer) { CImg<typename T::primitive>* img = LayerToCImg<typename T::type>::convert(inputLayer); //Should rescale values based on output format i.e. PNG/JPG is 0-255, HDR different. const DataFormatBase* outFormat = DataFLOAT32::get(); std::string fileExtension = filesystem::getFileExtension(filePath); if (extToBaseTypeMap_.find(fileExtension) != extToBaseTypeMap_.end()) { outFormat = DataFormatBase::get(extToBaseTypeMap_[fileExtension]); } //Image is up-side-down img->mirror('y'); const DataFormatBase* inFormat = inputLayer->getDataFormat(); double inMin = inFormat->getMin(); double inMax = inFormat->getMax(); double outMin = outFormat->getMin(); double outMax = outFormat->getMax(); //Special treatment for float data types: // For float input images, we assume that the range is [0,1] (which is the same as rendered in a Canvas) // For float output images, we normalize to [0,1] // Note that no normalization is performed if both input and output are float images if (inFormat->getNumericType() == DataFormatEnums::FLOAT_TYPE) { inMin = 0.0; inMax = 1.0; } if (outFormat->getNumericType() == DataFormatEnums::FLOAT_TYPE) { outMin = 0.0; outMax = 1.0; } //The image values should be rescaled if the ranges of the input and output are different if (inMin != outMin || inMax != outMax) { typename T::primitive* data = img->data(); double scale = (outMax - outMin) / (inMax - inMin); for (size_t i = 0; i < img->size(); i++) data[i] = static_cast<typename T::primitive>( glm::clamp( (static_cast<double>(data[i]) - inMin)*scale + outMin , outMin , outMax)); } img->save(filePath); delete img; } }; struct CImgRescaleLayerDispatcher { using type = void*; template <typename T> void* dispatch(const LayerRAM* inputLayerRAM, uvec2 dst_dim) { auto img = std::unique_ptr<CImg<typename T::primitive>>(LayerToCImg<typename T::type>::convert(inputLayerRAM)); img->resize(dst_dim.x, dst_dim.y, -100, -100, 3); return CImgToIvwConvert<typename T::primitive>::convert(nullptr, img.get()); } }; struct CImgLoadVolumeDispatcher { using type = void*; template <typename T> void* dispatch(void* dst, const char* filePath, size3_t& dimensions, DataFormatEnums::Id& formatId, const DataFormatBase* dataFormat) { CImg<typename T::primitive> img(filePath); size_t components = static_cast<size_t>(img.spectrum()); dimensions = size3_t(img.width(), img.height(), img.depth()); const DataFormatBase* loadedDataFormat = DataFormatBase::get(dataFormat->getNumericType(), components, sizeof(typename T::primitive) * 8); if (loadedDataFormat) formatId = loadedDataFormat->getId(); else throw Exception("CImgLoadVolumeDispatcher, could not find proper data type"); //Image is up-side-down img.mirror('y'); return CImgToIvwConvert<typename T::primitive>::convert(dst, &img); } }; ////////////////////// CImgUtils /////////////////////////////////////////////////// void* CImgUtils::loadLayerData(void* dst, const std::string& filePath, uvec2& dimensions, DataFormatEnums::Id& formatId, bool rescaleToDim) { std::string fileExtension = filesystem::getFileExtension(filePath); if (extToBaseTypeMap_.find(fileExtension) != extToBaseTypeMap_.end()) { formatId = extToBaseTypeMap_[fileExtension]; } else { formatId = DataFormatEnums::FLOAT32; } const DataFormatBase* dataFormat = DataFormatBase::get(formatId); CImgLoadLayerDispatcher disp; return dataFormat->dispatch(disp, dst, filePath.c_str(), dimensions, formatId, dataFormat, rescaleToDim); } void* CImgUtils::loadVolumeData(void* dst, const std::string& filePath, size3_t& dimensions, DataFormatEnums::Id& formatId) { std::string fileExtension = filesystem::getFileExtension(filePath); if (extToBaseTypeMap_.find(fileExtension) != extToBaseTypeMap_.end()) { formatId = extToBaseTypeMap_[fileExtension]; } else { formatId = DataFormatEnums::FLOAT32; } const DataFormatBase* dataFormat = DataFormatBase::get(formatId); CImgLoadVolumeDispatcher disp; return dataFormat->dispatch(disp, dst, filePath.c_str(), dimensions, formatId, dataFormat); } void CImgUtils::saveLayer(const std::string& filePath, const Layer* inputLayer) { CImgSaveLayerDispatcher disp; const LayerRAM* inputLayerRam = inputLayer->getRepresentation<LayerRAM>(); inputLayer->getDataFormat()->dispatch(disp, filePath.c_str(), inputLayerRam); } std::vector<unsigned char>* CImgUtils::saveLayerToBuffer(std::string& fileType, const Layer* inputLayer) { CImgNormalizedLayerDispatcher disp; const LayerRAM* inputLayerRam = inputLayer->getRepresentation<LayerRAM>(); // Can only produce raw output fileType = "raw"; return inputLayer->getDataFormat()->dispatch(disp, inputLayerRam); } void* CImgUtils::rescaleLayer(const Layer* inputLayer, uvec2 dst_dim) { const LayerRAM* layerRam = inputLayer->getRepresentation<LayerRAM>(); return rescaleLayerRAM(layerRam, dst_dim); } void* CImgUtils::rescaleLayerRAM(const LayerRAM* srcLayerRam, uvec2 dst_dim) { CImgRescaleLayerDispatcher disp; return srcLayerRam->getDataFormat()->dispatch(disp, srcLayerRam, dst_dim); } } // namespace #include <warn/pop> <|endoftext|>
<commit_before>#include <SD.h> #include <SPI.h> #include "sd_epaper.h" #include "ePaperDfs.h" void sd_epaper::begin(EPD_size sz) { DISP_LEN = 200; DISP_WIDTH = 96; LINE_BYTE = 200/8; clear(); } void sd_epaper::putPixel(int x, int y, unsigned char pixel) { int x1 = x; int y1 = y; if(x>DISP_LEN || y>DISP_WIDTH)return; int bit = x & 0x07; int byte = (x>>3) + y * LINE_BYTE; int mask = 0x01 << bit; if (BLACK == pixel) sram_image[byte] |= mask; else sram_image[byte] &= ~mask; } unsigned char sd_epaper::clear() { memset(sram_image, 0x00, 5808); } sd_epaper eSD; <commit_msg>Translated tabs in sd_epaper.cpp<commit_after>#include <SD.h> #include <SPI.h> #include "sd_epaper.h" #include "ePaperDfs.h" void sd_epaper::begin(EPD_size sz) { DISP_LEN = 200; DISP_WIDTH = 96; LINE_BYTE = 200/8; clear(); } void sd_epaper::putPixel(int x, int y, unsigned char pixel) { int x1 = x; int y1 = y; if(x>DISP_LEN || y>DISP_WIDTH)return; int bit = x & 0x07; int byte = (x>>3) + y * LINE_BYTE; int mask = 0x01 << bit; if (BLACK == pixel) sram_image[byte] |= mask; else sram_image[byte] &= ~mask; } unsigned char sd_epaper::clear() { memset(sram_image, 0x00, 5808); } sd_epaper eSD; <|endoftext|>
<commit_before>/* -------------------------------------------------------------------------- * * OpenSim: AssemblySolver.cpp * * -------------------------------------------------------------------------- * * The OpenSim API is a toolkit for musculoskeletal modeling and simulation. * * See http://opensim.stanford.edu and the NOTICE file for more information. * * OpenSim is developed at Stanford University and supported by the US * * National Institutes of Health (U54 GM072970, R24 HD065690) and by DARPA * * through the Warrior Web program. * * * * Copyright (c) 2005-2012 Stanford University and the Authors * * Author(s): Ajay Seth * * * * 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 "AssemblySolver.h" #include "Model/Model.h" #include <OpenSim/Common/Constant.h> using namespace std; using namespace SimTK; namespace OpenSim { //______________________________________________________________________________ /** * An implementation of the AssemblySolver * * @param model to assemble */ AssemblySolver::AssemblySolver (const Model &model, const SimTK::Array_<CoordinateReference> &coordinateReferences, double constraintWeight) : Solver(model), _coordinateReferencesp(coordinateReferences) { setAuthors("Ajay Seth"); _assembler = NULL; _constraintWeight = constraintWeight; // default accuracy _accuracy = 1e-4; // Get model coordinates const CoordinateSet& modelCoordSet = getModel().getCoordinateSet(); SimTK::Array_<CoordinateReference>::iterator p; // Cycle through coordinate references for(p = _coordinateReferencesp.begin(); p != _coordinateReferencesp.end(); p++) { if(p){ //Find if any references that are empty and throw them away if(p->getName() == "" || p->getName() == "unknown"){ //Get rid of the corresponding reference too p = _coordinateReferencesp.erase(p); } // Otherwise an error if the coordinate does not exist for this model else if ( !modelCoordSet.contains(p->getName())){ throw(Exception("AssemblySolver: Model does not contain coordinate "+p->getName()+".")); } } } } AssemblySolver::~AssemblySolver() { delete _assembler; } /* Internal method to convert the CoordinateReferences into goals of the assembly solver. Subclasses, override and call base to include other goals such as point of interest matching (Marker tracking). This method is automatically called by assemble. */ void AssemblySolver::setupGoals(SimTK::State &s) { // wipe-out the previous SimTK::Assembler delete _assembler; _assembler = new SimTK::Assembler(getModel().getMultibodySystem()); _assembler->setAccuracy(_accuracy); // Define weights on constraints. Note can be specified SimTK::Infinity to strictly enforce constraint // otherwise the weighted constraint error becomes a goal. _assembler->setSystemConstraintsWeight(_constraintWeight); // clear any old coordinate goals _coordinateAssemblyConditions.clear(); // Get model coordinates const CoordinateSet& modelCoordSet = getModel().getCoordinateSet(); // Restrict solution to set range of any of the coordinates that are clamped for(int i=0; i<modelCoordSet.getSize(); ++i){ const Coordinate& coord = modelCoordSet[i]; if(coord.getClamped(s)){ _assembler->restrictQ(coord.getBodyIndex(), MobilizerQIndex(coord.getMobilizerQIndex()), coord.getRangeMin(), coord.getRangeMax()); } } SimTK::Array_<CoordinateReference>::iterator p; // Cycle through coordinate references for(p = _coordinateReferencesp.begin(); p != _coordinateReferencesp.end(); p++) { if(p){ CoordinateReference *coordRef = p; const Coordinate &coord = modelCoordSet.get(coordRef->getName()); if(coord.getLocked(s)){ //cout << "AssemblySolver: coordinate " << coord.getName() << " is locked/prescribed and will be excluded." << endl; _assembler->lockQ(coord.getBodyIndex(), SimTK::MobilizerQIndex(coord.getMobilizerQIndex())); //No longer need the lock on coord.setLocked(s, false); //Get rid of the corresponding reference too _coordinateReferencesp.erase(p); p--; //decrement since erase automatically points to next in the list } else if(!(coord.get_is_free_to_satisfy_constraints())) { // Make this reference and its current value a goal of the Assembler SimTK::QValue *coordGoal = new SimTK::QValue(coord.getBodyIndex(), SimTK::MobilizerQIndex(coord.getMobilizerQIndex()), coordRef->getValue(s) ); // keep a handle to the goal so we can update _coordinateAssemblyConditions.push_back(coordGoal); // Add coordinate matching goal to the ik objective SimTK::AssemblyConditionIndex acIx = _assembler->adoptAssemblyGoal(coordGoal, coordRef->getWeight(s)); } } } unsigned int nqrefs = _coordinateReferencesp.size(), nqgoals = _coordinateAssemblyConditions.size(); //Should have a one-to-one matched arrays if(nqrefs != nqgoals) throw Exception("AsemblySolver::setupGoals() has a mismatch between number of references and goals."); } /** Once a set of coordinates has been specified its target value can be updated directly */ void AssemblySolver::updateCoordinateReference(const std::string &coordName, double value, double weight) { SimTK::Array_<CoordinateReference>::iterator p; // Cycle through coordinate references for(p = _coordinateReferencesp.begin(); p != _coordinateReferencesp.end(); p++) { if(p->getName() == coordName){ p->setValueFunction(*new Constant(value)); p->setWeight(weight); return; } } } /** Internal method to update the time, reference values and/or their weights that define the goals, based on the passed in state. */ void AssemblySolver::updateGoals(const SimTK::State &s) { unsigned int nqrefs = _coordinateReferencesp.size(); for(unsigned int i=0; i<nqrefs; i++){ //update goal values from reference. _coordinateAssemblyConditions[i]->setValue ((_coordinateReferencesp)[i].getValue(s)); //_assembler->setAssemblyConditionWeight(_coordinateAssemblyConditions[i]-> } } //______________________________________________________________________________ /** * Assemble the model such that it satisfies configuration goals and constraints * The input state is used to initialize the assembly and then is updated to * return the resulting assembled configuration. */ void AssemblySolver::assemble(SimTK::State &state) { // Make a working copy of the state that will be used to set the internal // state of the solver. This is necessary because we may wish to disable // redundant constraints, but do not want this to effect the state of // constraints the user expects SimTK::State s = state; // Make sure goals are up-to-date. setupGoals(s); // Let assembler perform some internal setup _assembler->initialize(s); /* TODO: Useful to include through debug message/log in the future printf("UNASSEMBLED CONFIGURATION (normerr=%g, maxerr=%g, cost=%g)\n", _assembler->calcCurrentErrorNorm(), max(abs(_assembler->getInternalState().getQErr())), _assembler->calcCurrentGoal()); cout << "Model numQs: " << _assembler->getInternalState().getNQ() << " Assembler num freeQs: " << _assembler->getNumFreeQs() << endl; */ try{ // Now do the assembly and return the updated state. _assembler->assemble(); // Update the q's in the state passed in _assembler->updateFromInternalState(s); state.updQ() = s.getQ(); state.updU() = s.getU(); // Get model coordinates const CoordinateSet& modelCoordSet = getModel().getCoordinateSet(); // Make sure the locks in original state are restored for(int i=0; i< modelCoordSet.getSize(); ++i){ bool isLocked = modelCoordSet[i].getLocked(state); if(isLocked) modelCoordSet[i].setLocked(state, isLocked); } /* TODO: Useful to include through debug message/log in the future printf("ASSEMBLED CONFIGURATION (acc=%g tol=%g normerr=%g, maxerr=%g, cost=%g)\n", _assembler->getAccuracyInUse(), _assembler->getErrorToleranceInUse(), _assembler->calcCurrentErrorNorm(), max(abs(_assembler->getInternalState().getQErr())), _assembler->calcCurrentGoal()); printf("# initializations=%d\n", _assembler->getNumInitializations()); printf("# assembly steps: %d\n", _assembler->getNumAssemblySteps()); printf(" evals: goal=%d grad=%d error=%d jac=%d\n", _assembler->getNumGoalEvals(), _assembler->getNumGoalGradientEvals(), _assembler->getNumErrorEvals(), _assembler->getNumErrorJacobianEvals()); */ } catch (const std::exception& ex) { std::string msg = "AssemblySolver::assemble() Failed: "; msg += ex.what(); throw Exception(msg); } } /** Obtain a model configuration that meets the assembly conditions (desired values and constraints) given a state that satisfies or is close to satisfying the constraints. Note there can be no change in the number of constraints or desired coordinates. Desired coordinate values can and should be updated between repeated calls to track a desired trajectory of coordinate values. */ void AssemblySolver::track(SimTK::State &s) { // move the target locations or angles, etc... just do not change number of goals // and their type (constrained vs. weighted) if(_assembler && _assembler->isInitialized()){ updateGoals(s); } else{ throw Exception( "AssemblySolver::track() failed: assemble() must be called first."); } /* TODO: Useful to include through debug message/log in the future printf("UNASSEMBLED(track) CONFIGURATION (normerr=%g, maxerr=%g, cost=%g)\n", _assembler->calcCurrentErrorNorm(), max(abs(_assembler->getInternalState().getQErr())), _assembler->calcCurrentGoal() ); cout << "Model numQs: " << _assembler->getInternalState().getNQ() << " Assembler num freeQs: " << _assembler->getNumFreeQs() << endl; */ try{ // Now do the assembly and return the updated state. _assembler->track(s.getTime()); // update the state from the result of the assembler _assembler->updateFromInternalState(s); /* TODO: Useful to include through debug message/log in the future printf("Tracking: t= %f (acc=%g tol=%g normerr=%g, maxerr=%g, cost=%g)\n", s.getTime(), _assembler->getAccuracyInUse(), _assembler->getErrorToleranceInUse(), _assembler->calcCurrentErrorNorm(), max(abs(_assembler->getInternalState().getQErr())), _assembler->calcCurrentGoal()); */ } catch (const std::exception& ex) { std::cout << "AssemblySolver::track() attempt Failed: " << ex.what() << std::endl; throw Exception("AssemblySolver::track() attempt failed."); } } } // end of namespace OpenSim <commit_msg>Unused variable.<commit_after>/* -------------------------------------------------------------------------- * * OpenSim: AssemblySolver.cpp * * -------------------------------------------------------------------------- * * The OpenSim API is a toolkit for musculoskeletal modeling and simulation. * * See http://opensim.stanford.edu and the NOTICE file for more information. * * OpenSim is developed at Stanford University and supported by the US * * National Institutes of Health (U54 GM072970, R24 HD065690) and by DARPA * * through the Warrior Web program. * * * * Copyright (c) 2005-2012 Stanford University and the Authors * * Author(s): Ajay Seth * * * * 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 "AssemblySolver.h" #include "Model/Model.h" #include <OpenSim/Common/Constant.h> using namespace std; using namespace SimTK; namespace OpenSim { //______________________________________________________________________________ /** * An implementation of the AssemblySolver * * @param model to assemble */ AssemblySolver::AssemblySolver (const Model &model, const SimTK::Array_<CoordinateReference> &coordinateReferences, double constraintWeight) : Solver(model), _coordinateReferencesp(coordinateReferences) { setAuthors("Ajay Seth"); _assembler = NULL; _constraintWeight = constraintWeight; // default accuracy _accuracy = 1e-4; // Get model coordinates const CoordinateSet& modelCoordSet = getModel().getCoordinateSet(); SimTK::Array_<CoordinateReference>::iterator p; // Cycle through coordinate references for(p = _coordinateReferencesp.begin(); p != _coordinateReferencesp.end(); p++) { if(p){ //Find if any references that are empty and throw them away if(p->getName() == "" || p->getName() == "unknown"){ //Get rid of the corresponding reference too p = _coordinateReferencesp.erase(p); } // Otherwise an error if the coordinate does not exist for this model else if ( !modelCoordSet.contains(p->getName())){ throw(Exception("AssemblySolver: Model does not contain coordinate "+p->getName()+".")); } } } } AssemblySolver::~AssemblySolver() { delete _assembler; } /* Internal method to convert the CoordinateReferences into goals of the assembly solver. Subclasses, override and call base to include other goals such as point of interest matching (Marker tracking). This method is automatically called by assemble. */ void AssemblySolver::setupGoals(SimTK::State &s) { // wipe-out the previous SimTK::Assembler delete _assembler; _assembler = new SimTK::Assembler(getModel().getMultibodySystem()); _assembler->setAccuracy(_accuracy); // Define weights on constraints. Note can be specified SimTK::Infinity to strictly enforce constraint // otherwise the weighted constraint error becomes a goal. _assembler->setSystemConstraintsWeight(_constraintWeight); // clear any old coordinate goals _coordinateAssemblyConditions.clear(); // Get model coordinates const CoordinateSet& modelCoordSet = getModel().getCoordinateSet(); // Restrict solution to set range of any of the coordinates that are clamped for(int i=0; i<modelCoordSet.getSize(); ++i){ const Coordinate& coord = modelCoordSet[i]; if(coord.getClamped(s)){ _assembler->restrictQ(coord.getBodyIndex(), MobilizerQIndex(coord.getMobilizerQIndex()), coord.getRangeMin(), coord.getRangeMax()); } } SimTK::Array_<CoordinateReference>::iterator p; // Cycle through coordinate references for(p = _coordinateReferencesp.begin(); p != _coordinateReferencesp.end(); p++) { if(p){ CoordinateReference *coordRef = p; const Coordinate &coord = modelCoordSet.get(coordRef->getName()); if(coord.getLocked(s)){ //cout << "AssemblySolver: coordinate " << coord.getName() << " is locked/prescribed and will be excluded." << endl; _assembler->lockQ(coord.getBodyIndex(), SimTK::MobilizerQIndex(coord.getMobilizerQIndex())); //No longer need the lock on coord.setLocked(s, false); //Get rid of the corresponding reference too _coordinateReferencesp.erase(p); p--; //decrement since erase automatically points to next in the list } else if(!(coord.get_is_free_to_satisfy_constraints())) { // Make this reference and its current value a goal of the Assembler SimTK::QValue *coordGoal = new SimTK::QValue(coord.getBodyIndex(), SimTK::MobilizerQIndex(coord.getMobilizerQIndex()), coordRef->getValue(s) ); // keep a handle to the goal so we can update _coordinateAssemblyConditions.push_back(coordGoal); // Add coordinate matching goal to the ik objective _assembler->adoptAssemblyGoal(coordGoal, coordRef->getWeight(s)); } } } unsigned int nqrefs = _coordinateReferencesp.size(), nqgoals = _coordinateAssemblyConditions.size(); //Should have a one-to-one matched arrays if(nqrefs != nqgoals) throw Exception("AsemblySolver::setupGoals() has a mismatch between number of references and goals."); } /** Once a set of coordinates has been specified its target value can be updated directly */ void AssemblySolver::updateCoordinateReference(const std::string &coordName, double value, double weight) { SimTK::Array_<CoordinateReference>::iterator p; // Cycle through coordinate references for(p = _coordinateReferencesp.begin(); p != _coordinateReferencesp.end(); p++) { if(p->getName() == coordName){ p->setValueFunction(*new Constant(value)); p->setWeight(weight); return; } } } /** Internal method to update the time, reference values and/or their weights that define the goals, based on the passed in state. */ void AssemblySolver::updateGoals(const SimTK::State &s) { unsigned int nqrefs = _coordinateReferencesp.size(); for(unsigned int i=0; i<nqrefs; i++){ //update goal values from reference. _coordinateAssemblyConditions[i]->setValue ((_coordinateReferencesp)[i].getValue(s)); //_assembler->setAssemblyConditionWeight(_coordinateAssemblyConditions[i]-> } } //______________________________________________________________________________ /** * Assemble the model such that it satisfies configuration goals and constraints * The input state is used to initialize the assembly and then is updated to * return the resulting assembled configuration. */ void AssemblySolver::assemble(SimTK::State &state) { // Make a working copy of the state that will be used to set the internal // state of the solver. This is necessary because we may wish to disable // redundant constraints, but do not want this to effect the state of // constraints the user expects SimTK::State s = state; // Make sure goals are up-to-date. setupGoals(s); // Let assembler perform some internal setup _assembler->initialize(s); /* TODO: Useful to include through debug message/log in the future printf("UNASSEMBLED CONFIGURATION (normerr=%g, maxerr=%g, cost=%g)\n", _assembler->calcCurrentErrorNorm(), max(abs(_assembler->getInternalState().getQErr())), _assembler->calcCurrentGoal()); cout << "Model numQs: " << _assembler->getInternalState().getNQ() << " Assembler num freeQs: " << _assembler->getNumFreeQs() << endl; */ try{ // Now do the assembly and return the updated state. _assembler->assemble(); // Update the q's in the state passed in _assembler->updateFromInternalState(s); state.updQ() = s.getQ(); state.updU() = s.getU(); // Get model coordinates const CoordinateSet& modelCoordSet = getModel().getCoordinateSet(); // Make sure the locks in original state are restored for(int i=0; i< modelCoordSet.getSize(); ++i){ bool isLocked = modelCoordSet[i].getLocked(state); if(isLocked) modelCoordSet[i].setLocked(state, isLocked); } /* TODO: Useful to include through debug message/log in the future printf("ASSEMBLED CONFIGURATION (acc=%g tol=%g normerr=%g, maxerr=%g, cost=%g)\n", _assembler->getAccuracyInUse(), _assembler->getErrorToleranceInUse(), _assembler->calcCurrentErrorNorm(), max(abs(_assembler->getInternalState().getQErr())), _assembler->calcCurrentGoal()); printf("# initializations=%d\n", _assembler->getNumInitializations()); printf("# assembly steps: %d\n", _assembler->getNumAssemblySteps()); printf(" evals: goal=%d grad=%d error=%d jac=%d\n", _assembler->getNumGoalEvals(), _assembler->getNumGoalGradientEvals(), _assembler->getNumErrorEvals(), _assembler->getNumErrorJacobianEvals()); */ } catch (const std::exception& ex) { std::string msg = "AssemblySolver::assemble() Failed: "; msg += ex.what(); throw Exception(msg); } } /** Obtain a model configuration that meets the assembly conditions (desired values and constraints) given a state that satisfies or is close to satisfying the constraints. Note there can be no change in the number of constraints or desired coordinates. Desired coordinate values can and should be updated between repeated calls to track a desired trajectory of coordinate values. */ void AssemblySolver::track(SimTK::State &s) { // move the target locations or angles, etc... just do not change number of goals // and their type (constrained vs. weighted) if(_assembler && _assembler->isInitialized()){ updateGoals(s); } else{ throw Exception( "AssemblySolver::track() failed: assemble() must be called first."); } /* TODO: Useful to include through debug message/log in the future printf("UNASSEMBLED(track) CONFIGURATION (normerr=%g, maxerr=%g, cost=%g)\n", _assembler->calcCurrentErrorNorm(), max(abs(_assembler->getInternalState().getQErr())), _assembler->calcCurrentGoal() ); cout << "Model numQs: " << _assembler->getInternalState().getNQ() << " Assembler num freeQs: " << _assembler->getNumFreeQs() << endl; */ try{ // Now do the assembly and return the updated state. _assembler->track(s.getTime()); // update the state from the result of the assembler _assembler->updateFromInternalState(s); /* TODO: Useful to include through debug message/log in the future printf("Tracking: t= %f (acc=%g tol=%g normerr=%g, maxerr=%g, cost=%g)\n", s.getTime(), _assembler->getAccuracyInUse(), _assembler->getErrorToleranceInUse(), _assembler->calcCurrentErrorNorm(), max(abs(_assembler->getInternalState().getQErr())), _assembler->calcCurrentGoal()); */ } catch (const std::exception& ex) { std::cout << "AssemblySolver::track() attempt Failed: " << ex.what() << std::endl; throw Exception("AssemblySolver::track() attempt failed."); } } } // end of namespace OpenSim <|endoftext|>
<commit_before>/* * Copyright (C) 2014 MediaSift Ltd. * * 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. */ #ifndef SERVED_PATH_SEG_MATCHER_HPP #define SERVED_PATH_SEG_MATCHER_HPP #include <string> #include <memory> #include <served/parameters.hpp> namespace served { namespace mux { /* * A representation of a segment of a handler path for matching requests. */ class segment_matcher { public: /* * Checks whether the path segment matches this segment matcher. * * @param path_segment the path segment to check matching against. * * @return true is the path segment matches, false otherwise. */ virtual bool check_match(const std::string & path_segment) = 0; /* * Appends any parameters extracted from the path segment to a list of params. * * This is used to propagate any REST parameters. * * @param params the list of parameters to append to * @param path_segment the segment of path the variable should be extracted from */ virtual void get_param(served::parameters & params, const std::string & path_segment) = 0; }; typedef std::shared_ptr<segment_matcher> segment_matcher_ptr; } } // mux, served #endif // SERVED_PATH_SEG_MATCHER_HPP <commit_msg>Added missing virtual destructor<commit_after>/* * Copyright (C) 2014 MediaSift Ltd. * * 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. */ #ifndef SERVED_PATH_SEG_MATCHER_HPP #define SERVED_PATH_SEG_MATCHER_HPP #include <string> #include <memory> #include <served/parameters.hpp> namespace served { namespace mux { /* * A representation of a segment of a handler path for matching requests. */ class segment_matcher { public: /* * Checks whether the path segment matches this segment matcher. * * @param path_segment the path segment to check matching against. * * @return true is the path segment matches, false otherwise. */ virtual bool check_match(const std::string & path_segment) = 0; /* * Appends any parameters extracted from the path segment to a list of params. * * This is used to propagate any REST parameters. * * @param params the list of parameters to append to * @param path_segment the segment of path the variable should be extracted from */ virtual void get_param(served::parameters & params, const std::string & path_segment) = 0; /* * Class destructor. */ virtual ~segment_matcher() { } }; typedef std::shared_ptr<segment_matcher> segment_matcher_ptr; } } // mux, served #endif // SERVED_PATH_SEG_MATCHER_HPP <|endoftext|>
<commit_before>#include "AliMuonCompactMapping.h" #include "AliCDBManager.h" #include "AliMpCDB.h" #include "AliMpDEIterator.h" #include <vector> #include "AliMpDEManager.h" #include "AliMpManuIterator.h" #include "AliMpDDLStore.h" #include "AliMpDetElement.h" #include <cassert> namespace { Int_t DECODELOW(UInt_t e) { return e & 0x0000FFFF; } Int_t DECODEHIGH(UInt_t e) { return (e & 0xFFFF0000) >> 16; } UInt_t ENCODE(Int_t a16, Int_t b16) { return ( ( a16 & 0x0000FFFF ) << 16 ) | ( b16 & 0x0000FFFF ); } } Int_t AliMuonCompactMapping::GetDetElemIdFromAbsManuIndex(Int_t index) const { return GetDetElemIdFromAbsManuId(AbsManuId(index)); } Int_t AliMuonCompactMapping::AbsManuId(UInt_t index) const { if ( index>mManuIds.size()) { std::cout << index << " > " << mManuIds.size() << std::endl; } return mManuIds[index]; } Int_t AliMuonCompactMapping::GetManuIdFromAbsManuId(UInt_t absManuId) const { return DECODELOW(absManuId); } Int_t AliMuonCompactMapping::GetDetElemIdFromAbsManuId(UInt_t absManuId) const { return DECODEHIGH(absManuId); } Int_t AliMuonCompactMapping::GetNofPadsFromAbsManuIndex(Int_t index) const { return mNpads[index]; } Int_t AliMuonCompactMapping::FindManuAbsIndex(Int_t detElemId, Int_t manuId) const { UInt_t encoded = ENCODE(detElemId,manuId); auto p = mManuMap.find(encoded); return p->second; } AliMuonCompactMapping* AliMuonCompactMapping::GetCompactMapping(const char* ocdbPath, Int_t runNumber) { static AliMuonCompactMapping* cm(0x0); if (!cm) { cm = new AliMuonCompactMapping; AliCDBManager* man = AliCDBManager::Instance(); if (!man->IsDefaultStorageSet()) { man->SetDefaultStorage(ocdbPath); man->SetRun(runNumber); } AliMpCDB::LoadAll(); // first get a sorted list of the detElemId AliMpDEIterator deit; deit.First(); std::vector<int> deids; while (!deit.IsDone()) { Int_t detElemId = deit.CurrentDEId(); if ( AliMpDEManager::GetStationType(detElemId) != AliMp::kStationTrigger ) { deids.push_back(detElemId); } deit.Next(); } std::sort(deids.begin(),deids.end()); // then for each DE get one sorted list of manuIds std::vector<int>::size_type totalNofManus(0); for ( std::vector<int>::size_type i = 0; i < deids.size(); ++i ) { AliMpManuIterator it; Int_t detElemId, manuId; std::vector<int> bendingManuids; std::vector<int> nonBendingManuids; // get the list of manu ids on both planes // for this detection element while ( it.Next(detElemId,manuId) ) { if ( detElemId == deids[i] ) { if ( manuId >= 1024 ) { nonBendingManuids.push_back(manuId); } if ( manuId < 1024 ) { bendingManuids.push_back(manuId); } } } detElemId = deids[i]; // insure manuids are sorted (should be the case // already, though) std::sort(bendingManuids.begin(),bendingManuids.end()); std::sort(nonBendingManuids.begin(),nonBendingManuids.end()); // add those manus to the global array of AbsManuIds // and update the relevant "links" std::vector<int>& allManuOfThisDE = bendingManuids; allManuOfThisDE.insert(allManuOfThisDE.end(), nonBendingManuids.begin(), nonBendingManuids.end()); UInt_t ix = cm->mManuIds.size(); for ( std::vector<int>::size_type i = 0; i < allManuOfThisDE.size(); ++i ) { Int_t manuId = allManuOfThisDE[i]; UInt_t encodedManu = ENCODE(detElemId,manuId); cm->mManuMap[encodedManu]=ix; cm->mManuIds.push_back(encodedManu); // get the number of pads per manu (quite usefull in // some instances, e.g. to compute occupancies...) // AliMpDetElement* de = AliMpDDLStore::Instance()->GetDetElement(detElemId); cm->mNpads.push_back(de->NofChannelsInManu(manuId)); ++ix; } totalNofManus += allManuOfThisDE.size(); // std::cout << Form("DE %04d (%3d) ",deids[i], // allManuOfThisDE.size()); // // for ( std::vector<int>::size_type j = 0; // j < allManuOfThisDE.size(); ++j ) // { // std::cout << Form("%04d ",allManuOfThisDE[j]); // } // std::cout << std::endl; } // std::cout << "Total number of manus : " << totalNofManus << std::endl; assert(totalNofManus==16828); assert(cm->mNpads.size()==totalNofManus); } return cm; } void AliMuonCompactMapping::GenerateStaticOffsets() { // generate the detection element ids arrays // that are needed in some other part of the code Int_t currentDetElemId = -1; std::vector<int> de; std::vector<int> offset; for ( unsigned int i = 0; i < mManuIds.size(); ++i ) { Int_t absManuId = AbsManuId(i); Int_t detElemId = GetDetElemIdFromAbsManuId(absManuId); if (detElemId != currentDetElemId) { currentDetElemId = detElemId; de.push_back(detElemId); offset.push_back(i); } } assert(de.size()==156); assert(offset.size()==156); std::cout << "std::vector<int> detectionElementIds = {"; for ( std::vector<int>::size_type i = 0; i < de.size(); ++i ) { std::cout << de[i]; if ( i < de.size() - 1 ) { std::cout << ","; } } std::cout << "};" << std::endl; std::cout << "std::vector<int> detectionElementIdOffsets = {"; for ( std::vector<int>::size_type i = 0; i < offset.size(); ++i ) { std::cout << offset[i]; if ( i < offset.size() - 1 ) { std::cout << ","; } } std::cout << "};" << std::endl; } std::ostream& operator<<(std::ostream& os, const AliMuonCompactMapping& cm) { // consistency check for ( unsigned int i = 0; i < cm.mManuIds.size(); ++i ) { Int_t absManuId = cm.AbsManuId(i); os << Form("ENCODEDMANUID[%6d]=%04d : DE %04d MANU %04d", i,absManuId,cm.GetDetElemIdFromAbsManuId(absManuId), cm.GetManuIdFromAbsManuId(absManuId)) << std::endl; } return os; } <commit_msg>Missing include (not caught on macosx, sorry about that)<commit_after>#include "AliMuonCompactMapping.h" #include "AliCDBManager.h" #include "AliMpCDB.h" #include "AliMpDEIterator.h" #include <vector> #include "AliMpDEManager.h" #include "AliMpManuIterator.h" #include "AliMpDDLStore.h" #include "AliMpDetElement.h" #include <cassert> #include <algorithm> namespace { Int_t DECODELOW(UInt_t e) { return e & 0x0000FFFF; } Int_t DECODEHIGH(UInt_t e) { return (e & 0xFFFF0000) >> 16; } UInt_t ENCODE(Int_t a16, Int_t b16) { return ( ( a16 & 0x0000FFFF ) << 16 ) | ( b16 & 0x0000FFFF ); } } Int_t AliMuonCompactMapping::GetDetElemIdFromAbsManuIndex(Int_t index) const { return GetDetElemIdFromAbsManuId(AbsManuId(index)); } Int_t AliMuonCompactMapping::AbsManuId(UInt_t index) const { if ( index>mManuIds.size()) { std::cout << index << " > " << mManuIds.size() << std::endl; } return mManuIds[index]; } Int_t AliMuonCompactMapping::GetManuIdFromAbsManuId(UInt_t absManuId) const { return DECODELOW(absManuId); } Int_t AliMuonCompactMapping::GetDetElemIdFromAbsManuId(UInt_t absManuId) const { return DECODEHIGH(absManuId); } Int_t AliMuonCompactMapping::GetNofPadsFromAbsManuIndex(Int_t index) const { return mNpads[index]; } Int_t AliMuonCompactMapping::FindManuAbsIndex(Int_t detElemId, Int_t manuId) const { UInt_t encoded = ENCODE(detElemId,manuId); auto p = mManuMap.find(encoded); return p->second; } AliMuonCompactMapping* AliMuonCompactMapping::GetCompactMapping(const char* ocdbPath, Int_t runNumber) { static AliMuonCompactMapping* cm(0x0); if (!cm) { cm = new AliMuonCompactMapping; AliCDBManager* man = AliCDBManager::Instance(); if (!man->IsDefaultStorageSet()) { man->SetDefaultStorage(ocdbPath); man->SetRun(runNumber); } AliMpCDB::LoadAll(); // first get a sorted list of the detElemId AliMpDEIterator deit; deit.First(); std::vector<int> deids; while (!deit.IsDone()) { Int_t detElemId = deit.CurrentDEId(); if ( AliMpDEManager::GetStationType(detElemId) != AliMp::kStationTrigger ) { deids.push_back(detElemId); } deit.Next(); } std::sort(deids.begin(),deids.end()); // then for each DE get one sorted list of manuIds std::vector<int>::size_type totalNofManus(0); for ( std::vector<int>::size_type i = 0; i < deids.size(); ++i ) { AliMpManuIterator it; Int_t detElemId, manuId; std::vector<int> bendingManuids; std::vector<int> nonBendingManuids; // get the list of manu ids on both planes // for this detection element while ( it.Next(detElemId,manuId) ) { if ( detElemId == deids[i] ) { if ( manuId >= 1024 ) { nonBendingManuids.push_back(manuId); } if ( manuId < 1024 ) { bendingManuids.push_back(manuId); } } } detElemId = deids[i]; // insure manuids are sorted (should be the case // already, though) std::sort(bendingManuids.begin(),bendingManuids.end()); std::sort(nonBendingManuids.begin(),nonBendingManuids.end()); // add those manus to the global array of AbsManuIds // and update the relevant "links" std::vector<int>& allManuOfThisDE = bendingManuids; allManuOfThisDE.insert(allManuOfThisDE.end(), nonBendingManuids.begin(), nonBendingManuids.end()); UInt_t ix = cm->mManuIds.size(); for ( std::vector<int>::size_type i = 0; i < allManuOfThisDE.size(); ++i ) { Int_t manuId = allManuOfThisDE[i]; UInt_t encodedManu = ENCODE(detElemId,manuId); cm->mManuMap[encodedManu]=ix; cm->mManuIds.push_back(encodedManu); // get the number of pads per manu (quite usefull in // some instances, e.g. to compute occupancies...) // AliMpDetElement* de = AliMpDDLStore::Instance()->GetDetElement(detElemId); cm->mNpads.push_back(de->NofChannelsInManu(manuId)); ++ix; } totalNofManus += allManuOfThisDE.size(); // std::cout << Form("DE %04d (%3d) ",deids[i], // allManuOfThisDE.size()); // // for ( std::vector<int>::size_type j = 0; // j < allManuOfThisDE.size(); ++j ) // { // std::cout << Form("%04d ",allManuOfThisDE[j]); // } // std::cout << std::endl; } // std::cout << "Total number of manus : " << totalNofManus << std::endl; assert(totalNofManus==16828); assert(cm->mNpads.size()==totalNofManus); } return cm; } void AliMuonCompactMapping::GenerateStaticOffsets() { // generate the detection element ids arrays // that are needed in some other part of the code Int_t currentDetElemId = -1; std::vector<int> de; std::vector<int> offset; for ( unsigned int i = 0; i < mManuIds.size(); ++i ) { Int_t absManuId = AbsManuId(i); Int_t detElemId = GetDetElemIdFromAbsManuId(absManuId); if (detElemId != currentDetElemId) { currentDetElemId = detElemId; de.push_back(detElemId); offset.push_back(i); } } assert(de.size()==156); assert(offset.size()==156); std::cout << "std::vector<int> detectionElementIds = {"; for ( std::vector<int>::size_type i = 0; i < de.size(); ++i ) { std::cout << de[i]; if ( i < de.size() - 1 ) { std::cout << ","; } } std::cout << "};" << std::endl; std::cout << "std::vector<int> detectionElementIdOffsets = {"; for ( std::vector<int>::size_type i = 0; i < offset.size(); ++i ) { std::cout << offset[i]; if ( i < offset.size() - 1 ) { std::cout << ","; } } std::cout << "};" << std::endl; } std::ostream& operator<<(std::ostream& os, const AliMuonCompactMapping& cm) { // consistency check for ( unsigned int i = 0; i < cm.mManuIds.size(); ++i ) { Int_t absManuId = cm.AbsManuId(i); os << Form("ENCODEDMANUID[%6d]=%04d : DE %04d MANU %04d", i,absManuId,cm.GetDetElemIdFromAbsManuId(absManuId), cm.GetManuIdFromAbsManuId(absManuId)) << std::endl; } return os; } <|endoftext|>
<commit_before>// // Wagon contacts: EMCAL Gustavo.Conesa.Balbastre@cern.ch // PHOS Yuri.Kharlov@cern.ch // AliAnalysisTaskParticleCorrelation *AddTaskCalorimeterQA(TString data, Bool_t kPrintSettings = kFALSE,Bool_t kSimulation = kFALSE,TString outputFile = "", Bool_t oldAOD=kFALSE) { // Creates a PartCorr task for calorimeters performance studies, configures it and adds it to the analysis manager. // Get the pointer to the existing analysis manager via the static access method. //============================================================================== AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager(); if (!mgr) { ::Error("AddTaskPartCorr", "No analysis manager to connect to."); return NULL; } // Check the analysis type using the event handlers connected to the analysis manager. //============================================================================== if (!mgr->GetInputEventHandler()) { ::Error("AddTaskPartCorr", "This task requires an input event handler"); return NULL; } TString inputDataType = mgr->GetInputEventHandler()->GetDataType(); // can be "ESD" or "AOD" Bool_t kUseKinematics = (mgr->GetMCtruthEventHandler())?kTRUE:kFALSE; cout<<"********* ACCESS KINE? "<<kUseKinematics<<endl; // Configure analysis //=========================================================================== //Reader //For this particular analysis few things done by the reader. //Nothing else needs to be set. AliCaloTrackReader * reader = 0x0; if (data=="AOD") reader = new AliCaloTrackAODReader(); else if(data=="ESD") reader = new AliCaloTrackESDReader(); //reader->SetDebug(10);//10 for lots of messages reader->SwitchOnEMCALCells(); reader->SwitchOnPHOSCells(); reader->SwitchOnEMCAL(); reader->SwitchOnPHOS(); reader->SwitchOnCTS(); reader->SetEMCALPtMin(0.); reader->SetPHOSPtMin (0.); reader->SetCTSPtMin (0.); reader->SetZvertexCut(10.); if(kUseKinematics){ if(inputDataType == "ESD"){ reader->SwitchOnStack(); reader->SwitchOffAODMCParticles(); } else if(inputDataType == "AOD"){ reader->SwitchOffStack(); reader->SwitchOnAODMCParticles(); } } //if(!kSimulation) reader->SetFiredTriggerClassName("CINT1B-ABCE-NOPF-ALL"); reader->SetDeltaAODFileName(""); //Do not create deltaAOD file, this analysis do not create branches. reader->SwitchOffWriteDeltaAOD() ; if(oldAOD) reader->SwitchOnOldAODs(); if(kPrintSettings) reader->Print(""); // *** Calorimeters Utils *** AliCalorimeterUtils *cu = new AliCalorimeterUtils; // Remove clusters close to borders, at least max energy cell is 1 cell away cu->SetNumberOfCellsFromEMCALBorder(1); cu->SetNumberOfCellsFromPHOSBorder(2); // Remove EMCAL hottest channels for first LHC10 periods cu->SwitchOnBadChannelsRemoval(); // SM0 cu->SetEMCALChannelStatus(0,3,13); cu->SetEMCALChannelStatus(0,44,1); cu->SetEMCALChannelStatus(0,3,13); cu->SetEMCALChannelStatus(0,20,7); cu->SetEMCALChannelStatus(0,38,2); // SM1 cu->SetEMCALChannelStatus(1,4,7); cu->SetEMCALChannelStatus(1,4,13); cu->SetEMCALChannelStatus(1,9,20); cu->SetEMCALChannelStatus(1,14,15); cu->SetEMCALChannelStatus(1,23,16); cu->SetEMCALChannelStatus(1,32,23); cu->SetEMCALChannelStatus(1,37,5); cu->SetEMCALChannelStatus(1,40,1); cu->SetEMCALChannelStatus(1,40,2); cu->SetEMCALChannelStatus(1,40,5); cu->SetEMCALChannelStatus(1,41,0); cu->SetEMCALChannelStatus(1,41,1); cu->SetEMCALChannelStatus(1,41,2); cu->SetEMCALChannelStatus(1,41,4); // SM2 cu->SetEMCALChannelStatus(2,14,15); cu->SetEMCALChannelStatus(2,18,16); cu->SetEMCALChannelStatus(2,18,17); cu->SetEMCALChannelStatus(2,18,18); cu->SetEMCALChannelStatus(2,18,20); cu->SetEMCALChannelStatus(2,18,21); cu->SetEMCALChannelStatus(2,18,23); cu->SetEMCALChannelStatus(2,19,16); cu->SetEMCALChannelStatus(2,19,17); cu->SetEMCALChannelStatus(2,19,19); cu->SetEMCALChannelStatus(2,19,20); cu->SetEMCALChannelStatus(2,19,21); cu->SetEMCALChannelStatus(2,19,22); //SM3 cu->SetEMCALChannelStatus(3,4,7); //Recalibration //cu->SwitchOnRecalibration(); //TFile * f = new TFile("RecalibrationFactors.root","read"); //cu->SetEMCALChannelRecalibrationFactors(0,(TH2F*)f->Get("EMCALRecalFactors_SM0")); //cu->SetEMCALChannelRecalibrationFactors(1,(TH2F*)f->Get("EMCALRecalFactors_SM1")); //cu->SetEMCALChannelRecalibrationFactors(2,(TH2F*)f->Get("EMCALRecalFactors_SM2")); //cu->SetEMCALChannelRecalibrationFactors(3,(TH2F*)f->Get("EMCALRecalFactors_SM3")); cu->SetDebug(-1); if(kPrintSettings) cu->Print(""); // ##### Analysis algorithm settings #### //AliFiducialCut * fidCut = new AliFiducialCut(); //fidCut->DoCTSFiducialCut(kFALSE) ; //fidCut->DoEMCALFiducialCut(kTRUE) ; //fidCut->DoPHOSFiducialCut(kTRUE) ; AliAnaCalorimeterQA *emcalQA = new AliAnaCalorimeterQA(); //emcalQA->SetDebug(2); //10 for lots of messages emcalQA->SetCalorimeter("EMCAL"); if(kUseKinematics) emcalQA->SwitchOnDataMC() ;//Access MC stack and fill more histograms, AOD MC not implemented yet. else emcalQA->SwitchOffDataMC() ; emcalQA->AddToHistogramsName("EMCAL_"); //Begining of histograms name //emcalQA->SetFiducialCut(fidCut); emcalQA->SwitchOffFiducialCut(); emcalQA->SwitchOffPlotsMaking(); emcalQA->SwitchOnCorrelation(); if(!kUseKinematics)emcalQA->SetTimeCut(400,850);//Open for the moment //Set Histrograms bins and ranges emcalQA->SetHistoPtRangeAndNBins(0, 50, 200) ; emcalQA->SetHistoFinePtRangeAndNBins(0, 10, 200) ; // bining for fhAmpId emcalQA->SetHistoPhiRangeAndNBins(79*TMath::DegToRad(), 121*TMath::DegToRad(), 100) ; emcalQA->SetHistoEtaRangeAndNBins(-0.71, 0.71, 200) ; emcalQA->SetNumberOfModules(4); //EMCAL first year emcalQA->SetHistoMassRangeAndNBins(0., 1, 400) ; emcalQA->SetHistoAsymmetryRangeAndNBins(0., 1. , 10 ); emcalQA->SetHistoPOverERangeAndNBins(0,10.,100); emcalQA->SetHistodEdxRangeAndNBins(0.,200.,200); emcalQA->SetHistodRRangeAndNBins(0.,TMath::Pi(),150); emcalQA->SetHistoTimeRangeAndNBins(300.,900,300); emcalQA->SetHistoRatioRangeAndNBins(0.,2.,100); emcalQA->SetHistoVertexDistRangeAndNBins(0.,500.,500); emcalQA->SetHistoNClusterCellRangeAndNBins(0,500,500); emcalQA->SetHistoXRangeAndNBins(-230,90,120); emcalQA->SetHistoYRangeAndNBins(370,450,40); emcalQA->SetHistoZRangeAndNBins(-400,400,200); emcalQA->SetHistoRRangeAndNBins(400,450,25); emcalQA->SetHistoV0SignalRangeAndNBins(0,5000,500); emcalQA->SetHistoV0MultiplicityRangeAndNBins(0,5000,500); emcalQA->SetHistoTrackMultiplicityRangeAndNBins(0,5000,500); //emcalQA->GetMCAnalysisUtils()->SetDebug(10); if(kPrintSettings) emcalQA->Print(""); AliAnaCalorimeterQA *phosQA = new AliAnaCalorimeterQA(); //phosQA->SetDebug(2); //10 for lots of messages phosQA->SetCalorimeter("PHOS"); if(kUseKinematics) phosQA->SwitchOnDataMC() ;//Access MC stack and fill more histograms, AOD MC not implemented yet. else phosQA->SwitchOffDataMC() ; phosQA->AddToHistogramsName("PHOS_");//Begining of histograms name //phosQA->SetFiducialCut(fidCut); phosQA->SwitchOffFiducialCut(); //phosQA->GetMCAnalysisUtils()->SetDebug(10); phosQA->SwitchOffPlotsMaking(); //Set Histrograms bins and ranges phosQA->SetHistoPtRangeAndNBins(0, 50, 200) ; phosQA->SetHistoFinePtRangeAndNBins(0, 10, 200) ; // bining for fhAmpId phosQA->SetHistoPhiRangeAndNBins(259*TMath::DegToRad(), 321*TMath::DegToRad(), 130) ; phosQA->SetHistoEtaRangeAndNBins(-0.125, 0.125, 57) ; phosQA->SetNumberOfModules(3); //PHOS first year phosQA->SetHistoMassRangeAndNBins(0., 1., 400) ; phosQA->SetHistoAsymmetryRangeAndNBins(0., 1. , 10) ; phosQA->SetHistoPOverERangeAndNBins(0,10.,100); phosQA->SetHistodEdxRangeAndNBins(0.,200.,200); phosQA->SetHistodRRangeAndNBins(0.,TMath::Pi(),150); phosQA->SetHistoTimeRangeAndNBins(0.,300,300); phosQA->SetHistoRatioRangeAndNBins(0.,2.,100); phosQA->SetHistoVertexDistRangeAndNBins(0.,500.,500); phosQA->SetHistoNClusterCellRangeAndNBins(0,500,500); phosQA->SetHistoXRangeAndNBins(-100,400,100); phosQA->SetHistoYRangeAndNBins(-490,-290,100); phosQA->SetHistoZRangeAndNBins(-80,80,100); phosQA->SetHistoRRangeAndNBins(440,480,80); phosQA->SetHistoV0SignalRangeAndNBins(0,5000,500); phosQA->SetHistoV0MultiplicityRangeAndNBins(0,5000,500); phosQA->SetHistoTrackMultiplicityRangeAndNBins(0,5000,500); // #### Configure Maker #### AliAnaPartCorrMaker * maker = new AliAnaPartCorrMaker(); maker->SetReader(reader);//pointer to reader maker->SetCaloUtils(cu); //pointer to calorimeter utils maker->AddAnalysis(emcalQA,0); maker->AddAnalysis(phosQA,1); maker->SetAnaDebug(-1) ; // 0 to at least print the event number maker->SwitchOnHistogramsMaker() ; maker->SwitchOffAODsMaker() ; if(kPrintSettings) maker->Print(""); printf("======================== \n"); printf(" End Configuration of Calorimeter QA \n"); printf("======================== \n"); // Create task //=========================================================================== AliAnalysisTaskParticleCorrelation * task = new AliAnalysisTaskParticleCorrelation ("CalorimeterPerformance"); task->SetConfigFileName(""); //Don't configure the analysis via configuration file. //task->SetDebugLevel(-1); task->SelectCollisionCandidates(); task->SetAnalysisMaker(maker); mgr->AddTask(task); //Create containers // AliAnalysisDataContainer *cout_pc = mgr->CreateContainer("Calo.Performance",TList::Class(), // AliAnalysisManager::kOutputContainer, "Calo.Performance.root"); if(outputFile.Length()==0)outputFile = AliAnalysisManager::GetCommonFileName(); AliAnalysisDataContainer *cout_pc = mgr->CreateContainer("CaloQA", TList::Class(), AliAnalysisManager::kOutputContainer, Form("%s:CaloQA",outputFile.Data())); AliAnalysisDataContainer *cout_cuts = mgr->CreateContainer("CaloQACuts", TList::Class(), AliAnalysisManager::kParamContainer, Form("%s:CaloQACuts",outputFile.Data())); //Form("%s:PartCorrCuts",outputfile.Data())); // Create ONLY the output containers for the data produced by the task. // Get and connect other common input/output containers via the manager as below //============================================================================== mgr->ConnectInput (task, 0, mgr->GetCommonInputContainer()); mgr->ConnectOutput (task, 1, cout_pc); mgr->ConnectOutput (task, 2, cout_cuts); return task; } <commit_msg>settings for 2011 data taking<commit_after>// // Wagon contacts: EMCAL Gustavo.Conesa.Balbastre@cern.ch // PHOS Yuri.Kharlov@cern.ch // AliAnalysisTaskParticleCorrelation *AddTaskCalorimeterQA(TString data, Bool_t kPrintSettings = kFALSE,Bool_t kSimulation = kFALSE,TString outputFile = "", Bool_t oldAOD=kFALSE) { // Creates a PartCorr task for calorimeters performance studies, configures it and adds it to the analysis manager. // Get the pointer to the existing analysis manager via the static access method. //============================================================================== AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager(); if (!mgr) { ::Error("AddTaskPartCorr", "No analysis manager to connect to."); return NULL; } // Check the analysis type using the event handlers connected to the analysis manager. //============================================================================== if (!mgr->GetInputEventHandler()) { ::Error("AddTaskPartCorr", "This task requires an input event handler"); return NULL; } TString inputDataType = mgr->GetInputEventHandler()->GetDataType(); // can be "ESD" or "AOD" Bool_t kUseKinematics = (mgr->GetMCtruthEventHandler())?kTRUE:kFALSE; cout<<"********* ACCESS KINE? "<<kUseKinematics<<endl; // Configure analysis //=========================================================================== //Reader //For this particular analysis few things done by the reader. //Nothing else needs to be set. AliCaloTrackReader * reader = 0x0; if (data=="AOD") reader = new AliCaloTrackAODReader(); else if(data=="ESD") reader = new AliCaloTrackESDReader(); //reader->SetDebug(10);//10 for lots of messages reader->SwitchOnEMCALCells(); reader->SwitchOnPHOSCells(); reader->SwitchOnEMCAL(); reader->SwitchOnPHOS(); reader->SwitchOnCTS(); reader->SetEMCALPtMin(0.); reader->SetPHOSPtMin (0.); reader->SetCTSPtMin (0.); reader->SetZvertexCut(10.); if(kUseKinematics){ if(inputDataType == "ESD"){ reader->SwitchOnStack(); reader->SwitchOffAODMCParticles(); } else if(inputDataType == "AOD"){ reader->SwitchOffStack(); reader->SwitchOnAODMCParticles(); } } //if(!kSimulation) reader->SetFiredTriggerClassName("CINT1B-ABCE-NOPF-ALL"); reader->SetDeltaAODFileName(""); //Do not create deltaAOD file, this analysis do not create branches. reader->SwitchOffWriteDeltaAOD() ; if(oldAOD) reader->SwitchOnOldAODs(); if(kPrintSettings) reader->Print(""); // *** Calorimeters Utils *** AliCalorimeterUtils *cu = new AliCalorimeterUtils; // Remove clusters close to borders, at least max energy cell is 1 cell away cu->SetNumberOfCellsFromEMCALBorder(1); cu->SetNumberOfCellsFromPHOSBorder(2); cu->SetEMCALGeometryName("EMCAL_COMPLETEV1"); // Remove EMCAL hottest channels for first LHC10 periods //cu->SwitchOnBadChannelsRemoval(); // SM0 //cu->SetEMCALChannelStatus(0,3,13); cu->SetEMCALChannelStatus(0,44,1); cu->SetEMCALChannelStatus(0,3,13); //cu->SetEMCALChannelStatus(0,20,7); cu->SetEMCALChannelStatus(0,38,2); // SM1 //cu->SetEMCALChannelStatus(1,4,7); cu->SetEMCALChannelStatus(1,4,13); cu->SetEMCALChannelStatus(1,9,20); //cu->SetEMCALChannelStatus(1,14,15); cu->SetEMCALChannelStatus(1,23,16); cu->SetEMCALChannelStatus(1,32,23); //cu->SetEMCALChannelStatus(1,37,5); cu->SetEMCALChannelStatus(1,40,1); cu->SetEMCALChannelStatus(1,40,2); //cu->SetEMCALChannelStatus(1,40,5); cu->SetEMCALChannelStatus(1,41,0); cu->SetEMCALChannelStatus(1,41,1); //cu->SetEMCALChannelStatus(1,41,2); cu->SetEMCALChannelStatus(1,41,4); // SM2 //cu->SetEMCALChannelStatus(2,14,15); cu->SetEMCALChannelStatus(2,18,16); cu->SetEMCALChannelStatus(2,18,17); //cu->SetEMCALChannelStatus(2,18,18); cu->SetEMCALChannelStatus(2,18,20); cu->SetEMCALChannelStatus(2,18,21); //cu->SetEMCALChannelStatus(2,18,23); cu->SetEMCALChannelStatus(2,19,16); cu->SetEMCALChannelStatus(2,19,17); //cu->SetEMCALChannelStatus(2,19,19); cu->SetEMCALChannelStatus(2,19,20); cu->SetEMCALChannelStatus(2,19,21); //cu->SetEMCALChannelStatus(2,19,22); //SM3 //cu->SetEMCALChannelStatus(3,4,7); //Recalibration //cu->SwitchOnRecalibration(); //TFile * f = new TFile("RecalibrationFactors.root","read"); //cu->SetEMCALChannelRecalibrationFactors(0,(TH2F*)f->Get("EMCALRecalFactors_SM0")); //cu->SetEMCALChannelRecalibrationFactors(1,(TH2F*)f->Get("EMCALRecalFactors_SM1")); //cu->SetEMCALChannelRecalibrationFactors(2,(TH2F*)f->Get("EMCALRecalFactors_SM2")); //cu->SetEMCALChannelRecalibrationFactors(3,(TH2F*)f->Get("EMCALRecalFactors_SM3")); cu->SetDebug(-1); if(kPrintSettings) cu->Print(""); // ##### Analysis algorithm settings #### //AliFiducialCut * fidCut = new AliFiducialCut(); //fidCut->DoCTSFiducialCut(kFALSE) ; //fidCut->DoEMCALFiducialCut(kTRUE) ; //fidCut->DoPHOSFiducialCut(kTRUE) ; AliAnaCalorimeterQA *emcalQA = new AliAnaCalorimeterQA(); //emcalQA->SetDebug(2); //10 for lots of messages emcalQA->SetCalorimeter("EMCAL"); if(kUseKinematics) emcalQA->SwitchOnDataMC() ;//Access MC stack and fill more histograms, AOD MC not implemented yet. else emcalQA->SwitchOffDataMC() ; emcalQA->AddToHistogramsName("EMCAL_"); //Begining of histograms name //emcalQA->SetFiducialCut(fidCut); emcalQA->SwitchOffFiducialCut(); emcalQA->SwitchOffPlotsMaking(); emcalQA->SwitchOnCorrelation(); if(!kUseKinematics)emcalQA->SetTimeCut(400,850);//Open for the moment //Set Histrograms bins and ranges emcalQA->SetHistoPtRangeAndNBins(0, 50, 200) ; emcalQA->SetHistoFinePtRangeAndNBins(0, 10, 200) ; // bining for fhAmpId emcalQA->SetHistoPhiRangeAndNBins(79*TMath::DegToRad(), 121*TMath::DegToRad(), 100) ; emcalQA->SetHistoEtaRangeAndNBins(-0.71, 0.71, 200) ; emcalQA->SetNumberOfModules(10); //EMCAL first year emcalQA->SetHistoMassRangeAndNBins(0., 1, 400) ; emcalQA->SetHistoAsymmetryRangeAndNBins(0., 1. , 10 ); emcalQA->SetHistoPOverERangeAndNBins(0,10.,100); emcalQA->SetHistodEdxRangeAndNBins(0.,200.,200); emcalQA->SetHistodRRangeAndNBins(0.,TMath::Pi(),150); emcalQA->SetHistoTimeRangeAndNBins(300.,900,300); emcalQA->SetHistoRatioRangeAndNBins(0.,2.,100); emcalQA->SetHistoVertexDistRangeAndNBins(0.,500.,500); emcalQA->SetHistoNClusterCellRangeAndNBins(0,500,500); emcalQA->SetHistoXRangeAndNBins(-230,90,120); emcalQA->SetHistoYRangeAndNBins(370,450,40); emcalQA->SetHistoZRangeAndNBins(-400,400,200); emcalQA->SetHistoRRangeAndNBins(400,450,25); emcalQA->SetHistoV0SignalRangeAndNBins(0,5000,500); emcalQA->SetHistoV0MultiplicityRangeAndNBins(0,5000,500); emcalQA->SetHistoTrackMultiplicityRangeAndNBins(0,5000,500); //emcalQA->GetMCAnalysisUtils()->SetDebug(10); if(kPrintSettings) emcalQA->Print(""); AliAnaCalorimeterQA *phosQA = new AliAnaCalorimeterQA(); //phosQA->SetDebug(2); //10 for lots of messages phosQA->SetCalorimeter("PHOS"); if(kUseKinematics) phosQA->SwitchOnDataMC() ;//Access MC stack and fill more histograms, AOD MC not implemented yet. else phosQA->SwitchOffDataMC() ; phosQA->AddToHistogramsName("PHOS_");//Begining of histograms name //phosQA->SetFiducialCut(fidCut); phosQA->SwitchOffFiducialCut(); //phosQA->GetMCAnalysisUtils()->SetDebug(10); phosQA->SwitchOffPlotsMaking(); //Set Histrograms bins and ranges phosQA->SetHistoPtRangeAndNBins(0, 50, 200) ; phosQA->SetHistoFinePtRangeAndNBins(0, 10, 200) ; // bining for fhAmpId phosQA->SetHistoPhiRangeAndNBins(259*TMath::DegToRad(), 321*TMath::DegToRad(), 130) ; phosQA->SetHistoEtaRangeAndNBins(-0.125, 0.125, 57) ; phosQA->SetNumberOfModules(3); //PHOS first year phosQA->SetHistoMassRangeAndNBins(0., 1., 400) ; phosQA->SetHistoAsymmetryRangeAndNBins(0., 1. , 10) ; phosQA->SetHistoPOverERangeAndNBins(0,10.,100); phosQA->SetHistodEdxRangeAndNBins(0.,200.,200); phosQA->SetHistodRRangeAndNBins(0.,TMath::Pi(),150); phosQA->SetHistoTimeRangeAndNBins(0.,300,300); phosQA->SetHistoRatioRangeAndNBins(0.,2.,100); phosQA->SetHistoVertexDistRangeAndNBins(0.,500.,500); phosQA->SetHistoNClusterCellRangeAndNBins(0,500,500); phosQA->SetHistoXRangeAndNBins(-100,400,100); phosQA->SetHistoYRangeAndNBins(-490,-290,100); phosQA->SetHistoZRangeAndNBins(-80,80,100); phosQA->SetHistoRRangeAndNBins(440,480,80); phosQA->SetHistoV0SignalRangeAndNBins(0,5000,500); phosQA->SetHistoV0MultiplicityRangeAndNBins(0,5000,500); phosQA->SetHistoTrackMultiplicityRangeAndNBins(0,5000,500); // #### Configure Maker #### AliAnaPartCorrMaker * maker = new AliAnaPartCorrMaker(); maker->SetReader(reader);//pointer to reader maker->SetCaloUtils(cu); //pointer to calorimeter utils maker->AddAnalysis(emcalQA,0); maker->AddAnalysis(phosQA,1); maker->SetAnaDebug(-1) ; // 0 to at least print the event number maker->SwitchOnHistogramsMaker() ; maker->SwitchOffAODsMaker() ; if(kPrintSettings) maker->Print(""); printf("======================== \n"); printf(" End Configuration of Calorimeter QA \n"); printf("======================== \n"); // Create task //=========================================================================== AliAnalysisTaskParticleCorrelation * task = new AliAnalysisTaskParticleCorrelation ("CalorimeterPerformance"); task->SetConfigFileName(""); //Don't configure the analysis via configuration file. //task->SetDebugLevel(-1); task->SelectCollisionCandidates(); task->SetAnalysisMaker(maker); mgr->AddTask(task); //Create containers // AliAnalysisDataContainer *cout_pc = mgr->CreateContainer("Calo.Performance",TList::Class(), // AliAnalysisManager::kOutputContainer, "Calo.Performance.root"); if(outputFile.Length()==0)outputFile = AliAnalysisManager::GetCommonFileName(); AliAnalysisDataContainer *cout_pc = mgr->CreateContainer("CaloQA", TList::Class(), AliAnalysisManager::kOutputContainer, Form("%s:CaloQA",outputFile.Data())); AliAnalysisDataContainer *cout_cuts = mgr->CreateContainer("CaloQACuts", TList::Class(), AliAnalysisManager::kParamContainer, Form("%s:CaloQACuts",outputFile.Data())); //Form("%s:PartCorrCuts",outputfile.Data())); // Create ONLY the output containers for the data produced by the task. // Get and connect other common input/output containers via the manager as below //============================================================================== mgr->ConnectInput (task, 0, mgr->GetCommonInputContainer()); mgr->ConnectOutput (task, 1, cout_pc); mgr->ConnectOutput (task, 2, cout_cuts); return task; } <|endoftext|>
<commit_before>// shader.cpp #include "shader.h" #include <fstream> #include <iostream> #include <sstream> #include <stdio.h> #include <vector> #include "demo/container/fixed_array.h" namespace demo { namespace rndr { // GLOBALS uint64 Shader::g_activeId = 0L; uint64 Shader::g_nextId = 0L; // MEMBER FUNCTIONS void Shader::load() { // stop if loaded if ( isLoaded() ) { return; } // create array of shaders cntr::FixedArray<GlShader> shaders( 6 ); for ( uint32 i = 0; i < 6; ++i ) { shaders.push( GlShader() ); } // populate shader structures shaders[0].filename = "res/shaders/" + _setName + "/vert.glsl"; shaders[0].type = GL_VERTEX_SHADER; shaders[1].filename = "res/shaders/" + _setName + "/tesc.glsl"; shaders[1].type = GL_TESS_CONTROL_SHADER; shaders[2].filename = "res/shaders/" + _setName + "/tese.glsl"; shaders[2].type = GL_TESS_EVALUATION_SHADER; shaders[3].filename = "res/shaders/" + _setName + "/geom.glsl"; shaders[3].type = GL_GEOMETRY_SHADER; shaders[4].filename = "res/shaders/" + _setName + "/frag.glsl"; shaders[4].type = GL_FRAGMENT_SHADER; shaders[5].filename = "res/shaders/" + _setName + "/comp.glsl"; shaders[5].type = GL_COMPUTE_SHADER; // compile shaders for ( int32 i = 0; i < shaders.size(); ++i ) { std::ifstream file( shaders[i].filename, std::ios::in ); // shader of that type doesn't exist so ignore it if ( !file ) { shaders.removeAt( i-- ); continue; } // read file std::stringstream buffer; String line; while ( !file.eof() ) { getline( buffer, line ); buffer << line << "\n"; } String content = buffer.str(); auto contentPtr = content.c_str(); // compile shader shaders[i].handle = glCreateShader( shaders[i].type ); uint32 handle = shaders[i].handle; glShaderSource( handle, 1, &contentPtr, nullptr ); glCompileShader( handle ); // check compilation result int32 success = GL_FALSE; int32 logLength; glGetShaderiv( handle, GL_COMPILE_STATUS, &success ); if ( success == GL_FALSE ) { // display error glGetShaderiv( handle, GL_INFO_LOG_LENGTH, &logLength ); std::vector<char> error( ( logLength > 1 ) ? logLength : 1 ); glGetShaderInfoLog( handle, logLength, nullptr, &error[0] ); std::cout << "Failed to compile " << shaders[i].filename << std::endl; std::cout << &error[0] << std::endl; // release resources and remove from list glDeleteShader( handle ); shaders.removeAt( i-- ); continue; } } // create program and attach shaders (also delete shaders) uint32 program = glCreateProgram(); for ( int32 i = 0; i < shaders.size(); ++i ) { glAttachShader( program, shaders[i].handle ); glDeleteShader( shaders[i].handle ); } // link the program glLinkProgram( program ); // check result int32 success = GL_FALSE; int32 logLength; glGetProgramiv( program, GL_LINK_STATUS, &success ); if ( success == GL_FALSE ) { // display error glGetProgramiv( program, GL_INFO_LOG_LENGTH, &logLength ); std::vector<char> error( ( logLength > 1 ) ? logLength : 1 ); glGetProgramInfoLog( program, logLength, nullptr, &error[0] ); std::cout << "Failed to link " << _setName << std::endl; std::cout << &error[0] << std::endl; // release resources and delete program glDeleteProgram( program ); return; } // detach shaders for ( uint32 i = 0; i < shaders.size(); ++i ) { glDetachShader( program, shaders[i].handle ); } // store program _program = program; bindAttributes(); } void Shader::release() { if ( isActive() ) { g_activeId = 0; } glDeleteProgram( _program ); _program = 0; } // HELPER FUNCTIONS void Shader::bindAttributes() { // todo: bind attributes } } // End nspc rndr } // End nspc demo<commit_msg>Increase comment specificity.<commit_after>// shader.cpp #include "shader.h" #include <fstream> #include <iostream> #include <sstream> #include <stdio.h> #include <vector> #include "demo/container/fixed_array.h" namespace demo { namespace rndr { // GLOBALS uint64 Shader::g_activeId = 0L; uint64 Shader::g_nextId = 0L; // MEMBER FUNCTIONS void Shader::load() { // stop if loaded if ( isLoaded() ) { return; } // create array of shaders cntr::FixedArray<GlShader> shaders( 6 ); for ( uint32 i = 0; i < 6; ++i ) { shaders.push( GlShader() ); } // populate shader structures shaders[0].filename = "res/shaders/" + _setName + "/vert.glsl"; shaders[0].type = GL_VERTEX_SHADER; shaders[1].filename = "res/shaders/" + _setName + "/tesc.glsl"; shaders[1].type = GL_TESS_CONTROL_SHADER; shaders[2].filename = "res/shaders/" + _setName + "/tese.glsl"; shaders[2].type = GL_TESS_EVALUATION_SHADER; shaders[3].filename = "res/shaders/" + _setName + "/geom.glsl"; shaders[3].type = GL_GEOMETRY_SHADER; shaders[4].filename = "res/shaders/" + _setName + "/frag.glsl"; shaders[4].type = GL_FRAGMENT_SHADER; shaders[5].filename = "res/shaders/" + _setName + "/comp.glsl"; shaders[5].type = GL_COMPUTE_SHADER; // compile shaders for ( int32 i = 0; i < shaders.size(); ++i ) { std::ifstream file( shaders[i].filename, std::ios::in ); // shader of that type doesn't exist so ignore it if ( !file ) { shaders.removeAt( i-- ); continue; } // read file std::stringstream buffer; String line; while ( !file.eof() ) { getline( buffer, line ); buffer << line << "\n"; } String content = buffer.str(); auto contentPtr = content.c_str(); // compile shader shaders[i].handle = glCreateShader( shaders[i].type ); uint32 handle = shaders[i].handle; glShaderSource( handle, 1, &contentPtr, nullptr ); glCompileShader( handle ); // check compilation result int32 success = GL_FALSE; int32 logLength; glGetShaderiv( handle, GL_COMPILE_STATUS, &success ); if ( success == GL_FALSE ) { // display error glGetShaderiv( handle, GL_INFO_LOG_LENGTH, &logLength ); std::vector<char> error( ( logLength > 1 ) ? logLength : 1 ); glGetShaderInfoLog( handle, logLength, nullptr, &error[0] ); std::cout << "Failed to compile " << shaders[i].filename << std::endl; std::cout << &error[0] << std::endl; // release resources and remove from list glDeleteShader( handle ); shaders.removeAt( i-- ); continue; } } // create program and attach shaders (also delete shaders) uint32 program = glCreateProgram(); for ( int32 i = 0; i < shaders.size(); ++i ) { glAttachShader( program, shaders[i].handle ); glDeleteShader( shaders[i].handle ); } // link the program glLinkProgram( program ); // check result int32 success = GL_FALSE; int32 logLength; glGetProgramiv( program, GL_LINK_STATUS, &success ); if ( success == GL_FALSE ) { // display error glGetProgramiv( program, GL_INFO_LOG_LENGTH, &logLength ); std::vector<char> error( ( logLength > 1 ) ? logLength : 1 ); glGetProgramInfoLog( program, logLength, nullptr, &error[0] ); std::cout << "Failed to link " << _setName << std::endl; std::cout << &error[0] << std::endl; // release resources and delete program glDeleteProgram( program ); return; } // detach shaders for ( uint32 i = 0; i < shaders.size(); ++i ) { glDetachShader( program, shaders[i].handle ); } // store program and bind attributes _program = program; bindAttributes(); } void Shader::release() { if ( isActive() ) { g_activeId = 0; } glDeleteProgram( _program ); _program = 0; } // HELPER FUNCTIONS void Shader::bindAttributes() { // todo: bind attributes } } // End nspc rndr } // End nspc demo<|endoftext|>
<commit_before>/***************************************************************************** * video.cpp : wxWindows plugin for vlc ***************************************************************************** * Copyright (C) 2000-2004, 2003 VideoLAN * $Id$ * * Authors: Gildas Bazin <gbazin@videolan.org> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111, USA. *****************************************************************************/ /***************************************************************************** * Preamble *****************************************************************************/ #include <vlc/vlc.h> #include <vlc/vout.h> #include <vlc/intf.h> #include "wxwindows.h" static void *GetWindow( intf_thread_t *p_intf, vout_thread_t *, int *pi_x_hint, int *pi_y_hint, unsigned int *pi_width_hint, unsigned int *pi_height_hint ); static void ReleaseWindow( intf_thread_t *p_intf, void *p_window ); static int ControlWindow( intf_thread_t *p_intf, void *p_window, int i_query, va_list args ); /* IDs for the controls and the menu commands */ enum { UpdateSize_Event = wxID_HIGHEST + 1, UpdateHide_Event, SetStayOnTop_Event, ID_HIDE_TIMER }; class VideoWindow: public wxWindow { public: /* Constructor */ VideoWindow( intf_thread_t *_p_intf, wxWindow *p_parent ); virtual ~VideoWindow(); void *GetWindow( vout_thread_t *p_vout, int *, int *, unsigned int *, unsigned int * ); void ReleaseWindow( void * ); int ControlWindow( void *, int, va_list ); private: intf_thread_t *p_intf; vout_thread_t *p_vout; wxWindow *p_parent; vlc_mutex_t lock; vlc_bool_t b_shown; vlc_bool_t b_auto_size; wxWindow *p_child_window; wxTimer m_hide_timer; void UpdateSize( wxEvent& event ); void UpdateHide( wxEvent& event ); void OnControlEvent( wxCommandEvent& event ); void OnHideTimer( wxTimerEvent& WXUNUSED(event)); DECLARE_EVENT_TABLE(); }; DEFINE_LOCAL_EVENT_TYPE( wxEVT_VLC_VIDEO ); BEGIN_EVENT_TABLE(VideoWindow, wxWindow) EVT_CUSTOM( wxEVT_SIZE, UpdateSize_Event, VideoWindow::UpdateSize ) EVT_CUSTOM( wxEVT_SIZE, UpdateHide_Event, VideoWindow::UpdateHide ) EVT_COMMAND( SetStayOnTop_Event, wxEVT_VLC_VIDEO, VideoWindow::OnControlEvent ) EVT_TIMER( ID_HIDE_TIMER, VideoWindow::OnHideTimer ) END_EVENT_TABLE() /***************************************************************************** * Public methods. *****************************************************************************/ wxWindow *CreateVideoWindow( intf_thread_t *p_intf, wxWindow *p_parent ) { return new VideoWindow( p_intf, p_parent ); } void UpdateVideoWindow( intf_thread_t *p_intf, wxWindow *p_window ) { #if (wxCHECK_VERSION(2,5,0)) if( p_window && p_intf->p_sys->p_video_sizer && p_window->IsShown() ) p_intf->p_sys->p_video_sizer->SetMinSize( p_window->GetSize() ); #endif } /***************************************************************************** * Constructor. *****************************************************************************/ VideoWindow::VideoWindow( intf_thread_t *_p_intf, wxWindow *_p_parent ): wxWindow( _p_parent, -1 ) { /* Initializations */ p_intf = _p_intf; p_parent = _p_parent; vlc_mutex_init( p_intf, &lock ); b_auto_size = config_GetInt( p_intf, "wxwin-autosize" ); p_vout = NULL; m_hide_timer.SetOwner( this, ID_HIDE_TIMER ); p_intf->pf_request_window = ::GetWindow; p_intf->pf_release_window = ::ReleaseWindow; p_intf->pf_control_window = ::ControlWindow; p_intf->p_sys->p_video_window = this; wxSize child_size = wxSize(0,0); if( !b_auto_size ) { WindowSettings *ws = p_intf->p_sys->p_window_settings; wxPoint p; bool b_shown; // Maybe this size should be an option child_size = wxSize( wxSystemSettings::GetMetric(wxSYS_SCREEN_X) / 2, wxSystemSettings::GetMetric(wxSYS_SCREEN_Y) / 2 ); ws->GetSettings( WindowSettings::ID_VIDEO, b_shown, p, child_size ); SetSize( child_size ); } p_child_window = new wxWindow( this, -1, wxDefaultPosition, child_size ); p_child_window->Show(); Show(); b_shown = VLC_TRUE; p_intf->p_sys->p_video_sizer = new wxBoxSizer( wxHORIZONTAL ); #if (wxCHECK_VERSION(2,5,0)) p_intf->p_sys->p_video_sizer->Add( this, 1, wxEXPAND|wxFIXED_MINSIZE ); #else p_intf->p_sys->p_video_sizer->Add( this, 1, wxEXPAND ); #endif ReleaseWindow( NULL ); } VideoWindow::~VideoWindow() { vlc_mutex_lock( &lock ); if( p_vout ) { if( !p_intf->psz_switch_intf ) { if( vout_Control( p_vout, VOUT_CLOSE ) != VLC_SUCCESS ) vout_Control( p_vout, VOUT_REPARENT ); } else { if( vout_Control( p_vout, VOUT_REPARENT ) != VLC_SUCCESS ) vout_Control( p_vout, VOUT_CLOSE ); } } p_intf->pf_request_window = NULL; p_intf->pf_release_window = NULL; p_intf->pf_control_window = NULL; vlc_mutex_unlock( &lock ); if( !b_auto_size ) { WindowSettings *ws = p_intf->p_sys->p_window_settings; ws->SetSettings( WindowSettings::ID_VIDEO, true, GetPosition(), GetSize() ); } vlc_mutex_destroy( &lock ); } /***************************************************************************** * Private methods. *****************************************************************************/ static void *GetWindow( intf_thread_t *p_intf, vout_thread_t *p_vout, int *pi_x_hint, int *pi_y_hint, unsigned int *pi_width_hint, unsigned int *pi_height_hint ) { return p_intf->p_sys->p_video_window->GetWindow( p_vout, pi_x_hint, pi_y_hint, pi_width_hint, pi_height_hint ); } /* Part of the hack to get the X11 window handle from the GtkWidget */ #ifdef __WXGTK__ extern "C" { #ifdef __WXGTK20__ int gdk_x11_drawable_get_xid( void * ); #endif void *gtk_widget_get_parent_window( void * ); } #endif void *VideoWindow::GetWindow( vout_thread_t *_p_vout, int *pi_x_hint, int *pi_y_hint, unsigned int *pi_width_hint, unsigned int *pi_height_hint ) { #if defined(__WXGTK__) || defined(WIN32) vlc_mutex_lock( &lock ); if( p_vout ) { vlc_mutex_unlock( &lock ); msg_Dbg( p_intf, "Video window already in use" ); return NULL; } p_vout = _p_vout; wxSizeEvent event( wxSize(*pi_width_hint, *pi_height_hint), UpdateSize_Event ); AddPendingEvent( event ); vlc_mutex_unlock( &lock ); p_child_window->SetBackgroundColour( *wxBLACK ); SetBackgroundColour( *wxBLACK ); Refresh(); #ifdef __WXGTK__ GtkWidget *p_widget = p_child_window->GetHandle(); #ifdef __WXGTK20__ return (void *)gdk_x11_drawable_get_xid( gtk_widget_get_parent_window( p_widget ) ); #elif defined(__WXGTK__) return (void *)*(int *)( (char *)gtk_widget_get_parent_window( p_widget ) + 2 * sizeof(void *) ); #endif #elif defined(WIN32) return (void*)GetHandle(); #endif #else // defined(__WXGTK__) || defined(WIN32) return NULL; #endif } static void ReleaseWindow( intf_thread_t *p_intf, void *p_window ) { return p_intf->p_sys->p_video_window->ReleaseWindow( p_window ); } void VideoWindow::ReleaseWindow( void *p_window ) { vlc_mutex_lock( &lock ); p_vout = NULL; vlc_mutex_unlock( &lock ); if( !b_auto_size ) return; #if defined(__WXGTK__) || defined(WIN32) wxSizeEvent event( wxSize(0, 0), UpdateHide_Event ); AddPendingEvent( event ); #endif } void VideoWindow::UpdateSize( wxEvent &_event ) { m_hide_timer.Stop(); if( !b_auto_size ) return; wxSizeEvent * event = (wxSizeEvent*)(&_event); if( !b_shown ) { p_intf->p_sys->p_video_sizer->Show( this, TRUE ); p_intf->p_sys->p_video_sizer->Layout(); SetFocus(); b_shown = VLC_TRUE; } p_intf->p_sys->p_video_sizer->SetMinSize( event->GetSize() ); wxCommandEvent intf_event( wxEVT_INTF, 0 ); p_parent->AddPendingEvent( intf_event ); } void VideoWindow::UpdateHide( wxEvent &_event ) { if( b_auto_size ) m_hide_timer.Start( 200, wxTIMER_ONE_SHOT ); } void VideoWindow::OnHideTimer( wxTimerEvent& WXUNUSED(event)) { if( b_shown ) { p_intf->p_sys->p_video_sizer->Show( this, FALSE ); Hide(); p_intf->p_sys->p_video_sizer->Layout(); b_shown = VLC_FALSE; } p_intf->p_sys->p_video_sizer->SetMinSize( wxSize(0,0) ); wxCommandEvent intf_event( wxEVT_INTF, 0 ); p_parent->AddPendingEvent( intf_event ); p_child_window->SetBackgroundColour( wxNullColour ); SetBackgroundColour( wxNullColour ); Refresh(); } void VideoWindow::OnControlEvent( wxCommandEvent &event ) { switch( event.GetId() ) { case SetStayOnTop_Event: wxCommandEvent intf_event( wxEVT_INTF, 1 ); intf_event.SetInt( event.GetInt() ); p_parent->AddPendingEvent( intf_event ); break; } } static int ControlWindow( intf_thread_t *p_intf, void *p_window, int i_query, va_list args ) { return p_intf->p_sys->p_video_window->ControlWindow( p_window, i_query, args ); } int VideoWindow::ControlWindow( void *p_window, int i_query, va_list args ) { int i_ret = VLC_EGENERIC; vlc_mutex_lock( &lock ); switch( i_query ) { case VOUT_SET_ZOOM: { if( !b_auto_size ) break; double f_arg = va_arg( args, double ); /* Update dimensions */ wxSizeEvent event( wxSize((int)(p_vout->i_window_width * f_arg), (int)(p_vout->i_window_height * f_arg)), UpdateSize_Event ); AddPendingEvent( event ); i_ret = VLC_SUCCESS; } break; case VOUT_SET_STAY_ON_TOP: { int i_arg = va_arg( args, int ); wxCommandEvent event( wxEVT_VLC_VIDEO, SetStayOnTop_Event ); event.SetInt( i_arg ); AddPendingEvent( event ); i_ret = VLC_SUCCESS; } break; default: msg_Dbg( p_intf, "control query not supported" ); break; } vlc_mutex_unlock( &lock ); return i_ret; } <commit_msg>* modules/gui/wxwindows/video.cpp: fixes.<commit_after>/***************************************************************************** * video.cpp : wxWindows plugin for vlc ***************************************************************************** * Copyright (C) 2000-2004, 2003 VideoLAN * $Id$ * * Authors: Gildas Bazin <gbazin@videolan.org> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111, USA. *****************************************************************************/ /***************************************************************************** * Preamble *****************************************************************************/ #include <vlc/vlc.h> #include <vlc/vout.h> #include <vlc/intf.h> #include "wxwindows.h" static void *GetWindow( intf_thread_t *p_intf, vout_thread_t *, int *pi_x_hint, int *pi_y_hint, unsigned int *pi_width_hint, unsigned int *pi_height_hint ); static void ReleaseWindow( intf_thread_t *p_intf, void *p_window ); static int ControlWindow( intf_thread_t *p_intf, void *p_window, int i_query, va_list args ); /* IDs for the controls and the menu commands */ enum { UpdateSize_Event = wxID_HIGHEST + 1, UpdateHide_Event, SetStayOnTop_Event, ID_HIDE_TIMER }; class VideoWindow: public wxWindow { public: /* Constructor */ VideoWindow( intf_thread_t *_p_intf, wxWindow *p_parent ); virtual ~VideoWindow(); void *GetWindow( vout_thread_t *p_vout, int *, int *, unsigned int *, unsigned int * ); void ReleaseWindow( void * ); int ControlWindow( void *, int, va_list ); private: intf_thread_t *p_intf; vout_thread_t *p_vout; wxWindow *p_parent; vlc_mutex_t lock; vlc_bool_t b_shown; vlc_bool_t b_auto_size; wxWindow *p_child_window; wxTimer m_hide_timer; void UpdateSize( wxEvent& event ); void UpdateHide( wxEvent& event ); void OnControlEvent( wxCommandEvent& event ); void OnHideTimer( wxTimerEvent& WXUNUSED(event)); DECLARE_EVENT_TABLE(); }; DEFINE_LOCAL_EVENT_TYPE( wxEVT_VLC_VIDEO ); BEGIN_EVENT_TABLE(VideoWindow, wxWindow) EVT_CUSTOM( wxEVT_SIZE, UpdateSize_Event, VideoWindow::UpdateSize ) EVT_CUSTOM( wxEVT_SIZE, UpdateHide_Event, VideoWindow::UpdateHide ) EVT_COMMAND( SetStayOnTop_Event, wxEVT_VLC_VIDEO, VideoWindow::OnControlEvent ) EVT_TIMER( ID_HIDE_TIMER, VideoWindow::OnHideTimer ) END_EVENT_TABLE() /***************************************************************************** * Public methods. *****************************************************************************/ wxWindow *CreateVideoWindow( intf_thread_t *p_intf, wxWindow *p_parent ) { return new VideoWindow( p_intf, p_parent ); } void UpdateVideoWindow( intf_thread_t *p_intf, wxWindow *p_window ) { #if (wxCHECK_VERSION(2,5,0)) if( p_window && p_intf->p_sys->p_video_sizer && p_window->IsShown() ) p_intf->p_sys->p_video_sizer->SetMinSize( p_window->GetSize() ); #endif } /***************************************************************************** * Constructor. *****************************************************************************/ VideoWindow::VideoWindow( intf_thread_t *_p_intf, wxWindow *_p_parent ): wxWindow( _p_parent, -1 ) { /* Initializations */ p_intf = _p_intf; p_parent = _p_parent; vlc_mutex_init( p_intf, &lock ); b_auto_size = config_GetInt( p_intf, "wxwin-autosize" ); p_vout = NULL; m_hide_timer.SetOwner( this, ID_HIDE_TIMER ); p_intf->pf_request_window = ::GetWindow; p_intf->pf_release_window = ::ReleaseWindow; p_intf->pf_control_window = ::ControlWindow; p_intf->p_sys->p_video_window = this; wxSize child_size = wxSize(0,0); if( !b_auto_size ) { WindowSettings *ws = p_intf->p_sys->p_window_settings; wxPoint p; bool b_shown; // Maybe this size should be an option child_size = wxSize( wxSystemSettings::GetMetric(wxSYS_SCREEN_X) / 2, wxSystemSettings::GetMetric(wxSYS_SCREEN_Y) / 2 ); ws->GetSettings( WindowSettings::ID_VIDEO, b_shown, p, child_size ); SetSize( child_size ); } p_child_window = new wxWindow( this, -1, wxDefaultPosition, child_size ); if( !b_auto_size ) { SetBackgroundColour( *wxBLACK ); p_child_window->SetBackgroundColour( *wxBLACK ); } p_child_window->Show(); Show(); b_shown = VLC_TRUE; p_intf->p_sys->p_video_sizer = new wxBoxSizer( wxHORIZONTAL ); #if (wxCHECK_VERSION(2,5,0)) p_intf->p_sys->p_video_sizer->Add( this, 1, wxEXPAND|wxFIXED_MINSIZE ); #else p_intf->p_sys->p_video_sizer->Add( this, 1, wxEXPAND ); #endif ReleaseWindow( NULL ); } VideoWindow::~VideoWindow() { vlc_mutex_lock( &lock ); if( p_vout ) { if( !p_intf->psz_switch_intf ) { if( vout_Control( p_vout, VOUT_CLOSE ) != VLC_SUCCESS ) vout_Control( p_vout, VOUT_REPARENT ); } else { if( vout_Control( p_vout, VOUT_REPARENT ) != VLC_SUCCESS ) vout_Control( p_vout, VOUT_CLOSE ); } } p_intf->pf_request_window = NULL; p_intf->pf_release_window = NULL; p_intf->pf_control_window = NULL; vlc_mutex_unlock( &lock ); if( !b_auto_size ) { WindowSettings *ws = p_intf->p_sys->p_window_settings; ws->SetSettings( WindowSettings::ID_VIDEO, true, GetPosition(), GetSize() ); } vlc_mutex_destroy( &lock ); } /***************************************************************************** * Private methods. *****************************************************************************/ static void *GetWindow( intf_thread_t *p_intf, vout_thread_t *p_vout, int *pi_x_hint, int *pi_y_hint, unsigned int *pi_width_hint, unsigned int *pi_height_hint ) { return p_intf->p_sys->p_video_window->GetWindow( p_vout, pi_x_hint, pi_y_hint, pi_width_hint, pi_height_hint ); } /* Part of the hack to get the X11 window handle from the GtkWidget */ #ifdef __WXGTK__ extern "C" { #ifdef __WXGTK20__ int gdk_x11_drawable_get_xid( void * ); #endif void *gtk_widget_get_parent_window( void * ); } #endif void *VideoWindow::GetWindow( vout_thread_t *_p_vout, int *pi_x_hint, int *pi_y_hint, unsigned int *pi_width_hint, unsigned int *pi_height_hint ) { #if defined(__WXGTK__) || defined(WIN32) vlc_mutex_lock( &lock ); if( p_vout ) { vlc_mutex_unlock( &lock ); msg_Dbg( p_intf, "Video window already in use" ); return NULL; } p_vout = _p_vout; wxSizeEvent event( wxSize(*pi_width_hint, *pi_height_hint), UpdateSize_Event ); AddPendingEvent( event ); vlc_mutex_unlock( &lock ); #ifdef __WXGTK__ GtkWidget *p_widget = p_child_window->GetHandle(); #ifdef __WXGTK20__ return (void *)gdk_x11_drawable_get_xid( gtk_widget_get_parent_window( p_widget ) ); #elif defined(__WXGTK__) return (void *)*(int *)( (char *)gtk_widget_get_parent_window( p_widget ) + 2 * sizeof(void *) ); #endif #elif defined(WIN32) return (void*)GetHandle(); #endif #else // defined(__WXGTK__) || defined(WIN32) return NULL; #endif } static void ReleaseWindow( intf_thread_t *p_intf, void *p_window ) { return p_intf->p_sys->p_video_window->ReleaseWindow( p_window ); } void VideoWindow::ReleaseWindow( void *p_window ) { vlc_mutex_lock( &lock ); p_vout = NULL; vlc_mutex_unlock( &lock ); if( !b_auto_size ) return; #if defined(__WXGTK__) || defined(WIN32) wxSizeEvent event( wxSize(0, 0), UpdateHide_Event ); AddPendingEvent( event ); #endif } void VideoWindow::UpdateSize( wxEvent &_event ) { m_hide_timer.Stop(); if( !b_auto_size ) return; wxSizeEvent * event = (wxSizeEvent*)(&_event); if( !b_shown ) { p_intf->p_sys->p_video_sizer->Show( this, TRUE ); p_intf->p_sys->p_video_sizer->Layout(); SetFocus(); b_shown = VLC_TRUE; } p_intf->p_sys->p_video_sizer->SetMinSize( event->GetSize() ); wxCommandEvent intf_event( wxEVT_INTF, 0 ); p_parent->AddPendingEvent( intf_event ); } void VideoWindow::UpdateHide( wxEvent &_event ) { if( b_auto_size ) m_hide_timer.Start( 200, wxTIMER_ONE_SHOT ); } void VideoWindow::OnHideTimer( wxTimerEvent& WXUNUSED(event)) { if( b_shown ) { p_intf->p_sys->p_video_sizer->Show( this, FALSE ); SetSize( 0, 0 ); p_intf->p_sys->p_video_sizer->Layout(); b_shown = VLC_FALSE; } p_intf->p_sys->p_video_sizer->SetMinSize( wxSize(0,0) ); wxCommandEvent intf_event( wxEVT_INTF, 0 ); p_parent->AddPendingEvent( intf_event ); } void VideoWindow::OnControlEvent( wxCommandEvent &event ) { switch( event.GetId() ) { case SetStayOnTop_Event: wxCommandEvent intf_event( wxEVT_INTF, 1 ); intf_event.SetInt( event.GetInt() ); p_parent->AddPendingEvent( intf_event ); break; } } static int ControlWindow( intf_thread_t *p_intf, void *p_window, int i_query, va_list args ) { return p_intf->p_sys->p_video_window->ControlWindow( p_window, i_query, args ); } int VideoWindow::ControlWindow( void *p_window, int i_query, va_list args ) { int i_ret = VLC_EGENERIC; vlc_mutex_lock( &lock ); switch( i_query ) { case VOUT_SET_ZOOM: { if( !b_auto_size ) break; double f_arg = va_arg( args, double ); /* Update dimensions */ wxSizeEvent event( wxSize((int)(p_vout->i_window_width * f_arg), (int)(p_vout->i_window_height * f_arg)), UpdateSize_Event ); AddPendingEvent( event ); i_ret = VLC_SUCCESS; } break; case VOUT_SET_STAY_ON_TOP: { int i_arg = va_arg( args, int ); wxCommandEvent event( wxEVT_VLC_VIDEO, SetStayOnTop_Event ); event.SetInt( i_arg ); AddPendingEvent( event ); i_ret = VLC_SUCCESS; } break; default: msg_Dbg( p_intf, "control query not supported" ); break; } vlc_mutex_unlock( &lock ); return i_ret; } <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: splash.hxx,v $ * * $Revision: 1.3 $ * * last change: $Author: rt $ $Date: 2003-12-01 18:06:09 $ * * 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 _COM_SUN_STAR_LANG_XSERVICEINFO_HPP_ #include <com/sun/star/lang/XServiceInfo.hpp> #endif #ifndef _COM_SUN_STAR_UNO_EXCEPTION_HPP_ #include <com/sun/star/uno/Exception.hpp> #endif #ifndef _COM_SUN_STAR_UNO_REFERENCE_H_ #include <com/sun/star/uno/Reference.h> #endif #ifndef _COM_SUN_STAR_LANG_XCOMPONENT_HPP_ #include <com/sun/star/lang/XComponent.hpp> #endif #ifndef _COM_SUN_STAR_TASK_XSTATUSINDICATOR_HPP_ #include <com/sun/star/task/XStatusIndicator.hpp> #endif #ifndef _COM_SUN_STAR_LANG_XINITIALIZATION_HPP_ #include <com/sun/star/lang/XInitialization.hpp> #endif #ifndef _CPPUHELPER_IMPLBASE2_HXX_ #include <cppuhelper/implbase2.hxx> #endif #ifndef _CPPUHELPER_INTERFACECONTAINER_H_ #include <cppuhelper/interfacecontainer.h> #endif #ifndef _SFX_HELP_HXX #include <sfx2/sfxhelp.hxx> #endif #ifndef _SV_INTROWIN_HXX #include <vcl/introwin.hxx> #endif #ifndef _SV_BITMAP_HXX #include <vcl/bitmap.hxx> #endif #include <com/sun/star/lang/XSingleServiceFactory.hpp> #include <osl/mutex.hxx> #include <sfx2/sfxuno.hxx> using namespace ::rtl; using namespace ::com::sun::star::uno; using namespace ::com::sun::star::lang; using namespace ::com::sun::star::task; namespace desktop { class SplashScreen : public ::cppu::WeakImplHelper2< XStatusIndicator, XInitialization > , public IntroWindow { private: // don't allow anybody but ourselves to create instances of this class SplashScreen(const SplashScreen&); SplashScreen(void); SplashScreen operator =(const SplashScreen&); SplashScreen(const Reference< XMultiServiceFactory >& xFactory); DECL_LINK( AppEventListenerHdl, VclWindowEvent * ); virtual ~SplashScreen(); void initBitmap(); void updateStatus(); static SplashScreen *_pINSTANCE; static const sal_Char *serviceName; static const sal_Char *implementationName; static const sal_Char *supportedServiceNames[]; static osl::Mutex _aMutex; Reference< XMultiServiceFactory > _rFactory; Bitmap _aIntroBmp; sal_Int32 _iMax; sal_Int32 _iProgress; sal_Bool _bPaintBitmap; sal_Bool _bPaintProgress; sal_Bool _bVisible; long _height, _width, _tlx, _tly, _barwidth; const long _xoffset, _yoffset, _barheight, _barspace; public: static Reference< XInterface > getInstance(const Reference < XMultiServiceFactory >& xFactory); // static service info static OUString impl_getImplementationName(); static Sequence<OUString> impl_getSupportedServiceNames(); // XStatusIndicator virtual void SAL_CALL end() throw ( RuntimeException ); virtual void SAL_CALL reset() throw ( RuntimeException ); virtual void SAL_CALL setText(const OUString& aText) throw ( RuntimeException ); virtual void SAL_CALL setValue(sal_Int32 nValue) throw ( RuntimeException ); virtual void SAL_CALL start(const OUString& aText, sal_Int32 nRange) throw ( RuntimeException ); // XInitialize virtual void SAL_CALL initialize( const ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Any>& aArguments ) throw ( RuntimeException ); // workwindow virtual void Paint( const Rectangle& ); }; } <commit_msg>INTEGRATION: CWS fwk02ea (1.3.98); FILE MERGED 2004/06/01 15:35:12 lo 1.3.98.1: #i29643# #i26375# licens dialog behavior + helpids<commit_after>/************************************************************************* * * $RCSfile: splash.hxx,v $ * * $Revision: 1.4 $ * * last change: $Author: kz $ $Date: 2004-06-10 13:36: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 _COM_SUN_STAR_LANG_XSERVICEINFO_HPP_ #include <com/sun/star/lang/XServiceInfo.hpp> #endif #ifndef _COM_SUN_STAR_UNO_EXCEPTION_HPP_ #include <com/sun/star/uno/Exception.hpp> #endif #ifndef _COM_SUN_STAR_UNO_REFERENCE_H_ #include <com/sun/star/uno/Reference.h> #endif #ifndef _COM_SUN_STAR_LANG_XCOMPONENT_HPP_ #include <com/sun/star/lang/XComponent.hpp> #endif #ifndef _COM_SUN_STAR_TASK_XSTATUSINDICATOR_HPP_ #include <com/sun/star/task/XStatusIndicator.hpp> #endif #ifndef _COM_SUN_STAR_LANG_XINITIALIZATION_HPP_ #include <com/sun/star/lang/XInitialization.hpp> #endif #ifndef _CPPUHELPER_IMPLBASE2_HXX_ #include <cppuhelper/implbase2.hxx> #endif #ifndef _CPPUHELPER_INTERFACECONTAINER_H_ #include <cppuhelper/interfacecontainer.h> #endif #ifndef _SFX_HELP_HXX #include <sfx2/sfxhelp.hxx> #endif #ifndef _SV_INTROWIN_HXX #include <vcl/introwin.hxx> #endif #ifndef _SV_BITMAP_HXX #include <vcl/bitmap.hxx> #endif #include <com/sun/star/lang/XSingleServiceFactory.hpp> #include <osl/mutex.hxx> #include <sfx2/sfxuno.hxx> #include <vcl/virdev.hxx> using namespace ::rtl; using namespace ::com::sun::star::uno; using namespace ::com::sun::star::lang; using namespace ::com::sun::star::task; namespace desktop { class SplashScreen : public ::cppu::WeakImplHelper2< XStatusIndicator, XInitialization > , public IntroWindow { private: // don't allow anybody but ourselves to create instances of this class SplashScreen(const SplashScreen&); SplashScreen(void); SplashScreen operator =(const SplashScreen&); SplashScreen(const Reference< XMultiServiceFactory >& xFactory); DECL_LINK( AppEventListenerHdl, VclWindowEvent * ); virtual ~SplashScreen(); void initBitmap(); void updateStatus(); static SplashScreen *_pINSTANCE; static const sal_Char *serviceName; static const sal_Char *implementationName; static const sal_Char *supportedServiceNames[]; static osl::Mutex _aMutex; Reference< XMultiServiceFactory > _rFactory; VirtualDevice _vdev; Bitmap _aIntroBmp; sal_Int32 _iMax; sal_Int32 _iProgress; sal_Bool _bPaintBitmap; sal_Bool _bPaintProgress; sal_Bool _bVisible; long _height, _width, _tlx, _tly, _barwidth; const long _xoffset, _yoffset, _barheight, _barspace; public: static Reference< XInterface > getInstance(const Reference < XMultiServiceFactory >& xFactory); // static service info static OUString impl_getImplementationName(); static Sequence<OUString> impl_getSupportedServiceNames(); // XStatusIndicator virtual void SAL_CALL end() throw ( RuntimeException ); virtual void SAL_CALL reset() throw ( RuntimeException ); virtual void SAL_CALL setText(const OUString& aText) throw ( RuntimeException ); virtual void SAL_CALL setValue(sal_Int32 nValue) throw ( RuntimeException ); virtual void SAL_CALL start(const OUString& aText, sal_Int32 nRange) throw ( RuntimeException ); // XInitialize virtual void SAL_CALL initialize( const ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Any>& aArguments ) throw ( RuntimeException ); // workwindow virtual void Paint( const Rectangle& ); }; } <|endoftext|>
<commit_before>// Copyright 2021 Google LLC // // 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 // // https://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 "distbench_test_sequencer.h" #include "distbench_node_manager.h" #include "distbench_utils.h" #include "protocol_driver_allocator.h" #include "gtest/gtest.h" #include "gtest_utils.h" #include "glog/logging.h" namespace distbench { struct DistBenchTester { ~DistBenchTester(); absl::Status Initialize(int num_nodes); std::unique_ptr<TestSequencer> test_sequencer; std::unique_ptr<DistBenchTestSequencer::Stub> test_sequencer_stub; std::vector<std::unique_ptr<NodeManager>> nodes; std::unique_ptr<distbench::RealClock> clock; }; DistBenchTester::~DistBenchTester() { test_sequencer->Shutdown(); for (size_t i = 0; i < nodes.size(); ++i) { nodes[i]->Shutdown(); } test_sequencer->Wait(); for (size_t i = 0; i < nodes.size(); ++i) { nodes[i]->Wait(); } FreePort(test_sequencer->GetOpts().port); for (size_t i = 0; i < nodes.size(); ++i) { FreePort(nodes[i]->GetOpts().port); } } absl::Status DistBenchTester::Initialize(int num_nodes) { test_sequencer = std::make_unique<TestSequencer>(); distbench::TestSequencerOpts ts_opts = {}; ts_opts.port = AllocatePort(); test_sequencer->Initialize(ts_opts); nodes.resize(num_nodes); clock = std::make_unique<distbench::RealClock>(); for (int i = 0; i < num_nodes; ++i) { distbench::NodeManagerOpts nm_opts = {}; nm_opts.port = AllocatePort(); nm_opts.test_sequencer_service_address = test_sequencer->service_address(); nodes[i] = std::make_unique<NodeManager>(clock.get()); auto ret = nodes[i]->Initialize(nm_opts); if (!ret.ok()) return ret; } std::shared_ptr<grpc::ChannelCredentials> client_creds = MakeChannelCredentials(); std::shared_ptr<grpc::Channel> channel = grpc::CreateChannel( test_sequencer->service_address(), client_creds); test_sequencer_stub = DistBenchTestSequencer::NewStub(channel); return absl::OkStatus(); } TEST(DistBenchTestSequencer, ctor) { TestSequencer test_sequencer; } TEST(DistBenchTestSequencer, init) { distbench::TestSequencerOpts ts_opts = {}; ts_opts.port = AllocatePort(); TestSequencer test_sequencer; test_sequencer.Initialize(ts_opts); test_sequencer.Shutdown(); FreePort(ts_opts.port); } TEST(DistBenchTestSequencer, empty_group) { DistBenchTester tester; ASSERT_OK(tester.Initialize(0)); } TEST(DistBenchTestSequencer, nonempty_group) { DistBenchTester tester; ASSERT_OK(tester.Initialize(3)); TestSequence test_sequence; auto* test = test_sequence.add_tests(); auto* s1 = test->add_services(); s1->set_name("s1"); s1->set_count(1); auto* s2 = test->add_services(); s2->set_name("s2"); s2->set_count(2); auto* l1 = test->add_action_lists(); l1->set_name("s1"); l1->add_action_names("s1/ping"); auto a1 = test->add_actions(); a1->set_name("s1/ping"); a1->set_rpc_name("echo"); a1->mutable_iterations()->set_max_iteration_count(10); auto* r1 = test->add_rpc_descriptions(); r1->set_name("echo"); r1->set_client("s1"); r1->set_server("s2"); auto* l2 = test->add_action_lists(); l2->set_name("echo"); TestSequenceResults results; grpc::ClientContext context; std::chrono::system_clock::time_point deadline = std::chrono::system_clock::now() + std::chrono::seconds(10); context.set_deadline(deadline); grpc::Status status = tester.test_sequencer_stub->RunTestSequence( &context, test_sequence, &results); ASSERT_OK(status); LOG(INFO) << "TestSequenceResults: " << results.DebugString(); ASSERT_EQ(results.test_results().size(), 1); auto& test_results = results.test_results(0); ASSERT_EQ(test_results.service_logs().instance_logs_size(), 1); const auto& instance_results_it = test_results.service_logs().instance_logs().find("s1/0"); ASSERT_NE(instance_results_it, test_results.service_logs().instance_logs().end()); auto s2_0 = instance_results_it->second.peer_logs().find("s2/0"); ASSERT_NE(s2_0, instance_results_it->second.peer_logs().end()); auto s2_0_echo = s2_0->second.rpc_logs().find(0); ASSERT_NE(s2_0_echo, s2_0->second.rpc_logs().end()); ASSERT_TRUE(s2_0_echo->second.failed_rpc_samples().empty()); ASSERT_EQ(s2_0_echo->second.successful_rpc_samples_size(), 10); auto s2_1 = instance_results_it->second.peer_logs().find("s2/1"); ASSERT_NE(s2_1, instance_results_it->second.peer_logs().end()); auto s2_1_echo = s2_1->second.rpc_logs().find(0); ASSERT_NE(s2_1_echo, s2_1->second.rpc_logs().end()); ASSERT_TRUE(s2_1_echo->second.failed_rpc_samples().empty()); ASSERT_EQ(s2_1_echo->second.successful_rpc_samples_size(), 10); } void RunIntenseTraffic(const char* protocol) { DistBenchTester tester; ASSERT_OK(tester.Initialize(6)); TestSequence test_sequence; auto* test = test_sequence.add_tests(); test->set_default_protocol(protocol); auto* s1 = test->add_services(); s1->set_name("s1"); s1->set_count(1); auto* s2 = test->add_services(); s2->set_name("s2"); s2->set_count(5); auto* l1 = test->add_action_lists(); l1->set_name("s1"); l1->add_action_names("s1/ping"); auto a1 = test->add_actions(); a1->set_name("s1/ping"); a1->set_rpc_name("echo"); a1->mutable_iterations()->set_max_iteration_count(10); auto* iterations = a1->mutable_iterations(); iterations->set_max_duration_us(200000); iterations->set_max_iteration_count(2000); iterations->set_max_parallel_iterations(10); auto* r1 = test->add_rpc_descriptions(); r1->set_name("echo"); r1->set_client("s1"); r1->set_server("s2"); auto* l2 = test->add_action_lists(); l2->set_name("echo"); TestSequenceResults results; std::chrono::system_clock::time_point deadline = std::chrono::system_clock::now() + std::chrono::seconds(200); grpc::ClientContext context; grpc::ClientContext context2; grpc::ClientContext context3; context.set_deadline(deadline); context2.set_deadline(deadline); context3.set_deadline(deadline); grpc::Status status = tester.test_sequencer_stub->RunTestSequence( &context, test_sequence, &results); LOG(INFO) << status.error_message(); ASSERT_OK(status); iterations->clear_max_iteration_count(); status = tester.test_sequencer_stub->RunTestSequence( &context2, test_sequence, &results); LOG(INFO) << status.error_message(); ASSERT_OK(status); iterations->clear_max_duration_us(); iterations->set_max_iteration_count(2000); status = tester.test_sequencer_stub->RunTestSequence( &context3, test_sequence, &results); LOG(INFO) << status.error_message(); ASSERT_OK(status); return; } TEST(DistBenchTestSequencer, 100k_grpc) { RunIntenseTraffic("grpc"); } TEST(DistBenchTestSequencer, 100k_grpc_async_callback) { RunIntenseTraffic("grpc_async_callback"); } } // namespace distbench <commit_msg>Add clique sequencer test<commit_after>// Copyright 2021 Google LLC // // 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 // // https://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 "distbench_test_sequencer.h" #include "distbench_node_manager.h" #include "distbench_utils.h" #include "protocol_driver_allocator.h" #include "gtest/gtest.h" #include "gtest_utils.h" #include "glog/logging.h" namespace distbench { struct DistBenchTester { ~DistBenchTester(); absl::Status Initialize(int num_nodes); std::unique_ptr<TestSequencer> test_sequencer; std::unique_ptr<DistBenchTestSequencer::Stub> test_sequencer_stub; std::vector<std::unique_ptr<NodeManager>> nodes; std::unique_ptr<distbench::RealClock> clock; }; DistBenchTester::~DistBenchTester() { test_sequencer->Shutdown(); for (size_t i = 0; i < nodes.size(); ++i) { nodes[i]->Shutdown(); } test_sequencer->Wait(); for (size_t i = 0; i < nodes.size(); ++i) { nodes[i]->Wait(); } FreePort(test_sequencer->GetOpts().port); for (size_t i = 0; i < nodes.size(); ++i) { FreePort(nodes[i]->GetOpts().port); } } absl::Status DistBenchTester::Initialize(int num_nodes) { test_sequencer = std::make_unique<TestSequencer>(); distbench::TestSequencerOpts ts_opts = {}; ts_opts.port = AllocatePort(); test_sequencer->Initialize(ts_opts); nodes.resize(num_nodes); clock = std::make_unique<distbench::RealClock>(); for (int i = 0; i < num_nodes; ++i) { distbench::NodeManagerOpts nm_opts = {}; nm_opts.port = AllocatePort(); nm_opts.test_sequencer_service_address = test_sequencer->service_address(); nodes[i] = std::make_unique<NodeManager>(clock.get()); auto ret = nodes[i]->Initialize(nm_opts); if (!ret.ok()) return ret; } std::shared_ptr<grpc::ChannelCredentials> client_creds = MakeChannelCredentials(); std::shared_ptr<grpc::Channel> channel = grpc::CreateChannel( test_sequencer->service_address(), client_creds); test_sequencer_stub = DistBenchTestSequencer::NewStub(channel); return absl::OkStatus(); } TEST(DistBenchTestSequencer, ctor) { TestSequencer test_sequencer; } TEST(DistBenchTestSequencer, init) { distbench::TestSequencerOpts ts_opts = {}; ts_opts.port = AllocatePort(); TestSequencer test_sequencer; test_sequencer.Initialize(ts_opts); test_sequencer.Shutdown(); FreePort(ts_opts.port); } TEST(DistBenchTestSequencer, empty_group) { DistBenchTester tester; ASSERT_OK(tester.Initialize(0)); } TEST(DistBenchTestSequencer, nonempty_group) { DistBenchTester tester; ASSERT_OK(tester.Initialize(3)); TestSequence test_sequence; auto* test = test_sequence.add_tests(); auto* s1 = test->add_services(); s1->set_name("s1"); s1->set_count(1); auto* s2 = test->add_services(); s2->set_name("s2"); s2->set_count(2); auto* l1 = test->add_action_lists(); l1->set_name("s1"); l1->add_action_names("s1/ping"); auto a1 = test->add_actions(); a1->set_name("s1/ping"); a1->set_rpc_name("echo"); a1->mutable_iterations()->set_max_iteration_count(10); auto* r1 = test->add_rpc_descriptions(); r1->set_name("echo"); r1->set_client("s1"); r1->set_server("s2"); auto* l2 = test->add_action_lists(); l2->set_name("echo"); TestSequenceResults results; grpc::ClientContext context; std::chrono::system_clock::time_point deadline = std::chrono::system_clock::now() + std::chrono::seconds(10); context.set_deadline(deadline); grpc::Status status = tester.test_sequencer_stub->RunTestSequence( &context, test_sequence, &results); ASSERT_OK(status); LOG(INFO) << "TestSequenceResults: " << results.DebugString(); ASSERT_EQ(results.test_results().size(), 1); auto& test_results = results.test_results(0); ASSERT_EQ(test_results.service_logs().instance_logs_size(), 1); const auto& instance_results_it = test_results.service_logs().instance_logs().find("s1/0"); ASSERT_NE(instance_results_it, test_results.service_logs().instance_logs().end()); auto s2_0 = instance_results_it->second.peer_logs().find("s2/0"); ASSERT_NE(s2_0, instance_results_it->second.peer_logs().end()); auto s2_0_echo = s2_0->second.rpc_logs().find(0); ASSERT_NE(s2_0_echo, s2_0->second.rpc_logs().end()); ASSERT_TRUE(s2_0_echo->second.failed_rpc_samples().empty()); ASSERT_EQ(s2_0_echo->second.successful_rpc_samples_size(), 10); auto s2_1 = instance_results_it->second.peer_logs().find("s2/1"); ASSERT_NE(s2_1, instance_results_it->second.peer_logs().end()); auto s2_1_echo = s2_1->second.rpc_logs().find(0); ASSERT_NE(s2_1_echo, s2_1->second.rpc_logs().end()); ASSERT_TRUE(s2_1_echo->second.failed_rpc_samples().empty()); ASSERT_EQ(s2_1_echo->second.successful_rpc_samples_size(), 10); } void RunIntenseTraffic(const char* protocol) { DistBenchTester tester; ASSERT_OK(tester.Initialize(6)); TestSequence test_sequence; auto* test = test_sequence.add_tests(); test->set_default_protocol(protocol); auto* s1 = test->add_services(); s1->set_name("s1"); s1->set_count(1); auto* s2 = test->add_services(); s2->set_name("s2"); s2->set_count(5); auto* l1 = test->add_action_lists(); l1->set_name("s1"); l1->add_action_names("s1/ping"); auto a1 = test->add_actions(); a1->set_name("s1/ping"); a1->set_rpc_name("echo"); a1->mutable_iterations()->set_max_iteration_count(10); auto* iterations = a1->mutable_iterations(); iterations->set_max_duration_us(200000); iterations->set_max_iteration_count(2000); iterations->set_max_parallel_iterations(10); auto* r1 = test->add_rpc_descriptions(); r1->set_name("echo"); r1->set_client("s1"); r1->set_server("s2"); auto* l2 = test->add_action_lists(); l2->set_name("echo"); TestSequenceResults results; std::chrono::system_clock::time_point deadline = std::chrono::system_clock::now() + std::chrono::seconds(200); grpc::ClientContext context; grpc::ClientContext context2; grpc::ClientContext context3; context.set_deadline(deadline); context2.set_deadline(deadline); context3.set_deadline(deadline); grpc::Status status = tester.test_sequencer_stub->RunTestSequence( &context, test_sequence, &results); LOG(INFO) << status.error_message(); ASSERT_OK(status); iterations->clear_max_iteration_count(); status = tester.test_sequencer_stub->RunTestSequence( &context2, test_sequence, &results); LOG(INFO) << status.error_message(); ASSERT_OK(status); iterations->clear_max_duration_us(); iterations->set_max_iteration_count(2000); status = tester.test_sequencer_stub->RunTestSequence( &context3, test_sequence, &results); LOG(INFO) << status.error_message(); ASSERT_OK(status); return; } TEST(DistBenchTestSequencer, 100k_grpc) { RunIntenseTraffic("grpc"); } TEST(DistBenchTestSequencer, 100k_grpc_async_callback) { RunIntenseTraffic("grpc_async_callback"); } TEST(DistBenchTestSequencer, clique_test) { int nb_cliques = 3; DistBenchTester tester; ASSERT_OK(tester.Initialize(nb_cliques)); TestSequence test_sequence; auto* test = test_sequence.add_tests(); auto* s1 = test->add_services(); s1->set_name("clique"); s1->set_count(nb_cliques); auto* l1 = test->add_action_lists(); l1->set_name("clique"); l1->add_action_names("clique_queries"); auto a1 = test->add_actions(); a1->set_name("clique_queries"); a1->mutable_iterations()->set_max_duration_us(10000000); a1->mutable_iterations()->set_open_loop_interval_ns(16000000); a1->mutable_iterations()->set_open_loop_interval_distribution("sync_burst"); a1->set_rpc_name("clique_query"); auto* r1 = test->add_rpc_descriptions(); r1->set_name("clique_query"); r1->set_client("clique"); r1->set_server("clique"); r1->set_fanout_filter("all"); auto* l2 = test->add_action_lists(); l2->set_name("clique_query"); TestSequenceResults results; grpc::ClientContext context; std::chrono::system_clock::time_point deadline = std::chrono::system_clock::now() + std::chrono::seconds(15); context.set_deadline(deadline); grpc::Status status = tester.test_sequencer_stub->RunTestSequence( &context, test_sequence, &results); ASSERT_OK(status); LOG(INFO) << "TestSequenceResults: " << results.DebugString(); ASSERT_EQ(results.test_results().size(), 1); auto& test_results = results.test_results(0); const auto &log_summary = test_results.log_summary(); size_t pos = log_summary.find("N: ") + 3; ASSERT_NE(pos, std::string::npos); const std::string N_value = log_summary.substr(pos); std::string N_value2 = N_value.substr(0, N_value.find(" ")); int N; ASSERT_EQ(absl::SimpleAtoi(N_value2, &N), true); bool correct_number = (624 * (nb_cliques * (nb_cliques - 1)) <= N) && (626 * (nb_cliques * (nb_cliques - 1)) >= N); ASSERT_EQ(correct_number, true); ASSERT_EQ(test_results.service_logs().instance_logs_size(), 3); const auto& instance_results_it = test_results.service_logs().instance_logs().find("clique/0"); ASSERT_NE(instance_results_it, test_results.service_logs().instance_logs().end()); } } // namespace distbench <|endoftext|>
<commit_before>/*++ Copyright (c) 2016 Microsoft Corporation Module Name: bv_bounds_tactic.cpp Abstract: Contextual bounds simplification tactic. Author: Nikolaj Bjorner (nbjorner) 2016-2-12 --*/ #include "bv_bounds_tactic.h" #include "ctx_simplify_tactic.h" #include "bv_decl_plugin.h" #include "ast_pp.h" static rational uMaxInt(unsigned sz) { return rational::power_of_two(sz) - rational::one(); } namespace { struct interval { // l < h: [l, h] // l > h: [0, h] U [l, UMAX_INT] rational l, h; unsigned sz; bool tight; interval() {} interval(const rational& l, const rational& h, unsigned sz, bool tight = false) : l(l), h(h), sz(sz), tight(tight) { // canonicalize full set if (is_wrapped() && l == h + rational::one()) { this->l = rational::zero(); this->h = uMaxInt(sz); } SASSERT(invariant()); } bool invariant() const { return !l.is_neg() && !h.is_neg() && l <= uMaxInt(sz) && h <= uMaxInt(sz) && (!is_wrapped() || l != h+rational::one()); } bool is_full() const { return l.is_zero() && h == uMaxInt(sz); } bool is_wrapped() const { return l > h; } bool is_singleton() const { return l == h; } bool operator==(const interval& b) const { SASSERT(sz == b.sz); return l == b.l && h == b.h && tight == b.tight; } bool operator!=(const interval& b) const { return !(*this == b); } bool implies(const interval& b) const { if (b.is_full()) return true; if (is_full()) return false; if (is_wrapped()) { // l >= b.l >= b.h >= h return b.is_wrapped() && h <= b.h && l >= b.l; } else if (b.is_wrapped()) { // b.l > b.h >= h >= l // h >= l >= b.l > b.h return h <= b.h || l >= b.l; } else { // return l >= b.l && h <= b.h; } } /// return false if intersection is unsat bool intersect(const interval& b, interval& result) const { if (is_full() || *this == b) { result = b; return true; } if (b.is_full()) { result = *this; return true; } if (is_wrapped()) { if (b.is_wrapped()) { if (h >= b.l) { result = b; } else if (b.h >= l) { result = *this; } else { result = interval(std::max(l, b.l), std::min(h, b.h), sz); } } else { return b.intersect(*this, result); } } else if (b.is_wrapped()) { // ... b.h ... l ... h ... b.l .. if (h < b.l && l > b.h) { return false; } // ... l ... b.l ... h ... if (h >= b.l && l <= b.h) { result = b; } else if (h >= b.l) { result = interval(b.l, h, sz); } else { // ... l .. b.h .. h .. b.l ... SASSERT(l <= b.h); result = interval(l, std::min(h, b.h), sz); } } else { if (l > b.h || h < b.l) return false; // 0 .. l.. l' ... h ... h' result = interval(std::max(l, b.l), std::min(h, b.h), sz, tight && b.tight); } return true; } /// return false if negation is empty bool negate(interval& result) const { if (!tight) { result = interval(rational::zero(), uMaxInt(sz), true); return true; } if (is_full()) return false; if (l.is_zero()) { result = interval(h + rational::one(), uMaxInt(sz), sz); } else if (uMaxInt(sz) == h) { result = interval(rational::zero(), l - rational::one(), sz); } else { result = interval(h + rational::one(), l - rational::one(), sz); } return true; } }; std::ostream& operator<<(std::ostream& o, const interval& I) { o << "[" << I.l << ", " << I.h << "]"; return o; } class bv_bounds_simplifier : public ctx_simplify_tactic::simplifier { typedef obj_map<expr, interval> map; typedef obj_map<expr, bool> expr_set; typedef obj_map<expr, expr_set*> expr_list_map; ast_manager& m; params_ref m_params; bool m_propagate_eq; bv_util m_bv; vector<map> m_scopes; map *m_bound; expr_list_map m_expr_vars; bool is_bound(expr *e, expr*& v, interval& b) { rational n; expr *lhs, *rhs; unsigned sz; if (m_bv.is_bv_ule(e, lhs, rhs)) { if (m_bv.is_numeral(lhs, n, sz)) { // C ule x <=> x uge C if (m_bv.is_numeral(rhs)) return false; b = interval(n, uMaxInt(sz), sz, true); v = rhs; return true; } if (m_bv.is_numeral(rhs, n, sz)) { // x ule C b = interval(rational::zero(), n, sz, true); v = lhs; return true; } } else if (m_bv.is_bv_sle(e, lhs, rhs)) { if (m_bv.is_numeral(lhs, n, sz)) { // C sle x <=> x sge C if (m_bv.is_numeral(rhs)) return false; b = interval(n, rational::power_of_two(sz-1) - rational::one(), sz, true); v = rhs; return true; } if (m_bv.is_numeral(rhs, n, sz)) { // x sle C b = interval(rational::power_of_two(sz-1), n, sz, true); v = lhs; return true; } } else if (m.is_eq(e, lhs, rhs)) { if (m_bv.is_numeral(lhs, n, sz)) { if (m_bv.is_numeral(rhs)) return false; b = interval(n, n, sz, true); v = rhs; return true; } if (m_bv.is_numeral(rhs, n, sz)) { b = interval(n, n, sz, true); v = lhs; return true; } } return false; } expr_set* get_expr_vars(expr* t) { expr_set*& entry = m_expr_vars.insert_if_not_there2(t, 0)->get_data().m_value; if (entry) return entry; expr_set* set = alloc(expr_set); entry = set; if (!m_bv.is_numeral(t)) set->insert(t, true); if (!is_app(t)) return set; app* a = to_app(t); for (unsigned i = 0; i < a->get_num_args(); ++i) { expr_set* set_arg = get_expr_vars(a->get_arg(i)); for (expr_set::iterator I = set_arg->begin(), E = set_arg->end(); I != E; ++I) { set->insert(I->m_key, true); } } return set; } bool expr_has_bounds(expr* t) { if (!m.is_bool(t)) return false; app* a = to_app(t); if (m_bv.is_bv_ule(t) || m_bv.is_bv_sle(t) || m.is_eq(t)) return m_bv.is_numeral(a->get_arg(0)) ^ m_bv.is_numeral(a->get_arg(1)); for (unsigned i = 0; i < a->get_num_args(); ++i) { if (expr_has_bounds(a->get_arg(i))) return true; } return false; } public: bv_bounds_simplifier(ast_manager& m, params_ref const& p) : m(m), m_params(p), m_bv(m) { m_scopes.push_back(map()); m_bound = &m_scopes.back(); updt_params(p); } virtual void updt_params(params_ref const & p) { m_propagate_eq = p.get_bool("propagate_eq", false); } static void get_param_descrs(param_descrs& r) { r.insert("propagate-eq", CPK_BOOL, "(default: false) propagate equalities from inequalities"); } virtual ~bv_bounds_simplifier() { for (expr_list_map::iterator I = m_expr_vars.begin(), E = m_expr_vars.end(); I != E; ++I) { dealloc(I->m_value); } } virtual bool assert_expr(expr * t, bool sign) { while (m.is_not(t, t)) { sign = !sign; } interval b; expr* t1; if (is_bound(t, t1, b)) { SASSERT(!m_bv.is_numeral(t1)); if (sign) VERIFY(b.negate(b)); push(); TRACE("bv", tout << (sign?"(not ":"") << mk_pp(t, m) << (sign ? ")" : "") << ": " << mk_pp(t1, m) << " in " << b << "\n";); interval& r = m_bound->insert_if_not_there2(t1, b)->get_data().m_value; return r.intersect(b, r); } return true; } virtual bool simplify(expr* t, expr_ref& result) { expr* t1; interval b; if (m_bound->find(t, b) && b.is_singleton()) { result = m_bv.mk_numeral(b.l, m_bv.get_bv_size(t)); return true; } if (!m.is_bool(t)) return false; bool sign = false; while (m.is_not(t, t)) { sign = !sign; } if (!is_bound(t, t1, b)) return false; if (sign && b.tight) { sign = false; if (!b.negate(b)) { result = m.mk_false(); return true; } } interval ctx, intr; result = 0; if (m_bound->find(t1, ctx)) { if (ctx.implies(b)) { result = m.mk_true(); } else if (!b.intersect(ctx, intr)) { result = m.mk_false(); } else if (m_propagate_eq && intr.is_singleton()) { result = m.mk_eq(t1, m_bv.mk_numeral(intr.l, m.get_sort(t1))); } } else if (b.is_full() && b.tight) { result = m.mk_true(); } CTRACE("bv", result != 0, tout << mk_pp(t, m) << " " << b << " (ctx: " << ctx << ") (intr: " << intr << "): " << result << "\n";); if (sign && result != 0) result = m.mk_not(result); return result != 0; } virtual bool may_simplify(expr* t) { if (m_bv.is_numeral(t)) return false; expr_set* used_exprs = get_expr_vars(t); for (map::iterator I = m_bound->begin(), E = m_bound->end(); I != E; ++I) { if (I->m_value.is_singleton() && used_exprs->contains(I->m_key)) return true; } return expr_has_bounds(t); } virtual void push() { TRACE("bv", tout << "push\n";); unsigned sz = m_scopes.size(); m_scopes.resize(sz + 1); m_bound = &m_scopes.back(); m_bound->~map(); new (m_bound) map(m_scopes[sz - 1]); } virtual void pop(unsigned num_scopes) { TRACE("bv", tout << "pop: " << num_scopes << "\n";); m_scopes.shrink(m_scopes.size() - num_scopes); m_bound = &m_scopes.back(); } virtual simplifier * translate(ast_manager & m) { return alloc(bv_bounds_simplifier, m, m_params); } virtual unsigned scope_level() const { return m_scopes.size() - 1; } }; } tactic * mk_bv_bounds_tactic(ast_manager & m, params_ref const & p) { return clean(alloc(ctx_simplify_tactic, m, alloc(bv_bounds_simplifier, m, p), p)); } <commit_msg>bv_bounds: make may_simplify() more aggressive for the common case of a single comparison fix expr_has_bounds to handle cases like (bvadd (ite c t e) ...)<commit_after>/*++ Copyright (c) 2016 Microsoft Corporation Module Name: bv_bounds_tactic.cpp Abstract: Contextual bounds simplification tactic. Author: Nikolaj Bjorner (nbjorner) 2016-2-12 --*/ #include "bv_bounds_tactic.h" #include "ctx_simplify_tactic.h" #include "bv_decl_plugin.h" #include "ast_pp.h" static rational uMaxInt(unsigned sz) { return rational::power_of_two(sz) - rational::one(); } namespace { struct interval { // l < h: [l, h] // l > h: [0, h] U [l, UMAX_INT] rational l, h; unsigned sz; bool tight; interval() {} interval(const rational& l, const rational& h, unsigned sz, bool tight = false) : l(l), h(h), sz(sz), tight(tight) { // canonicalize full set if (is_wrapped() && l == h + rational::one()) { this->l = rational::zero(); this->h = uMaxInt(sz); } SASSERT(invariant()); } bool invariant() const { return !l.is_neg() && !h.is_neg() && l <= uMaxInt(sz) && h <= uMaxInt(sz) && (!is_wrapped() || l != h+rational::one()); } bool is_full() const { return l.is_zero() && h == uMaxInt(sz); } bool is_wrapped() const { return l > h; } bool is_singleton() const { return l == h; } bool operator==(const interval& b) const { SASSERT(sz == b.sz); return l == b.l && h == b.h && tight == b.tight; } bool operator!=(const interval& b) const { return !(*this == b); } bool implies(const interval& b) const { if (b.is_full()) return true; if (is_full()) return false; if (is_wrapped()) { // l >= b.l >= b.h >= h return b.is_wrapped() && h <= b.h && l >= b.l; } else if (b.is_wrapped()) { // b.l > b.h >= h >= l // h >= l >= b.l > b.h return h <= b.h || l >= b.l; } else { // return l >= b.l && h <= b.h; } } /// return false if intersection is unsat bool intersect(const interval& b, interval& result) const { if (is_full() || *this == b) { result = b; return true; } if (b.is_full()) { result = *this; return true; } if (is_wrapped()) { if (b.is_wrapped()) { if (h >= b.l) { result = b; } else if (b.h >= l) { result = *this; } else { result = interval(std::max(l, b.l), std::min(h, b.h), sz); } } else { return b.intersect(*this, result); } } else if (b.is_wrapped()) { // ... b.h ... l ... h ... b.l .. if (h < b.l && l > b.h) { return false; } // ... l ... b.l ... h ... if (h >= b.l && l <= b.h) { result = b; } else if (h >= b.l) { result = interval(b.l, h, sz); } else { // ... l .. b.h .. h .. b.l ... SASSERT(l <= b.h); result = interval(l, std::min(h, b.h), sz); } } else { if (l > b.h || h < b.l) return false; // 0 .. l.. l' ... h ... h' result = interval(std::max(l, b.l), std::min(h, b.h), sz, tight && b.tight); } return true; } /// return false if negation is empty bool negate(interval& result) const { if (!tight) { result = interval(rational::zero(), uMaxInt(sz), true); return true; } if (is_full()) return false; if (l.is_zero()) { result = interval(h + rational::one(), uMaxInt(sz), sz); } else if (uMaxInt(sz) == h) { result = interval(rational::zero(), l - rational::one(), sz); } else { result = interval(h + rational::one(), l - rational::one(), sz); } return true; } }; std::ostream& operator<<(std::ostream& o, const interval& I) { o << "[" << I.l << ", " << I.h << "]"; return o; } class bv_bounds_simplifier : public ctx_simplify_tactic::simplifier { typedef obj_map<expr, interval> map; typedef obj_map<expr, bool> expr_set; typedef obj_map<expr, expr_set*> expr_list_map; ast_manager& m; params_ref m_params; bool m_propagate_eq; bv_util m_bv; vector<map> m_scopes; map *m_bound; expr_list_map m_expr_vars; bool is_bound(expr *e, expr*& v, interval& b) { rational n; expr *lhs, *rhs; unsigned sz; if (m_bv.is_bv_ule(e, lhs, rhs)) { if (m_bv.is_numeral(lhs, n, sz)) { // C ule x <=> x uge C if (m_bv.is_numeral(rhs)) return false; b = interval(n, uMaxInt(sz), sz, true); v = rhs; return true; } if (m_bv.is_numeral(rhs, n, sz)) { // x ule C b = interval(rational::zero(), n, sz, true); v = lhs; return true; } } else if (m_bv.is_bv_sle(e, lhs, rhs)) { if (m_bv.is_numeral(lhs, n, sz)) { // C sle x <=> x sge C if (m_bv.is_numeral(rhs)) return false; b = interval(n, rational::power_of_two(sz-1) - rational::one(), sz, true); v = rhs; return true; } if (m_bv.is_numeral(rhs, n, sz)) { // x sle C b = interval(rational::power_of_two(sz-1), n, sz, true); v = lhs; return true; } } else if (m.is_eq(e, lhs, rhs)) { if (m_bv.is_numeral(lhs, n, sz)) { if (m_bv.is_numeral(rhs)) return false; b = interval(n, n, sz, true); v = rhs; return true; } if (m_bv.is_numeral(rhs, n, sz)) { b = interval(n, n, sz, true); v = lhs; return true; } } return false; } expr_set* get_expr_vars(expr* t) { expr_set*& entry = m_expr_vars.insert_if_not_there2(t, 0)->get_data().m_value; if (entry) return entry; expr_set* set = alloc(expr_set); entry = set; if (!m_bv.is_numeral(t)) set->insert(t, true); if (!is_app(t)) return set; app* a = to_app(t); for (unsigned i = 0; i < a->get_num_args(); ++i) { expr_set* set_arg = get_expr_vars(a->get_arg(i)); for (expr_set::iterator I = set_arg->begin(), E = set_arg->end(); I != E; ++I) { set->insert(I->m_key, true); } } return set; } bool expr_has_bounds(expr* t) { app* a = to_app(t); if ((m_bv.is_bv_ule(t) || m_bv.is_bv_sle(t) || m.is_eq(t)) && (m_bv.is_numeral(a->get_arg(0)) || m_bv.is_numeral(a->get_arg(1)))) return true; for (unsigned i = 0; i < a->get_num_args(); ++i) { if (expr_has_bounds(a->get_arg(i))) return true; } return false; } public: bv_bounds_simplifier(ast_manager& m, params_ref const& p) : m(m), m_params(p), m_bv(m) { m_scopes.push_back(map()); m_bound = &m_scopes.back(); updt_params(p); } virtual void updt_params(params_ref const & p) { m_propagate_eq = p.get_bool("propagate_eq", false); } static void get_param_descrs(param_descrs& r) { r.insert("propagate-eq", CPK_BOOL, "(default: false) propagate equalities from inequalities"); } virtual ~bv_bounds_simplifier() { for (expr_list_map::iterator I = m_expr_vars.begin(), E = m_expr_vars.end(); I != E; ++I) { dealloc(I->m_value); } } virtual bool assert_expr(expr * t, bool sign) { while (m.is_not(t, t)) { sign = !sign; } interval b; expr* t1; if (is_bound(t, t1, b)) { SASSERT(!m_bv.is_numeral(t1)); if (sign) VERIFY(b.negate(b)); push(); TRACE("bv", tout << (sign?"(not ":"") << mk_pp(t, m) << (sign ? ")" : "") << ": " << mk_pp(t1, m) << " in " << b << "\n";); interval& r = m_bound->insert_if_not_there2(t1, b)->get_data().m_value; return r.intersect(b, r); } return true; } virtual bool simplify(expr* t, expr_ref& result) { expr* t1; interval b; if (m_bound->find(t, b) && b.is_singleton()) { result = m_bv.mk_numeral(b.l, m_bv.get_bv_size(t)); return true; } if (!m.is_bool(t)) return false; bool sign = false; while (m.is_not(t, t)) { sign = !sign; } if (!is_bound(t, t1, b)) return false; if (sign && b.tight) { sign = false; if (!b.negate(b)) { result = m.mk_false(); return true; } } interval ctx, intr; result = 0; if (m_bound->find(t1, ctx)) { if (ctx.implies(b)) { result = m.mk_true(); } else if (!b.intersect(ctx, intr)) { result = m.mk_false(); } else if (m_propagate_eq && intr.is_singleton()) { result = m.mk_eq(t1, m_bv.mk_numeral(intr.l, m.get_sort(t1))); } } else if (b.is_full() && b.tight) { result = m.mk_true(); } CTRACE("bv", result != 0, tout << mk_pp(t, m) << " " << b << " (ctx: " << ctx << ") (intr: " << intr << "): " << result << "\n";); if (sign && result != 0) result = m.mk_not(result); return result != 0; } virtual bool may_simplify(expr* t) { if (m_bv.is_numeral(t)) return false; expr_set* used_exprs = get_expr_vars(t); for (map::iterator I = m_bound->begin(), E = m_bound->end(); I != E; ++I) { if (I->m_value.is_singleton() && used_exprs->contains(I->m_key)) return true; } while (m.is_not(t, t)); expr* t1; interval b; // skip common case: single bound constraint without any context for simplification if (is_bound(t, t1, b)) { return m_bound->contains(t1); } return expr_has_bounds(t); } virtual void push() { TRACE("bv", tout << "push\n";); unsigned sz = m_scopes.size(); m_scopes.resize(sz + 1); m_bound = &m_scopes.back(); m_bound->~map(); new (m_bound) map(m_scopes[sz - 1]); } virtual void pop(unsigned num_scopes) { TRACE("bv", tout << "pop: " << num_scopes << "\n";); m_scopes.shrink(m_scopes.size() - num_scopes); m_bound = &m_scopes.back(); } virtual simplifier * translate(ast_manager & m) { return alloc(bv_bounds_simplifier, m, m_params); } virtual unsigned scope_level() const { return m_scopes.size() - 1; } }; } tactic * mk_bv_bounds_tactic(ast_manager & m, params_ref const & p) { return clean(alloc(ctx_simplify_tactic, m, alloc(bv_bounds_simplifier, m, p), p)); } <|endoftext|>
<commit_before>/* * Copyright (c) Facebook, Inc. and its affiliates. * * 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 <folly/Portability.h> #if FOLLY_HAS_COROUTINES #include <folly/Optional.h> #include <folly/ScopeGuard.h> #include <folly/executors/ManualExecutor.h> #include <folly/experimental/coro/Baton.h> #include <folly/experimental/coro/BlockingWait.h> #include <folly/experimental/coro/Invoke.h> #include <folly/experimental/coro/Utils.h> #include <folly/fibers/FiberManager.h> #include <folly/fibers/FiberManagerMap.h> #include <folly/portability/GTest.h> #include <memory> #include <type_traits> static_assert( std::is_same< decltype(folly::coro::blockingWait( std::declval<folly::coro::AwaitableReady<void>>())), void>::value, ""); static_assert( std::is_same< decltype(folly::coro::blockingWait( std::declval<folly::coro::AwaitableReady<int>>())), int>::value, ""); static_assert( std::is_same< decltype(folly::coro::blockingWait( std::declval<folly::coro::AwaitableReady<int&>>())), int&>::value, ""); static_assert( std::is_same< decltype(folly::coro::blockingWait( std::declval<folly::coro::AwaitableReady<int&&>>())), int>::value, "blockingWait() should convert rvalue-reference-returning awaitables " "into a returned prvalue to avoid potential lifetime issues since " "its possible the rvalue reference could have been to some temporary " "object stored inside the Awaiter which would have been destructed " "by the time blockingWait returns."); class BlockingWaitTest : public testing::Test {}; TEST_F(BlockingWaitTest, SynchronousCompletionVoidResult) { folly::coro::blockingWait(folly::coro::AwaitableReady<void>{}); } TEST_F(BlockingWaitTest, SynchronousCompletionPRValueResult) { EXPECT_EQ( 123, folly::coro::blockingWait(folly::coro::AwaitableReady<int>{123})); EXPECT_EQ( "hello", folly::coro::blockingWait( folly::coro::AwaitableReady<std::string>("hello"))); } TEST_F(BlockingWaitTest, SynchronousCompletionLValueResult) { int value = 123; int& result = folly::coro::blockingWait(folly::coro::AwaitableReady<int&>{value}); EXPECT_EQ(&value, &result); EXPECT_EQ(123, result); } TEST_F(BlockingWaitTest, SynchronousCompletionRValueResult) { auto p = std::make_unique<int>(123); auto* ptr = p.get(); // Should return a prvalue which will lifetime-extend when assigned to an // auto&& local variable. auto&& result = folly::coro::blockingWait( folly::coro::AwaitableReady<std::unique_ptr<int>&&>{std::move(p)}); EXPECT_EQ(ptr, result.get()); EXPECT_FALSE(p); } struct TrickyAwaitable { struct Awaiter { std::unique_ptr<int> value_; bool await_ready() const { return false; } bool await_suspend(std::experimental::coroutine_handle<>) { value_ = std::make_unique<int>(42); return false; } std::unique_ptr<int>&& await_resume() { return std::move(value_); } }; Awaiter operator co_await() { return {}; } }; TEST_F(BlockingWaitTest, ReturnRvalueReferenceFromAwaiter) { // This awaitable stores the result in the temporary Awaiter object that // is placed on the coroutine frame as part of the co_await expression. // It then returns an rvalue-reference to the value inside this temporary // Awaiter object. This test is making sure that we copy/move the result // before destructing the Awaiter object. auto result = folly::coro::blockingWait(TrickyAwaitable{}); CHECK(result); CHECK_EQ(42, *result); } TEST_F(BlockingWaitTest, AsynchronousCompletionOnAnotherThread) { folly::coro::Baton baton; std::thread t{[&] { baton.post(); }}; SCOPE_EXIT { t.join(); }; folly::coro::blockingWait(baton); } template <typename T> class SimplePromise { public: class WaitOperation { public: explicit WaitOperation( folly::coro::Baton& baton, folly::Optional<T>& value) noexcept : awaiter_(baton), value_(value) {} bool await_ready() { return awaiter_.await_ready(); } template <typename Promise> auto await_suspend(std::experimental::coroutine_handle<Promise> h) { return awaiter_.await_suspend(h); } T&& await_resume() { awaiter_.await_resume(); return std::move(*value_); } private: folly::coro::Baton::WaitOperation awaiter_; folly::Optional<T>& value_; }; SimplePromise() = default; WaitOperation operator co_await() { return WaitOperation{baton_, value_}; } template <typename... Args> void emplace(Args&&... args) { value_.emplace(static_cast<Args&&>(args)...); baton_.post(); } private: folly::coro::Baton baton_; folly::Optional<T> value_; }; TEST_F(BlockingWaitTest, WaitOnSimpleAsyncPromise) { SimplePromise<std::string> p; std::thread t{[&] { p.emplace("hello coroutines!"); }}; SCOPE_EXIT { t.join(); }; auto result = folly::coro::blockingWait(p); EXPECT_EQ("hello coroutines!", result); } struct MoveCounting { int count_; MoveCounting() noexcept : count_(0) {} MoveCounting(MoveCounting&& other) noexcept : count_(other.count_ + 1) {} MoveCounting& operator=(MoveCounting&& other) = delete; }; TEST_F(BlockingWaitTest, WaitOnMoveOnlyAsyncPromise) { SimplePromise<MoveCounting> p; std::thread t{[&] { p.emplace(); }}; SCOPE_EXIT { t.join(); }; auto result = folly::coro::blockingWait(p); // Number of move-constructions: // 0. Value is in-place constructed in Optional<T> // 0. await_resume() returns rvalue reference to Optional<T> value. // 1. return_value() moves value into Try<T> // 2. Value is moved from Try<T> to blockingWait() return value. EXPECT_GE(2, result.count_); } TEST_F(BlockingWaitTest, moveCountingAwaitableReady) { folly::coro::AwaitableReady<MoveCounting> awaitable{MoveCounting{}}; auto result = folly::coro::blockingWait(awaitable); // Moves: // 1. Move value into AwaitableReady // 2. Move value to await_resume() return-value // 3. Move value to Try<T> // 4. Move value to blockingWait() return-value EXPECT_GE(4, result.count_); } TEST_F(BlockingWaitTest, WaitInFiber) { SimplePromise<int> promise; folly::EventBase evb; auto& fm = folly::fibers::getFiberManager(evb); auto future = fm.addTaskFuture([&] { return folly::coro::blockingWait(promise); }); evb.loopOnce(); EXPECT_FALSE(future.isReady()); promise.emplace(42); evb.loopOnce(); EXPECT_TRUE(future.isReady()); EXPECT_EQ(42, std::move(future).get()); } TEST_F(BlockingWaitTest, WaitTaskInFiber) { SimplePromise<int> promise; folly::EventBase evb; auto& fm = folly::fibers::getFiberManager(evb); auto future = fm.addTaskFuture([&] { return folly::coro::blockingWait(folly::coro::co_invoke( [&]() -> folly::coro::Task<int> { co_return co_await promise; })); }); evb.loopOnce(); EXPECT_FALSE(future.isReady()); promise.emplace(42); evb.loopOnce(); EXPECT_TRUE(future.isReady()); EXPECT_EQ(42, std::move(future).get()); } struct ExpectedException {}; TEST_F(BlockingWaitTest, WaitTaskInFiberException) { folly::EventBase evb; auto& fm = folly::fibers::getFiberManager(evb); fm.addTask([] { try { folly::coro::blockingWait( folly::coro::co_invoke([&]() -> folly::coro::Task<void> { folly::via(co_await folly::coro::co_current_executor, []() {}); throw ExpectedException(); })); } catch (const ExpectedException&) { } }); evb.loop(); } TEST_F(BlockingWaitTest, WaitOnSemiFuture) { int result = folly::coro::blockingWait(folly::makeSemiFuture(123)); CHECK_EQ(result, 123); } TEST_F(BlockingWaitTest, RequestContext) { folly::RequestContext::create(); std::shared_ptr<folly::RequestContext> ctx1, ctx2; ctx1 = folly::RequestContext::saveContext(); folly::coro::blockingWait([&]() -> folly::coro::Task<void> { EXPECT_EQ(ctx1.get(), folly::RequestContext::get()); folly::RequestContextScopeGuard guard; ctx2 = folly::RequestContext::saveContext(); EXPECT_NE(ctx1, ctx2); co_await folly::coro::co_reschedule_on_current_executor; EXPECT_EQ(ctx2.get(), folly::RequestContext::get()); co_return; }()); EXPECT_EQ(ctx1.get(), folly::RequestContext::get()); } TEST_F(BlockingWaitTest, DrivableExecutor) { folly::ManualExecutor executor; folly::coro::blockingWait( [&]() -> folly::coro::Task<void> { folly::Executor* taskExecutor = co_await folly::coro::co_current_executor; EXPECT_EQ(&executor, taskExecutor); }(), &executor); } TEST_F(BlockingWaitTest, ReleaseExecutorFromAnotherThread) { auto fn = []() { auto c1 = folly::makePromiseContract<folly::Executor::KeepAlive<>>(); auto c2 = folly::makePromiseContract<folly::Unit>(); std::thread t{[&] { auto e = std::move(c1.second).get(); c2.first.setValue(folly::Unit{}); std::this_thread::sleep_for(std::chrono::microseconds(1)); e = {}; }}; folly::ManualExecutor executor; folly::coro::blockingWait([&]() -> folly::coro::Task<void> { folly::Executor::KeepAlive<> taskExecutor = co_await folly::coro::co_current_executor; c1.first.setValue(std::move(taskExecutor)); co_await std::move(c2.second); }()); t.join(); }; std::vector<std::thread> threads; for (int i = 0; i < 100; ++i) { threads.emplace_back(fn); } for (auto& t : threads) { t.join(); } } #endif <commit_msg>Improve blockingWait test<commit_after>/* * Copyright (c) Facebook, Inc. and its affiliates. * * 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 <folly/Portability.h> #if FOLLY_HAS_COROUTINES #include <folly/Optional.h> #include <folly/ScopeGuard.h> #include <folly/executors/ManualExecutor.h> #include <folly/experimental/coro/Baton.h> #include <folly/experimental/coro/BlockingWait.h> #include <folly/experimental/coro/Invoke.h> #include <folly/experimental/coro/Utils.h> #include <folly/fibers/FiberManager.h> #include <folly/fibers/FiberManagerMap.h> #include <folly/portability/GTest.h> #include <memory> #include <type_traits> static_assert( std::is_same< decltype(folly::coro::blockingWait( std::declval<folly::coro::AwaitableReady<void>>())), void>::value, ""); static_assert( std::is_same< decltype(folly::coro::blockingWait( std::declval<folly::coro::AwaitableReady<int>>())), int>::value, ""); static_assert( std::is_same< decltype(folly::coro::blockingWait( std::declval<folly::coro::AwaitableReady<int&>>())), int&>::value, ""); static_assert( std::is_same< decltype(folly::coro::blockingWait( std::declval<folly::coro::AwaitableReady<int&&>>())), int>::value, "blockingWait() should convert rvalue-reference-returning awaitables " "into a returned prvalue to avoid potential lifetime issues since " "its possible the rvalue reference could have been to some temporary " "object stored inside the Awaiter which would have been destructed " "by the time blockingWait returns."); class BlockingWaitTest : public testing::Test {}; TEST_F(BlockingWaitTest, SynchronousCompletionVoidResult) { folly::coro::blockingWait(folly::coro::AwaitableReady<void>{}); } TEST_F(BlockingWaitTest, SynchronousCompletionPRValueResult) { EXPECT_EQ( 123, folly::coro::blockingWait(folly::coro::AwaitableReady<int>{123})); EXPECT_EQ( "hello", folly::coro::blockingWait( folly::coro::AwaitableReady<std::string>("hello"))); } TEST_F(BlockingWaitTest, SynchronousCompletionLValueResult) { int value = 123; int& result = folly::coro::blockingWait(folly::coro::AwaitableReady<int&>{value}); EXPECT_EQ(&value, &result); EXPECT_EQ(123, result); } TEST_F(BlockingWaitTest, SynchronousCompletionRValueResult) { auto p = std::make_unique<int>(123); auto* ptr = p.get(); // Should return a prvalue which will lifetime-extend when assigned to an // auto&& local variable. auto&& result = folly::coro::blockingWait( folly::coro::AwaitableReady<std::unique_ptr<int>&&>{std::move(p)}); EXPECT_EQ(ptr, result.get()); EXPECT_FALSE(p); } struct TrickyAwaitable { struct Awaiter { std::unique_ptr<int> value_; bool await_ready() const { return false; } bool await_suspend(std::experimental::coroutine_handle<>) { value_ = std::make_unique<int>(42); return false; } std::unique_ptr<int>&& await_resume() { return std::move(value_); } }; Awaiter operator co_await() { return {}; } }; TEST_F(BlockingWaitTest, ReturnRvalueReferenceFromAwaiter) { // This awaitable stores the result in the temporary Awaiter object that // is placed on the coroutine frame as part of the co_await expression. // It then returns an rvalue-reference to the value inside this temporary // Awaiter object. This test is making sure that we copy/move the result // before destructing the Awaiter object. auto result = folly::coro::blockingWait(TrickyAwaitable{}); CHECK(result); CHECK_EQ(42, *result); } TEST_F(BlockingWaitTest, AsynchronousCompletionOnAnotherThread) { folly::coro::Baton baton; std::thread t{[&] { baton.post(); }}; SCOPE_EXIT { t.join(); }; folly::coro::blockingWait(baton); } template <typename T> class SimplePromise { public: class WaitOperation { public: explicit WaitOperation( folly::coro::Baton& baton, folly::Optional<T>& value) noexcept : awaiter_(baton), value_(value) {} bool await_ready() { return awaiter_.await_ready(); } template <typename Promise> auto await_suspend(std::experimental::coroutine_handle<Promise> h) { return awaiter_.await_suspend(h); } T&& await_resume() { awaiter_.await_resume(); return std::move(*value_); } private: folly::coro::Baton::WaitOperation awaiter_; folly::Optional<T>& value_; }; SimplePromise() = default; WaitOperation operator co_await() { return WaitOperation{baton_, value_}; } template <typename... Args> void emplace(Args&&... args) { value_.emplace(static_cast<Args&&>(args)...); baton_.post(); } private: folly::coro::Baton baton_; folly::Optional<T> value_; }; TEST_F(BlockingWaitTest, WaitOnSimpleAsyncPromise) { SimplePromise<std::string> p; std::thread t{[&] { p.emplace("hello coroutines!"); }}; SCOPE_EXIT { t.join(); }; auto result = folly::coro::blockingWait(p); EXPECT_EQ("hello coroutines!", result); } struct MoveCounting { int count_; MoveCounting() noexcept : count_(0) {} MoveCounting(MoveCounting&& other) noexcept : count_(other.count_ + 1) {} MoveCounting& operator=(MoveCounting&& other) = delete; }; TEST_F(BlockingWaitTest, WaitOnMoveOnlyAsyncPromise) { SimplePromise<MoveCounting> p; std::thread t{[&] { p.emplace(); }}; SCOPE_EXIT { t.join(); }; auto result = folly::coro::blockingWait(p); // Number of move-constructions: // 0. Value is in-place constructed in Optional<T> // 0. await_resume() returns rvalue reference to Optional<T> value. // 1. return_value() moves value into Try<T> // 2. Value is moved from Try<T> to blockingWait() return value. EXPECT_GE(2, result.count_); } TEST_F(BlockingWaitTest, moveCountingAwaitableReady) { folly::coro::AwaitableReady<MoveCounting> awaitable{MoveCounting{}}; auto result = folly::coro::blockingWait(awaitable); // Moves: // 1. Move value into AwaitableReady // 2. Move value to await_resume() return-value // 3. Move value to Try<T> // 4. Move value to blockingWait() return-value EXPECT_GE(4, result.count_); } TEST_F(BlockingWaitTest, WaitInFiber) { SimplePromise<int> promise; folly::EventBase evb; auto& fm = folly::fibers::getFiberManager(evb); auto future = fm.addTaskFuture([&] { return folly::coro::blockingWait(promise); }); evb.loopOnce(); EXPECT_FALSE(future.isReady()); promise.emplace(42); evb.loopOnce(); EXPECT_TRUE(future.isReady()); EXPECT_EQ(42, std::move(future).get()); } TEST_F(BlockingWaitTest, WaitTaskInFiber) { SimplePromise<int> promise; folly::EventBase evb; auto& fm = folly::fibers::getFiberManager(evb); auto future = fm.addTaskFuture([&] { return folly::coro::blockingWait(folly::coro::co_invoke( [&]() -> folly::coro::Task<int> { co_return co_await promise; })); }); evb.loopOnce(); EXPECT_FALSE(future.isReady()); promise.emplace(42); evb.loopOnce(); EXPECT_TRUE(future.isReady()); EXPECT_EQ(42, std::move(future).get()); } struct ExpectedException {}; TEST_F(BlockingWaitTest, WaitTaskInFiberException) { folly::EventBase evb; auto& fm = folly::fibers::getFiberManager(evb); EXPECT_TRUE( fm.addTaskFuture([&] { try { folly::coro::blockingWait( folly::coro::co_invoke([&]() -> folly::coro::Task<void> { folly::via( co_await folly::coro::co_current_executor, []() {}); throw ExpectedException(); })); return false; } catch (const ExpectedException&) { return true; } }) .getVia(&evb)); } TEST_F(BlockingWaitTest, WaitOnSemiFuture) { int result = folly::coro::blockingWait(folly::makeSemiFuture(123)); CHECK_EQ(result, 123); } TEST_F(BlockingWaitTest, RequestContext) { folly::RequestContext::create(); std::shared_ptr<folly::RequestContext> ctx1, ctx2; ctx1 = folly::RequestContext::saveContext(); folly::coro::blockingWait([&]() -> folly::coro::Task<void> { EXPECT_EQ(ctx1.get(), folly::RequestContext::get()); folly::RequestContextScopeGuard guard; ctx2 = folly::RequestContext::saveContext(); EXPECT_NE(ctx1, ctx2); co_await folly::coro::co_reschedule_on_current_executor; EXPECT_EQ(ctx2.get(), folly::RequestContext::get()); co_return; }()); EXPECT_EQ(ctx1.get(), folly::RequestContext::get()); } TEST_F(BlockingWaitTest, DrivableExecutor) { folly::ManualExecutor executor; folly::coro::blockingWait( [&]() -> folly::coro::Task<void> { folly::Executor* taskExecutor = co_await folly::coro::co_current_executor; EXPECT_EQ(&executor, taskExecutor); }(), &executor); } TEST_F(BlockingWaitTest, ReleaseExecutorFromAnotherThread) { auto fn = []() { auto c1 = folly::makePromiseContract<folly::Executor::KeepAlive<>>(); auto c2 = folly::makePromiseContract<folly::Unit>(); std::thread t{[&] { auto e = std::move(c1.second).get(); c2.first.setValue(folly::Unit{}); std::this_thread::sleep_for(std::chrono::microseconds(1)); e = {}; }}; folly::ManualExecutor executor; folly::coro::blockingWait([&]() -> folly::coro::Task<void> { folly::Executor::KeepAlive<> taskExecutor = co_await folly::coro::co_current_executor; c1.first.setValue(std::move(taskExecutor)); co_await std::move(c2.second); }()); t.join(); }; std::vector<std::thread> threads; for (int i = 0; i < 100; ++i) { threads.emplace_back(fn); } for (auto& t : threads) { t.join(); } } #endif <|endoftext|>
<commit_before>/* * Copyright (c) Meta Platforms, Inc. and affiliates. * * 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 <folly/synchronization/AsymmetricMemoryBarrier.h> #include <mutex> #include <folly/Exception.h> #include <folly/Indestructible.h> #include <folly/portability/SysMembarrier.h> #include <folly/portability/SysMman.h> namespace folly { namespace { struct DummyPageCreator { DummyPageCreator() { get(); } static void* get() { static auto ptr = kIsLinux ? create() : nullptr; return ptr; } private: static void* create() { auto ptr = mmap(nullptr, 1, PROT_READ, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0); checkUnixError(reinterpret_cast<ssize_t>(ptr), "mmap"); // Optimistically try to lock the page so it stays resident. Could make // the heavy barrier faster. auto r = mlock(ptr, 1); if (r != 0) { // Do nothing. } return ptr; } }; // Make sure dummy page is always initialized before shutdown. DummyPageCreator dummyPageCreator; void mprotectMembarrier() { auto dummyPage = dummyPageCreator.get(); // This function is required to be safe to call on shutdown, // so we must leak the mutex. static Indestructible<std::mutex> mprotectMutex; std::lock_guard<std::mutex> lg(*mprotectMutex); int r = 0; // We want to downgrade the page while it is resident. To do that, it must // first be upgraded and forced to be resident. r = mprotect(dummyPage, 1, PROT_READ | PROT_WRITE); checkUnixError(r, "mprotect"); // Force the page to be resident. If it is already resident, almost no-op. *static_cast<char*>(dummyPage) = 0; // Downgrade the page. Forces a memory barrier in every core running any // of the process's threads. On a sane platform. r = mprotect(dummyPage, 1, PROT_READ); checkUnixError(r, "mprotect"); } } // namespace void asymmetricHeavyBarrier() { if (kIsLinux) { static const bool useSysMembarrier = detail::sysMembarrierPrivateExpeditedAvailable(); if (useSysMembarrier) { auto r = detail::sysMembarrierPrivateExpedited(); checkUnixError(r, "membarrier"); } else { mprotectMembarrier(); } } else { std::atomic_thread_fence(std::memory_order_seq_cst); } } } // namespace folly <commit_msg>no need to pre-map the async-memory-barrier fallback page<commit_after>/* * Copyright (c) Meta Platforms, Inc. and affiliates. * * 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 <folly/synchronization/AsymmetricMemoryBarrier.h> #include <mutex> #include <folly/Exception.h> #include <folly/Indestructible.h> #include <folly/portability/SysMembarrier.h> #include <folly/portability/SysMman.h> namespace folly { namespace { void mprotectMembarrier() { // This function is required to be safe to call on shutdown, // so we must leak the mutex. static Indestructible<std::mutex> mprotectMutex; std::lock_guard<std::mutex> lg(*mprotectMutex); // Ensure that we have a dummy page. The page is not used to store data; // rather, it is used only for the side-effects of page operations. static void* dummyPage = nullptr; if (dummyPage == nullptr) { dummyPage = mmap(nullptr, 1, PROT_READ, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0); checkUnixError(reinterpret_cast<ssize_t>(dummyPage), "mmap"); // Optimistically try to lock the page so it stays resident, in theory // making the heavy barrier faster than otherwise. std::ignore = mlock(dummyPage, 1); } int r = 0; // We want to downgrade the page while it is resident. To do that, it must // first be upgraded and forced to be resident. r = mprotect(dummyPage, 1, PROT_READ | PROT_WRITE); checkUnixError(r, "mprotect"); // Force the page to be resident. If it is already resident, almost no-op. *static_cast<char*>(dummyPage) = 0; // Downgrade the page. Forces a memory barrier in every core running any // of the process's threads. On a sane platform. r = mprotect(dummyPage, 1, PROT_READ); checkUnixError(r, "mprotect"); } } // namespace void asymmetricHeavyBarrier() { if (kIsLinux) { static const bool useSysMembarrier = detail::sysMembarrierPrivateExpeditedAvailable(); if (useSysMembarrier) { auto r = detail::sysMembarrierPrivateExpedited(); checkUnixError(r, "membarrier"); } else { mprotectMembarrier(); } } else { std::atomic_thread_fence(std::memory_order_seq_cst); } } } // namespace folly <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: persistentwindowstate.cxx,v $ * * $Revision: 1.13 $ * * last change: $Author: ihi $ $Date: 2007-04-16 16:41:24 $ * * 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_framework.hxx" //_________________________________________________________________________________________________________________ // my own includes //_________________________________________________________________________________________________________________ #ifndef __FRAMEWORK_PATTERN_WINDOW_HXX_ #include <pattern/window.hxx> #endif #ifndef __FRAMEWORK_HELPER_PERSISTENTWINDOWSTATE_HXX_ #include <helper/persistentwindowstate.hxx> #endif #ifndef __FRAMEWORK_THREADHELP_WRITEGUARD_HXX_ #include <threadhelp/writeguard.hxx> #endif #ifndef __FRAMEWORK_THREADHELP_READGUARD_HXX_ #include <threadhelp/readguard.hxx> #endif #ifndef __FRAMEWORK_MACROS_GENERIC_HXX_ #include <macros/generic.hxx> #endif #ifndef __FRAMEWORK_SERVICES_H_ #include <services.h> #endif //_________________________________________________________________________________________________________________ // interface includes //_________________________________________________________________________________________________________________ #ifndef _COM_SUN_STAR_AWT_XWINDOW_HPP_ #include <com/sun/star/awt/XWindow.hpp> #endif #ifndef _COM_SUN_STAR_LANG_XSERVICXEINFO_HPP_ #include <com/sun/star/lang/XServiceInfo.hpp> #endif #ifndef _COM_SUN_STAR_LANG_ILLEGALARGUMENTEXCEPTION_HPP_ #include <com/sun/star/lang/IllegalArgumentException.hpp> #endif #ifndef _COM_SUN_STAR_FRAME_XMODULEMANAGER_HPP_ #include <com/sun/star/frame/XModuleManager.hpp> #endif //_________________________________________________________________________________________________________________ // other includes //_________________________________________________________________________________________________________________ #ifndef _COMPHELPER_CONFIGURATIONHELPER_HXX_ #include <comphelper/configurationhelper.hxx> #endif #ifndef _SV_WINDOW_HXX #include <vcl/window.hxx> #endif #ifndef _SV_SYSWIN_HXX #include <vcl/syswin.hxx> #endif #ifndef _TOOLKIT_HELPER_VCLUNOHELPER_HXX_ #include <toolkit/unohlp.hxx> #endif #ifndef _SV_SVAPP_HXX #include <vcl/svapp.hxx> #endif #ifndef _SV_WRKWIN_HXX #include <vcl/wrkwin.hxx> #endif //_________________________________________________________________________________________________________________ // namespace namespace framework{ namespace fpw = ::framework::pattern::window; //_________________________________________________________________________________________________________________ // definitions //***************************************************************************************************************** // XInterface, XTypeProvider DEFINE_XINTERFACE_4(PersistentWindowState , OWeakObject , DIRECT_INTERFACE (css::lang::XTypeProvider ), DIRECT_INTERFACE (css::lang::XInitialization ), DIRECT_INTERFACE (css::frame::XFrameActionListener ), DERIVED_INTERFACE(css::lang::XEventListener,css::frame::XFrameActionListener)) DEFINE_XTYPEPROVIDER_4(PersistentWindowState , css::lang::XTypeProvider , css::lang::XInitialization , css::frame::XFrameActionListener, css::lang::XEventListener ) //***************************************************************************************************************** PersistentWindowState::PersistentWindowState(const css::uno::Reference< css::lang::XMultiServiceFactory >& xSMGR) : ThreadHelpBase (&Application::GetSolarMutex()) , m_xSMGR (xSMGR ) , m_bWindowStateAlreadySet(sal_False ) { } //***************************************************************************************************************** PersistentWindowState::~PersistentWindowState() { } //***************************************************************************************************************** void SAL_CALL PersistentWindowState::initialize(const css::uno::Sequence< css::uno::Any >& lArguments) throw(css::uno::Exception , css::uno::RuntimeException) { // check arguments css::uno::Reference< css::frame::XFrame > xFrame; if (lArguments.getLength() < 1) throw css::lang::IllegalArgumentException( DECLARE_ASCII("Empty argument list!"), static_cast< ::cppu::OWeakObject* >(this), 1); lArguments[0] >>= xFrame; if (!xFrame.is()) throw css::lang::IllegalArgumentException( DECLARE_ASCII("No valid frame specified!"), static_cast< ::cppu::OWeakObject* >(this), 1); // SAFE -> ---------------------------------- WriteGuard aWriteLock(m_aLock); // hold the frame as weak reference(!) so it can die everytimes :-) m_xFrame = xFrame; aWriteLock.unlock(); // <- SAFE ---------------------------------- // start listening xFrame->addFrameActionListener(this); } //***************************************************************************************************************** void SAL_CALL PersistentWindowState::frameAction(const css::frame::FrameActionEvent& aEvent) throw(css::uno::RuntimeException) { // SAFE -> ---------------------------------- ReadGuard aReadLock(m_aLock); css::uno::Reference< css::lang::XMultiServiceFactory > xSMGR = m_xSMGR ; css::uno::Reference< css::frame::XFrame > xFrame(m_xFrame.get(), css::uno::UNO_QUERY); sal_Bool bRestoreWindowState = !m_bWindowStateAlreadySet; aReadLock.unlock(); // <- SAFE ---------------------------------- // frame already gone ? We hold it weak only ... if (!xFrame.is()) return; // no window -> no position and size available css::uno::Reference< css::awt::XWindow > xWindow = xFrame->getContainerWindow(); if (!xWindow.is()) return; // unknown module -> no configuration available! ::rtl::OUString sModuleName = PersistentWindowState::implst_identifyModule(xSMGR, xFrame); if (!sModuleName.getLength()) return; switch(aEvent.Action) { case css::frame::FrameAction_COMPONENT_ATTACHED : { if (bRestoreWindowState) { ::rtl::OUString sWindowState = PersistentWindowState::implst_getWindowStateFromConfig(xSMGR, sModuleName); PersistentWindowState::implst_setWindowStateOnWindow(xWindow,sWindowState); // SAFE -> ---------------------------------- WriteGuard aWriteLock(m_aLock); m_bWindowStateAlreadySet = sal_True; aWriteLock.unlock(); // <- SAFE ---------------------------------- } } break; case css::frame::FrameAction_COMPONENT_REATTACHED : { // nothing todo here, because its not allowed to change position and size // of an alredy existing frame! } break; case css::frame::FrameAction_COMPONENT_DETACHING : { ::rtl::OUString sWindowState = PersistentWindowState::implst_getWindowStateFromWindow(xWindow); PersistentWindowState::implst_setWindowStateOnConfig(xSMGR, sModuleName, sWindowState); } break; default: break; } } //***************************************************************************************************************** void SAL_CALL PersistentWindowState::disposing(const css::lang::EventObject&) throw(css::uno::RuntimeException) { // nothing todo here - because we hold the frame as weak reference only } //***************************************************************************************************************** ::rtl::OUString PersistentWindowState::implst_identifyModule(const css::uno::Reference< css::lang::XMultiServiceFactory >& xSMGR , const css::uno::Reference< css::frame::XFrame >& xFrame) { ::rtl::OUString sModuleName; css::uno::Reference< css::frame::XModuleManager > xModuleManager( xSMGR->createInstance(SERVICENAME_MODULEMANAGER), css::uno::UNO_QUERY_THROW); try { sModuleName = xModuleManager->identify(xFrame); } catch(const css::uno::RuntimeException& exRun) { throw exRun; } catch(const css::uno::Exception&) { sModuleName = ::rtl::OUString(); } return sModuleName; } //***************************************************************************************************************** ::rtl::OUString PersistentWindowState::implst_getWindowStateFromConfig(const css::uno::Reference< css::lang::XMultiServiceFactory >& xSMGR , const ::rtl::OUString& sModuleName) { ::rtl::OUString sWindowState; ::rtl::OUStringBuffer sRelPathBuf(256); sRelPathBuf.appendAscii("Office/Factories/*[\""); sRelPathBuf.append (sModuleName ); sRelPathBuf.appendAscii("\"]" ); ::rtl::OUString sPackage = ::rtl::OUString::createFromAscii("org.openoffice.Setup/"); ::rtl::OUString sRelPath = sRelPathBuf.makeStringAndClear(); ::rtl::OUString sKey = ::rtl::OUString::createFromAscii("ooSetupFactoryWindowAttributes"); try { css::uno::Any aWindowState = ::comphelper::ConfigurationHelper::readDirectKey(xSMGR, sPackage, sRelPath, sKey, ::comphelper::ConfigurationHelper::E_READONLY); aWindowState >>= sWindowState; } catch(const css::uno::RuntimeException& exRun) { throw exRun; } catch(const css::uno::Exception&) { sWindowState = ::rtl::OUString(); } return sWindowState; } //***************************************************************************************************************** void PersistentWindowState::implst_setWindowStateOnConfig(const css::uno::Reference< css::lang::XMultiServiceFactory >& xSMGR , const ::rtl::OUString& sModuleName , const ::rtl::OUString& sWindowState) { ::rtl::OUStringBuffer sRelPathBuf(256); sRelPathBuf.appendAscii("Office/Factories/*[\""); sRelPathBuf.append (sModuleName ); sRelPathBuf.appendAscii("\"]" ); ::rtl::OUString sPackage = ::rtl::OUString::createFromAscii("org.openoffice.Setup/"); ::rtl::OUString sRelPath = sRelPathBuf.makeStringAndClear(); ::rtl::OUString sKey = ::rtl::OUString::createFromAscii("ooSetupFactoryWindowAttributes"); try { ::comphelper::ConfigurationHelper::writeDirectKey(xSMGR, sPackage, sRelPath, sKey, css::uno::makeAny(sWindowState), ::comphelper::ConfigurationHelper::E_STANDARD); } catch(const css::uno::RuntimeException& exRun) { throw exRun; } catch(const css::uno::Exception&) {} } //***************************************************************************************************************** ::rtl::OUString PersistentWindowState::implst_getWindowStateFromWindow(const css::uno::Reference< css::awt::XWindow >& xWindow) { ::rtl::OUString sWindowState; if (xWindow.is()) { // SOLAR SAFE -> ------------------------ ::vos::OClearableGuard aSolarLock(Application::GetSolarMutex()); Window* pWindow = VCLUnoHelper::GetWindow(xWindow); // check for system window is neccessary to guarantee correct pointer cast! if ( (pWindow ) && (pWindow->IsSystemWindow()) ) { ULONG nMask = WINDOWSTATE_MASK_ALL; nMask &= ~(WINDOWSTATE_MASK_MINIMIZED); sWindowState = B2U_ENC( ((SystemWindow*)pWindow)->GetWindowState(nMask), RTL_TEXTENCODING_UTF8); } aSolarLock.clear(); // <- SOLAR SAFE ------------------------ } return sWindowState; } //********************************************************************************************************* void PersistentWindowState::implst_setWindowStateOnWindow(const css::uno::Reference< css::awt::XWindow >& xWindow , const ::rtl::OUString& sWindowState) { if ( (!xWindow.is() ) || ( sWindowState.getLength() < 1) ) return; // SOLAR SAFE -> ------------------------ ::vos::OClearableGuard aSolarLock(Application::GetSolarMutex()); Window* pWindow = VCLUnoHelper::GetWindow(xWindow); if (!pWindow) return; // check for system and work window - its neccessary to guarantee correct pointer cast! sal_Bool bSystemWindow = pWindow->IsSystemWindow(); sal_Bool bWorkWindow = (pWindow->GetType() == WINDOW_WORKWINDOW); if (!bSystemWindow && !bWorkWindow) return; SystemWindow* pSystemWindow = (SystemWindow*)pWindow; WorkWindow* pWorkWindow = (WorkWindow* )pWindow; // dont save this special state! if (pWorkWindow->IsMinimized()) return; pSystemWindow->SetWindowState(U2B_ENC(sWindowState,RTL_TEXTENCODING_UTF8)); aSolarLock.clear(); // <- SOLAR SAFE ------------------------ } } // namespace framework <commit_msg>INTEGRATION: CWS dba23b (1.13.28); FILE MERGED 2007/06/11 09:12:52 as 1.13.28.1: #i78286# bind _beamer to isTopWindow instead of isTopFrame<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: persistentwindowstate.cxx,v $ * * $Revision: 1.14 $ * * last change: $Author: rt $ $Date: 2007-07-24 11:52:15 $ * * 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_framework.hxx" //_________________________________________________________________________________________________________________ // my own includes //_________________________________________________________________________________________________________________ #ifndef __FRAMEWORK_PATTERN_WINDOW_HXX_ #include <pattern/window.hxx> #endif #ifndef __FRAMEWORK_HELPER_PERSISTENTWINDOWSTATE_HXX_ #include <helper/persistentwindowstate.hxx> #endif #ifndef __FRAMEWORK_THREADHELP_WRITEGUARD_HXX_ #include <threadhelp/writeguard.hxx> #endif #ifndef __FRAMEWORK_THREADHELP_READGUARD_HXX_ #include <threadhelp/readguard.hxx> #endif #ifndef __FRAMEWORK_MACROS_GENERIC_HXX_ #include <macros/generic.hxx> #endif #ifndef __FRAMEWORK_SERVICES_H_ #include <services.h> #endif //_________________________________________________________________________________________________________________ // interface includes //_________________________________________________________________________________________________________________ #ifndef _COM_SUN_STAR_AWT_XWINDOW_HPP_ #include <com/sun/star/awt/XWindow.hpp> #endif #ifndef _COM_SUN_STAR_LANG_XSERVICXEINFO_HPP_ #include <com/sun/star/lang/XServiceInfo.hpp> #endif #ifndef _COM_SUN_STAR_LANG_ILLEGALARGUMENTEXCEPTION_HPP_ #include <com/sun/star/lang/IllegalArgumentException.hpp> #endif #ifndef _COM_SUN_STAR_FRAME_XMODULEMANAGER_HPP_ #include <com/sun/star/frame/XModuleManager.hpp> #endif //_________________________________________________________________________________________________________________ // other includes //_________________________________________________________________________________________________________________ #ifndef _COMPHELPER_CONFIGURATIONHELPER_HXX_ #include <comphelper/configurationhelper.hxx> #endif #ifndef _SV_WINDOW_HXX #include <vcl/window.hxx> #endif #ifndef _SV_SYSWIN_HXX #include <vcl/syswin.hxx> #endif #ifndef _TOOLKIT_HELPER_VCLUNOHELPER_HXX_ #include <toolkit/unohlp.hxx> #endif #ifndef _SV_SVAPP_HXX #include <vcl/svapp.hxx> #endif #ifndef _SV_WRKWIN_HXX #include <vcl/wrkwin.hxx> #endif //_________________________________________________________________________________________________________________ // namespace namespace framework{ //_________________________________________________________________________________________________________________ // definitions //***************************************************************************************************************** // XInterface, XTypeProvider DEFINE_XINTERFACE_4(PersistentWindowState , OWeakObject , DIRECT_INTERFACE (css::lang::XTypeProvider ), DIRECT_INTERFACE (css::lang::XInitialization ), DIRECT_INTERFACE (css::frame::XFrameActionListener ), DERIVED_INTERFACE(css::lang::XEventListener,css::frame::XFrameActionListener)) DEFINE_XTYPEPROVIDER_4(PersistentWindowState , css::lang::XTypeProvider , css::lang::XInitialization , css::frame::XFrameActionListener, css::lang::XEventListener ) //***************************************************************************************************************** PersistentWindowState::PersistentWindowState(const css::uno::Reference< css::lang::XMultiServiceFactory >& xSMGR) : ThreadHelpBase (&Application::GetSolarMutex()) , m_xSMGR (xSMGR ) , m_bWindowStateAlreadySet(sal_False ) { } //***************************************************************************************************************** PersistentWindowState::~PersistentWindowState() { } //***************************************************************************************************************** void SAL_CALL PersistentWindowState::initialize(const css::uno::Sequence< css::uno::Any >& lArguments) throw(css::uno::Exception , css::uno::RuntimeException) { // check arguments css::uno::Reference< css::frame::XFrame > xFrame; if (lArguments.getLength() < 1) throw css::lang::IllegalArgumentException( DECLARE_ASCII("Empty argument list!"), static_cast< ::cppu::OWeakObject* >(this), 1); lArguments[0] >>= xFrame; if (!xFrame.is()) throw css::lang::IllegalArgumentException( DECLARE_ASCII("No valid frame specified!"), static_cast< ::cppu::OWeakObject* >(this), 1); // SAFE -> ---------------------------------- WriteGuard aWriteLock(m_aLock); // hold the frame as weak reference(!) so it can die everytimes :-) m_xFrame = xFrame; aWriteLock.unlock(); // <- SAFE ---------------------------------- // start listening xFrame->addFrameActionListener(this); } //***************************************************************************************************************** void SAL_CALL PersistentWindowState::frameAction(const css::frame::FrameActionEvent& aEvent) throw(css::uno::RuntimeException) { // SAFE -> ---------------------------------- ReadGuard aReadLock(m_aLock); css::uno::Reference< css::lang::XMultiServiceFactory > xSMGR = m_xSMGR ; css::uno::Reference< css::frame::XFrame > xFrame(m_xFrame.get(), css::uno::UNO_QUERY); sal_Bool bRestoreWindowState = !m_bWindowStateAlreadySet; aReadLock.unlock(); // <- SAFE ---------------------------------- // frame already gone ? We hold it weak only ... if (!xFrame.is()) return; // no window -> no position and size available css::uno::Reference< css::awt::XWindow > xWindow = xFrame->getContainerWindow(); if (!xWindow.is()) return; // unknown module -> no configuration available! ::rtl::OUString sModuleName = PersistentWindowState::implst_identifyModule(xSMGR, xFrame); if (!sModuleName.getLength()) return; switch(aEvent.Action) { case css::frame::FrameAction_COMPONENT_ATTACHED : { if (bRestoreWindowState) { ::rtl::OUString sWindowState = PersistentWindowState::implst_getWindowStateFromConfig(xSMGR, sModuleName); PersistentWindowState::implst_setWindowStateOnWindow(xWindow,sWindowState); // SAFE -> ---------------------------------- WriteGuard aWriteLock(m_aLock); m_bWindowStateAlreadySet = sal_True; aWriteLock.unlock(); // <- SAFE ---------------------------------- } } break; case css::frame::FrameAction_COMPONENT_REATTACHED : { // nothing todo here, because its not allowed to change position and size // of an alredy existing frame! } break; case css::frame::FrameAction_COMPONENT_DETACHING : { ::rtl::OUString sWindowState = PersistentWindowState::implst_getWindowStateFromWindow(xWindow); PersistentWindowState::implst_setWindowStateOnConfig(xSMGR, sModuleName, sWindowState); } break; default: break; } } //***************************************************************************************************************** void SAL_CALL PersistentWindowState::disposing(const css::lang::EventObject&) throw(css::uno::RuntimeException) { // nothing todo here - because we hold the frame as weak reference only } //***************************************************************************************************************** ::rtl::OUString PersistentWindowState::implst_identifyModule(const css::uno::Reference< css::lang::XMultiServiceFactory >& xSMGR , const css::uno::Reference< css::frame::XFrame >& xFrame) { ::rtl::OUString sModuleName; css::uno::Reference< css::frame::XModuleManager > xModuleManager( xSMGR->createInstance(SERVICENAME_MODULEMANAGER), css::uno::UNO_QUERY_THROW); try { sModuleName = xModuleManager->identify(xFrame); } catch(const css::uno::RuntimeException& exRun) { throw exRun; } catch(const css::uno::Exception&) { sModuleName = ::rtl::OUString(); } return sModuleName; } //***************************************************************************************************************** ::rtl::OUString PersistentWindowState::implst_getWindowStateFromConfig(const css::uno::Reference< css::lang::XMultiServiceFactory >& xSMGR , const ::rtl::OUString& sModuleName) { ::rtl::OUString sWindowState; ::rtl::OUStringBuffer sRelPathBuf(256); sRelPathBuf.appendAscii("Office/Factories/*[\""); sRelPathBuf.append (sModuleName ); sRelPathBuf.appendAscii("\"]" ); ::rtl::OUString sPackage = ::rtl::OUString::createFromAscii("org.openoffice.Setup/"); ::rtl::OUString sRelPath = sRelPathBuf.makeStringAndClear(); ::rtl::OUString sKey = ::rtl::OUString::createFromAscii("ooSetupFactoryWindowAttributes"); try { css::uno::Any aWindowState = ::comphelper::ConfigurationHelper::readDirectKey(xSMGR, sPackage, sRelPath, sKey, ::comphelper::ConfigurationHelper::E_READONLY); aWindowState >>= sWindowState; } catch(const css::uno::RuntimeException& exRun) { throw exRun; } catch(const css::uno::Exception&) { sWindowState = ::rtl::OUString(); } return sWindowState; } //***************************************************************************************************************** void PersistentWindowState::implst_setWindowStateOnConfig(const css::uno::Reference< css::lang::XMultiServiceFactory >& xSMGR , const ::rtl::OUString& sModuleName , const ::rtl::OUString& sWindowState) { ::rtl::OUStringBuffer sRelPathBuf(256); sRelPathBuf.appendAscii("Office/Factories/*[\""); sRelPathBuf.append (sModuleName ); sRelPathBuf.appendAscii("\"]" ); ::rtl::OUString sPackage = ::rtl::OUString::createFromAscii("org.openoffice.Setup/"); ::rtl::OUString sRelPath = sRelPathBuf.makeStringAndClear(); ::rtl::OUString sKey = ::rtl::OUString::createFromAscii("ooSetupFactoryWindowAttributes"); try { ::comphelper::ConfigurationHelper::writeDirectKey(xSMGR, sPackage, sRelPath, sKey, css::uno::makeAny(sWindowState), ::comphelper::ConfigurationHelper::E_STANDARD); } catch(const css::uno::RuntimeException& exRun) { throw exRun; } catch(const css::uno::Exception&) {} } //***************************************************************************************************************** ::rtl::OUString PersistentWindowState::implst_getWindowStateFromWindow(const css::uno::Reference< css::awt::XWindow >& xWindow) { ::rtl::OUString sWindowState; if (xWindow.is()) { // SOLAR SAFE -> ------------------------ ::vos::OClearableGuard aSolarLock(Application::GetSolarMutex()); Window* pWindow = VCLUnoHelper::GetWindow(xWindow); // check for system window is neccessary to guarantee correct pointer cast! if ( (pWindow ) && (pWindow->IsSystemWindow()) ) { ULONG nMask = WINDOWSTATE_MASK_ALL; nMask &= ~(WINDOWSTATE_MASK_MINIMIZED); sWindowState = B2U_ENC( ((SystemWindow*)pWindow)->GetWindowState(nMask), RTL_TEXTENCODING_UTF8); } aSolarLock.clear(); // <- SOLAR SAFE ------------------------ } return sWindowState; } //********************************************************************************************************* void PersistentWindowState::implst_setWindowStateOnWindow(const css::uno::Reference< css::awt::XWindow >& xWindow , const ::rtl::OUString& sWindowState) { if ( (!xWindow.is() ) || ( sWindowState.getLength() < 1) ) return; // SOLAR SAFE -> ------------------------ ::vos::OClearableGuard aSolarLock(Application::GetSolarMutex()); Window* pWindow = VCLUnoHelper::GetWindow(xWindow); if (!pWindow) return; // check for system and work window - its neccessary to guarantee correct pointer cast! sal_Bool bSystemWindow = pWindow->IsSystemWindow(); sal_Bool bWorkWindow = (pWindow->GetType() == WINDOW_WORKWINDOW); if (!bSystemWindow && !bWorkWindow) return; SystemWindow* pSystemWindow = (SystemWindow*)pWindow; WorkWindow* pWorkWindow = (WorkWindow* )pWindow; // dont save this special state! if (pWorkWindow->IsMinimized()) return; pSystemWindow->SetWindowState(U2B_ENC(sWindowState,RTL_TEXTENCODING_UTF8)); aSolarLock.clear(); // <- SOLAR SAFE ------------------------ } } // namespace framework <|endoftext|>
<commit_before>#include <stdexcept> #include <stan/math/matrix/rank.hpp> #include <gtest/gtest.h> template <typename T> void test_rank() { using stan::math::rank; T c(1); c[0] = 1.7; EXPECT_EQ( rank(c,1) , 0 ); EXPECT_THROW( rank(c,0), std::out_of_range); EXPECT_THROW( rank(c,2), std::out_of_range); T e(2); e[0] = 5.9; e[1] = -1.2; EXPECT_EQ( rank(e,1) , 1 ); EXPECT_EQ( rank(e,2) , 0 ); EXPECT_THROW( rank(e,0), std::out_of_range); EXPECT_THROW( rank(e,3), std::out_of_range); T g(3); g[0] = 5.9; g[1] = -1.2; g[2] = 192.13456; EXPECT_EQ( rank(g,1) , 1 ); EXPECT_EQ( rank(g,2) , 0 ); EXPECT_EQ( rank(g,3) , 2 ); EXPECT_THROW( rank(g,0), std::out_of_range); EXPECT_THROW( rank(g,4), std::out_of_range); T z; EXPECT_THROW( rank(z,0), std::out_of_range); EXPECT_THROW( rank(z,1), std::out_of_range); EXPECT_THROW( rank(z,2), std::out_of_range); } TEST(MathMatrix,rank) { using stan::math::rank; test_rank<std::vector<int> >(); test_rank<std::vector<double> >(); test_rank<Eigen::Matrix<double,Eigen::Dynamic,1> >(); test_rank<Eigen::Matrix<double,1,Eigen::Dynamic> >(); }<commit_msg>Fixed rank(v,s) unit test warning of implicit convertion from double to int.<commit_after>#include <stdexcept> #include <stan/math/matrix/rank.hpp> #include <gtest/gtest.h> template <typename T> void test_rank() { using stan::math::rank; T c(1); c[0] = 1.7; EXPECT_EQ(rank(c,1), 0); EXPECT_THROW(rank(c,0), std::out_of_range); EXPECT_THROW(rank(c,2), std::out_of_range); T e(2); e[0] = 5.9; e[1] = -1.2; EXPECT_EQ(rank(e,1), 1); EXPECT_EQ(rank(e,2), 0); EXPECT_THROW(rank(e,0), std::out_of_range); EXPECT_THROW(rank(e,3), std::out_of_range); T g(3); g[0] = 5.9; g[1] = -1.2; g[2] = 192.13456; EXPECT_EQ(rank(g,1), 1); EXPECT_EQ(rank(g,2), 0); EXPECT_EQ(rank(g,3), 2); EXPECT_THROW(rank(g,0), std::out_of_range); EXPECT_THROW(rank(g,4), std::out_of_range); T z; EXPECT_THROW(rank(z,0), std::out_of_range); EXPECT_THROW(rank(z,1), std::out_of_range); EXPECT_THROW(rank(z,2), std::out_of_range); } template <typename T> void test_rank_int() { using stan::math::rank; T c(1); c[0] = 1; EXPECT_EQ(rank(c,1), 0); EXPECT_THROW(rank(c,0), std::out_of_range); EXPECT_THROW(rank(c,2), std::out_of_range); T e(2); e[0] = 5; e[1] = -1; EXPECT_EQ(rank(e,1), 1); EXPECT_EQ(rank(e,2), 0); EXPECT_THROW(rank(e,0), std::out_of_range); EXPECT_THROW(rank(e,3), std::out_of_range); T g(3); g[0] = 5; g[1] = -1; g[2] = 192; EXPECT_EQ(rank(g,1), 1); EXPECT_EQ(rank(g,2), 0); EXPECT_EQ(rank(g,3), 2); EXPECT_THROW(rank(g,0), std::out_of_range); EXPECT_THROW(rank(g,4), std::out_of_range); T z; EXPECT_THROW(rank(z,0), std::out_of_range); EXPECT_THROW(rank(z,1), std::out_of_range); EXPECT_THROW(rank(z,2), std::out_of_range); } TEST(MathMatrix,rank) { using stan::math::rank; test_rank< std::vector<double> >(); test_rank< Eigen::Matrix<double,Eigen::Dynamic,1> >(); test_rank< Eigen::Matrix<double,1,Eigen::Dynamic> >(); test_rank_int< std::vector<int> >(); test_rank_int< std::vector<double> >(); test_rank_int< Eigen::Matrix<double,Eigen::Dynamic,1> >(); test_rank_int< Eigen::Matrix<double,1,Eigen::Dynamic> >(); }<|endoftext|>
<commit_before>// Copyright (c) 2020 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 "net/third_party/quiche/src/quic/core/quic_network_blackhole_detector.h" #include "net/third_party/quiche/src/quic/core/quic_constants.h" namespace quic { namespace { class AlarmDelegate : public QuicAlarm::Delegate { public: explicit AlarmDelegate(QuicNetworkBlackholeDetector* detector) : detector_(detector) {} AlarmDelegate(const AlarmDelegate&) = delete; AlarmDelegate& operator=(const AlarmDelegate&) = delete; void OnAlarm() override { detector_->OnAlarm(); } private: QuicNetworkBlackholeDetector* detector_; }; } // namespace QuicNetworkBlackholeDetector::QuicNetworkBlackholeDetector( Delegate* delegate, QuicConnectionArena* arena, QuicAlarmFactory* alarm_factory) : delegate_(delegate), alarm_( alarm_factory->CreateAlarm(arena->New<AlarmDelegate>(this), arena)) {} void QuicNetworkBlackholeDetector::OnAlarm() { QuicTime next_deadline = GetEarliestDeadline(); if (!next_deadline.IsInitialized()) { QUIC_BUG << "BlackholeDetector alarm fired unexpectedly"; return; } QUIC_DLOG(INFO) << "BlackholeDetector alarm firing. next_deadline:" << next_deadline << ", path_degrading_deadline_:" << path_degrading_deadline_ << ", path_mtu_reduction_deadline_:" << path_mtu_reduction_deadline_ << ", blackhole_deadline_:" << blackhole_deadline_; if (path_degrading_deadline_ == next_deadline) { path_degrading_deadline_ = QuicTime::Zero(); delegate_->OnPathDegradingDetected(); } if (path_mtu_reduction_deadline_ == next_deadline) { path_mtu_reduction_deadline_ = QuicTime::Zero(); delegate_->OnPathMtuReductionDetected(); } if (blackhole_deadline_ == next_deadline) { blackhole_deadline_ = QuicTime::Zero(); delegate_->OnBlackholeDetected(); } UpdateAlarm(); } void QuicNetworkBlackholeDetector::StopDetection() { alarm_->Cancel(); path_degrading_deadline_ = QuicTime::Zero(); blackhole_deadline_ = QuicTime::Zero(); path_mtu_reduction_deadline_ = QuicTime::Zero(); } void QuicNetworkBlackholeDetector::RestartDetection( QuicTime path_degrading_deadline, QuicTime blackhole_deadline, QuicTime path_mtu_reduction_deadline) { path_degrading_deadline_ = path_degrading_deadline; blackhole_deadline_ = blackhole_deadline; path_mtu_reduction_deadline_ = path_mtu_reduction_deadline; QUIC_BUG_IF(blackhole_deadline_.IsInitialized() && blackhole_deadline_ != GetLastDeadline()) << "Blackhole detection deadline should be the last deadline."; UpdateAlarm(); } QuicTime QuicNetworkBlackholeDetector::GetEarliestDeadline() const { QuicTime result = QuicTime::Zero(); for (QuicTime t : {path_degrading_deadline_, blackhole_deadline_, path_mtu_reduction_deadline_}) { if (!t.IsInitialized()) { continue; } if (!result.IsInitialized() || t < result) { result = t; } } return result; } QuicTime QuicNetworkBlackholeDetector::GetLastDeadline() const { return std::max({path_degrading_deadline_, blackhole_deadline_, path_mtu_reduction_deadline_}); } void QuicNetworkBlackholeDetector::UpdateAlarm() const { QuicTime next_deadline = GetEarliestDeadline(); QUIC_DLOG(INFO) << "Updating alarm. next_deadline:" << next_deadline << ", path_degrading_deadline_:" << path_degrading_deadline_ << ", path_mtu_reduction_deadline_:" << path_mtu_reduction_deadline_ << ", blackhole_deadline_:" << blackhole_deadline_; alarm_->Update(next_deadline, kAlarmGranularity); } bool QuicNetworkBlackholeDetector::IsDetectionInProgress() const { return alarm_->IsSet(); } } // namespace quic <commit_msg>Reduce noisy log message to VLOG rather than LOG(INFO).<commit_after>// Copyright (c) 2020 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 "net/third_party/quiche/src/quic/core/quic_network_blackhole_detector.h" #include "net/third_party/quiche/src/quic/core/quic_constants.h" namespace quic { namespace { class AlarmDelegate : public QuicAlarm::Delegate { public: explicit AlarmDelegate(QuicNetworkBlackholeDetector* detector) : detector_(detector) {} AlarmDelegate(const AlarmDelegate&) = delete; AlarmDelegate& operator=(const AlarmDelegate&) = delete; void OnAlarm() override { detector_->OnAlarm(); } private: QuicNetworkBlackholeDetector* detector_; }; } // namespace QuicNetworkBlackholeDetector::QuicNetworkBlackholeDetector( Delegate* delegate, QuicConnectionArena* arena, QuicAlarmFactory* alarm_factory) : delegate_(delegate), alarm_( alarm_factory->CreateAlarm(arena->New<AlarmDelegate>(this), arena)) {} void QuicNetworkBlackholeDetector::OnAlarm() { QuicTime next_deadline = GetEarliestDeadline(); if (!next_deadline.IsInitialized()) { QUIC_BUG << "BlackholeDetector alarm fired unexpectedly"; return; } QUIC_DVLOG(1) << "BlackholeDetector alarm firing. next_deadline:" << next_deadline << ", path_degrading_deadline_:" << path_degrading_deadline_ << ", path_mtu_reduction_deadline_:" << path_mtu_reduction_deadline_ << ", blackhole_deadline_:" << blackhole_deadline_; if (path_degrading_deadline_ == next_deadline) { path_degrading_deadline_ = QuicTime::Zero(); delegate_->OnPathDegradingDetected(); } if (path_mtu_reduction_deadline_ == next_deadline) { path_mtu_reduction_deadline_ = QuicTime::Zero(); delegate_->OnPathMtuReductionDetected(); } if (blackhole_deadline_ == next_deadline) { blackhole_deadline_ = QuicTime::Zero(); delegate_->OnBlackholeDetected(); } UpdateAlarm(); } void QuicNetworkBlackholeDetector::StopDetection() { alarm_->Cancel(); path_degrading_deadline_ = QuicTime::Zero(); blackhole_deadline_ = QuicTime::Zero(); path_mtu_reduction_deadline_ = QuicTime::Zero(); } void QuicNetworkBlackholeDetector::RestartDetection( QuicTime path_degrading_deadline, QuicTime blackhole_deadline, QuicTime path_mtu_reduction_deadline) { path_degrading_deadline_ = path_degrading_deadline; blackhole_deadline_ = blackhole_deadline; path_mtu_reduction_deadline_ = path_mtu_reduction_deadline; QUIC_BUG_IF(blackhole_deadline_.IsInitialized() && blackhole_deadline_ != GetLastDeadline()) << "Blackhole detection deadline should be the last deadline."; UpdateAlarm(); } QuicTime QuicNetworkBlackholeDetector::GetEarliestDeadline() const { QuicTime result = QuicTime::Zero(); for (QuicTime t : {path_degrading_deadline_, blackhole_deadline_, path_mtu_reduction_deadline_}) { if (!t.IsInitialized()) { continue; } if (!result.IsInitialized() || t < result) { result = t; } } return result; } QuicTime QuicNetworkBlackholeDetector::GetLastDeadline() const { return std::max({path_degrading_deadline_, blackhole_deadline_, path_mtu_reduction_deadline_}); } void QuicNetworkBlackholeDetector::UpdateAlarm() const { QuicTime next_deadline = GetEarliestDeadline(); QUIC_DVLOG(1) << "Updating alarm. next_deadline:" << next_deadline << ", path_degrading_deadline_:" << path_degrading_deadline_ << ", path_mtu_reduction_deadline_:" << path_mtu_reduction_deadline_ << ", blackhole_deadline_:" << blackhole_deadline_; alarm_->Update(next_deadline, kAlarmGranularity); } bool QuicNetworkBlackholeDetector::IsDetectionInProgress() const { return alarm_->IsSet(); } } // namespace quic <|endoftext|>
<commit_before>#ifndef __CALLBACK_OBJECT_HPP_INCLUDED #define __CALLBACK_OBJECT_HPP_INCLUDED #include "cpp/ylikuutio/common/any_value.hpp" #include "callback_engine.hpp" #include "callback_parameter.hpp" #include "cpp/ylikuutio/common/globals.hpp" // Include standard headers #include <cmath> // NAN #include <string> // std::string #include <unordered_map> // std::unordered_map #include <vector> // std::vector namespace callback_system { class CallbackObject { // CallbackObject is an object that contains a single callback. public: // constructor. CallbackObject(callback_system::CallbackEngine* callback_engine_pointer); // constructor. CallbackObject(InputParametersToAnyValueCallback callback, callback_system::CallbackEngine* callback_engine_pointer); // destructor. ~CallbackObject(); // add reference to an input variable. // this does not store the value to an appropriate hashmap. // storing the value must be done before or after this call. // each type has its own namespace! // void add_input_parameter(std::string name, AnyValue any_value, bool is_reference); friend class CallbackEngine; private: // execute this callback. AnyValue execute(); // this method sets a callback parameter pointer. void set_callback_parameter_pointer(uint32_t childID, void* parent_pointer); callback_system::CallbackEngine* callback_engine_pointer; // pointer to the callback engine. void bind_to_parent(); std::string output_type; std::string output_variable_name; std::vector<callback_system::CallbackParameter*> callback_parameter_pointer_vector; InputParametersToAnyValueCallback callback; }; } #endif <commit_msg>`uint32_t childID`.<commit_after>#ifndef __CALLBACK_OBJECT_HPP_INCLUDED #define __CALLBACK_OBJECT_HPP_INCLUDED #include "cpp/ylikuutio/common/any_value.hpp" #include "callback_engine.hpp" #include "callback_parameter.hpp" #include "cpp/ylikuutio/common/globals.hpp" // Include standard headers #include <cmath> // NAN #include <string> // std::string #include <unordered_map> // std::unordered_map #include <vector> // std::vector namespace callback_system { class CallbackObject { // CallbackObject is an object that contains a single callback. public: // constructor. CallbackObject(callback_system::CallbackEngine* callback_engine_pointer); // constructor. CallbackObject(InputParametersToAnyValueCallback callback, callback_system::CallbackEngine* callback_engine_pointer); // destructor. ~CallbackObject(); // add reference to an input variable. // this does not store the value to an appropriate hashmap. // storing the value must be done before or after this call. // each type has its own namespace! // void add_input_parameter(std::string name, AnyValue any_value, bool is_reference); friend class CallbackEngine; private: // execute this callback. AnyValue execute(); // this method sets a callback parameter pointer. void set_callback_parameter_pointer(uint32_t childID, void* parent_pointer); callback_system::CallbackEngine* callback_engine_pointer; // pointer to the callback engine. void bind_to_parent(); uint32_t childID; // callback object ID, returned by `callback_system::CallbackEngine->get_callback_objectID()`. std::string output_type; std::string output_variable_name; std::vector<callback_system::CallbackParameter*> callback_parameter_pointer_vector; InputParametersToAnyValueCallback callback; }; } #endif <|endoftext|>
<commit_before>#include <aleph/topology/io/LexicographicTriangulation.hh> #include <aleph/persistentHomology/Calculation.hh> #include <aleph/persistentHomology/PhiPersistence.hh> #include <aleph/topology/BarycentricSubdivision.hh> #include <aleph/topology/Simplex.hh> #include <aleph/topology/SimplicialComplex.hh> #include <aleph/topology/Skeleton.hh> #include <algorithm> #include <iostream> #include <string> #include <vector> using DataType = bool; using VertexType = unsigned short; using Simplex = aleph::topology::Simplex<DataType, VertexType>; using SimplicialComplex = aleph::topology::SimplicialComplex<Simplex>; /** Models a signature consisting of Betti numbers, i.e. a set of natural numbers. Signatures are comparable and are ordered lexicographically, i.e. in the manner one would expect. */ class Signature { public: template <class InputIterator> Signature( InputIterator begin, InputIterator end ) : _betti( begin, end ) { } bool operator<( const Signature& other ) const noexcept { return std::lexicographical_compare( _betti.begin(), _betti.end(), other._betti.begin(), other._betti.end() ); } long eulerCharacteristic() const noexcept { long chi = 0; bool s = true; for( auto&& betti : _betti ) { chi = s ? chi + betti : chi - betti; s = !s; } return chi; } using const_iterator = typename std::vector<std::size_t>::const_iterator; const_iterator begin() const noexcept { return _betti.begin(); } const_iterator end() const noexcept { return _betti.end() ; } private: std::vector<std::size_t> _betti; }; std::ostream& operator<<( std::ostream& o, const Signature& s ) { o << "("; for( auto it = s.begin(); it != s.end(); ++it ) { if( it != s.begin() ) o << ","; o << *it; } o << ")"; return o; } /** Converts a vector of persistence diagrams into a Betti signature. The maximum dimension needs to be specified in order to ensure that empty or missing persistence diagrams can still be handled correctly. */ template <class PersistenceDiagram> Signature makeSignature( const std::vector<PersistenceDiagram>& diagrams, std::size_t D ) { std::vector<std::size_t> bettiNumbers( D+1 ); for( auto&& diagram : diagrams ) { auto d = diagram.dimension(); auto b = diagram.betti(); bettiNumbers.at(d) = b; } return Signature( bettiNumbers.begin(), bettiNumbers.end() ); } /** Enumerates all possible perversities for a given dimension. One could say that this function is as wicked as possible. */ std::vector<aleph::Perversity> getPerversities( unsigned dimension ) { std::vector<aleph::Perversity> perversities; std::map< unsigned, std::vector<int> > possibleValues; for( unsigned d = 0; d < dimension; d++ ) { // Note that no shift in dimensions is required: as the dimension is // zero-based, the maximum value of the perversity in dimension zero // is zero. This is identical to demanding // // -1 \leq p_k \leq k-1 // // for k = [1,...,d]. for( int k = -1; k <= static_cast<int>( d ); k++ ) possibleValues[d].push_back( k ); } std::size_t numCombinations = 1; for( auto&& pair : possibleValues ) numCombinations *= pair.second.size(); // Stores the current index that was reached while traversing all // possible values of the perversity. The idea is that to add one // to the last index upon adding a new value. If the index is too // large, it goes back to zero and the previous index is modified // by one. std::vector<std::size_t> indices( possibleValues.size() ); for( std::size_t i = 0; i < numCombinations; i++ ) { std::vector<int> values; for( unsigned d = 0; d < dimension; d++ ) { auto index = indices.at(d); values.emplace_back( possibleValues.at(d).at(index) ); } // Always increase the last used index by one. If an overflow // occurs, the previous indices are updated as well. { auto last = dimension - 1; indices.at(last) = indices.at(last) + 1; // Check & propagate potential overflows to the previous indices // in the range. The index vector is reset to zero only when all // combinations have been visited. if( indices.at(last) >= possibleValues.at(last).size() ) { indices.at(last) = 0; for( unsigned d = 1; d < dimension; d++ ) { auto D = dimension - 1 - d; indices.at(D) = indices.at(D) + 1; if( indices.at(D) < possibleValues.at(D).size() ) break; else indices.at(D) = 0; } } } perversities.emplace_back( aleph::Perversity( values.begin(), values.end() ) ); } return perversities; } int main(int argc, char* argv[]) { if( argc <= 1 ) return -1; std::string filename = argv[1]; std::vector<SimplicialComplex> simplicialComplexes; aleph::topology::io::LexicographicTriangulationReader reader; reader( filename, simplicialComplexes ); // Create missing faces ---------------------------------------------- // // The triangulations are only specified by their top-level simplices, // so they need to be converted before being valid inputs for homology // calculations. for( auto&& K : simplicialComplexes ) { K.createMissingFaces(); K.sort(); } // Calculate homology ------------------------------------------------ // // We are only interested in the Betti numbers of the diagrams here as // the triangulations are not endowed with any weights or values. for( auto&& K : simplicialComplexes ) { bool dualize = true; bool includeAllUnpairedCreators = true; auto diagrams = aleph::calculatePersistenceDiagrams( K, dualize, includeAllUnpairedCreators ); auto signature = makeSignature( diagrams, K.dimension() ); std::cout << signature << "\t" << signature.eulerCharacteristic() << "\n"; } // Calculate intersection homology ----------------------------------- // // The basic idea is to first decompose the given simplicial complex // into its skeletons. These skeletons then serve as a filtration of // the complex. In addition to this, we also calculate a barycentric // subdivision of the simplicial complex. The triangulation is hence // always "flag-like" following the paper: // // Elementary construction of perverse sheaves // Robert MacPhersonl and Kari Vilonen // Inventiones Mathematicae, Volume 84, pp. 403--435, 1986 // // As a last step, we iterate over all possible perversities for the // given triangulation and calculate their intersection homology. std::vector< std::vector<Signature> > allIntersectionHomologySignatures; allIntersectionHomologySignatures.reserve( simplicialComplexes.size() ); for( auto&& K : simplicialComplexes ) { std::vector<SimplicialComplex> skeletons; skeletons.reserve( K.dimension() + 1 ); aleph::topology::Skeleton skeleton; for( std::size_t d = 0; d <= K.dimension(); d++ ) skeletons.emplace_back( skeleton( d, K ) ); aleph::topology::BarycentricSubdivision subdivision; auto L = subdivision( K ); // TODO: this is not optimal because the simplicial complexes may // share the same dimensionality. auto perversities = getPerversities( static_cast<unsigned>( K.dimension() ) ); std::vector<Signature> signatures; signatures.reserve( perversities.size() ); for( auto&& perversity : perversities ) { auto diagrams = aleph::calculateIntersectionHomology( L, skeletons, perversity ); auto signature = makeSignature( diagrams, K.dimension() ); std::cout << signature << " " << std::flush; signatures.push_back( signature ); } std::sort( signatures.begin(), signatures.end() ); allIntersectionHomologySignatures.emplace_back( signatures ); std::cout << "\n"; } } <commit_msg>Preparing JSON output format<commit_after>#include <aleph/topology/io/LexicographicTriangulation.hh> #include <aleph/persistentHomology/Calculation.hh> #include <aleph/persistentHomology/PhiPersistence.hh> #include <aleph/topology/BarycentricSubdivision.hh> #include <aleph/topology/Simplex.hh> #include <aleph/topology/SimplicialComplex.hh> #include <aleph/topology/Skeleton.hh> #include <algorithm> #include <iostream> #include <string> #include <vector> using DataType = bool; using VertexType = unsigned short; using Simplex = aleph::topology::Simplex<DataType, VertexType>; using SimplicialComplex = aleph::topology::SimplicialComplex<Simplex>; /** Models a signature consisting of Betti numbers, i.e. a set of natural numbers. Signatures are comparable and are ordered lexicographically, i.e. in the manner one would expect. */ class Signature { public: template <class InputIterator> Signature( InputIterator begin, InputIterator end ) : _betti( begin, end ) { } bool operator<( const Signature& other ) const noexcept { return std::lexicographical_compare( _betti.begin(), _betti.end(), other._betti.begin(), other._betti.end() ); } long eulerCharacteristic() const noexcept { long chi = 0; bool s = true; for( auto&& betti : _betti ) { chi = s ? chi + betti : chi - betti; s = !s; } return chi; } using const_iterator = typename std::vector<std::size_t>::const_iterator; const_iterator begin() const noexcept { return _betti.begin(); } const_iterator end() const noexcept { return _betti.end() ; } private: std::vector<std::size_t> _betti; }; std::ostream& operator<<( std::ostream& o, const Signature& s ) { o << "["; for( auto it = s.begin(); it != s.end(); ++it ) { if( it != s.begin() ) o << ","; o << *it; } o << "]"; return o; } /** Converts a vector of persistence diagrams into a Betti signature. The maximum dimension needs to be specified in order to ensure that empty or missing persistence diagrams can still be handled correctly. */ template <class PersistenceDiagram> Signature makeSignature( const std::vector<PersistenceDiagram>& diagrams, std::size_t D ) { std::vector<std::size_t> bettiNumbers( D+1 ); for( auto&& diagram : diagrams ) { auto d = diagram.dimension(); auto b = diagram.betti(); bettiNumbers.at(d) = b; } return Signature( bettiNumbers.begin(), bettiNumbers.end() ); } /** Enumerates all possible perversities for a given dimension. One could say that this function is as wicked as possible. */ std::vector<aleph::Perversity> getPerversities( unsigned dimension ) { std::vector<aleph::Perversity> perversities; std::map< unsigned, std::vector<int> > possibleValues; for( unsigned d = 0; d < dimension; d++ ) { // Note that no shift in dimensions is required: as the dimension is // zero-based, the maximum value of the perversity in dimension zero // is zero. This is identical to demanding // // -1 \leq p_k \leq k-1 // // for k = [1,...,d]. for( int k = -1; k <= static_cast<int>( d ); k++ ) possibleValues[d].push_back( k ); } std::size_t numCombinations = 1; for( auto&& pair : possibleValues ) numCombinations *= pair.second.size(); // Stores the current index that was reached while traversing all // possible values of the perversity. The idea is that to add one // to the last index upon adding a new value. If the index is too // large, it goes back to zero and the previous index is modified // by one. std::vector<std::size_t> indices( possibleValues.size() ); for( std::size_t i = 0; i < numCombinations; i++ ) { std::vector<int> values; for( unsigned d = 0; d < dimension; d++ ) { auto index = indices.at(d); values.emplace_back( possibleValues.at(d).at(index) ); } // Always increase the last used index by one. If an overflow // occurs, the previous indices are updated as well. { auto last = dimension - 1; indices.at(last) = indices.at(last) + 1; // Check & propagate potential overflows to the previous indices // in the range. The index vector is reset to zero only when all // combinations have been visited. if( indices.at(last) >= possibleValues.at(last).size() ) { indices.at(last) = 0; for( unsigned d = 1; d < dimension; d++ ) { auto D = dimension - 1 - d; indices.at(D) = indices.at(D) + 1; if( indices.at(D) < possibleValues.at(D).size() ) break; else indices.at(D) = 0; } } } perversities.emplace_back( aleph::Perversity( values.begin(), values.end() ) ); } return perversities; } int main(int argc, char* argv[]) { if( argc <= 1 ) return -1; std::string filename = argv[1]; std::vector<SimplicialComplex> simplicialComplexes; aleph::topology::io::LexicographicTriangulationReader reader; reader( filename, simplicialComplexes ); // Create missing faces ---------------------------------------------- // // The triangulations are only specified by their top-level simplices, // so they need to be converted before being valid inputs for homology // calculations. for( auto&& K : simplicialComplexes ) { K.createMissingFaces(); K.sort(); } // Calculate homology ------------------------------------------------ // // We are only interested in the Betti numbers of the diagrams here as // the triangulations are not endowed with any weights or values. for( auto&& K : simplicialComplexes ) { std::cout << "{\n"; bool dualize = true; bool includeAllUnpairedCreators = true; auto diagrams = aleph::calculatePersistenceDiagrams( K, dualize, includeAllUnpairedCreators ); auto signature = makeSignature( diagrams, K.dimension() ); std::cout << " " << "betti:" << " " << signature << "\n" << " " << "euler:" << " " << signature.eulerCharacteristic() << "\n"; std::cout << "}\n"; } // Calculate intersection homology ----------------------------------- // // The basic idea is to first decompose the given simplicial complex // into its skeletons. These skeletons then serve as a filtration of // the complex. In addition to this, we also calculate a barycentric // subdivision of the simplicial complex. The triangulation is hence // always "flag-like" following the paper: // // Elementary construction of perverse sheaves // Robert MacPhersonl and Kari Vilonen // Inventiones Mathematicae, Volume 84, pp. 403--435, 1986 // // As a last step, we iterate over all possible perversities for the // given triangulation and calculate their intersection homology. std::vector< std::vector<Signature> > allIntersectionHomologySignatures; allIntersectionHomologySignatures.reserve( simplicialComplexes.size() ); for( auto&& K : simplicialComplexes ) { std::vector<SimplicialComplex> skeletons; skeletons.reserve( K.dimension() + 1 ); aleph::topology::Skeleton skeleton; for( std::size_t d = 0; d <= K.dimension(); d++ ) skeletons.emplace_back( skeleton( d, K ) ); aleph::topology::BarycentricSubdivision subdivision; auto L = subdivision( K ); // TODO: this is not optimal because the simplicial complexes may // share the same dimensionality. auto perversities = getPerversities( static_cast<unsigned>( K.dimension() ) ); std::vector<Signature> signatures; signatures.reserve( perversities.size() ); for( auto&& perversity : perversities ) { auto diagrams = aleph::calculateIntersectionHomology( L, skeletons, perversity ); auto signature = makeSignature( diagrams, K.dimension() ); std::cout << signature << " " << std::flush; signatures.push_back( signature ); } std::sort( signatures.begin(), signatures.end() ); allIntersectionHomologySignatures.emplace_back( signatures ); std::cout << "\n"; } } <|endoftext|>
<commit_before>// Copyright (c) 2012-2019 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 <util/system.h> #include <test/util/setup_common.h> #include <memory> #include <boost/test/unit_test.hpp> BOOST_FIXTURE_TEST_SUITE(allocator_tests, BasicTestingSetup) BOOST_AUTO_TEST_CASE(arena_tests) { // Fake memory base address for testing // without actually using memory. void *synth_base = reinterpret_cast<void*>(0x08000000); const size_t synth_size = 1024*1024; Arena b(synth_base, synth_size, 16); void *chunk = b.alloc(1000); #ifdef ARENA_DEBUG b.walk(); #endif BOOST_CHECK(chunk != nullptr); BOOST_CHECK(b.stats().used == 1008); // Aligned to 16 BOOST_CHECK(b.stats().total == synth_size); // Nothing has disappeared? b.free(chunk); #ifdef ARENA_DEBUG b.walk(); #endif BOOST_CHECK(b.stats().used == 0); BOOST_CHECK(b.stats().free == synth_size); try { // Test exception on double-free b.free(chunk); BOOST_CHECK(0); } catch(std::runtime_error &) { } void *a0 = b.alloc(128); void *a1 = b.alloc(256); void *a2 = b.alloc(512); BOOST_CHECK(b.stats().used == 896); BOOST_CHECK(b.stats().total == synth_size); #ifdef ARENA_DEBUG b.walk(); #endif b.free(a0); #ifdef ARENA_DEBUG b.walk(); #endif BOOST_CHECK(b.stats().used == 768); b.free(a1); BOOST_CHECK(b.stats().used == 512); void *a3 = b.alloc(128); #ifdef ARENA_DEBUG b.walk(); #endif BOOST_CHECK(b.stats().used == 640); b.free(a2); BOOST_CHECK(b.stats().used == 128); b.free(a3); BOOST_CHECK(b.stats().used == 0); BOOST_CHECK_EQUAL(b.stats().chunks_used, 0U); BOOST_CHECK(b.stats().total == synth_size); BOOST_CHECK(b.stats().free == synth_size); BOOST_CHECK_EQUAL(b.stats().chunks_free, 1U); std::vector<void*> addr; BOOST_CHECK(b.alloc(0) == nullptr); // allocating 0 always returns nullptr #ifdef ARENA_DEBUG b.walk(); #endif // Sweeping allocate all memory for (int x=0; x<1024; ++x) addr.push_back(b.alloc(1024)); BOOST_CHECK(b.stats().free == 0); BOOST_CHECK(b.alloc(1024) == nullptr); // memory is full, this must return nullptr BOOST_CHECK(b.alloc(0) == nullptr); for (int x=0; x<1024; ++x) b.free(addr[x]); addr.clear(); BOOST_CHECK(b.stats().total == synth_size); BOOST_CHECK(b.stats().free == synth_size); // Now in the other direction... for (int x=0; x<1024; ++x) addr.push_back(b.alloc(1024)); for (int x=0; x<1024; ++x) b.free(addr[1023-x]); addr.clear(); // Now allocate in smaller unequal chunks, then deallocate haphazardly // Not all the chunks will succeed allocating, but freeing nullptr is // allowed so that is no problem. for (int x=0; x<2048; ++x) addr.push_back(b.alloc(x+1)); for (int x=0; x<2048; ++x) b.free(addr[((x*23)%2048)^242]); addr.clear(); // Go entirely wild: free and alloc interleaved, // generate targets and sizes using pseudo-randomness. for (int x=0; x<2048; ++x) addr.push_back(nullptr); uint32_t s = 0x12345678; for (int x=0; x<5000; ++x) { int idx = s & (addr.size()-1); if (s & 0x80000000) { b.free(addr[idx]); addr[idx] = nullptr; } else if(!addr[idx]) { addr[idx] = b.alloc((s >> 16) & 2047); } bool lsb = s & 1; s >>= 1; if (lsb) s ^= 0xf00f00f0; // LFSR period 0xf7ffffe0 } for (void *ptr: addr) b.free(ptr); addr.clear(); BOOST_CHECK(b.stats().total == synth_size); BOOST_CHECK(b.stats().free == synth_size); } /** Mock LockedPageAllocator for testing */ class TestLockedPageAllocator: public LockedPageAllocator { public: TestLockedPageAllocator(int count_in, int lockedcount_in): count(count_in), lockedcount(lockedcount_in) {} void* AllocateLocked(size_t len, bool *lockingSuccess) override { *lockingSuccess = false; if (count > 0) { --count; if (lockedcount > 0) { --lockedcount; *lockingSuccess = true; } return reinterpret_cast<void*>(uint64_t{static_cast<uint64_t>(0x08000000) + (count << 24)}); // Fake address, do not actually use this memory } return nullptr; } void FreeLocked(void* addr, size_t len) override { } size_t GetLimit() override { return std::numeric_limits<size_t>::max(); } private: int count; int lockedcount; }; BOOST_AUTO_TEST_CASE(lockedpool_tests_mock) { // Test over three virtual arenas, of which one will succeed being locked std::unique_ptr<LockedPageAllocator> x = std::make_unique<TestLockedPageAllocator>(3, 1); LockedPool pool(std::move(x)); BOOST_CHECK(pool.stats().total == 0); BOOST_CHECK(pool.stats().locked == 0); // Ensure unreasonable requests are refused without allocating anything void *invalid_toosmall = pool.alloc(0); BOOST_CHECK(invalid_toosmall == nullptr); BOOST_CHECK(pool.stats().used == 0); BOOST_CHECK(pool.stats().free == 0); void *invalid_toobig = pool.alloc(LockedPool::ARENA_SIZE+1); BOOST_CHECK(invalid_toobig == nullptr); BOOST_CHECK(pool.stats().used == 0); BOOST_CHECK(pool.stats().free == 0); void *a0 = pool.alloc(LockedPool::ARENA_SIZE / 2); BOOST_CHECK(a0); BOOST_CHECK(pool.stats().locked == LockedPool::ARENA_SIZE); void *a1 = pool.alloc(LockedPool::ARENA_SIZE / 2); BOOST_CHECK(a1); void *a2 = pool.alloc(LockedPool::ARENA_SIZE / 2); BOOST_CHECK(a2); void *a3 = pool.alloc(LockedPool::ARENA_SIZE / 2); BOOST_CHECK(a3); void *a4 = pool.alloc(LockedPool::ARENA_SIZE / 2); BOOST_CHECK(a4); void *a5 = pool.alloc(LockedPool::ARENA_SIZE / 2); BOOST_CHECK(a5); // We've passed a count of three arenas, so this allocation should fail void *a6 = pool.alloc(16); BOOST_CHECK(!a6); pool.free(a0); pool.free(a2); pool.free(a4); pool.free(a1); pool.free(a3); pool.free(a5); BOOST_CHECK(pool.stats().total == 3*LockedPool::ARENA_SIZE); BOOST_CHECK(pool.stats().locked == LockedPool::ARENA_SIZE); BOOST_CHECK(pool.stats().used == 0); } // These tests used the live LockedPoolManager object, this is also used // by other tests so the conditions are somewhat less controllable and thus the // tests are somewhat more error-prone. BOOST_AUTO_TEST_CASE(lockedpool_tests_live) { LockedPoolManager &pool = LockedPoolManager::Instance(); LockedPool::Stats initial = pool.stats(); void *a0 = pool.alloc(16); BOOST_CHECK(a0); // Test reading and writing the allocated memory *((uint32_t*)a0) = 0x1234; BOOST_CHECK(*((uint32_t*)a0) == 0x1234); pool.free(a0); try { // Test exception on double-free pool.free(a0); BOOST_CHECK(0); } catch(std::runtime_error &) { } // If more than one new arena was allocated for the above tests, something is wrong BOOST_CHECK(pool.stats().total <= (initial.total + LockedPool::ARENA_SIZE)); // Usage must be back to where it started BOOST_CHECK(pool.stats().used == initial.used); } BOOST_AUTO_TEST_SUITE_END() <commit_msg>test: remove BasicTestingSetup from allocator unit tests<commit_after>// Copyright (c) 2012-2019 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 <support/lockedpool.h> #include <util/system.h> #include <limits> #include <memory> #include <stdexcept> #include <utility> #include <vector> #include <boost/test/unit_test.hpp> BOOST_AUTO_TEST_SUITE(allocator_tests) BOOST_AUTO_TEST_CASE(arena_tests) { // Fake memory base address for testing // without actually using memory. void *synth_base = reinterpret_cast<void*>(0x08000000); const size_t synth_size = 1024*1024; Arena b(synth_base, synth_size, 16); void *chunk = b.alloc(1000); #ifdef ARENA_DEBUG b.walk(); #endif BOOST_CHECK(chunk != nullptr); BOOST_CHECK(b.stats().used == 1008); // Aligned to 16 BOOST_CHECK(b.stats().total == synth_size); // Nothing has disappeared? b.free(chunk); #ifdef ARENA_DEBUG b.walk(); #endif BOOST_CHECK(b.stats().used == 0); BOOST_CHECK(b.stats().free == synth_size); try { // Test exception on double-free b.free(chunk); BOOST_CHECK(0); } catch(std::runtime_error &) { } void *a0 = b.alloc(128); void *a1 = b.alloc(256); void *a2 = b.alloc(512); BOOST_CHECK(b.stats().used == 896); BOOST_CHECK(b.stats().total == synth_size); #ifdef ARENA_DEBUG b.walk(); #endif b.free(a0); #ifdef ARENA_DEBUG b.walk(); #endif BOOST_CHECK(b.stats().used == 768); b.free(a1); BOOST_CHECK(b.stats().used == 512); void *a3 = b.alloc(128); #ifdef ARENA_DEBUG b.walk(); #endif BOOST_CHECK(b.stats().used == 640); b.free(a2); BOOST_CHECK(b.stats().used == 128); b.free(a3); BOOST_CHECK(b.stats().used == 0); BOOST_CHECK_EQUAL(b.stats().chunks_used, 0U); BOOST_CHECK(b.stats().total == synth_size); BOOST_CHECK(b.stats().free == synth_size); BOOST_CHECK_EQUAL(b.stats().chunks_free, 1U); std::vector<void*> addr; BOOST_CHECK(b.alloc(0) == nullptr); // allocating 0 always returns nullptr #ifdef ARENA_DEBUG b.walk(); #endif // Sweeping allocate all memory for (int x=0; x<1024; ++x) addr.push_back(b.alloc(1024)); BOOST_CHECK(b.stats().free == 0); BOOST_CHECK(b.alloc(1024) == nullptr); // memory is full, this must return nullptr BOOST_CHECK(b.alloc(0) == nullptr); for (int x=0; x<1024; ++x) b.free(addr[x]); addr.clear(); BOOST_CHECK(b.stats().total == synth_size); BOOST_CHECK(b.stats().free == synth_size); // Now in the other direction... for (int x=0; x<1024; ++x) addr.push_back(b.alloc(1024)); for (int x=0; x<1024; ++x) b.free(addr[1023-x]); addr.clear(); // Now allocate in smaller unequal chunks, then deallocate haphazardly // Not all the chunks will succeed allocating, but freeing nullptr is // allowed so that is no problem. for (int x=0; x<2048; ++x) addr.push_back(b.alloc(x+1)); for (int x=0; x<2048; ++x) b.free(addr[((x*23)%2048)^242]); addr.clear(); // Go entirely wild: free and alloc interleaved, // generate targets and sizes using pseudo-randomness. for (int x=0; x<2048; ++x) addr.push_back(nullptr); uint32_t s = 0x12345678; for (int x=0; x<5000; ++x) { int idx = s & (addr.size()-1); if (s & 0x80000000) { b.free(addr[idx]); addr[idx] = nullptr; } else if(!addr[idx]) { addr[idx] = b.alloc((s >> 16) & 2047); } bool lsb = s & 1; s >>= 1; if (lsb) s ^= 0xf00f00f0; // LFSR period 0xf7ffffe0 } for (void *ptr: addr) b.free(ptr); addr.clear(); BOOST_CHECK(b.stats().total == synth_size); BOOST_CHECK(b.stats().free == synth_size); } /** Mock LockedPageAllocator for testing */ class TestLockedPageAllocator: public LockedPageAllocator { public: TestLockedPageAllocator(int count_in, int lockedcount_in): count(count_in), lockedcount(lockedcount_in) {} void* AllocateLocked(size_t len, bool *lockingSuccess) override { *lockingSuccess = false; if (count > 0) { --count; if (lockedcount > 0) { --lockedcount; *lockingSuccess = true; } return reinterpret_cast<void*>(uint64_t{static_cast<uint64_t>(0x08000000) + (count << 24)}); // Fake address, do not actually use this memory } return nullptr; } void FreeLocked(void* addr, size_t len) override { } size_t GetLimit() override { return std::numeric_limits<size_t>::max(); } private: int count; int lockedcount; }; BOOST_AUTO_TEST_CASE(lockedpool_tests_mock) { // Test over three virtual arenas, of which one will succeed being locked std::unique_ptr<LockedPageAllocator> x = std::make_unique<TestLockedPageAllocator>(3, 1); LockedPool pool(std::move(x)); BOOST_CHECK(pool.stats().total == 0); BOOST_CHECK(pool.stats().locked == 0); // Ensure unreasonable requests are refused without allocating anything void *invalid_toosmall = pool.alloc(0); BOOST_CHECK(invalid_toosmall == nullptr); BOOST_CHECK(pool.stats().used == 0); BOOST_CHECK(pool.stats().free == 0); void *invalid_toobig = pool.alloc(LockedPool::ARENA_SIZE+1); BOOST_CHECK(invalid_toobig == nullptr); BOOST_CHECK(pool.stats().used == 0); BOOST_CHECK(pool.stats().free == 0); void *a0 = pool.alloc(LockedPool::ARENA_SIZE / 2); BOOST_CHECK(a0); BOOST_CHECK(pool.stats().locked == LockedPool::ARENA_SIZE); void *a1 = pool.alloc(LockedPool::ARENA_SIZE / 2); BOOST_CHECK(a1); void *a2 = pool.alloc(LockedPool::ARENA_SIZE / 2); BOOST_CHECK(a2); void *a3 = pool.alloc(LockedPool::ARENA_SIZE / 2); BOOST_CHECK(a3); void *a4 = pool.alloc(LockedPool::ARENA_SIZE / 2); BOOST_CHECK(a4); void *a5 = pool.alloc(LockedPool::ARENA_SIZE / 2); BOOST_CHECK(a5); // We've passed a count of three arenas, so this allocation should fail void *a6 = pool.alloc(16); BOOST_CHECK(!a6); pool.free(a0); pool.free(a2); pool.free(a4); pool.free(a1); pool.free(a3); pool.free(a5); BOOST_CHECK(pool.stats().total == 3*LockedPool::ARENA_SIZE); BOOST_CHECK(pool.stats().locked == LockedPool::ARENA_SIZE); BOOST_CHECK(pool.stats().used == 0); } // These tests used the live LockedPoolManager object, this is also used // by other tests so the conditions are somewhat less controllable and thus the // tests are somewhat more error-prone. BOOST_AUTO_TEST_CASE(lockedpool_tests_live) { LockedPoolManager &pool = LockedPoolManager::Instance(); LockedPool::Stats initial = pool.stats(); void *a0 = pool.alloc(16); BOOST_CHECK(a0); // Test reading and writing the allocated memory *((uint32_t*)a0) = 0x1234; BOOST_CHECK(*((uint32_t*)a0) == 0x1234); pool.free(a0); try { // Test exception on double-free pool.free(a0); BOOST_CHECK(0); } catch(std::runtime_error &) { } // If more than one new arena was allocated for the above tests, something is wrong BOOST_CHECK(pool.stats().total <= (initial.total + LockedPool::ARENA_SIZE)); // Usage must be back to where it started BOOST_CHECK(pool.stats().used == initial.used); } BOOST_AUTO_TEST_SUITE_END() <|endoftext|>