text
stringlengths
54
60.6k
<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/predictors/predictor_database.h" #include "base/bind.h" #include "base/file_util.h" #include "base/files/file_path.h" #include "base/logging.h" #include "base/metrics/histogram.h" #include "base/stringprintf.h" #include "chrome/browser/predictors/autocomplete_action_predictor_table.h" #include "chrome/browser/predictors/resource_prefetch_predictor.h" #include "chrome/browser/predictors/resource_prefetch_predictor_tables.h" #include "chrome/browser/prerender/prerender_field_trial.h" #include "chrome/browser/profiles/profile.h" #include "content/public/browser/browser_thread.h" #include "sql/connection.h" #include "sql/statement.h" using content::BrowserThread; namespace { // TODO(shishir): This should move to a more generic name. const base::FilePath::CharType kPredictorDatabaseName[] = FILE_PATH_LITERAL("Network Action Predictor"); } // namespace namespace predictors { // Refcounted as it is created, initialized and destroyed on a different thread // to the DB thread that is required for all methods performing database access. class PredictorDatabaseInternal : public base::RefCountedThreadSafe<PredictorDatabaseInternal> { private: friend class base::RefCountedThreadSafe<PredictorDatabaseInternal>; friend class PredictorDatabase; explicit PredictorDatabaseInternal(Profile* profile); virtual ~PredictorDatabaseInternal(); // Opens the database file from the profile path. Separated from the // constructor to ease construction/destruction of this object on one thread // but database access on the DB thread. void Initialize(); void LogDatabaseStats(); // DB Thread. // Cancels pending DB transactions. Should only be called on the UI thread. void SetCancelled(); bool is_resource_prefetch_predictor_enabled_; base::FilePath db_path_; scoped_ptr<sql::Connection> db_; // TODO(shishir): These tables may not need to be refcounted. Maybe move them // to using a WeakPtr instead. scoped_refptr<AutocompleteActionPredictorTable> autocomplete_table_; scoped_refptr<ResourcePrefetchPredictorTables> resource_prefetch_tables_; DISALLOW_COPY_AND_ASSIGN(PredictorDatabaseInternal); }; PredictorDatabaseInternal::PredictorDatabaseInternal(Profile* profile) : db_path_(profile->GetPath().Append(kPredictorDatabaseName)), db_(new sql::Connection()), autocomplete_table_(new AutocompleteActionPredictorTable()), resource_prefetch_tables_(new ResourcePrefetchPredictorTables()) { // TODO (tburkard): initialize logged_in_table_ member. ResourcePrefetchPredictorConfig config; is_resource_prefetch_predictor_enabled_ = IsSpeculativeResourcePrefetchingEnabled(profile, &config); } PredictorDatabaseInternal::~PredictorDatabaseInternal() { // The connection pointer needs to be deleted on the DB thread since there // might be a task in progress on the DB thread which uses this connection. BrowserThread::DeleteSoon(BrowserThread::DB, FROM_HERE, db_.release()); } void PredictorDatabaseInternal::Initialize() { CHECK(BrowserThread::CurrentlyOn(BrowserThread::DB)); db_->set_exclusive_locking(); bool success = db_->Open(db_path_); if (!success) return; autocomplete_table_->Initialize(db_.get()); resource_prefetch_tables_->Initialize(db_.get()); LogDatabaseStats(); } void PredictorDatabaseInternal::SetCancelled() { CHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); autocomplete_table_->SetCancelled(); resource_prefetch_tables_->SetCancelled(); } void PredictorDatabaseInternal::LogDatabaseStats() { CHECK(BrowserThread::CurrentlyOn(BrowserThread::DB)); int64 db_size; bool success = file_util::GetFileSize(db_path_, &db_size); DCHECK(success) << "Failed to get file size for " << db_path_.value(); UMA_HISTOGRAM_MEMORY_KB("PredictorDatabase.DatabaseSizeKB", static_cast<int>(db_size / 1024)); autocomplete_table_->LogDatabaseStats(); if (is_resource_prefetch_predictor_enabled_) resource_prefetch_tables_->LogDatabaseStats(); } PredictorDatabase::PredictorDatabase(Profile* profile) : db_(new PredictorDatabaseInternal(profile)) { BrowserThread::PostTask(BrowserThread::DB, FROM_HERE, base::Bind(&PredictorDatabaseInternal::Initialize, db_)); } PredictorDatabase::~PredictorDatabase() { } void PredictorDatabase::Shutdown() { db_->SetCancelled(); } scoped_refptr<AutocompleteActionPredictorTable> PredictorDatabase::autocomplete_table() { return db_->autocomplete_table_; } scoped_refptr<ResourcePrefetchPredictorTables> PredictorDatabase::resource_prefetch_tables() { return db_->resource_prefetch_tables_; } sql::Connection* PredictorDatabase::GetDatabase() { return db_->db_.get(); } } // namespace predictors <commit_msg>Revert 194504 "Fix build break"<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/predictors/predictor_database.h" #include "base/bind.h" #include "base/file_util.h" #include "base/files/file_path.h" #include "base/logging.h" #include "base/metrics/histogram.h" #include "base/stringprintf.h" #include "chrome/browser/predictors/autocomplete_action_predictor_table.h" #include "chrome/browser/predictors/resource_prefetch_predictor.h" #include "chrome/browser/predictors/resource_prefetch_predictor_tables.h" #include "chrome/browser/prerender/prerender_field_trial.h" #include "chrome/browser/profiles/profile.h" #include "content/public/browser/browser_thread.h" #include "sql/connection.h" #include "sql/statement.h" using content::BrowserThread; namespace { // TODO(shishir): This should move to a more generic name. const base::FilePath::CharType kPredictorDatabaseName[] = FILE_PATH_LITERAL("Network Action Predictor"); } // namespace namespace predictors { // Refcounted as it is created, initialized and destroyed on a different thread // to the DB thread that is required for all methods performing database access. class PredictorDatabaseInternal : public base::RefCountedThreadSafe<PredictorDatabaseInternal> { private: friend class base::RefCountedThreadSafe<PredictorDatabaseInternal>; friend class PredictorDatabase; explicit PredictorDatabaseInternal(Profile* profile); virtual ~PredictorDatabaseInternal(); // Opens the database file from the profile path. Separated from the // constructor to ease construction/destruction of this object on one thread // but database access on the DB thread. void Initialize(); void LogDatabaseStats(); // DB Thread. // Cancels pending DB transactions. Should only be called on the UI thread. void SetCancelled(); bool is_resource_prefetch_predictor_enabled_; base::FilePath db_path_; scoped_ptr<sql::Connection> db_; // TODO(shishir): These tables may not need to be refcounted. Maybe move them // to using a WeakPtr instead. scoped_refptr<AutocompleteActionPredictorTable> autocomplete_table_; scoped_refptr<ResourcePrefetchPredictorTables> resource_prefetch_tables_; DISALLOW_COPY_AND_ASSIGN(PredictorDatabaseInternal); }; PredictorDatabaseInternal::PredictorDatabaseInternal(Profile* profile) : db_path_(profile->GetPath().Append(kPredictorDatabaseName)), db_(new sql::Connection()), autocomplete_table_(new AutocompleteActionPredictorTable()), logged_in_table_(new LoggedInPredictorTable()), resource_prefetch_tables_(new ResourcePrefetchPredictorTables()) { ResourcePrefetchPredictorConfig config; is_resource_prefetch_predictor_enabled_ = IsSpeculativeResourcePrefetchingEnabled(profile, &config); } PredictorDatabaseInternal::~PredictorDatabaseInternal() { // The connection pointer needs to be deleted on the DB thread since there // might be a task in progress on the DB thread which uses this connection. BrowserThread::DeleteSoon(BrowserThread::DB, FROM_HERE, db_.release()); } void PredictorDatabaseInternal::Initialize() { CHECK(BrowserThread::CurrentlyOn(BrowserThread::DB)); db_->set_exclusive_locking(); bool success = db_->Open(db_path_); if (!success) return; autocomplete_table_->Initialize(db_.get()); resource_prefetch_tables_->Initialize(db_.get()); LogDatabaseStats(); } void PredictorDatabaseInternal::SetCancelled() { CHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); autocomplete_table_->SetCancelled(); resource_prefetch_tables_->SetCancelled(); } void PredictorDatabaseInternal::LogDatabaseStats() { CHECK(BrowserThread::CurrentlyOn(BrowserThread::DB)); int64 db_size; bool success = file_util::GetFileSize(db_path_, &db_size); DCHECK(success) << "Failed to get file size for " << db_path_.value(); UMA_HISTOGRAM_MEMORY_KB("PredictorDatabase.DatabaseSizeKB", static_cast<int>(db_size / 1024)); autocomplete_table_->LogDatabaseStats(); if (is_resource_prefetch_predictor_enabled_) resource_prefetch_tables_->LogDatabaseStats(); } PredictorDatabase::PredictorDatabase(Profile* profile) : db_(new PredictorDatabaseInternal(profile)) { BrowserThread::PostTask(BrowserThread::DB, FROM_HERE, base::Bind(&PredictorDatabaseInternal::Initialize, db_)); } PredictorDatabase::~PredictorDatabase() { } void PredictorDatabase::Shutdown() { db_->SetCancelled(); } scoped_refptr<AutocompleteActionPredictorTable> PredictorDatabase::autocomplete_table() { return db_->autocomplete_table_; } scoped_refptr<ResourcePrefetchPredictorTables> PredictorDatabase::resource_prefetch_tables() { return db_->resource_prefetch_tables_; } sql::Connection* PredictorDatabase::GetDatabase() { return db_->db_.get(); } } // namespace predictors <|endoftext|>
<commit_before>/* * Copyright (c) 2005, Peter Sommerlad and IFS Institute for Software at HSR Rapperswil, Switzerland * All rights reserved. * * This library/application is free software; you can redistribute and/or modify it under the terms of * the license that is included with this library/application in the file license.txt. */ //--- interface include -------------------------------------------------------- #include "PersistentLDAPConnection.h" //--- project modules used ----------------------------------------------------- #include "LDAPMessageEntry.h" #include "LDAPConnectionManager.h" #include "ldap-extension.h" //--- standard modules used ---------------------------------------------------- #include "Dbg.h" #include "Threads.h" #include "StringStream.h" #include "Base64.h" #include "MD5.h" //--- c-modules used ----------------------------------------------------------- /* Function to set up thread-specific data. */ void PersistentLDAPConnection::tsd_setup() { StartTrace(PersistentLDAPConnection.tsd_setup); void *tsd = NULL; if ( GETTLSDATA(LDAPConnectionManager::fgErrnoKey, tsd, void) ) { Trace("Thread specific data for fgErrnoKey already set up. Thread [" << Thread::MyId() << "]"); return; } tsd = (void *) calloc( 1, sizeof(struct ldap_error) ); if ( !SETTLSDATA(LDAPConnectionManager::fgErrnoKey, tsd) ) { Trace("Setting Thread specific data for fgErrnoKey failed. Thread [" << Thread::MyId() << "]"); } } void PersistentLDAPConnection::tsd_destruct(void *tsd) { StartTrace(PersistentLDAPConnection.tsd_destruct); if ( tsd != (void *) NULL ) { free(tsd); } } /* Function for setting an LDAP error. */ void PersistentLDAPConnection::set_ld_error( int err, char *matched, char *errmsg, void *dummy ) { StartTrace(PersistentLDAPConnection.set_ld_error); PersistentLDAPConnection::ldap_error *le = NULL; GETTLSDATA(LDAPConnectionManager::fgErrnoKey, le, ldap_error); le->le_errno = err; if ( le->le_matched != NULL ) { ldap_memfree( le->le_matched ); } le->le_matched = matched; if ( le->le_errmsg != NULL ) { ldap_memfree( le->le_errmsg ); } le->le_errmsg = errmsg; } /* Function for getting an LDAP error. */ int PersistentLDAPConnection::get_ld_error( char **matched, char **errmsg, void *dummy ) { StartTrace(PersistentLDAPConnection.get_ld_error); PersistentLDAPConnection::ldap_error *le = NULL; GETTLSDATA(LDAPConnectionManager::fgErrnoKey, le, ldap_error); if ( matched != NULL ) { *matched = le->le_matched; } if ( errmsg != NULL ) { *errmsg = le->le_errmsg; } return( le->le_errno ); } /* Function for setting errno. */ void PersistentLDAPConnection::set_errno( int err ) { StartTrace(PersistentLDAPConnection.set_errno); errno = err; } /* Function for getting errno. */ int PersistentLDAPConnection::get_errno( void ) { StartTrace(PersistentLDAPConnection.get_errno); return( errno ); } PersistentLDAPConnection::PersistentLDAPConnection(ROAnything connectionParams) : LDAPConnection(connectionParams) { StartTrace(PersistentLDAPConnection.PersistentLDAPConnection); fRebindTimeout = connectionParams["RebindTimeout"].AsLong(0L); fTryAutoRebind = connectionParams["TryAutoRebind"].AsLong(0L) > 0L; fMaxConnections = connectionParams["MaxConnections"].AsLong(0L); TraceAny(connectionParams, "ConnectionParams"); fPoolId = ""; } PersistentLDAPConnection::~PersistentLDAPConnection() { StartTrace(PersistentLDAPConnection.~PersistentLDAPConnection); } int PersistentLDAPConnection::GetMaxConnections() { StartTrace(PersistentLDAPConnection.GetMaxConnections); return fMaxConnections; } bool PersistentLDAPConnection::SetErrnoHandler(LDAPErrorHandler eh) { StartTrace(PersistentLDAPConnection.SetErrnoHandler); tsd_setup(); struct ldap_thread_fns tfns; /* Set the function pointers for dealing with mutexes and error information. */ memset( &tfns, '\0', sizeof(struct ldap_thread_fns) ); tfns.ltf_get_errno = get_errno; tfns.ltf_set_errno = set_errno; tfns.ltf_get_lderrno = get_ld_error; tfns.ltf_set_lderrno = set_ld_error; tfns.ltf_lderrno_arg = NULL; /* Set up this session to use those function pointers. */ if ( ::ldap_set_option( fHandle, LDAP_OPT_THREAD_FN_PTRS, (void *) &tfns ) != LDAP_SUCCESS ) { Trace("ldap_set_option: LDAP_OPT_THREAD_FN_PTRS FAILED"); eh.HandleSessionError(fHandle, "Could not set errno handlers."); return false; } return true; } PersistentLDAPConnection::EConnectState PersistentLDAPConnection::DoConnectHook(ROAnything bindParams, LDAPErrorHandler &eh) { StartTrace(PersistentLDAPConnection.DoConnectHook); TraceAny(bindParams, "bindParams"); fPoolId = GetLdapPoolId(bindParams); Anything returned = LDAPConnectionManager::LDAPCONNMGR()->GetLdapConnection(eh.IsRetry(), GetMaxConnections(), fPoolId, fRebindTimeout); PersistentLDAPConnection::EConnectState eConnectState = returned["MustRebind"].AsBool(1) == false ? PersistentLDAPConnection::eMustNotRebind : PersistentLDAPConnection::eMustRebind; fHandle = (LDAP *) returned["Handle"].AsIFAObject(0); if ( eConnectState == PersistentLDAPConnection::eMustNotRebind ) { Trace("Retrning: " << ConnectRetToString(PersistentLDAPConnection::eOk)); eConnectState = PersistentLDAPConnection::eOk; } Trace("eConnectState: " << ConnectRetToString(eConnectState) << " Handle: " << DumpConnectionHandle(fHandle)); return eConnectState; } bool PersistentLDAPConnection::ReleaseHandleInfo() { StartTrace(PersistentLDAPConnection.ReleaseHandleInfo); bool ret = LDAPConnectionManager::LDAPCONNMGR()->ReleaseHandleInfo(fMaxConnections, fPoolId); return ret; } bool PersistentLDAPConnection::Bind(String bindName, String bindPW, int &msgId, LDAPErrorHandler eh) { StartTrace(LDAPConnection.PersistentLDAPConnection); String errMsg = "Binding request failed. "; errMsg << "[Server: '" << fServer << "', Port: '" << fPort << "'] "; if ( bindName.IsEqual("") || bindName.IsEqual("Anonymous") ) { Trace("Binding as Anonymous"); errMsg << " (Anonymous bind.)"; msgId = ::ldap_simple_bind( fHandle, NULL, NULL ); } else { errMsg << " (Authorized bind.)"; if ( bindPW == "undefined" ) { Trace("Bindpassword NOT OK: pwd = [" << bindPW << "]"); eh.HandleSessionError(fHandle, errMsg); return false; } else { Trace("Binding with <" << bindName << "><" << bindPW << ">"); msgId = ::ldap_simple_bind( fHandle, bindName, bindPW ); } } // bind request successful? if ( msgId == -1 ) { Trace("Binding request FAILED!"); eh.HandleSessionError(fHandle, errMsg); Disconnect(); return false; } Trace("Binding request SUCCEEDED, waiting for connection..."); return true; } LDAPConnection::EConnectState PersistentLDAPConnection::DoConnect(ROAnything bindParams, LDAPErrorHandler eh) { StartTrace(PersistentLDAPConnection.DoConnect); // set handle to null fHandle = NULL; String errMsg; String bindName = bindParams["BindName"].AsString(""); String bindPW = bindParams["BindPW"].AsString(""); long maxConnections = bindParams["MaxConnections"].AsLong(0); PersistentLDAPConnection::EConnectState eConnectState = PersistentLDAPConnection::eNok; if ( (eConnectState = DoConnectHook(bindParams, eh)) == PersistentLDAPConnection::eOk ) { SetErrnoHandler(eh); return eConnectState; } // get connection handle if ( !(fHandle = Init(eh)) ) { return eInitNok; } // set protocol, timeout and rebind procedure if ( !SetProtocol(eh) || !SetConnectionTimeout(eh) || !SetSearchTimeout(eh) || !SetErrnoHandler(eh) /* || !SetRebindProc(eh) */ ) { return eSetOptionsNok; } // send bind request (asynchronous) int msgId; if ( !Bind(bindName, bindPW, msgId, eh) ) { return eBindNok; } // wait for bind result (using msgId) Anything result; bool ret = WaitForResult(msgId, result, eh); if ( ret ) { LDAPConnectionManager::LDAPCONNMGR()->SetLdapConnection(maxConnections, fPoolId, fHandle); if ( eConnectState == PersistentLDAPConnection::eMustRebind ) { return PersistentLDAPConnection::eRebindOk; } } return ret ? PersistentLDAPConnection::eOk : PersistentLDAPConnection::eBindNok; } bool PersistentLDAPConnection::WaitForResult(int msgId, Anything &result, LDAPErrorHandler &eh) { StartTrace(PersistentLDAPConnection.WaitForResult); timeval tv; tv.tv_sec = fSearchTimeout; tv.tv_usec = 0; timeval *tvp = (fSearchTimeout == 0) ? NULL : &tv; bool finished = false; bool success = false; String errMsg; int resultCode; LDAPMessage *ldapResult; LDAPMessageEntry lmAutoDestruct(&ldapResult); // automatic destructor for LDAPMessage lmAutoDestruct.Use(); while (!finished) { // wait for result resultCode = ldap_result(fHandle, msgId, 1, tvp, &ldapResult); // check result if (resultCode == -1 && fSearchTimeout == 0) { // error, abandon! Trace("WaitForResult [Timeout: 0] received an error"); int opRet; ldap_parse_result( fHandle, ldapResult, &opRet, NULL, NULL, NULL, NULL, 0 ); errMsg << "Synchronous Wait4Result: ErrorCode: [" << (long)opRet << "] ErrorMsg: " << ldap_err2string( opRet ); HandleWait4ResultError(msgId, errMsg, eh); finished = true; } else if (resultCode == 0 || (resultCode == -1 && fSearchTimeout != 0)) { // resultCode 0 means timeout, abandon Trace("WaitForResult [Timeout != 0] encountered a timeout ..."); errMsg << "Asynchronous Wait4Result: The request <" << (long) msgId << "> timed out."; HandleWait4ResultError(msgId, errMsg, eh); if ( fTryAutoRebind ) { eh.SetShouldRetry(); } finished = true; } else { // received a result int errCode = ldap_result2error(fHandle, ldapResult, 0); if (errCode == LDAP_SUCCESS || errCode == LDAP_SIZELIMIT_EXCEEDED) { Trace("WaitForResult recieved a result and considers it to be ok ..."); success = true; // transform LDAPResult into an Anything with Meta Information TransformResult(ldapResult, result, eh.GetQueryParams()); // add extra flag to inform client, if sizelimit was exceeded if (errCode == LDAP_SIZELIMIT_EXCEEDED) { result["SizeLimitExceeded"] = 1; } } else if (errCode == LDAP_COMPARE_FALSE || errCode == LDAP_COMPARE_TRUE) { Trace("WaitForResult recieved a result and considers it to be ok (compare) ..."); success = true; // this is a bit special int rc; ldap_get_option(fHandle, LDAP_OPT_ERROR_NUMBER, &rc); result["Type"] = "LDAP_RES_COMPARE"; result["Equal"] = (errCode == LDAP_COMPARE_TRUE); result["LdapCode"] = rc; result["LdapMsg"] = ldap_err2string(rc); } else { Trace("WaitForResult recieved a result and considers it to be WRONG ..."); errMsg = "LDAP request failed."; eh.HandleSessionError(fHandle, errMsg); } finished = true; } } return success; } void PersistentLDAPConnection::HandleWait4ResultError(int msgId, String &errMsg, LDAPErrorHandler eh) { StartTrace(PersistentLDAPConnection.HandleWait4ResultError); if ( msgId != -1 ) { int errCode = ldap_abandon(fHandle, msgId); errMsg << " Request abandoned: " << (errCode == LDAP_SUCCESS ? " successfully." : " FAILED!"); } else { errMsg << " Request abandoned: binding handle was invalid, ldap_abandon not called"; } eh.HandleSessionError(fHandle, errMsg); // Invalidate our handle because LDAP server might be down, will rebind next time! LDAPConnectionManager::LDAPCONNMGR()->SetLdapConnection(GetMaxConnections(), fPoolId, (LDAP *) NULL); } String PersistentLDAPConnection::Base64ArmouredMD5Hash(const String &text) { StartTrace(PersistentLDAPConnection.Base64ArmouredMD5Hash); String hash, result; MD5Signer::DoHash(text, hash); Base64Regular b64("b64reg"); b64.DoEncode(result, hash); return result; } String PersistentLDAPConnection::GetLdapPoolId(ROAnything bindParams) { StartTrace(PersistentLDAPConnection.GetLdapPoolId); String bindName = bindParams["BindName"].AsString(""); String bindPW = Base64ArmouredMD5Hash(bindParams["BindPW"].AsString("")); return String("Host[") << fServer << "] Port[" << fPort << "] DN[" << bindName << "] BindPW[" << bindPW << "] ConnTimeout[" << fConnectionTimeout << "]"; } String PersistentLDAPConnection::GetLdapPoolId(const String &server, long port, const String &bindName, const String &bindPW, long connectionTimeout) { StartTrace(PersistentLDAPConnection.GetLdapPoolId); String armouredPW = Base64ArmouredMD5Hash(bindPW); return String("Host[") << server << "] Port[" << port << "] DN[" << bindName << "] BindPW[" << armouredPW << "] ConnTimeout[" << connectionTimeout << "]"; } <commit_msg>added include for memeset<commit_after>/* * Copyright (c) 2005, Peter Sommerlad and IFS Institute for Software at HSR Rapperswil, Switzerland * All rights reserved. * * This library/application is free software; you can redistribute and/or modify it under the terms of * the license that is included with this library/application in the file license.txt. */ //--- interface include -------------------------------------------------------- #include "PersistentLDAPConnection.h" //--- project modules used ----------------------------------------------------- #include "LDAPMessageEntry.h" #include "LDAPConnectionManager.h" #include "ldap-extension.h" //--- standard modules used ---------------------------------------------------- #include "Dbg.h" #include "Threads.h" #include "StringStream.h" #include "Base64.h" #include "MD5.h" //--- c-modules used ----------------------------------------------------------- #include <stdlib.h> /* Function to set up thread-specific data. */ void PersistentLDAPConnection::tsd_setup() { StartTrace(PersistentLDAPConnection.tsd_setup); void *tsd = NULL; if ( GETTLSDATA(LDAPConnectionManager::fgErrnoKey, tsd, void) ) { Trace("Thread specific data for fgErrnoKey already set up. Thread [" << Thread::MyId() << "]"); return; } tsd = (void *) calloc( 1, sizeof(struct ldap_error) ); if ( !SETTLSDATA(LDAPConnectionManager::fgErrnoKey, tsd) ) { Trace("Setting Thread specific data for fgErrnoKey failed. Thread [" << Thread::MyId() << "]"); } } void PersistentLDAPConnection::tsd_destruct(void *tsd) { StartTrace(PersistentLDAPConnection.tsd_destruct); if ( tsd != (void *) NULL ) { free(tsd); } } /* Function for setting an LDAP error. */ void PersistentLDAPConnection::set_ld_error( int err, char *matched, char *errmsg, void *dummy ) { StartTrace(PersistentLDAPConnection.set_ld_error); PersistentLDAPConnection::ldap_error *le = NULL; GETTLSDATA(LDAPConnectionManager::fgErrnoKey, le, ldap_error); le->le_errno = err; if ( le->le_matched != NULL ) { ldap_memfree( le->le_matched ); } le->le_matched = matched; if ( le->le_errmsg != NULL ) { ldap_memfree( le->le_errmsg ); } le->le_errmsg = errmsg; } /* Function for getting an LDAP error. */ int PersistentLDAPConnection::get_ld_error( char **matched, char **errmsg, void *dummy ) { StartTrace(PersistentLDAPConnection.get_ld_error); PersistentLDAPConnection::ldap_error *le = NULL; GETTLSDATA(LDAPConnectionManager::fgErrnoKey, le, ldap_error); if ( matched != NULL ) { *matched = le->le_matched; } if ( errmsg != NULL ) { *errmsg = le->le_errmsg; } return( le->le_errno ); } /* Function for setting errno. */ void PersistentLDAPConnection::set_errno( int err ) { StartTrace(PersistentLDAPConnection.set_errno); errno = err; } /* Function for getting errno. */ int PersistentLDAPConnection::get_errno( void ) { StartTrace(PersistentLDAPConnection.get_errno); return( errno ); } PersistentLDAPConnection::PersistentLDAPConnection(ROAnything connectionParams) : LDAPConnection(connectionParams) { StartTrace(PersistentLDAPConnection.PersistentLDAPConnection); fRebindTimeout = connectionParams["RebindTimeout"].AsLong(0L); fTryAutoRebind = connectionParams["TryAutoRebind"].AsLong(0L) > 0L; fMaxConnections = connectionParams["MaxConnections"].AsLong(0L); TraceAny(connectionParams, "ConnectionParams"); fPoolId = ""; } PersistentLDAPConnection::~PersistentLDAPConnection() { StartTrace(PersistentLDAPConnection.~PersistentLDAPConnection); } int PersistentLDAPConnection::GetMaxConnections() { StartTrace(PersistentLDAPConnection.GetMaxConnections); return fMaxConnections; } bool PersistentLDAPConnection::SetErrnoHandler(LDAPErrorHandler eh) { StartTrace(PersistentLDAPConnection.SetErrnoHandler); tsd_setup(); struct ldap_thread_fns tfns; /* Set the function pointers for dealing with mutexes and error information. */ memset( &tfns, '\0', sizeof(struct ldap_thread_fns) ); tfns.ltf_get_errno = get_errno; tfns.ltf_set_errno = set_errno; tfns.ltf_get_lderrno = get_ld_error; tfns.ltf_set_lderrno = set_ld_error; tfns.ltf_lderrno_arg = NULL; /* Set up this session to use those function pointers. */ if ( ::ldap_set_option( fHandle, LDAP_OPT_THREAD_FN_PTRS, (void *) &tfns ) != LDAP_SUCCESS ) { Trace("ldap_set_option: LDAP_OPT_THREAD_FN_PTRS FAILED"); eh.HandleSessionError(fHandle, "Could not set errno handlers."); return false; } return true; } PersistentLDAPConnection::EConnectState PersistentLDAPConnection::DoConnectHook(ROAnything bindParams, LDAPErrorHandler &eh) { StartTrace(PersistentLDAPConnection.DoConnectHook); TraceAny(bindParams, "bindParams"); fPoolId = GetLdapPoolId(bindParams); Anything returned = LDAPConnectionManager::LDAPCONNMGR()->GetLdapConnection(eh.IsRetry(), GetMaxConnections(), fPoolId, fRebindTimeout); PersistentLDAPConnection::EConnectState eConnectState = returned["MustRebind"].AsBool(1) == false ? PersistentLDAPConnection::eMustNotRebind : PersistentLDAPConnection::eMustRebind; fHandle = (LDAP *) returned["Handle"].AsIFAObject(0); if ( eConnectState == PersistentLDAPConnection::eMustNotRebind ) { Trace("Retrning: " << ConnectRetToString(PersistentLDAPConnection::eOk)); eConnectState = PersistentLDAPConnection::eOk; } Trace("eConnectState: " << ConnectRetToString(eConnectState) << " Handle: " << DumpConnectionHandle(fHandle)); return eConnectState; } bool PersistentLDAPConnection::ReleaseHandleInfo() { StartTrace(PersistentLDAPConnection.ReleaseHandleInfo); bool ret = LDAPConnectionManager::LDAPCONNMGR()->ReleaseHandleInfo(fMaxConnections, fPoolId); return ret; } bool PersistentLDAPConnection::Bind(String bindName, String bindPW, int &msgId, LDAPErrorHandler eh) { StartTrace(LDAPConnection.PersistentLDAPConnection); String errMsg = "Binding request failed. "; errMsg << "[Server: '" << fServer << "', Port: '" << fPort << "'] "; if ( bindName.IsEqual("") || bindName.IsEqual("Anonymous") ) { Trace("Binding as Anonymous"); errMsg << " (Anonymous bind.)"; msgId = ::ldap_simple_bind( fHandle, NULL, NULL ); } else { errMsg << " (Authorized bind.)"; if ( bindPW == "undefined" ) { Trace("Bindpassword NOT OK: pwd = [" << bindPW << "]"); eh.HandleSessionError(fHandle, errMsg); return false; } else { Trace("Binding with <" << bindName << "><" << bindPW << ">"); msgId = ::ldap_simple_bind( fHandle, bindName, bindPW ); } } // bind request successful? if ( msgId == -1 ) { Trace("Binding request FAILED!"); eh.HandleSessionError(fHandle, errMsg); Disconnect(); return false; } Trace("Binding request SUCCEEDED, waiting for connection..."); return true; } LDAPConnection::EConnectState PersistentLDAPConnection::DoConnect(ROAnything bindParams, LDAPErrorHandler eh) { StartTrace(PersistentLDAPConnection.DoConnect); // set handle to null fHandle = NULL; String errMsg; String bindName = bindParams["BindName"].AsString(""); String bindPW = bindParams["BindPW"].AsString(""); long maxConnections = bindParams["MaxConnections"].AsLong(0); PersistentLDAPConnection::EConnectState eConnectState = PersistentLDAPConnection::eNok; if ( (eConnectState = DoConnectHook(bindParams, eh)) == PersistentLDAPConnection::eOk ) { SetErrnoHandler(eh); return eConnectState; } // get connection handle if ( !(fHandle = Init(eh)) ) { return eInitNok; } // set protocol, timeout and rebind procedure if ( !SetProtocol(eh) || !SetConnectionTimeout(eh) || !SetSearchTimeout(eh) || !SetErrnoHandler(eh) /* || !SetRebindProc(eh) */ ) { return eSetOptionsNok; } // send bind request (asynchronous) int msgId; if ( !Bind(bindName, bindPW, msgId, eh) ) { return eBindNok; } // wait for bind result (using msgId) Anything result; bool ret = WaitForResult(msgId, result, eh); if ( ret ) { LDAPConnectionManager::LDAPCONNMGR()->SetLdapConnection(maxConnections, fPoolId, fHandle); if ( eConnectState == PersistentLDAPConnection::eMustRebind ) { return PersistentLDAPConnection::eRebindOk; } } return ret ? PersistentLDAPConnection::eOk : PersistentLDAPConnection::eBindNok; } bool PersistentLDAPConnection::WaitForResult(int msgId, Anything &result, LDAPErrorHandler &eh) { StartTrace(PersistentLDAPConnection.WaitForResult); timeval tv; tv.tv_sec = fSearchTimeout; tv.tv_usec = 0; timeval *tvp = (fSearchTimeout == 0) ? NULL : &tv; bool finished = false; bool success = false; String errMsg; int resultCode; LDAPMessage *ldapResult; LDAPMessageEntry lmAutoDestruct(&ldapResult); // automatic destructor for LDAPMessage lmAutoDestruct.Use(); while (!finished) { // wait for result resultCode = ldap_result(fHandle, msgId, 1, tvp, &ldapResult); // check result if (resultCode == -1 && fSearchTimeout == 0) { // error, abandon! Trace("WaitForResult [Timeout: 0] received an error"); int opRet; ldap_parse_result( fHandle, ldapResult, &opRet, NULL, NULL, NULL, NULL, 0 ); errMsg << "Synchronous Wait4Result: ErrorCode: [" << (long)opRet << "] ErrorMsg: " << ldap_err2string( opRet ); HandleWait4ResultError(msgId, errMsg, eh); finished = true; } else if (resultCode == 0 || (resultCode == -1 && fSearchTimeout != 0)) { // resultCode 0 means timeout, abandon Trace("WaitForResult [Timeout != 0] encountered a timeout ..."); errMsg << "Asynchronous Wait4Result: The request <" << (long) msgId << "> timed out."; HandleWait4ResultError(msgId, errMsg, eh); if ( fTryAutoRebind ) { eh.SetShouldRetry(); } finished = true; } else { // received a result int errCode = ldap_result2error(fHandle, ldapResult, 0); if (errCode == LDAP_SUCCESS || errCode == LDAP_SIZELIMIT_EXCEEDED) { Trace("WaitForResult recieved a result and considers it to be ok ..."); success = true; // transform LDAPResult into an Anything with Meta Information TransformResult(ldapResult, result, eh.GetQueryParams()); // add extra flag to inform client, if sizelimit was exceeded if (errCode == LDAP_SIZELIMIT_EXCEEDED) { result["SizeLimitExceeded"] = 1; } } else if (errCode == LDAP_COMPARE_FALSE || errCode == LDAP_COMPARE_TRUE) { Trace("WaitForResult recieved a result and considers it to be ok (compare) ..."); success = true; // this is a bit special int rc; ldap_get_option(fHandle, LDAP_OPT_ERROR_NUMBER, &rc); result["Type"] = "LDAP_RES_COMPARE"; result["Equal"] = (errCode == LDAP_COMPARE_TRUE); result["LdapCode"] = rc; result["LdapMsg"] = ldap_err2string(rc); } else { Trace("WaitForResult recieved a result and considers it to be WRONG ..."); errMsg = "LDAP request failed."; eh.HandleSessionError(fHandle, errMsg); } finished = true; } } return success; } void PersistentLDAPConnection::HandleWait4ResultError(int msgId, String &errMsg, LDAPErrorHandler eh) { StartTrace(PersistentLDAPConnection.HandleWait4ResultError); if ( msgId != -1 ) { int errCode = ldap_abandon(fHandle, msgId); errMsg << " Request abandoned: " << (errCode == LDAP_SUCCESS ? " successfully." : " FAILED!"); } else { errMsg << " Request abandoned: binding handle was invalid, ldap_abandon not called"; } eh.HandleSessionError(fHandle, errMsg); // Invalidate our handle because LDAP server might be down, will rebind next time! LDAPConnectionManager::LDAPCONNMGR()->SetLdapConnection(GetMaxConnections(), fPoolId, (LDAP *) NULL); } String PersistentLDAPConnection::Base64ArmouredMD5Hash(const String &text) { StartTrace(PersistentLDAPConnection.Base64ArmouredMD5Hash); String hash, result; MD5Signer::DoHash(text, hash); Base64Regular b64("b64reg"); b64.DoEncode(result, hash); return result; } String PersistentLDAPConnection::GetLdapPoolId(ROAnything bindParams) { StartTrace(PersistentLDAPConnection.GetLdapPoolId); String bindName = bindParams["BindName"].AsString(""); String bindPW = Base64ArmouredMD5Hash(bindParams["BindPW"].AsString("")); return String("Host[") << fServer << "] Port[" << fPort << "] DN[" << bindName << "] BindPW[" << bindPW << "] ConnTimeout[" << fConnectionTimeout << "]"; } String PersistentLDAPConnection::GetLdapPoolId(const String &server, long port, const String &bindName, const String &bindPW, long connectionTimeout) { StartTrace(PersistentLDAPConnection.GetLdapPoolId); String armouredPW = Base64ArmouredMD5Hash(bindPW); return String("Host[") << server << "] Port[" << port << "] DN[" << bindName << "] BindPW[" << armouredPW << "] ConnTimeout[" << connectionTimeout << "]"; } <|endoftext|>
<commit_before>/** * LLVM transformation pass to resolve indirect calls * * The transformation performs "devirtualization" which consists of * looking for indirect function calls and transforming them into a * switch statement that selects one of several direct function calls * to execute. Devirtualization happens if a pointer analysis can * resolve the indirect calls and compute all possible callees. **/ #include "transforms/DevirtFunctions.hh" #include "llvm/Pass.h" //#include "llvm/Analysis/CallGraph.h" #include "llvm/IR/MDBuilder.h" #include "llvm/Support/CommandLine.h" #include "llvm/Support/raw_ostream.h" #include "seadsa/CompleteCallGraph.hh" #include "seadsa/InitializePasses.hh" static llvm::cl::opt<unsigned> MaxNumTargets( "Pmax-num-targets", llvm::cl::desc( "Do not resolve if number of targets is greater than this number."), llvm::cl::init(9999)); /* * Resolve first C++ virtual calls by using a Class Hierarchy Analysis (CHA) * before using seadsa. **/ static llvm::cl::opt<bool> ResolveCallsByCHA("Pdevirt-with-cha", llvm::cl::desc("Resolve virtual calls by using CHA " "(useful for C++ programs)"), llvm::cl::init(false)); static llvm::cl::opt<bool> ResolveIncompleteCalls( "Presolve-incomplete-calls", llvm::cl::desc("Resolve indirect calls that might still require " "further reasoning about other modules" "(enable this option may be unsound)"), llvm::cl::init(false), llvm::cl::Hidden); namespace previrt { namespace transforms { using namespace llvm; /** ** Resolve indirect calls by one direct call for possible callee ** function **/ class DevirtualizeFunctionsPass : public ModulePass { public: static char ID; DevirtualizeFunctionsPass() : ModulePass(ID) { // Initialize sea-dsa pass llvm::PassRegistry &Registry = *llvm::PassRegistry::getPassRegistry(); llvm::initializeCompleteCallGraphPass(Registry); } virtual bool runOnModule(Module &M) override { // -- Get the call graph // CallGraph* CG = &(getAnalysis<CallGraphWrapperPass> ().getCallGraph ()); bool res = false; // -- Access to analysis pass which finds targets of indirect function calls DevirtualizeFunctions DF(/*CG*/ nullptr); if (ResolveCallsByCHA) { CallSiteResolverByCHA CSResolver(M); res |= DF.resolveCallSites(M, &CSResolver); } CallSiteResolverBySeaDsa CSResolver( M, getAnalysis<seadsa::CompleteCallGraph>(), ResolveIncompleteCalls, MaxNumTargets); res |= DF.resolveCallSites(M, &CSResolver); return res; } virtual void getAnalysisUsage(AnalysisUsage &AU) const override { // AU.addRequired<CallGraphWrapperPass>(); AU.addRequired<seadsa::CompleteCallGraph>(); // FIXME: DevirtualizeFunctions does not fully update the call // graph so we don't claim it's preserved. // AU.setPreservesAll(); // AU.addPreserved<CallGraphWrapperPass>(); } virtual StringRef getPassName() const override { return "Devirtualize indirect calls"; } }; // Currently unused but it might be useful in the future. /** Annotate indirect calls with all possible callees. * * For a given call site, the metadata, if present, indicates the * set of functions the call site could possibly target at * run-time. **/ class AnnotateIndirectCalls : public ModulePass { public: static char ID; AnnotateIndirectCalls() : ModulePass(ID) { // Initialize sea-dsa pass llvm::PassRegistry &Registry = *llvm::PassRegistry::getPassRegistry(); llvm::initializeCompleteCallGraphPass(Registry); } virtual bool runOnModule(Module &M) override { bool change = false; CallSiteResolverBySeaDsa CallSiteResolver( M, getAnalysis<seadsa::CompleteCallGraph>(), ResolveIncompleteCalls, MaxNumTargets); MDBuilder MDB(M.getContext()); for (auto &F : M) { for (auto &B : F) { for (auto &I : B) { if (isa<CallInst>(I) || isa<InvokeInst>(I)) { CallSite CS(&I); if (CS.isIndirectCall()) { const SmallVector<const Function *, 16> *Targets = CallSiteResolver.getTargets(CS); if (Targets) { std::vector<Function *> Callees; // remove constness for (const Function *CalleeF : *Targets) { Callees.push_back(const_cast<Function *>(CalleeF)); } MDNode *MDCallees = MDB.createCallees(Callees); I.setMetadata(LLVMContext::MD_callees, MDCallees); change = true; } } } } } } return change; } virtual void getAnalysisUsage(AnalysisUsage &AU) const override { AU.addRequired<seadsa::CompleteCallGraph>(); AU.setPreservesAll(); } virtual StringRef getPassName() const override { return "Annotate indirect calls with all possible callees"; } }; char DevirtualizeFunctionsPass::ID = 0; char AnnotateIndirectCalls::ID = 0; } // end namespace } // end namespace static llvm::RegisterPass<previrt::transforms::DevirtualizeFunctionsPass> X("Pdevirt", "Devirtualize indirect function calls by adding bounce functions"); static llvm::RegisterPass<previrt::transforms::AnnotateIndirectCalls> Y("Pannotate-indirect-calls", "Annotate indirect calls with metadata listing all possible callees"); <commit_msg>doc(DevirtFunctionsPass): fix description<commit_after>/** * LLVM transformation pass to resolve indirect calls * * The transformation performs "devirtualization" which consists of * looking for indirect function calls and transforming them into a * switch statement that selects one of several direct function calls * to execute. Devirtualization happens if a pointer analysis can * resolve the indirect calls and compute all possible callees. **/ #include "transforms/DevirtFunctions.hh" #include "llvm/Pass.h" //#include "llvm/Analysis/CallGraph.h" #include "llvm/IR/MDBuilder.h" #include "llvm/Support/CommandLine.h" #include "llvm/Support/raw_ostream.h" #include "seadsa/CompleteCallGraph.hh" #include "seadsa/InitializePasses.hh" static llvm::cl::opt<unsigned> MaxNumTargets( "Pmax-num-targets", llvm::cl::desc( "Do not resolve if number of targets is greater than this number."), llvm::cl::init(9999)); /* * Resolve first C++ virtual calls by using a Class Hierarchy Analysis (CHA) * before using seadsa. **/ static llvm::cl::opt<bool> ResolveCallsByCHA("Pdevirt-with-cha", llvm::cl::desc("Resolve virtual calls by using CHA " "(useful for C++ programs)"), llvm::cl::init(false)); static llvm::cl::opt<bool> ResolveIncompleteCalls( "Presolve-incomplete-calls", llvm::cl::desc("Resolve indirect calls that might still require " "further reasoning about other modules" "(enable this option may be unsound)"), llvm::cl::init(false), llvm::cl::Hidden); namespace previrt { namespace transforms { using namespace llvm; /** ** Resolve indirect calls by one direct call for possible callee ** function **/ class DevirtualizeFunctionsPass : public ModulePass { public: static char ID; DevirtualizeFunctionsPass() : ModulePass(ID) { // Initialize sea-dsa pass llvm::PassRegistry &Registry = *llvm::PassRegistry::getPassRegistry(); llvm::initializeCompleteCallGraphPass(Registry); } virtual bool runOnModule(Module &M) override { // -- Get the call graph // CallGraph* CG = &(getAnalysis<CallGraphWrapperPass> ().getCallGraph ()); bool res = false; // -- Access to analysis pass which finds targets of indirect function calls DevirtualizeFunctions DF(/*CG*/ nullptr); if (ResolveCallsByCHA) { CallSiteResolverByCHA CSResolver(M); res |= DF.resolveCallSites(M, &CSResolver); } CallSiteResolverBySeaDsa CSResolver( M, getAnalysis<seadsa::CompleteCallGraph>(), ResolveIncompleteCalls, MaxNumTargets); res |= DF.resolveCallSites(M, &CSResolver); return res; } virtual void getAnalysisUsage(AnalysisUsage &AU) const override { // AU.addRequired<CallGraphWrapperPass>(); AU.addRequired<seadsa::CompleteCallGraph>(); // FIXME: DevirtualizeFunctions does not fully update the call // graph so we don't claim it's preserved. // AU.setPreservesAll(); // AU.addPreserved<CallGraphWrapperPass>(); } virtual StringRef getPassName() const override { return "Devirtualize indirect calls"; } }; // Currently unused but it might be useful in the future. /** Annotate indirect calls with all possible callees. * * For a given call site, the metadata, if present, indicates the * set of functions the call site could possibly target at * run-time. **/ class AnnotateIndirectCalls : public ModulePass { public: static char ID; AnnotateIndirectCalls() : ModulePass(ID) { // Initialize sea-dsa pass llvm::PassRegistry &Registry = *llvm::PassRegistry::getPassRegistry(); llvm::initializeCompleteCallGraphPass(Registry); } virtual bool runOnModule(Module &M) override { bool change = false; CallSiteResolverBySeaDsa CallSiteResolver( M, getAnalysis<seadsa::CompleteCallGraph>(), ResolveIncompleteCalls, MaxNumTargets); MDBuilder MDB(M.getContext()); for (auto &F : M) { for (auto &B : F) { for (auto &I : B) { if (isa<CallInst>(I) || isa<InvokeInst>(I)) { CallSite CS(&I); if (CS.isIndirectCall()) { const SmallVector<const Function *, 16> *Targets = CallSiteResolver.getTargets(CS); if (Targets) { std::vector<Function *> Callees; // remove constness for (const Function *CalleeF : *Targets) { Callees.push_back(const_cast<Function *>(CalleeF)); } MDNode *MDCallees = MDB.createCallees(Callees); I.setMetadata(LLVMContext::MD_callees, MDCallees); change = true; } } } } } } return change; } virtual void getAnalysisUsage(AnalysisUsage &AU) const override { AU.addRequired<seadsa::CompleteCallGraph>(); AU.setPreservesAll(); } virtual StringRef getPassName() const override { return "Annotate indirect calls with all possible callees"; } }; char DevirtualizeFunctionsPass::ID = 0; char AnnotateIndirectCalls::ID = 0; } // end namespace } // end namespace static llvm::RegisterPass<previrt::transforms::DevirtualizeFunctionsPass> X("Pdevirt", "Devirtualize indirect function calls by adding multiple direct calls"); static llvm::RegisterPass<previrt::transforms::AnnotateIndirectCalls> Y("Pannotate-indirect-calls", "Annotate indirect calls with metadata listing all possible callees"); <|endoftext|>
<commit_before>/**************************************************************************** * * Copyright (c) 2016 PX4 Development Team. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * 3. Neither the name PX4 nor the names of its contributors may be * used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * ****************************************************************************/ /** * @file qshell.cpp * Listener for shell commands from posix * * @author Nicolas de Palezieux <ndepal@gmail.com> */ #include "qshell.h" #include <px4_log.h> #include <px4_tasks.h> #include <px4_time.h> #include <px4_posix.h> #include <px4_middleware.h> #include <dspal_platform.h> #include <unistd.h> #include <stdio.h> #include <string.h> #include <iostream> #include <fstream> #include <sstream> #include <signal.h> #include <stdio.h> #include <stdlib.h> #include "modules/uORB/uORB.h" #include <drivers/drv_hrt.h> #include "DriverFramework.hpp" extern void init_app_map(std::map<std::string, px4_main_t> &apps); extern void list_builtins(std::map<std::string, px4_main_t> &apps); using std::map; using std::string; px4::AppState QShell::appState; QShell::QShell() { init_app_map(apps); } int QShell::main() { int rc; appState.setRunning(true); int sub_qshell_req = orb_subscribe(ORB_ID(qshell_req)); if (sub_qshell_req == PX4_ERROR) { PX4_ERR("Error subscribing to qshell_req topic"); return -1; } int i = 0; while (!appState.exitRequested()) { bool updated = false; if (orb_check(sub_qshell_req, &updated) == 0) { if (updated) { PX4_DEBUG("[%d]qshell_req status is updated... reading new value", i); if (orb_copy(ORB_ID(qshell_req), sub_qshell_req, &m_qshell_req) != 0) { PX4_ERR("[%d]Error calling orb copy for qshell_req... ", i); break; } char current_char; std::string arg; std::vector<std::string> appargs; for (int str_idx = 0; str_idx < m_qshell_req.strlen; str_idx++) { current_char = m_qshell_req.string[str_idx]; if (isspace(current_char)) { // split at spaces if (arg.length()) { appargs.push_back(arg); arg = ""; } } else { arg += current_char; } } appargs.push_back(arg); // push last argument int ret = run_cmd(appargs); if (ret) { PX4_ERR("Failed to execute command"); } } } else { PX4_ERR("[%d]Error checking the updated status for qshell_req ", i); break; } // sleep for 1/2 sec. usleep(500000); ++i; } return 0; appState.setRunning(false); return rc; } int QShell::run_cmd(const std::vector<std::string> &appargs) { // command is appargs[0] std::string command = appargs[0]; if (command.compare("help") == 0) { list_builtins(apps); } //replaces app.find with iterator code to avoid null pointer exception for (map<string, px4_main_t>::iterator it = apps.begin(); it != apps.end(); ++it) { if (it->first == command) { const char *arg[2 + 1]; unsigned int i = 0; while (i < appargs.size() && appargs[i].c_str()[0] != '\0') { arg[i] = (char *)appargs[i].c_str(); PX4_DEBUG(" arg%d = '%s'\n", i, arg[i]); ++i; } arg[i] = (char *)0; //PX4_DEBUG_PRINTF(i); if (apps[command] == NULL) { PX4_ERR("Null function !!\n"); } else { return apps[command](i, (char **)arg); } } } PX4_ERR("Command %s not found", command.c_str()); return 1; } <commit_msg>Proper return value on qshell help<commit_after>/**************************************************************************** * * Copyright (c) 2016 PX4 Development Team. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * 3. Neither the name PX4 nor the names of its contributors may be * used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * ****************************************************************************/ /** * @file qshell.cpp * Listener for shell commands from posix * * @author Nicolas de Palezieux <ndepal@gmail.com> */ #include "qshell.h" #include <px4_log.h> #include <px4_tasks.h> #include <px4_time.h> #include <px4_posix.h> #include <px4_middleware.h> #include <dspal_platform.h> #include <unistd.h> #include <stdio.h> #include <string.h> #include <iostream> #include <fstream> #include <sstream> #include <signal.h> #include <stdio.h> #include <stdlib.h> #include "modules/uORB/uORB.h" #include <drivers/drv_hrt.h> #include "DriverFramework.hpp" extern void init_app_map(std::map<std::string, px4_main_t> &apps); extern void list_builtins(std::map<std::string, px4_main_t> &apps); using std::map; using std::string; px4::AppState QShell::appState; QShell::QShell() { init_app_map(apps); } int QShell::main() { int rc; appState.setRunning(true); int sub_qshell_req = orb_subscribe(ORB_ID(qshell_req)); if (sub_qshell_req == PX4_ERROR) { PX4_ERR("Error subscribing to qshell_req topic"); return -1; } int i = 0; while (!appState.exitRequested()) { bool updated = false; if (orb_check(sub_qshell_req, &updated) == 0) { if (updated) { PX4_DEBUG("[%d]qshell_req status is updated... reading new value", i); if (orb_copy(ORB_ID(qshell_req), sub_qshell_req, &m_qshell_req) != 0) { PX4_ERR("[%d]Error calling orb copy for qshell_req... ", i); break; } char current_char; std::string arg; std::vector<std::string> appargs; for (int str_idx = 0; str_idx < m_qshell_req.strlen; str_idx++) { current_char = m_qshell_req.string[str_idx]; if (isspace(current_char)) { // split at spaces if (arg.length()) { appargs.push_back(arg); arg = ""; } } else { arg += current_char; } } appargs.push_back(arg); // push last argument int ret = run_cmd(appargs); if (ret) { PX4_ERR("Failed to execute command"); } } } else { PX4_ERR("[%d]Error checking the updated status for qshell_req ", i); break; } // sleep for 1/2 sec. usleep(500000); ++i; } return 0; appState.setRunning(false); return rc; } int QShell::run_cmd(const std::vector<std::string> &appargs) { // command is appargs[0] std::string command = appargs[0]; if (command.compare("help") == 0) { list_builtins(apps); return 0; } //replaces app.find with iterator code to avoid null pointer exception for (map<string, px4_main_t>::iterator it = apps.begin(); it != apps.end(); ++it) { if (it->first == command) { const char *arg[2 + 1]; unsigned int i = 0; while (i < appargs.size() && appargs[i].c_str()[0] != '\0') { arg[i] = (char *)appargs[i].c_str(); PX4_DEBUG(" arg%d = '%s'\n", i, arg[i]); ++i; } arg[i] = (char *)0; //PX4_DEBUG_PRINTF(i); if (apps[command] == NULL) { PX4_ERR("Null function !!\n"); } else { return apps[command](i, (char **)arg); } } } PX4_ERR("Command %s not found", command.c_str()); return 1; } <|endoftext|>
<commit_before>/* * ClusterContracter.cpp * * Created on: 30.10.2012 * Author: Christian Staudt (christian.staudt@kit.edu) */ #include "ClusterContracter.h" namespace NetworKit { ClusterContracter::ClusterContracter() { // TODO Auto-generated constructor stub } ClusterContracter::~ClusterContracter() { // TODO Auto-generated destructor stub } std::pair<Graph, NodeMap<node> > ClusterContracter::run(Graph& G, Clustering& zeta) { Graph Gcon(0); // empty graph Gcon.markAsWeighted(); // Gcon will be a weighted graph IndexMap<cluster, node> clusterToSuperNode(zeta.upperBound(), none); // there is one supernode for each cluster // populate map cluster -> supernode G.forNodes([&](node v){ cluster c = zeta.clusterOf(v); if (! clusterToSuperNode.hasBeenSet(c)) { clusterToSuperNode[c] = Gcon.addNode(); // TODO: probably does not scale well, think about allocating ranges of nodes } }); int64_t n = G.numberOfNodes(); NodeMap<node> nodeToSuperNode(n); // set entries node -> supernode G.parallelForNodes([&](node v){ nodeToSuperNode[v] = clusterToSuperNode[zeta.clusterOf(v)]; }); // iterate over edges of G and create edges in Gcon or update edge and node weights in Gcon G.forWeightedEdges([&](node u, node v, edgeweight ew) { node su = nodeToSuperNode[u]; node sv = nodeToSuperNode[v]; if (zeta.clusterOf(u) == zeta.clusterOf(v)) { // add edge weight to supernode (self-loop) weight Gcon.setWeight(su, su, Gcon.weight(su, su) + ew); } else { // add edge weight to weight between two supernodes (or insert edge) Gcon.setWeight(su, sv, Gcon.weight(su, sv) + ew); } }); // TODO: parallel? return std::make_pair(Gcon, nodeToSuperNode); } } <commit_msg>bugfix TRACE<commit_after>/* * ClusterContracter.cpp * * Created on: 30.10.2012 * Author: Christian Staudt (christian.staudt@kit.edu) */ #include "ClusterContracter.h" namespace NetworKit { ClusterContracter::ClusterContracter() { // TODO Auto-generated constructor stub } ClusterContracter::~ClusterContracter() { // TODO Auto-generated destructor stub } std::pair<Graph, NodeMap<node> > ClusterContracter::run(Graph& G, Clustering& zeta) { Graph Gcon(0); // empty graph Gcon.markAsWeighted(); // Gcon will be a weighted graph IndexMap<cluster, node> clusterToSuperNode(zeta.upperBound(), none); // there is one supernode for each cluster // populate map cluster -> supernode G.forNodes([&](node v){ cluster c = zeta.clusterOf(v); if (! clusterToSuperNode.hasBeenSet(c)) { clusterToSuperNode[c] = Gcon.addNode(); // TODO: probably does not scale well, think about allocating ranges of nodes } }); int64_t n = G.numberOfNodes(); NodeMap<node> nodeToSuperNode(n); // set entries node -> supernode G.parallelForNodes([&](node v){ nodeToSuperNode[v] = clusterToSuperNode[zeta.clusterOf(v)]; }); // iterate over edges of G and create edges in Gcon or update edge and node weights in Gcon G.forWeightedEdges([&](node u, node v, edgeweight ew) { node su = nodeToSuperNode[u]; node sv = nodeToSuperNode[v]; TRACE("edge (", su, ", ", sv, ")"); if (zeta.clusterOf(u) == zeta.clusterOf(v)) { // add edge weight to supernode (self-loop) weight Gcon.setWeight(su, su, Gcon.weight(su, su) + ew); } else { // add edge weight to weight between two supernodes (or insert edge) Gcon.setWeight(su, sv, Gcon.weight(su, sv) + ew); } }); // TODO: parallel? return std::make_pair(Gcon, nodeToSuperNode); } } <|endoftext|>
<commit_before>/******************************************************************** * Description: interp_execute.cc * * Derived from a work by Thomas Kramer * * Author: * License: GPL Version 2 * System: Linux * * Copyright (c) 2004 All rights reserved. * * Last change: ********************************************************************/ #ifndef _GNU_SOURCE #define _GNU_SOURCE #endif #include <boost/python.hpp> #include <unistd.h> #include <stdio.h> #include <stdlib.h> #include <math.h> #include <string.h> #include <ctype.h> #include <sys/types.h> #include <sys/stat.h> #include "rs274ngc.hh" #include "rs274ngc_return.hh" #include "interp_internal.hh" #include "rs274ngc_interp.hh" #define RESULT_OK(x) ((x) == INTERP_OK || (x) == INTERP_EXECUTE_FINISH) /****************************************************************************/ /*! execute binary Returned value: int If execute_binary1 or execute_binary2 returns an error code, this returns that code. Otherwise, it returns INTERP_OK. Side effects: The value of left is set to the result of applying the operation to left and right. Called by: read_real_expression This just calls either execute_binary1 or execute_binary2. */ int Interp::execute_binary(double *left, int operation, double *right) { if (operation < AND2) CHP(execute_binary1(left, operation, right)); else CHP(execute_binary2(left, operation, right)); return INTERP_OK; } /****************************************************************************/ /*! execute_binary1 Returned Value: int If any of the following errors occur, this returns the error shown. Otherwise, it returns INTERP_OK. 1. operation is unknown: NCE_BUG_UNKNOWN_OPERATION 2. An attempt is made to divide by zero: NCE_ATTEMPT_TO_DIVIDE_BY_ZERO 3. An attempt is made to raise a negative number to a non-integer power: NCE_ATTEMPT_TO_RAISE_NEGATIVE_TO_NON_INTEGER_POWER Side effects: The result from performing the operation is put into what left points at. Called by: read_real_expression. This executes the operations: DIVIDED_BY, MODULO, POWER, TIMES. */ int Interp::execute_binary1(double *left, //!< pointer to the left operand int operation, //!< integer code for the operation double *right) //!< pointer to the right operand { switch (operation) { case DIVIDED_BY: CHKS((*right == 0.0), NCE_ATTEMPT_TO_DIVIDE_BY_ZERO); *left = (*left / *right); break; case MODULO: /* always calculates a positive answer */ *left = fmod(*left, *right); if (*left < 0.0) { *left = (*left + fabs(*right)); } break; case POWER: CHKS(((*left < 0.0) && (floor(*right) != *right)), NCE_ATTEMPT_TO_RAISE_NEGATIVE_TO_NON_INTEGER_POWER); *left = pow(*left, *right); break; case TIMES: *left = (*left * *right); break; default: ERS(NCE_BUG_UNKNOWN_OPERATION); } return INTERP_OK; } /****************************************************************************/ /*! execute_binary2 Returned Value: int If any of the following errors occur, this returns the error code shown. Otherwise, it returns INTERP_OK. 1. operation is unknown: NCE_BUG_UNKNOWN_OPERATION Side effects: The result from performing the operation is put into what left points at. Called by: read_real_expression. This executes the operations: AND2, EXCLUSIVE_OR, MINUS, NON_EXCLUSIVE_OR, PLUS. The RS274/NGC manual [NCMS] does not say what the calculated value of the three logical operations should be. This function calculates either 1.0 (meaning true) or 0.0 (meaning false). Any non-zero input value is taken as meaning true, and only 0.0 means false. */ int Interp::execute_binary2(double *left, //!< pointer to the left operand int operation, //!< integer code for the operation double *right) //!< pointer to the right operand { double diff; switch (operation) { case AND2: *left = ((*left == 0.0) || (*right == 0.0)) ? 0.0 : 1.0; break; case EXCLUSIVE_OR: *left = (((*left == 0.0) && (*right != 0.0)) || ((*left != 0.0) && (*right == 0.0))) ? 1.0 : 0.0; break; case MINUS: *left = (*left - *right); break; case NON_EXCLUSIVE_OR: *left = ((*left != 0.0) || (*right != 0.0)) ? 1.0 : 0.0; break; case PLUS: *left = (*left + *right); break; case LT: *left = (*left < *right) ? 1.0 : 0.0; break; case EQ: diff = *left - *right; diff = (diff < 0) ? -diff : diff; *left = (diff < TOLERANCE_EQUAL) ? 1.0 : 0.0; break; case NE: diff = *left - *right; diff = (diff < 0) ? -diff : diff; *left = (diff >= TOLERANCE_EQUAL) ? 1.0 : 0.0; break; case LE: *left = (*left <= *right) ? 1.0 : 0.0; break; case GE: *left = (*left >= *right) ? 1.0 : 0.0; break; case GT: *left = (*left > *right) ? 1.0 : 0.0; break; default: ERS(NCE_BUG_UNKNOWN_OPERATION); } return INTERP_OK; } /****************************************************************************/ /*! execute_block Returned Value: int If convert_stop returns INTERP_EXIT, this returns INTERP_EXIT. If any of the following functions is called and returns an error code, this returns that code. convert_comment convert_feed_mode convert_feed_rate convert_g convert_m convert_speed convert_stop convert_tool_select Otherwise, if the probe_flag in the settings is true, or the input_flag is set to true this returns INTERP_EXECUTE_FINISH. Otherwise, it returns INTERP_OK. Side effects: One block of RS274/NGC instructions is executed. Called by: Interp::execute This converts a block to zero to many actions. The order of execution of items in a block is critical to safe and effective machine operation, but is not specified clearly in the RS274/NGC documentation. Actions are executed in the following order: 1. any comment. 2. a feed mode setting (g93, g94, g95) 3. a feed rate (f) setting if in units_per_minute feed mode. 4. a spindle speed (s) setting. 5. a tool selection (t). 6. "m" commands as described in convert_m (includes tool change). 7. any g_codes (except g93, g94) as described in convert_g. 8. stopping commands (m0, m1, m2, m30, or m60). In inverse time feed mode, the explicit and implicit g code executions include feed rate setting with g1, g2, and g3. Also in inverse time feed mode, attempting a canned cycle cycle (g81 to g89) or setting a feed rate with g0 is illegal and will be detected and result in an error message. */ int Interp::execute_block(block_pointer block, //!< pointer to a block of RS274/NGC instructions setup_pointer settings) //!< pointer to machine settings { int status; if (settings->remap_level == 0) { block->line_number = settings->sequence_number; } else { // use saved_line_number of toplevel for motion-id block->line_number = settings->blocks[settings->remap_level].saved_line_number; } if ((block->comment[0] != 0) && ONCE(STEP_COMMENT)) { status = convert_comment(block->comment); CHP(status); } if ((block->g_modes[GM_SPINDLE_MODE] != -1) && ONCE(STEP_SPINDLE_MODE)) { status = convert_spindle_mode(block, settings); CHP(status); } if ((block->g_modes[GM_FEED_MODE] != -1) && ONCE(STEP_FEED_MODE)) { status = convert_feed_mode(block->g_modes[GM_FEED_MODE], settings); CHP(status); } if (block->f_flag){ if ((settings->feed_mode != INVERSE_TIME) && ONCE(STEP_SET_FEED_RATE)) { if (STEP_REMAPPED_IN_BLOCK(block, STEP_SET_FEED_RATE)) { return (convert_remapped_code(block, settings, STEP_SET_FEED_RATE, 'F')); } else { status = convert_feed_rate(block, settings); CHP(status); } } /* INVERSE_TIME is handled elsewhere */ } if ((block->s_flag) && ONCE(STEP_SET_SPINDLE_SPEED)){ if (STEP_REMAPPED_IN_BLOCK(block, STEP_SET_SPINDLE_SPEED)) { return (convert_remapped_code(block,settings,STEP_SET_SPINDLE_SPEED,'S')); } else { status = convert_speed(block, settings); CHP(status); } } if ((block->t_flag) && ONCE(STEP_PREPARE)) { if (STEP_REMAPPED_IN_BLOCK(block, STEP_PREPARE)) { return (convert_remapped_code(block,settings,STEP_PREPARE,'T')); } else { CHP(convert_tool_select(block, settings)); } } CHP(convert_m(block, settings)); CHP(convert_g(block, settings)); if ((block->m_modes[4] != -1) && ONCE(STEP_MGROUP4)) { /* converts m0, m1, m2, m30, or m60 */ if (STEP_REMAPPED_IN_BLOCK(block, STEP_MGROUP4)) { status = convert_remapped_code(block,settings,STEP_MGROUP4,'M',block->m_modes[4]); } else { status = convert_stop(block, settings); } if (status == INTERP_EXIT) { return(INTERP_EXIT); } else if (status != INTERP_OK) { ERP(status); } } if (settings->probe_flag) return (INTERP_EXECUTE_FINISH); if (settings->input_flag) return (INTERP_EXECUTE_FINISH); if (settings->toolchange_flag) return (INTERP_EXECUTE_FINISH); return INTERP_OK; } /****************************************************************************/ /*! execute_unary Returned Value: int If any of the following errors occur, this returns the error code shown. Otherwise, it returns INTERP_OK. 1. the operation is unknown: NCE_BUG_UNKNOWN_OPERATION 2. the argument to acos is not between minus and plus one: NCE_ARGUMENT_TO_ACOS_OUT_RANGE 3. the argument to asin is not between minus and plus one: NCE_ARGUMENT_TO_ASIN_OUT_RANGE 4. the argument to the natural logarithm is not positive: NCE_ZERO_OR_NEGATIVE_ARGUMENT_TO_LN 5. the argument to square root is negative: NCE_NEGATIVE_ARGUMENT_TO_SQRT Side effects: The result from performing the operation on the value in double_ptr is put into what double_ptr points at. Called by: read_unary. This executes the operations: ABS, ACOS, ASIN, COS, EXP, FIX, FUP, LN ROUND, SIN, SQRT, TAN All angle measures in the input or output are in degrees. */ int Interp::execute_unary(double *double_ptr, //!< pointer to the operand int operation) //!< integer code for the operation { switch (operation) { case ABS: if (*double_ptr < 0.0) *double_ptr = (-1.0 * *double_ptr); break; case ACOS: CHKS(((*double_ptr < -1.0) || (*double_ptr > 1.0)), NCE_ARGUMENT_TO_ACOS_OUT_OF_RANGE); *double_ptr = acos(*double_ptr); *double_ptr = ((*double_ptr * 180.0) / M_PIl); break; case ASIN: CHKS(((*double_ptr < -1.0) || (*double_ptr > 1.0)), NCE_ARGUMENT_TO_ASIN_OUT_OF_RANGE); *double_ptr = asin(*double_ptr); *double_ptr = ((*double_ptr * 180.0) / M_PIl); break; case COS: *double_ptr = cos((*double_ptr * M_PIl) / 180.0); break; case EXISTS: // do nothing here // result for the EXISTS function is set by Interp:read_unary() break; case EXP: *double_ptr = exp(*double_ptr); break; case FIX: *double_ptr = floor(*double_ptr); break; case FUP: *double_ptr = ceil(*double_ptr); break; case LN: CHKS((*double_ptr <= 0.0), NCE_ZERO_OR_NEGATIVE_ARGUMENT_TO_LN); *double_ptr = log(*double_ptr); break; case ROUND: *double_ptr = (double) ((int) (*double_ptr + ((*double_ptr < 0.0) ? -0.5 : 0.5))); break; case SIN: *double_ptr = sin((*double_ptr * M_PIl) / 180.0); break; case SQRT: CHKS((*double_ptr < 0.0), NCE_NEGATIVE_ARGUMENT_TO_SQRT); *double_ptr = sqrt(*double_ptr); break; case TAN: *double_ptr = tan((*double_ptr * M_PIl) / 180.0); break; default: ERS(NCE_BUG_UNKNOWN_OPERATION); } return INTERP_OK; } <commit_msg>Interp::execute_block(): remove INTERP_EXECUTE_FINISH<commit_after>/******************************************************************** * Description: interp_execute.cc * * Derived from a work by Thomas Kramer * * Author: * License: GPL Version 2 * System: Linux * * Copyright (c) 2004 All rights reserved. * * Last change: ********************************************************************/ #ifndef _GNU_SOURCE #define _GNU_SOURCE #endif #include <boost/python.hpp> #include <unistd.h> #include <stdio.h> #include <stdlib.h> #include <math.h> #include <string.h> #include <ctype.h> #include <sys/types.h> #include <sys/stat.h> #include "rs274ngc.hh" #include "rs274ngc_return.hh" #include "interp_internal.hh" #include "rs274ngc_interp.hh" /****************************************************************************/ /*! execute binary Returned value: int If execute_binary1 or execute_binary2 returns an error code, this returns that code. Otherwise, it returns INTERP_OK. Side effects: The value of left is set to the result of applying the operation to left and right. Called by: read_real_expression This just calls either execute_binary1 or execute_binary2. */ int Interp::execute_binary(double *left, int operation, double *right) { if (operation < AND2) CHP(execute_binary1(left, operation, right)); else CHP(execute_binary2(left, operation, right)); return INTERP_OK; } /****************************************************************************/ /*! execute_binary1 Returned Value: int If any of the following errors occur, this returns the error shown. Otherwise, it returns INTERP_OK. 1. operation is unknown: NCE_BUG_UNKNOWN_OPERATION 2. An attempt is made to divide by zero: NCE_ATTEMPT_TO_DIVIDE_BY_ZERO 3. An attempt is made to raise a negative number to a non-integer power: NCE_ATTEMPT_TO_RAISE_NEGATIVE_TO_NON_INTEGER_POWER Side effects: The result from performing the operation is put into what left points at. Called by: read_real_expression. This executes the operations: DIVIDED_BY, MODULO, POWER, TIMES. */ int Interp::execute_binary1(double *left, //!< pointer to the left operand int operation, //!< integer code for the operation double *right) //!< pointer to the right operand { switch (operation) { case DIVIDED_BY: CHKS((*right == 0.0), NCE_ATTEMPT_TO_DIVIDE_BY_ZERO); *left = (*left / *right); break; case MODULO: /* always calculates a positive answer */ *left = fmod(*left, *right); if (*left < 0.0) { *left = (*left + fabs(*right)); } break; case POWER: CHKS(((*left < 0.0) && (floor(*right) != *right)), NCE_ATTEMPT_TO_RAISE_NEGATIVE_TO_NON_INTEGER_POWER); *left = pow(*left, *right); break; case TIMES: *left = (*left * *right); break; default: ERS(NCE_BUG_UNKNOWN_OPERATION); } return INTERP_OK; } /****************************************************************************/ /*! execute_binary2 Returned Value: int If any of the following errors occur, this returns the error code shown. Otherwise, it returns INTERP_OK. 1. operation is unknown: NCE_BUG_UNKNOWN_OPERATION Side effects: The result from performing the operation is put into what left points at. Called by: read_real_expression. This executes the operations: AND2, EXCLUSIVE_OR, MINUS, NON_EXCLUSIVE_OR, PLUS. The RS274/NGC manual [NCMS] does not say what the calculated value of the three logical operations should be. This function calculates either 1.0 (meaning true) or 0.0 (meaning false). Any non-zero input value is taken as meaning true, and only 0.0 means false. */ int Interp::execute_binary2(double *left, //!< pointer to the left operand int operation, //!< integer code for the operation double *right) //!< pointer to the right operand { double diff; switch (operation) { case AND2: *left = ((*left == 0.0) || (*right == 0.0)) ? 0.0 : 1.0; break; case EXCLUSIVE_OR: *left = (((*left == 0.0) && (*right != 0.0)) || ((*left != 0.0) && (*right == 0.0))) ? 1.0 : 0.0; break; case MINUS: *left = (*left - *right); break; case NON_EXCLUSIVE_OR: *left = ((*left != 0.0) || (*right != 0.0)) ? 1.0 : 0.0; break; case PLUS: *left = (*left + *right); break; case LT: *left = (*left < *right) ? 1.0 : 0.0; break; case EQ: diff = *left - *right; diff = (diff < 0) ? -diff : diff; *left = (diff < TOLERANCE_EQUAL) ? 1.0 : 0.0; break; case NE: diff = *left - *right; diff = (diff < 0) ? -diff : diff; *left = (diff >= TOLERANCE_EQUAL) ? 1.0 : 0.0; break; case LE: *left = (*left <= *right) ? 1.0 : 0.0; break; case GE: *left = (*left >= *right) ? 1.0 : 0.0; break; case GT: *left = (*left > *right) ? 1.0 : 0.0; break; default: ERS(NCE_BUG_UNKNOWN_OPERATION); } return INTERP_OK; } /****************************************************************************/ /*! execute_block Returned Value: int If convert_stop returns INTERP_EXIT, this returns INTERP_EXIT. If any of the following functions is called and returns an error code, this returns that code. convert_comment convert_feed_mode convert_feed_rate convert_g convert_m convert_speed convert_stop convert_tool_select Otherwise, it returns INTERP_OK. Side effects: One block of RS274/NGC instructions is executed. Called by: Interp::execute This converts a block to zero to many actions. The order of execution of items in a block is critical to safe and effective machine operation, but is not specified clearly in the RS274/NGC documentation. Actions are executed in the following order: 1. any comment. 2. a feed mode setting (g93, g94, g95) 3. a feed rate (f) setting if in units_per_minute feed mode. 4. a spindle speed (s) setting. 5. a tool selection (t). 6. "m" commands as described in convert_m (includes tool change). 7. any g_codes (except g93, g94) as described in convert_g. 8. stopping commands (m0, m1, m2, m30, or m60). In inverse time feed mode, the explicit and implicit g code executions include feed rate setting with g1, g2, and g3. Also in inverse time feed mode, attempting a canned cycle cycle (g81 to g89) or setting a feed rate with g0 is illegal and will be detected and result in an error message. */ int Interp::execute_block(block_pointer block, //!< pointer to a block of RS274/NGC instructions setup_pointer settings) //!< pointer to machine settings { int status; if (settings->remap_level == 0) { block->line_number = settings->sequence_number; } else { // use saved_line_number of toplevel for motion-id block->line_number = settings->blocks[settings->remap_level].saved_line_number; } if ((block->comment[0] != 0) && ONCE(STEP_COMMENT)) { status = convert_comment(block->comment); CHP(status); } if ((block->g_modes[GM_SPINDLE_MODE] != -1) && ONCE(STEP_SPINDLE_MODE)) { status = convert_spindle_mode(block, settings); CHP(status); } if ((block->g_modes[GM_FEED_MODE] != -1) && ONCE(STEP_FEED_MODE)) { status = convert_feed_mode(block->g_modes[GM_FEED_MODE], settings); CHP(status); } if (block->f_flag){ if ((settings->feed_mode != INVERSE_TIME) && ONCE(STEP_SET_FEED_RATE)) { if (STEP_REMAPPED_IN_BLOCK(block, STEP_SET_FEED_RATE)) { return (convert_remapped_code(block, settings, STEP_SET_FEED_RATE, 'F')); } else { status = convert_feed_rate(block, settings); CHP(status); } } /* INVERSE_TIME is handled elsewhere */ } if ((block->s_flag) && ONCE(STEP_SET_SPINDLE_SPEED)){ if (STEP_REMAPPED_IN_BLOCK(block, STEP_SET_SPINDLE_SPEED)) { return (convert_remapped_code(block,settings,STEP_SET_SPINDLE_SPEED,'S')); } else { status = convert_speed(block, settings); CHP(status); } } if ((block->t_flag) && ONCE(STEP_PREPARE)) { if (STEP_REMAPPED_IN_BLOCK(block, STEP_PREPARE)) { return (convert_remapped_code(block,settings,STEP_PREPARE,'T')); } else { CHP(convert_tool_select(block, settings)); } } CHP(convert_m(block, settings)); CHP(convert_g(block, settings)); if ((block->m_modes[4] != -1) && ONCE(STEP_MGROUP4)) { /* converts m0, m1, m2, m30, or m60 */ if (STEP_REMAPPED_IN_BLOCK(block, STEP_MGROUP4)) { status = convert_remapped_code(block,settings,STEP_MGROUP4,'M',block->m_modes[4]); } else { status = convert_stop(block, settings); } if (status == INTERP_EXIT) { return(INTERP_EXIT); } else if (status != INTERP_OK) { ERP(status); } } return INTERP_OK; } /****************************************************************************/ /*! execute_unary Returned Value: int If any of the following errors occur, this returns the error code shown. Otherwise, it returns INTERP_OK. 1. the operation is unknown: NCE_BUG_UNKNOWN_OPERATION 2. the argument to acos is not between minus and plus one: NCE_ARGUMENT_TO_ACOS_OUT_RANGE 3. the argument to asin is not between minus and plus one: NCE_ARGUMENT_TO_ASIN_OUT_RANGE 4. the argument to the natural logarithm is not positive: NCE_ZERO_OR_NEGATIVE_ARGUMENT_TO_LN 5. the argument to square root is negative: NCE_NEGATIVE_ARGUMENT_TO_SQRT Side effects: The result from performing the operation on the value in double_ptr is put into what double_ptr points at. Called by: read_unary. This executes the operations: ABS, ACOS, ASIN, COS, EXP, FIX, FUP, LN ROUND, SIN, SQRT, TAN All angle measures in the input or output are in degrees. */ int Interp::execute_unary(double *double_ptr, //!< pointer to the operand int operation) //!< integer code for the operation { switch (operation) { case ABS: if (*double_ptr < 0.0) *double_ptr = (-1.0 * *double_ptr); break; case ACOS: CHKS(((*double_ptr < -1.0) || (*double_ptr > 1.0)), NCE_ARGUMENT_TO_ACOS_OUT_OF_RANGE); *double_ptr = acos(*double_ptr); *double_ptr = ((*double_ptr * 180.0) / M_PIl); break; case ASIN: CHKS(((*double_ptr < -1.0) || (*double_ptr > 1.0)), NCE_ARGUMENT_TO_ASIN_OUT_OF_RANGE); *double_ptr = asin(*double_ptr); *double_ptr = ((*double_ptr * 180.0) / M_PIl); break; case COS: *double_ptr = cos((*double_ptr * M_PIl) / 180.0); break; case EXISTS: // do nothing here // result for the EXISTS function is set by Interp:read_unary() break; case EXP: *double_ptr = exp(*double_ptr); break; case FIX: *double_ptr = floor(*double_ptr); break; case FUP: *double_ptr = ceil(*double_ptr); break; case LN: CHKS((*double_ptr <= 0.0), NCE_ZERO_OR_NEGATIVE_ARGUMENT_TO_LN); *double_ptr = log(*double_ptr); break; case ROUND: *double_ptr = (double) ((int) (*double_ptr + ((*double_ptr < 0.0) ? -0.5 : 0.5))); break; case SIN: *double_ptr = sin((*double_ptr * M_PIl) / 180.0); break; case SQRT: CHKS((*double_ptr < 0.0), NCE_NEGATIVE_ARGUMENT_TO_SQRT); *double_ptr = sqrt(*double_ptr); break; case TAN: *double_ptr = tan((*double_ptr * M_PIl) / 180.0); break; default: ERS(NCE_BUG_UNKNOWN_OPERATION); } return INTERP_OK; } <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: listenernotification.cxx,v $ * * $Revision: 1.4 $ * * last change: $Author: rt $ $Date: 2004-11-26 21:08:50 $ * * 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 COMPHELPER_INC_COMPHELPER_LISTENERNOTIFICATION_HXX #include <comphelper/listenernotification.hxx> #endif /** === begin UNO includes === **/ #ifndef _COM_SUN_STAR_LANG_DISPOSEDEXCEPTION_HPP_ #include <com/sun/star/lang/DisposedException.hpp> #endif /** === end UNO includes === **/ //........................................................................ namespace comphelper { //........................................................................ using namespace ::com::sun::star::uno; using namespace ::com::sun::star::lang; //==================================================================== //= OListenerContainer //==================================================================== //-------------------------------------------------------------------- OListenerContainer::OListenerContainer( ::osl::Mutex& _rMutex ) :m_aListeners( _rMutex ) { } //-------------------------------------------------------------------- void OListenerContainer::addListener( const Reference< XEventListener >& _rxListener ) { OSL_PRECOND( _rxListener.is(), "OListenerContainer::addListener: a NULL listener?!" ); if ( _rxListener.is() ) m_aListeners.addInterface( _rxListener ); } //-------------------------------------------------------------------- void OListenerContainer::removeListener( const Reference< XEventListener >& _rxListener ) { #if OSL_DEBUG_LEVEL > 0 ::cppu::OInterfaceIteratorHelper aIter( m_aListeners ); bool bFound = false; while ( aIter.hasMoreElements() && !bFound ) { bFound = ( Reference< XInterface >( aIter.next() ) == _rxListener ); } OSL_ENSURE( bFound, "OListenerContainer::removeListener: sure your listener handling is correct? The given listener is not registered!" ); #endif m_aListeners.removeInterface( _rxListener ); } //-------------------------------------------------------------------- void OListenerContainer::disposing( const EventObject& _rEventSource ) { m_aListeners.disposeAndClear( _rEventSource ); } //-------------------------------------------------------------------- bool OListenerContainer::notify( const EventObject& _rEvent ) SAL_THROW(( Exception )) { ::cppu::OInterfaceIteratorHelper aIter( m_aListeners ); bool bCancelled = false; while ( aIter.hasMoreElements() && !bCancelled ) { Reference< XEventListener > xListener( static_cast< XEventListener* >( aIter.next() ) ); if ( !xListener.is() ) continue; try { bCancelled = !implNotify( xListener, _rEvent ); } catch( const DisposedException& e ) { // DisposedExceptions from the listener might indicate a // broken connection to a different environment. OSL_ENSURE( e.Context.is(), "OListenerContainer::notify: caught dispose exception with empty Context field" ); // If the exception stems from the listener then remove it // from the list of listeners. If the Context field of the // exception is empty this is interpreted to indicate the // listener as well. if ( e.Context == xListener || !e.Context.is() ) aIter.remove(); } } return !bCancelled; } //........................................................................ } // namespace comphelper //........................................................................ <commit_msg>INTEGRATION: CWS ooo19126 (1.4.84); FILE MERGED 2005/09/05 15:24:01 rt 1.4.84.1: #i54170# Change license header: remove SISSL<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: listenernotification.cxx,v $ * * $Revision: 1.5 $ * * last change: $Author: rt $ $Date: 2005-09-08 02:50:23 $ * * 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 COMPHELPER_INC_COMPHELPER_LISTENERNOTIFICATION_HXX #include <comphelper/listenernotification.hxx> #endif /** === begin UNO includes === **/ #ifndef _COM_SUN_STAR_LANG_DISPOSEDEXCEPTION_HPP_ #include <com/sun/star/lang/DisposedException.hpp> #endif /** === end UNO includes === **/ //........................................................................ namespace comphelper { //........................................................................ using namespace ::com::sun::star::uno; using namespace ::com::sun::star::lang; //==================================================================== //= OListenerContainer //==================================================================== //-------------------------------------------------------------------- OListenerContainer::OListenerContainer( ::osl::Mutex& _rMutex ) :m_aListeners( _rMutex ) { } //-------------------------------------------------------------------- void OListenerContainer::addListener( const Reference< XEventListener >& _rxListener ) { OSL_PRECOND( _rxListener.is(), "OListenerContainer::addListener: a NULL listener?!" ); if ( _rxListener.is() ) m_aListeners.addInterface( _rxListener ); } //-------------------------------------------------------------------- void OListenerContainer::removeListener( const Reference< XEventListener >& _rxListener ) { #if OSL_DEBUG_LEVEL > 0 ::cppu::OInterfaceIteratorHelper aIter( m_aListeners ); bool bFound = false; while ( aIter.hasMoreElements() && !bFound ) { bFound = ( Reference< XInterface >( aIter.next() ) == _rxListener ); } OSL_ENSURE( bFound, "OListenerContainer::removeListener: sure your listener handling is correct? The given listener is not registered!" ); #endif m_aListeners.removeInterface( _rxListener ); } //-------------------------------------------------------------------- void OListenerContainer::disposing( const EventObject& _rEventSource ) { m_aListeners.disposeAndClear( _rEventSource ); } //-------------------------------------------------------------------- bool OListenerContainer::notify( const EventObject& _rEvent ) SAL_THROW(( Exception )) { ::cppu::OInterfaceIteratorHelper aIter( m_aListeners ); bool bCancelled = false; while ( aIter.hasMoreElements() && !bCancelled ) { Reference< XEventListener > xListener( static_cast< XEventListener* >( aIter.next() ) ); if ( !xListener.is() ) continue; try { bCancelled = !implNotify( xListener, _rEvent ); } catch( const DisposedException& e ) { // DisposedExceptions from the listener might indicate a // broken connection to a different environment. OSL_ENSURE( e.Context.is(), "OListenerContainer::notify: caught dispose exception with empty Context field" ); // If the exception stems from the listener then remove it // from the list of listeners. If the Context field of the // exception is empty this is interpreted to indicate the // listener as well. if ( e.Context == xListener || !e.Context.is() ) aIter.remove(); } } return !bCancelled; } //........................................................................ } // namespace comphelper //........................................................................ <|endoftext|>
<commit_before>// Copyright (c) 2009, Google Inc. // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // Unit tests for FileID #include <elf.h> #include <stdlib.h> #include "common/linux/file_id.h" #include "breakpad_googletest_includes.h" using namespace google_breakpad; namespace { typedef testing::Test FileIDTest; } TEST(FileIDTest, FileIDStrip) { // Calculate the File ID of our binary using // FileID::ElfFileIdentifier, then make a copy of our binary, // strip it, and ensure that we still get the same result. char exe_name[PATH_MAX]; ssize_t len = readlink("/proc/self/exe", exe_name, PATH_MAX - 1); ASSERT_NE(len, -1); exe_name[len] = '\0'; // copy our binary to a temp file, and strip it char templ[] = "/tmp/file-id-unittest-XXXXXX"; mktemp(templ); char cmdline[4096]; sprintf(cmdline, "cp \"%s\" \"%s\"", exe_name, templ); ASSERT_EQ(system(cmdline), 0); sprintf(cmdline, "strip \"%s\"", templ); ASSERT_EQ(system(cmdline), 0); uint8_t identifier1[sizeof(MDGUID)]; uint8_t identifier2[sizeof(MDGUID)]; FileID fileid1(exe_name); EXPECT_TRUE(fileid1.ElfFileIdentifier(identifier1)); FileID fileid2(templ); EXPECT_TRUE(fileid2.ElfFileIdentifier(identifier2)); char identifier_string1[37]; char identifier_string2[37]; FileID::ConvertIdentifierToString(identifier1, identifier_string1, 37); FileID::ConvertIdentifierToString(identifier2, identifier_string2, 37); EXPECT_STREQ(identifier_string1, identifier_string2); unlink(templ); } struct ElfClass32 { typedef Elf32_Ehdr Ehdr; typedef Elf32_Shdr Shdr; static const int kClass = ELFCLASS32; }; struct ElfClass64 { typedef Elf64_Ehdr Ehdr; typedef Elf64_Shdr Shdr; static const int kClass = ELFCLASS64; }; template<typename ElfClass> struct ElfishElf { typedef typename ElfClass::Ehdr Ehdr; typedef typename ElfClass::Shdr Shdr; Ehdr elf_header; Shdr text_header; Shdr string_header; char text_section[128]; char string_section[8]; static void Populate(ElfishElf* elf) { memset(elf, 0, sizeof(ElfishElf)); memcpy(elf, ELFMAG, SELFMAG); elf->elf_header.e_ident[EI_CLASS] = ElfClass::kClass; elf->elf_header.e_shoff = offsetof(ElfishElf, text_header); elf->elf_header.e_shnum = 2; elf->elf_header.e_shstrndx = 1; elf->text_header.sh_name = 0; elf->text_header.sh_type = SHT_PROGBITS; elf->text_header.sh_offset = offsetof(ElfishElf, text_section); elf->text_header.sh_size = sizeof(text_section); for (size_t i = 0; i < sizeof(text_section); ++i) { elf->text_section[i] = i * 3; } elf->string_header.sh_offset = offsetof(ElfishElf, string_section); strcpy(elf->string_section, ".text"); } }; TEST(FileIDTest, ElfClass) { uint8_t identifier[sizeof(MDGUID)]; const char expected_identifier_string[] = "80808080-8080-0000-0000-008080808080"; char identifier_string[sizeof(expected_identifier_string)]; ElfishElf<ElfClass32> elf32; ElfishElf<ElfClass32>::Populate(&elf32); EXPECT_TRUE(FileID::ElfFileIdentifierFromMappedFile(&elf32, identifier)); FileID::ConvertIdentifierToString(identifier, identifier_string, sizeof(identifier_string)); EXPECT_STREQ(expected_identifier_string, identifier_string); memset(identifier, 0, sizeof(identifier)); memset(identifier_string, 0, sizeof(identifier_string)); ElfishElf<ElfClass64> elf64; ElfishElf<ElfClass64>::Populate(&elf64); EXPECT_TRUE(FileID::ElfFileIdentifierFromMappedFile(&elf64, identifier)); FileID::ConvertIdentifierToString(identifier, identifier_string, sizeof(identifier_string)); EXPECT_STREQ(expected_identifier_string, identifier_string); } <commit_msg>Fix compilation of file_id_unittest. Review URL: http://breakpad.appspot.com/198001<commit_after>// Copyright (c) 2010, Google Inc. // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // Unit tests for FileID #include <elf.h> #include <stdlib.h> #include "common/linux/file_id.h" #include "breakpad_googletest_includes.h" using namespace google_breakpad; namespace { typedef testing::Test FileIDTest; } TEST(FileIDTest, FileIDStrip) { // Calculate the File ID of our binary using // FileID::ElfFileIdentifier, then make a copy of our binary, // strip it, and ensure that we still get the same result. char exe_name[PATH_MAX]; ssize_t len = readlink("/proc/self/exe", exe_name, PATH_MAX - 1); ASSERT_NE(len, -1); exe_name[len] = '\0'; // copy our binary to a temp file, and strip it char templ[] = "/tmp/file-id-unittest-XXXXXX"; mktemp(templ); char cmdline[4096]; sprintf(cmdline, "cp \"%s\" \"%s\"", exe_name, templ); ASSERT_EQ(system(cmdline), 0); sprintf(cmdline, "strip \"%s\"", templ); ASSERT_EQ(system(cmdline), 0); uint8_t identifier1[sizeof(MDGUID)]; uint8_t identifier2[sizeof(MDGUID)]; FileID fileid1(exe_name); EXPECT_TRUE(fileid1.ElfFileIdentifier(identifier1)); FileID fileid2(templ); EXPECT_TRUE(fileid2.ElfFileIdentifier(identifier2)); char identifier_string1[37]; char identifier_string2[37]; FileID::ConvertIdentifierToString(identifier1, identifier_string1, 37); FileID::ConvertIdentifierToString(identifier2, identifier_string2, 37); EXPECT_STREQ(identifier_string1, identifier_string2); unlink(templ); } struct ElfClass32 { typedef Elf32_Ehdr Ehdr; typedef Elf32_Shdr Shdr; static const int kClass = ELFCLASS32; }; struct ElfClass64 { typedef Elf64_Ehdr Ehdr; typedef Elf64_Shdr Shdr; static const int kClass = ELFCLASS64; }; template<typename ElfClass> struct ElfishElf { static const size_t kTextSectionSize = 128; typedef typename ElfClass::Ehdr Ehdr; typedef typename ElfClass::Shdr Shdr; Ehdr elf_header; Shdr text_header; Shdr string_header; char text_section[kTextSectionSize]; char string_section[8]; static void Populate(ElfishElf* elf) { memset(elf, 0, sizeof(ElfishElf)); memcpy(elf, ELFMAG, SELFMAG); elf->elf_header.e_ident[EI_CLASS] = ElfClass::kClass; elf->elf_header.e_shoff = offsetof(ElfishElf, text_header); elf->elf_header.e_shnum = 2; elf->elf_header.e_shstrndx = 1; elf->text_header.sh_name = 0; elf->text_header.sh_type = SHT_PROGBITS; elf->text_header.sh_offset = offsetof(ElfishElf, text_section); elf->text_header.sh_size = kTextSectionSize; for (size_t i = 0; i < kTextSectionSize; ++i) { elf->text_section[i] = i * 3; } elf->string_header.sh_offset = offsetof(ElfishElf, string_section); strcpy(elf->string_section, ".text"); } }; TEST(FileIDTest, ElfClass) { uint8_t identifier[sizeof(MDGUID)]; const char expected_identifier_string[] = "80808080-8080-0000-0000-008080808080"; char identifier_string[sizeof(expected_identifier_string)]; ElfishElf<ElfClass32> elf32; ElfishElf<ElfClass32>::Populate(&elf32); EXPECT_TRUE(FileID::ElfFileIdentifierFromMappedFile(&elf32, identifier)); FileID::ConvertIdentifierToString(identifier, identifier_string, sizeof(identifier_string)); EXPECT_STREQ(expected_identifier_string, identifier_string); memset(identifier, 0, sizeof(identifier)); memset(identifier_string, 0, sizeof(identifier_string)); ElfishElf<ElfClass64> elf64; ElfishElf<ElfClass64>::Populate(&elf64); EXPECT_TRUE(FileID::ElfFileIdentifierFromMappedFile(&elf64, identifier)); FileID::ConvertIdentifierToString(identifier, identifier_string, sizeof(identifier_string)); EXPECT_STREQ(expected_identifier_string, identifier_string); } <|endoftext|>
<commit_before>/** ****************************************************************************** * Xenia : Xbox 360 Emulator Research Project * ****************************************************************************** * Copyright 2015 Ben Vanik. All rights reserved. * * Released under the BSD license - see LICENSE in the root for more details. * ****************************************************************************** */ #include <algorithm> #include "xenia/base/assert.h" #include "xenia/base/logging.h" #include "xenia/base/math.h" #include "xenia/ui/vulkan/circular_buffer.h" namespace xe { namespace ui { namespace vulkan { CircularBuffer::CircularBuffer(VulkanDevice* device, VkBufferUsageFlags usage, VkDeviceSize capacity, VkDeviceSize alignment) : device_(device), capacity_(capacity) { VkResult status = VK_SUCCESS; // Create our internal buffer. VkBufferCreateInfo buffer_info; buffer_info.sType = VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO; buffer_info.pNext = nullptr; buffer_info.flags = 0; buffer_info.size = capacity; buffer_info.usage = usage; buffer_info.sharingMode = VK_SHARING_MODE_EXCLUSIVE; buffer_info.queueFamilyIndexCount = 0; buffer_info.pQueueFamilyIndices = nullptr; status = vkCreateBuffer(*device_, &buffer_info, nullptr, &gpu_buffer_); CheckResult(status, "vkCreateBuffer"); if (status != VK_SUCCESS) { assert_always(); } VkMemoryRequirements reqs; vkGetBufferMemoryRequirements(*device_, gpu_buffer_, &reqs); alignment_ = reqs.alignment; } CircularBuffer::~CircularBuffer() { Shutdown(); } VkResult CircularBuffer::Initialize(VkDeviceMemory memory, VkDeviceSize offset) { assert_true(offset % alignment_ == 0); gpu_memory_ = memory; gpu_base_ = offset; VkResult status = VK_SUCCESS; // Bind the buffer to its backing memory. status = vkBindBufferMemory(*device_, gpu_buffer_, gpu_memory_, gpu_base_); CheckResult(status, "vkBindBufferMemory"); if (status != VK_SUCCESS) { XELOGE("CircularBuffer::Initialize - Failed to bind memory!"); Shutdown(); return status; } // Map the memory so we can access it. status = vkMapMemory(*device_, gpu_memory_, gpu_base_, capacity_, 0, reinterpret_cast<void**>(&host_base_)); CheckResult(status, "vkMapMemory"); if (status != VK_SUCCESS) { XELOGE("CircularBuffer::Initialize - Failed to map memory!"); Shutdown(); return status; } return VK_SUCCESS; } VkResult CircularBuffer::Initialize() { VkResult status = VK_SUCCESS; VkMemoryRequirements reqs; vkGetBufferMemoryRequirements(*device_, gpu_buffer_, &reqs); // Allocate memory from the device to back the buffer. owns_gpu_memory_ = true; gpu_memory_ = device_->AllocateMemory(reqs); if (!gpu_memory_) { XELOGE("CircularBuffer::Initialize - Failed to allocate memory!"); Shutdown(); return VK_ERROR_INITIALIZATION_FAILED; } capacity_ = reqs.size; gpu_base_ = 0; // Bind the buffer to its backing memory. status = vkBindBufferMemory(*device_, gpu_buffer_, gpu_memory_, gpu_base_); CheckResult(status, "vkBindBufferMemory"); if (status != VK_SUCCESS) { XELOGE("CircularBuffer::Initialize - Failed to bind memory!"); Shutdown(); return status; } // Map the memory so we can access it. status = vkMapMemory(*device_, gpu_memory_, gpu_base_, capacity_, 0, reinterpret_cast<void**>(&host_base_)); CheckResult(status, "vkMapMemory"); if (status != VK_SUCCESS) { XELOGE("CircularBuffer::Initialize - Failed to map memory!"); Shutdown(); return status; } return VK_SUCCESS; } void CircularBuffer::Shutdown() { Clear(); if (host_base_) { vkUnmapMemory(*device_, gpu_memory_); host_base_ = nullptr; } if (gpu_buffer_) { vkDestroyBuffer(*device_, gpu_buffer_, nullptr); gpu_buffer_ = nullptr; } if (gpu_memory_ && owns_gpu_memory_) { vkFreeMemory(*device_, gpu_memory_, nullptr); gpu_memory_ = nullptr; } } void CircularBuffer::GetBufferMemoryRequirements(VkMemoryRequirements* reqs) { vkGetBufferMemoryRequirements(*device_, gpu_buffer_, reqs); } bool CircularBuffer::CanAcquire(VkDeviceSize length) { // Make sure the length is aligned. length = xe::round_up(length, alignment_); if (allocations_.empty()) { // Read head has caught up to write head (entire buffer available for write) assert_true(read_head_ == write_head_); return capacity_ >= length; } else if (write_head_ < read_head_) { // Write head wrapped around and is behind read head. // | write |---- read ----| return (read_head_ - write_head_) >= length; } else if (write_head_ > read_head_) { // Read head behind write head. // 1. Check if there's enough room from write -> capacity // | |---- read ----| write | if ((capacity_ - write_head_) >= length) { return true; } // 2. Check if there's enough room from 0 -> read // | write |---- read ----| | if ((read_head_ - 0) >= length) { return true; } } return false; } CircularBuffer::Allocation* CircularBuffer::Acquire(VkDeviceSize length, VkFence fence) { VkDeviceSize aligned_length = xe::round_up(length, alignment_); if (!CanAcquire(aligned_length)) { return nullptr; } assert_true(write_head_ % alignment_ == 0); if (write_head_ < read_head_) { // Write head behind read head. assert_true(read_head_ - write_head_ >= aligned_length); auto alloc = new Allocation(); alloc->host_ptr = host_base_ + write_head_; alloc->gpu_memory = gpu_memory_; alloc->offset = gpu_base_ + write_head_; alloc->length = length; alloc->aligned_length = aligned_length; alloc->fence = fence; write_head_ += aligned_length; allocations_.push_back(alloc); return alloc; } else { // Write head equal to/after read head if (capacity_ - write_head_ >= aligned_length) { // Free space from write -> capacity auto alloc = new Allocation(); alloc->host_ptr = host_base_ + write_head_; alloc->gpu_memory = gpu_memory_; alloc->offset = gpu_base_ + write_head_; alloc->length = length; alloc->aligned_length = aligned_length; alloc->fence = fence; write_head_ += aligned_length; allocations_.push_back(alloc); return alloc; } else if ((read_head_ - 0) >= aligned_length) { // Not enough space from write -> capacity, but there is enough free space // from begin -> read auto alloc = new Allocation(); alloc->host_ptr = host_base_ + 0; alloc->gpu_memory = gpu_memory_; alloc->offset = gpu_base_ + 0; alloc->length = length; alloc->aligned_length = aligned_length; alloc->fence = fence; write_head_ = aligned_length; allocations_.push_back(alloc); return alloc; } } return nullptr; } void CircularBuffer::Flush(Allocation* allocation) { VkMappedMemoryRange range; range.sType = VK_STRUCTURE_TYPE_MAPPED_MEMORY_RANGE; range.pNext = nullptr; range.memory = gpu_memory_; range.offset = gpu_base_ + allocation->offset; range.size = allocation->length; vkFlushMappedMemoryRanges(*device_, 1, &range); } void CircularBuffer::Flush(VkDeviceSize offset, VkDeviceSize length) { VkMappedMemoryRange range; range.sType = VK_STRUCTURE_TYPE_MAPPED_MEMORY_RANGE; range.pNext = nullptr; range.memory = gpu_memory_; range.offset = gpu_base_ + offset; range.size = length; vkFlushMappedMemoryRanges(*device_, 1, &range); } void CircularBuffer::Clear() { for (auto alloc : allocations_) { delete alloc; } allocations_.clear(); write_head_ = read_head_ = 0; } void CircularBuffer::Scavenge() { for (auto it = allocations_.begin(); it != allocations_.end();) { if (vkGetFenceStatus(*device_, (*it)->fence) != VK_SUCCESS) { // Don't bother freeing following allocations to ensure proper ordering. break; } if (capacity_ - read_head_ < (*it)->aligned_length) { // This allocation is stored at the beginning of the buffer. read_head_ = (*it)->aligned_length; } else { read_head_ += (*it)->aligned_length; } delete *it; it = allocations_.erase(it); } if (allocations_.empty()) { // Reset R/W heads to work around fragmentation issues. read_head_ = write_head_ = 0; } } } // namespace vulkan } // namespace ui } // namespace xe<commit_msg>[Vulkan UI] CircularBuffer: Actually use provided alignment<commit_after>/** ****************************************************************************** * Xenia : Xbox 360 Emulator Research Project * ****************************************************************************** * Copyright 2015 Ben Vanik. All rights reserved. * * Released under the BSD license - see LICENSE in the root for more details. * ****************************************************************************** */ #include <algorithm> #include "xenia/base/assert.h" #include "xenia/base/logging.h" #include "xenia/base/math.h" #include "xenia/ui/vulkan/circular_buffer.h" namespace xe { namespace ui { namespace vulkan { CircularBuffer::CircularBuffer(VulkanDevice* device, VkBufferUsageFlags usage, VkDeviceSize capacity, VkDeviceSize alignment) : device_(device), capacity_(capacity) { VkResult status = VK_SUCCESS; // Create our internal buffer. VkBufferCreateInfo buffer_info; buffer_info.sType = VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO; buffer_info.pNext = nullptr; buffer_info.flags = 0; buffer_info.size = capacity; buffer_info.usage = usage; buffer_info.sharingMode = VK_SHARING_MODE_EXCLUSIVE; buffer_info.queueFamilyIndexCount = 0; buffer_info.pQueueFamilyIndices = nullptr; status = vkCreateBuffer(*device_, &buffer_info, nullptr, &gpu_buffer_); CheckResult(status, "vkCreateBuffer"); if (status != VK_SUCCESS) { assert_always(); } VkMemoryRequirements reqs; vkGetBufferMemoryRequirements(*device_, gpu_buffer_, &reqs); alignment_ = xe::round_up(alignment, reqs.alignment); } CircularBuffer::~CircularBuffer() { Shutdown(); } VkResult CircularBuffer::Initialize(VkDeviceMemory memory, VkDeviceSize offset) { assert_true(offset % alignment_ == 0); gpu_memory_ = memory; gpu_base_ = offset; VkResult status = VK_SUCCESS; // Bind the buffer to its backing memory. status = vkBindBufferMemory(*device_, gpu_buffer_, gpu_memory_, gpu_base_); CheckResult(status, "vkBindBufferMemory"); if (status != VK_SUCCESS) { XELOGE("CircularBuffer::Initialize - Failed to bind memory!"); Shutdown(); return status; } // Map the memory so we can access it. status = vkMapMemory(*device_, gpu_memory_, gpu_base_, capacity_, 0, reinterpret_cast<void**>(&host_base_)); CheckResult(status, "vkMapMemory"); if (status != VK_SUCCESS) { XELOGE("CircularBuffer::Initialize - Failed to map memory!"); Shutdown(); return status; } return VK_SUCCESS; } VkResult CircularBuffer::Initialize() { VkResult status = VK_SUCCESS; VkMemoryRequirements reqs; vkGetBufferMemoryRequirements(*device_, gpu_buffer_, &reqs); // Allocate memory from the device to back the buffer. owns_gpu_memory_ = true; gpu_memory_ = device_->AllocateMemory(reqs); if (!gpu_memory_) { XELOGE("CircularBuffer::Initialize - Failed to allocate memory!"); Shutdown(); return VK_ERROR_INITIALIZATION_FAILED; } capacity_ = reqs.size; gpu_base_ = 0; // Bind the buffer to its backing memory. status = vkBindBufferMemory(*device_, gpu_buffer_, gpu_memory_, gpu_base_); CheckResult(status, "vkBindBufferMemory"); if (status != VK_SUCCESS) { XELOGE("CircularBuffer::Initialize - Failed to bind memory!"); Shutdown(); return status; } // Map the memory so we can access it. status = vkMapMemory(*device_, gpu_memory_, gpu_base_, capacity_, 0, reinterpret_cast<void**>(&host_base_)); CheckResult(status, "vkMapMemory"); if (status != VK_SUCCESS) { XELOGE("CircularBuffer::Initialize - Failed to map memory!"); Shutdown(); return status; } return VK_SUCCESS; } void CircularBuffer::Shutdown() { Clear(); if (host_base_) { vkUnmapMemory(*device_, gpu_memory_); host_base_ = nullptr; } if (gpu_buffer_) { vkDestroyBuffer(*device_, gpu_buffer_, nullptr); gpu_buffer_ = nullptr; } if (gpu_memory_ && owns_gpu_memory_) { vkFreeMemory(*device_, gpu_memory_, nullptr); gpu_memory_ = nullptr; } } void CircularBuffer::GetBufferMemoryRequirements(VkMemoryRequirements* reqs) { vkGetBufferMemoryRequirements(*device_, gpu_buffer_, reqs); } bool CircularBuffer::CanAcquire(VkDeviceSize length) { // Make sure the length is aligned. length = xe::round_up(length, alignment_); if (allocations_.empty()) { // Read head has caught up to write head (entire buffer available for write) assert_true(read_head_ == write_head_); return capacity_ >= length; } else if (write_head_ < read_head_) { // Write head wrapped around and is behind read head. // | write |---- read ----| return (read_head_ - write_head_) >= length; } else if (write_head_ > read_head_) { // Read head behind write head. // 1. Check if there's enough room from write -> capacity // | |---- read ----| write | if ((capacity_ - write_head_) >= length) { return true; } // 2. Check if there's enough room from 0 -> read // | write |---- read ----| | if ((read_head_ - 0) >= length) { return true; } } return false; } CircularBuffer::Allocation* CircularBuffer::Acquire(VkDeviceSize length, VkFence fence) { VkDeviceSize aligned_length = xe::round_up(length, alignment_); if (!CanAcquire(aligned_length)) { return nullptr; } assert_true(write_head_ % alignment_ == 0); if (write_head_ < read_head_) { // Write head behind read head. assert_true(read_head_ - write_head_ >= aligned_length); auto alloc = new Allocation(); alloc->host_ptr = host_base_ + write_head_; alloc->gpu_memory = gpu_memory_; alloc->offset = gpu_base_ + write_head_; alloc->length = length; alloc->aligned_length = aligned_length; alloc->fence = fence; write_head_ += aligned_length; allocations_.push_back(alloc); return alloc; } else { // Write head equal to/after read head if (capacity_ - write_head_ >= aligned_length) { // Free space from write -> capacity auto alloc = new Allocation(); alloc->host_ptr = host_base_ + write_head_; alloc->gpu_memory = gpu_memory_; alloc->offset = gpu_base_ + write_head_; alloc->length = length; alloc->aligned_length = aligned_length; alloc->fence = fence; write_head_ += aligned_length; allocations_.push_back(alloc); return alloc; } else if ((read_head_ - 0) >= aligned_length) { // Not enough space from write -> capacity, but there is enough free space // from begin -> read auto alloc = new Allocation(); alloc->host_ptr = host_base_ + 0; alloc->gpu_memory = gpu_memory_; alloc->offset = gpu_base_ + 0; alloc->length = length; alloc->aligned_length = aligned_length; alloc->fence = fence; write_head_ = aligned_length; allocations_.push_back(alloc); return alloc; } } return nullptr; } void CircularBuffer::Flush(Allocation* allocation) { VkMappedMemoryRange range; range.sType = VK_STRUCTURE_TYPE_MAPPED_MEMORY_RANGE; range.pNext = nullptr; range.memory = gpu_memory_; range.offset = gpu_base_ + allocation->offset; range.size = allocation->length; vkFlushMappedMemoryRanges(*device_, 1, &range); } void CircularBuffer::Flush(VkDeviceSize offset, VkDeviceSize length) { VkMappedMemoryRange range; range.sType = VK_STRUCTURE_TYPE_MAPPED_MEMORY_RANGE; range.pNext = nullptr; range.memory = gpu_memory_; range.offset = gpu_base_ + offset; range.size = length; vkFlushMappedMemoryRanges(*device_, 1, &range); } void CircularBuffer::Clear() { for (auto alloc : allocations_) { delete alloc; } allocations_.clear(); write_head_ = read_head_ = 0; } void CircularBuffer::Scavenge() { for (auto it = allocations_.begin(); it != allocations_.end();) { if (vkGetFenceStatus(*device_, (*it)->fence) != VK_SUCCESS) { // Don't bother freeing following allocations to ensure proper ordering. break; } if (capacity_ - read_head_ < (*it)->aligned_length) { // This allocation is stored at the beginning of the buffer. read_head_ = (*it)->aligned_length; } else { read_head_ += (*it)->aligned_length; } delete *it; it = allocations_.erase(it); } if (allocations_.empty()) { // Reset R/W heads to work around fragmentation issues. read_head_ = write_head_ = 0; } } } // namespace vulkan } // namespace ui } // namespace xe<|endoftext|>
<commit_before>/* * Copyright 2006-2008 The FLWOR Foundation. * * 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 "stdafx.h" #include "zorbatypes/decimal.h" #include "zorbatypes/float.h" #include "zorbatypes/integer.h" #include "zorbatypes/numconversions.h" #include "compiler/parser/symbol_table.h" #include "util/ascii_util.h" #include "util/xml_util.h" #include "util/uri_util.h" #include "util/utf8_util.h" #include "compiler/parser/xquery_driver.h" #include <cstdlib> #include <string> using namespace std; namespace zorba { static bool decode_string(const char *yytext, size_t yyleng, string *result) { char delim = yytext [0]; size_t i; for (i = 1; i + 1 < yyleng; i++) { char ch = yytext [i]; if (ch == '&') { int d = xml::parse_entity(yytext + i + 1, result); if (d < 0) return false; i += d; } else { *result += ch; if (ch == delim) ++i; } } return true; } symbol_table::symbol_table(size_t initial_heapsize) : heap(initial_heapsize), last_qname(-1) { } symbol_table::~symbol_table() { } size_t symbol_table::size() const { return (size_t)heap.size(); } // bool attribute == true when an attribute value is normalized static void normalize_eol(const char *text, size_t length, string *out, bool attribute = false) { size_t i; out->reserve (length + 1); char lastCh = '\0'; for (i = 0; i < length; i++) { char ch = text [i]; if (ch == '\r') *out += attribute ? ' ' : '\n'; else if (ch != '\n' || lastCh != '\r') *out += (attribute && (ch == '\t' || ch == '\n'))? ' ' : ch; lastCh = ch; } } off_t symbol_table::put(char const* text) { return put(text, strlen(text)); } // normalizationType == 2 is used for normalizing attribute values off_t symbol_table::put(char const* text, size_t length, int normalizationType) { string normStr; if (normalizationType == 1 || normalizationType == 2) { normalize_eol (text, length, &normStr, normalizationType == 2); text = normStr.c_str (); length = normStr.size (); } return heap.put(text, 0, length); } off_t symbol_table::put_ncname(char const* text, size_t length) { last_qname = heap.put(text, 0, length); return last_qname; } off_t symbol_table::put_qname(char const* text, size_t length, bool do_trim_start, bool do_trim_end, bool is_eqname) { if (do_trim_start) { text = ascii::trim_start_space(text, &length); } if (do_trim_end) { length = ascii::trim_end_space(text, length); } if (!is_eqname) { last_qname = heap.put(text, 0, length); } else { // EQName: Q{prefix}name string name; string prefix = text; string::size_type pos = prefix.rfind('}'); name = prefix.substr(pos+1); prefix = prefix.substr(1, pos); off_t uri = put_uri(prefix.c_str(), prefix.size()); name = get(uri) + ":" + name; last_qname = heap.put(name.c_str(), 0, name.size()); } return last_qname; } off_t symbol_table::put_uri(char const* text, size_t length) { // trim whitespace text = ascii::trim_space(text, &length); // normalize whitespace string result; if (! decode_string (text, length, &result)) return -1; ascii::normalize_space( result ); return heap.put (result.c_str (), 0, result.length ()); } off_t symbol_table::put_varname(char const* text, size_t length) { return heap.put(text, 0, length); } off_t symbol_table::put_entityref(char const* text, size_t length) { string result; if (xml::parse_entity (text + 1, &result) < 0) return -1; return heap.put(result.c_str(), 0, result.size ()); } off_t symbol_table::put_charref(char const* text, size_t length) { return heap.put (text + 1, 0, length - 1); } off_t symbol_table::put_stringlit(char const* yytext, size_t yyleng) { string eolNorm; normalize_eol (yytext, yyleng, &eolNorm); yytext = eolNorm.c_str (); yyleng = eolNorm.size (); string result; if (! decode_string (yytext, yyleng, &result)) return -1; return heap.put (result.c_str (), 0, result.length ()); } off_t symbol_table::put_json_stringliteral(char const* yytext, size_t yyleng, xquery_driver *driver, const location &loc) { string result; unsigned int cp; size_t len; bool found_escape = false; bool found_ampersand = false; for (const char* chr = yytext+1; (unsigned int)(chr-yytext)<yyleng-1; chr+=1) { if (*chr == '\\') { bool is_escape = true; chr += 1; switch (*chr) { case '\\': result += '\\'; break; case '/': result += '/'; break; case '\"': result += '\"'; break; case '\'': result += '\''; break; case 'b': result += '\b'; break; case 'f': result += '\f'; break; case 'n': result += '\n'; break; case 'r': result += '\r'; break; case 't': result += '\t'; break; case 'u': cp = 0; for (unsigned int i=0; i<4; i++, chr+=1) cp = (cp << 4) + uri::hex2dec[(unsigned int)*(chr+1)]; char tmp[10]; len = utf8::encode(cp, tmp); result.append(tmp, len); break; default: result += *(chr-1); result += *chr; is_escape = false; break; } if (is_escape) found_escape = true; } else { if (*chr == '&') found_ampersand = true; result += *chr; } } // for if (found_escape && driver->commonLanguageEnabled()) driver->addCommonLanguageWarning(loc, ZED(ZWST0009_JSON_ESCAPE)); if (found_ampersand && driver->commonLanguageEnabled()) driver->addCommonLanguageWarning(loc, ZED(ZWST0009_CHAR_REF)); return heap.put (result.c_str (), 0, result.length ()); } off_t symbol_table::put_commentcontent(char const* yytext, size_t yyleng) { string eolNorm; normalize_eol (yytext, yyleng, &eolNorm); yytext = eolNorm.c_str (); yyleng = eolNorm.size (); return heap.put (yytext, 0, yyleng); } xs_decimal* symbol_table::decimalval(char const* text, size_t length) { return new xs_decimal(text); } xs_double* symbol_table::doubleval(char const* text, size_t length) { try { return new xs_double(text); } catch ( std::range_error const& ) { return NULL; } } xs_integer* symbol_table::integerval(char const* text, size_t length) { try { return new xs_integer(text); } catch ( std::invalid_argument const& ) { return NULL; } } std::string symbol_table::get(off_t id) { size_t n = heap.get_length0(id); char *buf; buf = (char*)malloc(n+1); heap.get0(id, buf, 0, n+1); std::string retstr = string(buf, 0, n); free(buf); return retstr; } std::string symbol_table::get_last_qname() { return get(last_qname); } } /* namespace zorba */ /* vim:set et sw=2 ts=2: */ <commit_msg>Fixed exception catching.<commit_after>/* * Copyright 2006-2008 The FLWOR Foundation. * * 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 "stdafx.h" #include "zorbatypes/decimal.h" #include "zorbatypes/float.h" #include "zorbatypes/integer.h" #include "zorbatypes/numconversions.h" #include "compiler/parser/symbol_table.h" #include "util/ascii_util.h" #include "util/xml_util.h" #include "util/uri_util.h" #include "util/utf8_util.h" #include "compiler/parser/xquery_driver.h" #include <cstdlib> #include <string> using namespace std; namespace zorba { static bool decode_string(const char *yytext, size_t yyleng, string *result) { char delim = yytext [0]; size_t i; for (i = 1; i + 1 < yyleng; i++) { char ch = yytext [i]; if (ch == '&') { int d = xml::parse_entity(yytext + i + 1, result); if (d < 0) return false; i += d; } else { *result += ch; if (ch == delim) ++i; } } return true; } symbol_table::symbol_table(size_t initial_heapsize) : heap(initial_heapsize), last_qname(-1) { } symbol_table::~symbol_table() { } size_t symbol_table::size() const { return (size_t)heap.size(); } // bool attribute == true when an attribute value is normalized static void normalize_eol(const char *text, size_t length, string *out, bool attribute = false) { size_t i; out->reserve (length + 1); char lastCh = '\0'; for (i = 0; i < length; i++) { char ch = text [i]; if (ch == '\r') *out += attribute ? ' ' : '\n'; else if (ch != '\n' || lastCh != '\r') *out += (attribute && (ch == '\t' || ch == '\n'))? ' ' : ch; lastCh = ch; } } off_t symbol_table::put(char const* text) { return put(text, strlen(text)); } // normalizationType == 2 is used for normalizing attribute values off_t symbol_table::put(char const* text, size_t length, int normalizationType) { string normStr; if (normalizationType == 1 || normalizationType == 2) { normalize_eol (text, length, &normStr, normalizationType == 2); text = normStr.c_str (); length = normStr.size (); } return heap.put(text, 0, length); } off_t symbol_table::put_ncname(char const* text, size_t length) { last_qname = heap.put(text, 0, length); return last_qname; } off_t symbol_table::put_qname(char const* text, size_t length, bool do_trim_start, bool do_trim_end, bool is_eqname) { if (do_trim_start) { text = ascii::trim_start_space(text, &length); } if (do_trim_end) { length = ascii::trim_end_space(text, length); } if (!is_eqname) { last_qname = heap.put(text, 0, length); } else { // EQName: Q{prefix}name string name; string prefix = text; string::size_type pos = prefix.rfind('}'); name = prefix.substr(pos+1); prefix = prefix.substr(1, pos); off_t uri = put_uri(prefix.c_str(), prefix.size()); name = get(uri) + ":" + name; last_qname = heap.put(name.c_str(), 0, name.size()); } return last_qname; } off_t symbol_table::put_uri(char const* text, size_t length) { // trim whitespace text = ascii::trim_space(text, &length); // normalize whitespace string result; if (! decode_string (text, length, &result)) return -1; ascii::normalize_space( result ); return heap.put (result.c_str (), 0, result.length ()); } off_t symbol_table::put_varname(char const* text, size_t length) { return heap.put(text, 0, length); } off_t symbol_table::put_entityref(char const* text, size_t length) { string result; if (xml::parse_entity (text + 1, &result) < 0) return -1; return heap.put(result.c_str(), 0, result.size ()); } off_t symbol_table::put_charref(char const* text, size_t length) { return heap.put (text + 1, 0, length - 1); } off_t symbol_table::put_stringlit(char const* yytext, size_t yyleng) { string eolNorm; normalize_eol (yytext, yyleng, &eolNorm); yytext = eolNorm.c_str (); yyleng = eolNorm.size (); string result; if (! decode_string (yytext, yyleng, &result)) return -1; return heap.put (result.c_str (), 0, result.length ()); } off_t symbol_table::put_json_stringliteral(char const* yytext, size_t yyleng, xquery_driver *driver, const location &loc) { string result; unsigned int cp; size_t len; bool found_escape = false; bool found_ampersand = false; for (const char* chr = yytext+1; (unsigned int)(chr-yytext)<yyleng-1; chr+=1) { if (*chr == '\\') { bool is_escape = true; chr += 1; switch (*chr) { case '\\': result += '\\'; break; case '/': result += '/'; break; case '\"': result += '\"'; break; case '\'': result += '\''; break; case 'b': result += '\b'; break; case 'f': result += '\f'; break; case 'n': result += '\n'; break; case 'r': result += '\r'; break; case 't': result += '\t'; break; case 'u': cp = 0; for (unsigned int i=0; i<4; i++, chr+=1) cp = (cp << 4) + uri::hex2dec[(unsigned int)*(chr+1)]; char tmp[10]; len = utf8::encode(cp, tmp); result.append(tmp, len); break; default: result += *(chr-1); result += *chr; is_escape = false; break; } if (is_escape) found_escape = true; } else { if (*chr == '&') found_ampersand = true; result += *chr; } } // for if (found_escape && driver->commonLanguageEnabled()) driver->addCommonLanguageWarning(loc, ZED(ZWST0009_JSON_ESCAPE)); if (found_ampersand && driver->commonLanguageEnabled()) driver->addCommonLanguageWarning(loc, ZED(ZWST0009_CHAR_REF)); return heap.put (result.c_str (), 0, result.length ()); } off_t symbol_table::put_commentcontent(char const* yytext, size_t yyleng) { string eolNorm; normalize_eol (yytext, yyleng, &eolNorm); yytext = eolNorm.c_str (); yyleng = eolNorm.size (); return heap.put (yytext, 0, yyleng); } xs_decimal* symbol_table::decimalval(char const* text, size_t length) { return new xs_decimal(text); } xs_double* symbol_table::doubleval(char const* text, size_t length) { try { return new xs_double(text); } catch ( std::exception const& ) { return NULL; } } xs_integer* symbol_table::integerval(char const* text, size_t length) { try { return new xs_integer(text); } catch ( std::exception const& ) { return NULL; } } std::string symbol_table::get(off_t id) { size_t n = heap.get_length0(id); char *buf; buf = (char*)malloc(n+1); heap.get0(id, buf, 0, n+1); std::string retstr = string(buf, 0, n); free(buf); return retstr; } std::string symbol_table::get_last_qname() { return get(last_qname); } } /* namespace zorba */ /* vim:set et sw=2 ts=2: */ <|endoftext|>
<commit_before>#include <crypto/crypto_encryption.h> #include <event/event_callback.h> #include <event/event_main.h> #include <event/event_system.h> #include <io/net/tcp_server.h> #include <io/pipe/pipe.h> #include <io/pipe/pipe_producer.h> #include <io/pipe/splice.h> #include <io/socket/simple_server.h> #include <ssh/ssh_algorithm_negotiation.h> #include <ssh/ssh_protocol.h> #include <ssh/ssh_server_host_key.h> #include <ssh/ssh_session.h> #include <ssh/ssh_transport_pipe.h> /* * XXX Create an SSH chat program. Let only one of each user be connected at a time. Send lines of data to all others. */ class SSHConnection { struct SSHChannel { uint32_t local_channel_; uint32_t local_window_size_; uint32_t local_packet_size_; uint32_t remote_channel_; uint32_t remote_window_size_; uint32_t remote_packet_size_; std::map<std::string, Buffer> environment_; SSHChannel(uint32_t local_channel, uint32_t remote_channel, uint32_t local_window_size, uint32_t local_packet_size, uint32_t remote_window_size, uint32_t remote_packet_size) : local_channel_(local_channel), local_window_size_(local_window_size), local_packet_size_(local_packet_size), remote_channel_(remote_channel), remote_window_size_(remote_window_size), remote_packet_size_(remote_packet_size), environment_() { } }; LogHandle log_; Socket *peer_; SSH::Session session_; SSH::TransportPipe *pipe_; Action *receive_action_; Splice *splice_; Action *splice_action_; Action *close_action_; uint32_t channel_next_; std::map<uint32_t, SSHChannel *> channel_map_; std::map<uint32_t, uint32_t> remote_channel_map_; public: SSHConnection(Socket *peer) : log_("/ssh/connection"), peer_(peer), session_(SSH::ServerRole), pipe_(NULL), splice_(NULL), splice_action_(NULL), close_action_(NULL), channel_next_(0), channel_map_() { session_.algorithm_negotiation_ = new SSH::AlgorithmNegotiation(&session_); if (session_.role_ == SSH::ServerRole) { SSH::ServerHostKey *server_host_key = SSH::ServerHostKey::server(&session_, "ssh-server1.pem"); session_.algorithm_negotiation_->add_algorithm(server_host_key); } session_.algorithm_negotiation_->add_algorithms(); pipe_ = new SSH::TransportPipe(&session_); EventCallback *rcb = callback(this, &SSHConnection::receive_complete); receive_action_ = pipe_->receive(rcb); splice_ = new Splice(log_ + "/splice", peer_, pipe_, peer_); EventCallback *cb = callback(this, &SSHConnection::splice_complete); splice_action_ = splice_->start(cb); } ~SSHConnection() { ASSERT(log_, close_action_ == NULL); ASSERT(log_, splice_action_ == NULL); ASSERT(log_, splice_ == NULL); ASSERT(log_, receive_action_ == NULL); ASSERT(log_, pipe_ == NULL); ASSERT(log_, peer_ == NULL); } private: void receive_complete(Event e) { receive_action_->cancel(); receive_action_ = NULL; switch (e.type_) { case Event::Done: break; default: ERROR(log_) << "Unexpected event while waiting for a packet: " << e; return; } ASSERT(log_, !e.buffer_.empty()); Buffer service; Buffer type; Buffer msg; SSHChannel *channel; uint32_t recipient_channel, sender_channel, window_size, packet_size; bool want_reply; std::map<uint32_t, uint32_t>::const_iterator rchit; std::map<uint32_t, SSHChannel *>::const_iterator chit; switch (e.buffer_.peek()) { case SSH::Message::TransportDisconnectMessage: break; case SSH::Message::TransportServiceRequestMessage: /* Claim to support any kind of service the client requests. */ e.buffer_.skip(1); if (e.buffer_.empty()) { ERROR(log_) << "No service name after transport request."; return; } if (!SSH::String::decode(&service, &e.buffer_)) { ERROR(log_) << "Could not decode service name."; return; } if (!e.buffer_.empty()) { ERROR(log_) << "Extraneous data after service name."; return; } msg.append(SSH::Message::TransportServiceAcceptMessage); SSH::String::encode(&msg, service); pipe_->send(&msg); if (service.equal("ssh-userauth")) { msg.append(SSH::Message::UserAuthenticationBannerMessage); SSH::String::encode(&msg, std::string(" *\r\n\007 * This is a test server. Sessions, including authentication, may be logged.\r\n *\r\n")); SSH::String::encode(&msg, std::string("en-CA")); pipe_->send(&msg); } break; case SSH::Message::UserAuthenticationRequestMessage: /* Any authentication request succeeds. */ e.buffer_.skip(1); msg.append(SSH::Message::UserAuthenticationSuccessMessage); pipe_->send(&msg); break; case SSH::Message::ConnectionChannelOpen: /* Opening a channel. */ e.buffer_.skip(1); if (e.buffer_.empty()) { ERROR(log_) << "No channel type after channel open."; return; } if (!SSH::String::decode(&type, &e.buffer_)) { ERROR(log_) << "Could not decode channel type."; return; } if (!SSH::UInt32::decode(&sender_channel, &e.buffer_)) { ERROR(log_) << "Could not decode sender channel."; return; } if (!SSH::UInt32::decode(&window_size, &e.buffer_)) { ERROR(log_) << "Could not decode window size."; return; } if (!SSH::UInt32::decode(&packet_size, &e.buffer_)) { ERROR(log_) << "Could not decode packet size."; return; } /* Only support session channels. */ if (!type.equal("session")) { msg.append(SSH::Message::ConnectionChannelOpenFailure); SSH::UInt32::encode(&msg, sender_channel); SSH::UInt32::encode(&msg, 3); SSH::String::encode(&msg, std::string("Unsupported session type.")); SSH::String::encode(&msg, std::string("en-CA")); pipe_->send(&msg); return; } recipient_channel = sender_channel; sender_channel = channel_setup(recipient_channel, window_size, packet_size); /* Set up session. */ msg.append(SSH::Message::ConnectionChannelOpenConfirmation); SSH::UInt32::encode(&msg, recipient_channel); SSH::UInt32::encode(&msg, sender_channel); SSH::UInt32::encode(&msg, window_size); SSH::UInt32::encode(&msg, packet_size); pipe_->send(&msg); break; case SSH::Message::ConnectionChannelRequest: /* For now just fail any channel request. */ e.buffer_.skip(1); if (e.buffer_.empty()) { ERROR(log_) << "No channel after channel request."; return; } if (!SSH::UInt32::decode(&recipient_channel, &e.buffer_)) { ERROR(log_) << "Could not decode recipient channel."; return; } if (!SSH::String::decode(&type, &e.buffer_)) { ERROR(log_) << "Could not decode channel request type."; return; } if (e.buffer_.empty()) { ERROR(log_) << "Missing want_reply field."; return; } want_reply = e.buffer_.pop(); chit = channel_map_.find(recipient_channel); if (chit == channel_map_.end()) { if (want_reply) { msg.append(SSH::Message::ConnectionChannelRequestFailure); SSH::UInt32::encode(&msg, 0); /* XXX What to do for a request that fails due to unknown channel? */ pipe_->send(&msg); } break; } channel = chit->second; if (type.equal("pty-req")) { /* Fail for now. */ } else if (type.equal("env")) { Buffer keybuf; if (!SSH::String::decode(&keybuf, &e.buffer_)) { ERROR(log_) << "Could not decode environment key."; return; } Buffer value; if (!SSH::String::decode(&value, &e.buffer_)) { ERROR(log_) << "Could not decode environment value."; return; } std::string key; keybuf.extract(key); if (channel->environment_.find(key) == channel->environment_.end()) { channel->environment_[key] = value; DEBUG(log_) << "Client set environment variable."; if (want_reply) { msg.append(SSH::Message::ConnectionChannelRequestSuccess); SSH::UInt32::encode(&msg, channel->remote_channel_); pipe_->send(&msg); } break; } INFO(log_) << "Client attempted to set environment variable twice."; if (want_reply) { msg.append(SSH::Message::ConnectionChannelRequestFailure); SSH::UInt32::encode(&msg, channel->remote_channel_); pipe_->send(&msg); } break; } else if (type.equal("shell")) { if (want_reply) { msg.append(SSH::Message::ConnectionChannelRequestSuccess); SSH::UInt32::encode(&msg, channel->remote_channel_); pipe_->send(&msg); } break; } else { DEBUG(log_) << "Unhandled channel request type:" << std::endl << type.hexdump(); } if (want_reply) { msg.append(SSH::Message::ConnectionChannelRequestFailure); SSH::UInt32::encode(&msg, channel->remote_channel_); pipe_->send(&msg); } break; case SSH::Message::ConnectionChannelWindowAdjust: /* Follow our peer's lead on window adjustments. */ case SSH::Message::ConnectionChannelData: /* Just echo data back. We do not need to decode at present because channels are the same in both directions. */ pipe_->send(&e.buffer_); break; default: DEBUG(log_) << "Unhandled message:" << std::endl << e.buffer_.hexdump(); break; } EventCallback *rcb = callback(this, &SSHConnection::receive_complete); receive_action_ = pipe_->receive(rcb); } void close_complete(void) { close_action_->cancel(); close_action_ = NULL; ASSERT(log_, peer_ != NULL); delete peer_; peer_ = NULL; delete this; } void splice_complete(Event e) { splice_action_->cancel(); splice_action_ = NULL; switch (e.type_) { case Event::EOS: DEBUG(log_) << "Peer exiting normally."; break; case Event::Error: ERROR(log_) << "Peer exiting with error: " << e; break; default: ERROR(log_) << "Peer exiting with unknown event: " << e; break; } ASSERT(log_, splice_ != NULL); delete splice_; splice_ = NULL; if (receive_action_ != NULL) { INFO(log_) << "Peer exiting while waiting for a packet."; receive_action_->cancel(); receive_action_ = NULL; } ASSERT(log_, pipe_ != NULL); delete pipe_; pipe_ = NULL; ASSERT(log_, close_action_ == NULL); SimpleCallback *cb = callback(this, &SSHConnection::close_complete); close_action_ = peer_->close(cb); } uint32_t channel_setup(const uint32_t& remote_channel, const uint32_t& window_size, const uint32_t& packet_size) { std::map<uint32_t, SSHChannel *>::const_iterator it; uint32_t local_channel; uint32_t next = channel_next_; for (;;) { it = channel_map_.find(next); if (it == channel_map_.end()) break; next++; } channel_next_ = next + 1; local_channel = next; channel_map_[local_channel] = new SSHChannel(local_channel, remote_channel, 65536, 65536, window_size, packet_size); return (local_channel); } }; class SSHServer : public SimpleServer<TCPServer> { public: SSHServer(SocketAddressFamily family, const std::string& interface) : SimpleServer<TCPServer>("/ssh/server", family, interface) { } ~SSHServer() { } void client_connected(Socket *client) { new SSHConnection(client); } }; int main(void) { new SSHServer(SocketAddressFamilyIP, "[::]:2299"); event_main(); } <commit_msg>Enforce the provision that says that only a single resource may be connected to a session channel.<commit_after>#include <crypto/crypto_encryption.h> #include <event/event_callback.h> #include <event/event_main.h> #include <event/event_system.h> #include <io/net/tcp_server.h> #include <io/pipe/pipe.h> #include <io/pipe/pipe_producer.h> #include <io/pipe/splice.h> #include <io/socket/simple_server.h> #include <ssh/ssh_algorithm_negotiation.h> #include <ssh/ssh_protocol.h> #include <ssh/ssh_server_host_key.h> #include <ssh/ssh_session.h> #include <ssh/ssh_transport_pipe.h> /* * XXX Create an SSH chat program. Let only one of each user be connected at a time. Send lines of data to all others. */ class SSHConnection { struct SSHChannel { enum Mode { SetupMode, ShellMode, ExecMode, SubsystemMode }; Mode mode_; uint32_t local_channel_; uint32_t local_window_size_; uint32_t local_packet_size_; uint32_t remote_channel_; uint32_t remote_window_size_; uint32_t remote_packet_size_; std::map<std::string, Buffer> environment_; SSHChannel(uint32_t local_channel, uint32_t remote_channel, uint32_t local_window_size, uint32_t local_packet_size, uint32_t remote_window_size, uint32_t remote_packet_size) : mode_(SetupMode), local_channel_(local_channel), local_window_size_(local_window_size), local_packet_size_(local_packet_size), remote_channel_(remote_channel), remote_window_size_(remote_window_size), remote_packet_size_(remote_packet_size), environment_() { } }; LogHandle log_; Socket *peer_; SSH::Session session_; SSH::TransportPipe *pipe_; Action *receive_action_; Splice *splice_; Action *splice_action_; Action *close_action_; uint32_t channel_next_; std::map<uint32_t, SSHChannel *> channel_map_; std::map<uint32_t, uint32_t> remote_channel_map_; public: SSHConnection(Socket *peer) : log_("/ssh/connection"), peer_(peer), session_(SSH::ServerRole), pipe_(NULL), splice_(NULL), splice_action_(NULL), close_action_(NULL), channel_next_(0), channel_map_() { session_.algorithm_negotiation_ = new SSH::AlgorithmNegotiation(&session_); if (session_.role_ == SSH::ServerRole) { SSH::ServerHostKey *server_host_key = SSH::ServerHostKey::server(&session_, "ssh-server1.pem"); session_.algorithm_negotiation_->add_algorithm(server_host_key); } session_.algorithm_negotiation_->add_algorithms(); pipe_ = new SSH::TransportPipe(&session_); EventCallback *rcb = callback(this, &SSHConnection::receive_complete); receive_action_ = pipe_->receive(rcb); splice_ = new Splice(log_ + "/splice", peer_, pipe_, peer_); EventCallback *cb = callback(this, &SSHConnection::splice_complete); splice_action_ = splice_->start(cb); } ~SSHConnection() { ASSERT(log_, close_action_ == NULL); ASSERT(log_, splice_action_ == NULL); ASSERT(log_, splice_ == NULL); ASSERT(log_, receive_action_ == NULL); ASSERT(log_, pipe_ == NULL); ASSERT(log_, peer_ == NULL); } private: void receive_complete(Event e) { receive_action_->cancel(); receive_action_ = NULL; switch (e.type_) { case Event::Done: break; default: ERROR(log_) << "Unexpected event while waiting for a packet: " << e; return; } ASSERT(log_, !e.buffer_.empty()); Buffer service; Buffer type; Buffer msg; SSHChannel *channel; uint32_t recipient_channel, sender_channel, window_size, packet_size; bool want_reply; std::map<uint32_t, uint32_t>::const_iterator rchit; std::map<uint32_t, SSHChannel *>::const_iterator chit; switch (e.buffer_.peek()) { case SSH::Message::TransportDisconnectMessage: break; case SSH::Message::TransportServiceRequestMessage: /* Claim to support any kind of service the client requests. */ e.buffer_.skip(1); if (e.buffer_.empty()) { ERROR(log_) << "No service name after transport request."; return; } if (!SSH::String::decode(&service, &e.buffer_)) { ERROR(log_) << "Could not decode service name."; return; } if (!e.buffer_.empty()) { ERROR(log_) << "Extraneous data after service name."; return; } msg.append(SSH::Message::TransportServiceAcceptMessage); SSH::String::encode(&msg, service); pipe_->send(&msg); if (service.equal("ssh-userauth")) { msg.append(SSH::Message::UserAuthenticationBannerMessage); SSH::String::encode(&msg, std::string(" *\r\n\007 * This is a test server. Sessions, including authentication, may be logged.\r\n *\r\n")); SSH::String::encode(&msg, std::string("en-CA")); pipe_->send(&msg); } break; case SSH::Message::UserAuthenticationRequestMessage: /* Any authentication request succeeds. */ e.buffer_.skip(1); msg.append(SSH::Message::UserAuthenticationSuccessMessage); pipe_->send(&msg); break; case SSH::Message::ConnectionChannelOpen: /* Opening a channel. */ e.buffer_.skip(1); if (e.buffer_.empty()) { ERROR(log_) << "No channel type after channel open."; return; } if (!SSH::String::decode(&type, &e.buffer_)) { ERROR(log_) << "Could not decode channel type."; return; } if (!SSH::UInt32::decode(&sender_channel, &e.buffer_)) { ERROR(log_) << "Could not decode sender channel."; return; } if (!SSH::UInt32::decode(&window_size, &e.buffer_)) { ERROR(log_) << "Could not decode window size."; return; } if (!SSH::UInt32::decode(&packet_size, &e.buffer_)) { ERROR(log_) << "Could not decode packet size."; return; } /* Only support session channels. */ if (!type.equal("session")) { msg.append(SSH::Message::ConnectionChannelOpenFailure); SSH::UInt32::encode(&msg, sender_channel); SSH::UInt32::encode(&msg, 3); SSH::String::encode(&msg, std::string("Unsupported session type.")); SSH::String::encode(&msg, std::string("en-CA")); pipe_->send(&msg); return; } recipient_channel = sender_channel; sender_channel = channel_setup(recipient_channel, window_size, packet_size); /* Set up session. */ msg.append(SSH::Message::ConnectionChannelOpenConfirmation); SSH::UInt32::encode(&msg, recipient_channel); SSH::UInt32::encode(&msg, sender_channel); SSH::UInt32::encode(&msg, window_size); SSH::UInt32::encode(&msg, packet_size); pipe_->send(&msg); break; case SSH::Message::ConnectionChannelRequest: /* For now just fail any channel request. */ e.buffer_.skip(1); if (e.buffer_.empty()) { ERROR(log_) << "No channel after channel request."; return; } if (!SSH::UInt32::decode(&recipient_channel, &e.buffer_)) { ERROR(log_) << "Could not decode recipient channel."; return; } if (!SSH::String::decode(&type, &e.buffer_)) { ERROR(log_) << "Could not decode channel request type."; return; } if (e.buffer_.empty()) { ERROR(log_) << "Missing want_reply field."; return; } want_reply = e.buffer_.pop(); chit = channel_map_.find(recipient_channel); if (chit == channel_map_.end()) { if (want_reply) { msg.append(SSH::Message::ConnectionChannelRequestFailure); SSH::UInt32::encode(&msg, 0); /* XXX What to do for a request that fails due to unknown channel? */ pipe_->send(&msg); } break; } channel = chit->second; if (type.equal("pty-req")) { /* Fail for now. */ } else if (type.equal("env")) { Buffer keybuf; if (!SSH::String::decode(&keybuf, &e.buffer_)) { ERROR(log_) << "Could not decode environment key."; return; } Buffer value; if (!SSH::String::decode(&value, &e.buffer_)) { ERROR(log_) << "Could not decode environment value."; return; } std::string key; keybuf.extract(key); if (channel->environment_.find(key) == channel->environment_.end()) { channel->environment_[key] = value; DEBUG(log_) << "Client set environment variable."; if (want_reply) { msg.append(SSH::Message::ConnectionChannelRequestSuccess); SSH::UInt32::encode(&msg, channel->remote_channel_); pipe_->send(&msg); } break; } INFO(log_) << "Client attempted to set environment variable twice."; if (want_reply) { msg.append(SSH::Message::ConnectionChannelRequestFailure); SSH::UInt32::encode(&msg, channel->remote_channel_); pipe_->send(&msg); } break; } else if (type.equal("shell")) { if (channel->mode_ == SSHChannel::SetupMode) { channel->mode_ = SSHChannel::ShellMode; if (want_reply) { msg.append(SSH::Message::ConnectionChannelRequestSuccess); SSH::UInt32::encode(&msg, channel->remote_channel_); pipe_->send(&msg); } break; } ERROR(log_) << "Client requested a shell session, but session is not in setup mode."; } else { DEBUG(log_) << "Unhandled channel request type:" << std::endl << type.hexdump(); } if (want_reply) { msg.append(SSH::Message::ConnectionChannelRequestFailure); SSH::UInt32::encode(&msg, channel->remote_channel_); pipe_->send(&msg); } break; case SSH::Message::ConnectionChannelWindowAdjust: /* Follow our peer's lead on window adjustments. */ case SSH::Message::ConnectionChannelData: /* Just echo data back. We do not need to decode at present because channels are the same in both directions. */ pipe_->send(&e.buffer_); break; default: DEBUG(log_) << "Unhandled message:" << std::endl << e.buffer_.hexdump(); break; } EventCallback *rcb = callback(this, &SSHConnection::receive_complete); receive_action_ = pipe_->receive(rcb); } void close_complete(void) { close_action_->cancel(); close_action_ = NULL; ASSERT(log_, peer_ != NULL); delete peer_; peer_ = NULL; delete this; } void splice_complete(Event e) { splice_action_->cancel(); splice_action_ = NULL; switch (e.type_) { case Event::EOS: DEBUG(log_) << "Peer exiting normally."; break; case Event::Error: ERROR(log_) << "Peer exiting with error: " << e; break; default: ERROR(log_) << "Peer exiting with unknown event: " << e; break; } ASSERT(log_, splice_ != NULL); delete splice_; splice_ = NULL; if (receive_action_ != NULL) { INFO(log_) << "Peer exiting while waiting for a packet."; receive_action_->cancel(); receive_action_ = NULL; } ASSERT(log_, pipe_ != NULL); delete pipe_; pipe_ = NULL; ASSERT(log_, close_action_ == NULL); SimpleCallback *cb = callback(this, &SSHConnection::close_complete); close_action_ = peer_->close(cb); } uint32_t channel_setup(const uint32_t& remote_channel, const uint32_t& window_size, const uint32_t& packet_size) { std::map<uint32_t, SSHChannel *>::const_iterator it; uint32_t local_channel; uint32_t next = channel_next_; for (;;) { it = channel_map_.find(next); if (it == channel_map_.end()) break; next++; } channel_next_ = next + 1; local_channel = next; channel_map_[local_channel] = new SSHChannel(local_channel, remote_channel, 65536, 65536, window_size, packet_size); return (local_channel); } }; class SSHServer : public SimpleServer<TCPServer> { public: SSHServer(SocketAddressFamily family, const std::string& interface) : SimpleServer<TCPServer>("/ssh/server", family, interface) { } ~SSHServer() { } void client_connected(Socket *client) { new SSHConnection(client); } }; int main(void) { new SSHServer(SocketAddressFamilyIP, "[::]:2299"); event_main(); } <|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 <csql/defaults.h> using namespace stx; namespace csql { void installDefaultSymbols(SymbolTable* rt) { /* expressions/aggregate.h */ rt->registerFunction("count", expressions::kCountExpr); rt->registerFunction("sum", expressions::kSumExpr); rt->registerFunction("mean", expressions::kMeanExpr); //rt->registerSymbol( // "mean", // &expressions::meanExpr, // expressions::meanExprScratchpadSize(), // &expressions::meanExprFree); //rt->registerSymbol( // "avg", // &expressions::meanExpr, // expressions::meanExprScratchpadSize(), // &expressions::meanExprFree); //rt->registerSymbol( // "average", // &expressions::meanExpr, // expressions::meanExprScratchpadSize(), // &expressions::meanExprFree); //rt->registerSymbol( // "min", // &expressions::minExpr, // expressions::minExprScratchpadSize(), // &expressions::minExprFree); //rt->registerSymbol( // "max", // &expressions::maxExpr, // expressions::maxExprScratchpadSize(), // &expressions::maxExprFree); /* expressions/boolean.h */ rt->registerFunction("eq", PureFunction(&expressions::eqExpr)); rt->registerFunction("neq", PureFunction(&expressions::neqExpr)); rt->registerFunction("and", PureFunction(&expressions::andExpr)); rt->registerFunction("or", PureFunction(&expressions::orExpr)); rt->registerFunction("neg", PureFunction(&expressions::negExpr)); rt->registerFunction("lt", PureFunction(&expressions::ltExpr)); rt->registerFunction("lte", PureFunction(&expressions::lteExpr)); rt->registerFunction("gt", PureFunction(&expressions::gtExpr)); rt->registerFunction("gte", PureFunction(&expressions::gteExpr)); /* expressions/UnixTime.h */ rt->registerFunction( "FROM_TIMESTAMP", PureFunction(&expressions::fromTimestamp)); /* expressions/math.h */ rt->registerFunction("add", PureFunction(&expressions::addExpr)); rt->registerFunction("sub", PureFunction(&expressions::subExpr)); rt->registerFunction("mul", PureFunction(&expressions::mulExpr)); rt->registerFunction("div", PureFunction(&expressions::divExpr)); rt->registerFunction("mod", PureFunction(&expressions::modExpr)); rt->registerFunction("pow", PureFunction(&expressions::powExpr)); } } // namespace csql <commit_msg>update deps<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 <csql/defaults.h> using namespace stx; namespace csql { void installDefaultSymbols(SymbolTable* rt) { /* expressions/aggregate.h */ rt->registerFunction("count", expressions::kCountExpr); rt->registerFunction("sum", expressions::kSumExpr); //rt->registerSymbol( // "mean", // &expressions::meanExpr, // expressions::meanExprScratchpadSize(), // &expressions::meanExprFree); //rt->registerSymbol( // "avg", // &expressions::meanExpr, // expressions::meanExprScratchpadSize(), // &expressions::meanExprFree); //rt->registerSymbol( // "average", // &expressions::meanExpr, // expressions::meanExprScratchpadSize(), // &expressions::meanExprFree); //rt->registerSymbol( // "min", // &expressions::minExpr, // expressions::minExprScratchpadSize(), // &expressions::minExprFree); //rt->registerSymbol( // "max", // &expressions::maxExpr, // expressions::maxExprScratchpadSize(), // &expressions::maxExprFree); /* expressions/boolean.h */ rt->registerFunction("eq", PureFunction(&expressions::eqExpr)); rt->registerFunction("neq", PureFunction(&expressions::neqExpr)); rt->registerFunction("and", PureFunction(&expressions::andExpr)); rt->registerFunction("or", PureFunction(&expressions::orExpr)); rt->registerFunction("neg", PureFunction(&expressions::negExpr)); rt->registerFunction("lt", PureFunction(&expressions::ltExpr)); rt->registerFunction("lte", PureFunction(&expressions::lteExpr)); rt->registerFunction("gt", PureFunction(&expressions::gtExpr)); rt->registerFunction("gte", PureFunction(&expressions::gteExpr)); /* expressions/UnixTime.h */ rt->registerFunction( "FROM_TIMESTAMP", PureFunction(&expressions::fromTimestamp)); /* expressions/math.h */ rt->registerFunction("add", PureFunction(&expressions::addExpr)); rt->registerFunction("sub", PureFunction(&expressions::subExpr)); rt->registerFunction("mul", PureFunction(&expressions::mulExpr)); rt->registerFunction("div", PureFunction(&expressions::divExpr)); rt->registerFunction("mod", PureFunction(&expressions::modExpr)); rt->registerFunction("pow", PureFunction(&expressions::powExpr)); } } // namespace csql <|endoftext|>
<commit_before>/***************************Copyright-DO-NOT-REMOVE-THIS-LINE** * CONDOR Copyright Notice * * See LICENSE.TXT for additional notices and disclaimers. * * Copyright (c)1990-1998 CONDOR Team, Computer Sciences Department, * University of Wisconsin-Madison, Madison, WI. All Rights Reserved. * No use of the CONDOR Software Program Source Code is authorized * without the express consent of the CONDOR Team. For more information * contact: CONDOR Team, Attention: Professor Miron Livny, * 7367 Computer Sciences, 1210 W. Dayton St., Madison, WI 53706-1685, * (608) 262-0856 or miron@cs.wisc.edu. * * U.S. Government Rights Restrictions: Use, duplication, or disclosure * by the U.S. Government is subject to restrictions as set forth in * subparagraph (c)(1)(ii) of The Rights in Technical Data and Computer * Software clause at DFARS 252.227-7013 or subparagraphs (c)(1) and * (2) of Commercial Computer Software-Restricted Rights at 48 CFR * 52.227-19, as applicable, CONDOR Team, Attention: Professor Miron * Livny, 7367 Computer Sciences, 1210 W. Dayton St., Madison, * WI 53706-1685, (608) 262-0856 or miron@cs.wisc.edu. ****************************Copyright-DO-NOT-REMOVE-THIS-LINE**/ /* Here is the version string - update before a public release */ static char* CondorVersionString = "$Version: 6.1.2 1999/01/12 $"; extern "C" { char* CondorVersion() { return CondorVersionString; } } /* extern "C" */ <commit_msg>6.1.3 version string.<commit_after>/***************************Copyright-DO-NOT-REMOVE-THIS-LINE** * CONDOR Copyright Notice * * See LICENSE.TXT for additional notices and disclaimers. * * Copyright (c)1990-1998 CONDOR Team, Computer Sciences Department, * University of Wisconsin-Madison, Madison, WI. All Rights Reserved. * No use of the CONDOR Software Program Source Code is authorized * without the express consent of the CONDOR Team. For more information * contact: CONDOR Team, Attention: Professor Miron Livny, * 7367 Computer Sciences, 1210 W. Dayton St., Madison, WI 53706-1685, * (608) 262-0856 or miron@cs.wisc.edu. * * U.S. Government Rights Restrictions: Use, duplication, or disclosure * by the U.S. Government is subject to restrictions as set forth in * subparagraph (c)(1)(ii) of The Rights in Technical Data and Computer * Software clause at DFARS 252.227-7013 or subparagraphs (c)(1) and * (2) of Commercial Computer Software-Restricted Rights at 48 CFR * 52.227-19, as applicable, CONDOR Team, Attention: Professor Miron * Livny, 7367 Computer Sciences, 1210 W. Dayton St., Madison, * WI 53706-1685, (608) 262-0856 or miron@cs.wisc.edu. ****************************Copyright-DO-NOT-REMOVE-THIS-LINE**/ /* Here is the version string - update before a public release */ static char* CondorVersionString = "$Version: 6.1.3 1999/02/15 $"; extern "C" { char* CondorVersion() { return CondorVersionString; } } /* extern "C" */ <|endoftext|>
<commit_before>/* * Copyright (c) 2016, The OpenThread Authors. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. Neither the name of the copyright holder nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #define WPP_NAME "secure_coap_server.tmh" #include <coap/secure_coap_server.hpp> #include <common/logging.hpp> #include <meshcop/dtls.hpp> #include <thread/thread_netif.hpp> /** * @file * This file implements the secure CoAP server. */ namespace Thread { namespace Coap { SecureServer::SecureServer(ThreadNetif &aNetif, uint16_t aPort): Server(aNetif, aPort, &SecureServer::Send, &SecureServer::Receive), mTransmitCallback(NULL), mContext(NULL), mNetif(aNetif), mTransmitMessage(NULL), mTransmitTask(aNetif.GetIp6().mTaskletScheduler, &SecureServer::HandleUdpTransmit, this) { } ThreadError SecureServer::Start(TransportCallback aCallback, void *aContext) { ThreadError error = kThreadError_None; mTransmitCallback = aCallback; mContext = aContext; // Passing mTransmitCallback means that we do not want to use socket // to transmit/receive messages, so do not open it in that case. if (mTransmitCallback == NULL) { error = Server::Start(); } return error; } ThreadError SecureServer::Stop() { if (mNetif.GetDtls().IsStarted()) { mNetif.GetDtls().Stop(); } if (mTransmitMessage != NULL) { mTransmitMessage->Free(); mTransmitMessage = NULL; } mTransmitCallback = NULL; mContext = NULL; otLogFuncExit(); return Server::Stop(); } bool SecureServer::IsConnectionActive(void) { return mNetif.GetDtls().IsStarted(); }; ThreadError SecureServer::Send(void *aContext, Message &aMessage, const Ip6::MessageInfo &aMessageInfo) { return static_cast<SecureServer *>(aContext)->Send(aMessage, aMessageInfo); } ThreadError SecureServer::Send(Message &aMessage, const Ip6::MessageInfo &aMessageInfo) { (void)aMessageInfo; return mNetif.GetDtls().Send(aMessage, aMessage.GetLength()); } void SecureServer::Receive(void *aContext, Message &aMessage, const Ip6::MessageInfo &aMessageInfo) { return static_cast<SecureServer *>(aContext)->Receive(aMessage, aMessageInfo); } void SecureServer::Receive(Message &aMessage, const Ip6::MessageInfo &aMessageInfo) { otLogFuncEntry(); if (!mNetif.GetDtls().IsStarted()) { mPeerAddress.SetPeerAddr(aMessageInfo.GetPeerAddr()); mPeerAddress.SetPeerPort(aMessageInfo.GetPeerPort()); mNetif.GetDtls().Start(false, HandleDtlsConnected, HandleDtlsReceive, HandleDtlsSend, this); } else { // Once DTLS session is started, communicate only with a peer. VerifyOrExit((mPeerAddress.GetPeerAddr() == aMessageInfo.GetPeerAddr()) && (mPeerAddress.GetPeerPort() == aMessageInfo.GetPeerPort()), ;); } mNetif.GetDtls().SetClientId(mPeerAddress.GetPeerAddr().mFields.m8, sizeof(mPeerAddress.GetPeerAddr().mFields)); mNetif.GetDtls().Receive(aMessage, aMessage.GetOffset(), aMessage.GetLength() - aMessage.GetOffset()); exit: otLogFuncExit(); } ThreadError SecureServer::SetPsk(const uint8_t *aPsk, uint8_t aPskLength) { return mNetif.GetDtls().SetPsk(aPsk, aPskLength); } void SecureServer::HandleDtlsConnected(void *aContext, bool aConnected) { return static_cast<SecureServer *>(aContext)->HandleDtlsConnected(aConnected); } void SecureServer::HandleDtlsConnected(bool aConnected) { (void)aConnected; } void SecureServer::HandleDtlsReceive(void *aContext, uint8_t *aBuf, uint16_t aLength) { return static_cast<SecureServer *>(aContext)->HandleDtlsReceive(aBuf, aLength); } void SecureServer::HandleDtlsReceive(uint8_t *aBuf, uint16_t aLength) { Message *message; otLogFuncEntry(); VerifyOrExit((message = mNetif.GetIp6().mMessagePool.New(Message::kTypeIp6, 0)) != NULL, ;); SuccessOrExit(message->Append(aBuf, aLength)); ProcessReceivedMessage(*message, mPeerAddress); exit: if (message != NULL) { message->Free(); } otLogFuncExit(); } ThreadError SecureServer::HandleDtlsSend(void *aContext, const uint8_t *aBuf, uint16_t aLength, uint8_t aMessageSubType) { return static_cast<SecureServer *>(aContext)->HandleDtlsSend(aBuf, aLength, aMessageSubType); } ThreadError SecureServer::HandleDtlsSend(const uint8_t *aBuf, uint16_t aLength, uint8_t aMessageSubType) { ThreadError error = kThreadError_None; otLogFuncEntry(); if (mTransmitMessage == NULL) { VerifyOrExit((mTransmitMessage = mSocket.NewMessage(0)) != NULL, error = kThreadError_NoBufs); mTransmitMessage->SetSubType(aMessageSubType); mTransmitMessage->SetLinkSecurityEnabled(false); } VerifyOrExit(mTransmitMessage->Append(aBuf, aLength) == kThreadError_None, error = kThreadError_NoBufs); mTransmitTask.Post(); exit: if (error != kThreadError_None && mTransmitMessage != NULL) { mTransmitMessage->Free(); } otLogFuncExitErr(error); return error; } void SecureServer::HandleUdpTransmit(void *aContext) { return static_cast<SecureServer *>(aContext)->HandleUdpTransmit(); } void SecureServer::HandleUdpTransmit(void) { ThreadError error = kThreadError_None; otLogFuncEntry(); VerifyOrExit(mTransmitMessage != NULL, error = kThreadError_NoBufs); if (mTransmitCallback) { SuccessOrExit(error = mTransmitCallback(mContext, *mTransmitMessage, mPeerAddress)); } else { SuccessOrExit(error = mSocket.SendTo(*mTransmitMessage, mPeerAddress)); } exit: if (error != kThreadError_None && mTransmitMessage != NULL) { mTransmitMessage->Free(); } mTransmitMessage = NULL; otLogFuncExit(); } } // namespace Coap } // namespace Thread <commit_msg>Fix mismatching source address of secured CoAP server (#1520)<commit_after>/* * Copyright (c) 2016, The OpenThread Authors. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. Neither the name of the copyright holder nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #define WPP_NAME "secure_coap_server.tmh" #include <coap/secure_coap_server.hpp> #include <common/logging.hpp> #include <meshcop/dtls.hpp> #include <thread/thread_netif.hpp> /** * @file * This file implements the secure CoAP server. */ namespace Thread { namespace Coap { SecureServer::SecureServer(ThreadNetif &aNetif, uint16_t aPort): Server(aNetif, aPort, &SecureServer::Send, &SecureServer::Receive), mTransmitCallback(NULL), mContext(NULL), mNetif(aNetif), mTransmitMessage(NULL), mTransmitTask(aNetif.GetIp6().mTaskletScheduler, &SecureServer::HandleUdpTransmit, this) { } ThreadError SecureServer::Start(TransportCallback aCallback, void *aContext) { ThreadError error = kThreadError_None; mTransmitCallback = aCallback; mContext = aContext; // Passing mTransmitCallback means that we do not want to use socket // to transmit/receive messages, so do not open it in that case. if (mTransmitCallback == NULL) { error = Server::Start(); } return error; } ThreadError SecureServer::Stop() { if (mNetif.GetDtls().IsStarted()) { mNetif.GetDtls().Stop(); } if (mTransmitMessage != NULL) { mTransmitMessage->Free(); mTransmitMessage = NULL; } mTransmitCallback = NULL; mContext = NULL; otLogFuncExit(); return Server::Stop(); } bool SecureServer::IsConnectionActive(void) { return mNetif.GetDtls().IsStarted(); }; ThreadError SecureServer::Send(void *aContext, Message &aMessage, const Ip6::MessageInfo &aMessageInfo) { return static_cast<SecureServer *>(aContext)->Send(aMessage, aMessageInfo); } ThreadError SecureServer::Send(Message &aMessage, const Ip6::MessageInfo &aMessageInfo) { (void)aMessageInfo; return mNetif.GetDtls().Send(aMessage, aMessage.GetLength()); } void SecureServer::Receive(void *aContext, Message &aMessage, const Ip6::MessageInfo &aMessageInfo) { return static_cast<SecureServer *>(aContext)->Receive(aMessage, aMessageInfo); } void SecureServer::Receive(Message &aMessage, const Ip6::MessageInfo &aMessageInfo) { otLogFuncEntry(); if (!mNetif.GetDtls().IsStarted()) { mPeerAddress.SetPeerAddr(aMessageInfo.GetPeerAddr()); mPeerAddress.SetPeerPort(aMessageInfo.GetPeerPort()); if (mNetif.IsUnicastAddress(aMessageInfo.GetSockAddr())) { mPeerAddress.SetSockAddr(aMessageInfo.GetSockAddr()); } mPeerAddress.SetSockPort(aMessageInfo.GetSockPort()); mNetif.GetDtls().Start(false, HandleDtlsConnected, HandleDtlsReceive, HandleDtlsSend, this); } else { // Once DTLS session is started, communicate only with a peer. VerifyOrExit((mPeerAddress.GetPeerAddr() == aMessageInfo.GetPeerAddr()) && (mPeerAddress.GetPeerPort() == aMessageInfo.GetPeerPort()), ;); } mNetif.GetDtls().SetClientId(mPeerAddress.GetPeerAddr().mFields.m8, sizeof(mPeerAddress.GetPeerAddr().mFields)); mNetif.GetDtls().Receive(aMessage, aMessage.GetOffset(), aMessage.GetLength() - aMessage.GetOffset()); exit: otLogFuncExit(); } ThreadError SecureServer::SetPsk(const uint8_t *aPsk, uint8_t aPskLength) { return mNetif.GetDtls().SetPsk(aPsk, aPskLength); } void SecureServer::HandleDtlsConnected(void *aContext, bool aConnected) { return static_cast<SecureServer *>(aContext)->HandleDtlsConnected(aConnected); } void SecureServer::HandleDtlsConnected(bool aConnected) { (void)aConnected; } void SecureServer::HandleDtlsReceive(void *aContext, uint8_t *aBuf, uint16_t aLength) { return static_cast<SecureServer *>(aContext)->HandleDtlsReceive(aBuf, aLength); } void SecureServer::HandleDtlsReceive(uint8_t *aBuf, uint16_t aLength) { Message *message; otLogFuncEntry(); VerifyOrExit((message = mNetif.GetIp6().mMessagePool.New(Message::kTypeIp6, 0)) != NULL, ;); SuccessOrExit(message->Append(aBuf, aLength)); ProcessReceivedMessage(*message, mPeerAddress); exit: if (message != NULL) { message->Free(); } otLogFuncExit(); } ThreadError SecureServer::HandleDtlsSend(void *aContext, const uint8_t *aBuf, uint16_t aLength, uint8_t aMessageSubType) { return static_cast<SecureServer *>(aContext)->HandleDtlsSend(aBuf, aLength, aMessageSubType); } ThreadError SecureServer::HandleDtlsSend(const uint8_t *aBuf, uint16_t aLength, uint8_t aMessageSubType) { ThreadError error = kThreadError_None; otLogFuncEntry(); if (mTransmitMessage == NULL) { VerifyOrExit((mTransmitMessage = mSocket.NewMessage(0)) != NULL, error = kThreadError_NoBufs); mTransmitMessage->SetSubType(aMessageSubType); mTransmitMessage->SetLinkSecurityEnabled(false); } VerifyOrExit(mTransmitMessage->Append(aBuf, aLength) == kThreadError_None, error = kThreadError_NoBufs); mTransmitTask.Post(); exit: if (error != kThreadError_None && mTransmitMessage != NULL) { mTransmitMessage->Free(); } otLogFuncExitErr(error); return error; } void SecureServer::HandleUdpTransmit(void *aContext) { return static_cast<SecureServer *>(aContext)->HandleUdpTransmit(); } void SecureServer::HandleUdpTransmit(void) { ThreadError error = kThreadError_None; otLogFuncEntry(); VerifyOrExit(mTransmitMessage != NULL, error = kThreadError_NoBufs); if (mTransmitCallback) { SuccessOrExit(error = mTransmitCallback(mContext, *mTransmitMessage, mPeerAddress)); } else { SuccessOrExit(error = mSocket.SendTo(*mTransmitMessage, mPeerAddress)); } exit: if (error != kThreadError_None && mTransmitMessage != NULL) { mTransmitMessage->Free(); } mTransmitMessage = NULL; otLogFuncExit(); } } // namespace Coap } // namespace Thread <|endoftext|>
<commit_before>#include <gtest/gtest.h> #include "keycode.hpp" using namespace org_pqrs_KeyRemap4MacBook; TEST(ModifierFlag, stripFN) { unsigned int flags = ModifierFlag::SHIFT_L | ModifierFlag::CONTROL_R | ModifierFlag::COMMAND_R; EXPECT_EQ(ModifierFlag::stripFN(flags), flags); EXPECT_EQ(ModifierFlag::stripFN(flags | ModifierFlag::FN), flags); } TEST(ModifierFlag, stripCURSOR) { unsigned int flags = ModifierFlag::SHIFT_L | ModifierFlag::CONTROL_R | ModifierFlag::COMMAND_R; EXPECT_EQ(ModifierFlag::stripCURSOR(flags), flags); EXPECT_EQ(ModifierFlag::stripCURSOR(flags | ModifierFlag::CURSOR), flags); } TEST(ModifierFlag, stripKEYPAD) { unsigned int flags = ModifierFlag::SHIFT_L | ModifierFlag::CONTROL_R | ModifierFlag::COMMAND_R; EXPECT_EQ(ModifierFlag::stripKEYPAD(flags), flags); EXPECT_EQ(ModifierFlag::stripKEYPAD(flags | ModifierFlag::KEYPAD), flags); } TEST(ModifierFlag, stripNONE) { unsigned int flags = ModifierFlag::SHIFT_L | ModifierFlag::CONTROL_R | ModifierFlag::COMMAND_R; EXPECT_EQ(ModifierFlag::stripNONE(flags), flags); EXPECT_EQ(ModifierFlag::stripNONE(flags | ModifierFlag::NONE), flags); } TEST(ModifierFlag, isOn) { unsigned int flags = ModifierFlag::SHIFT_L | ModifierFlag::CONTROL_R | ModifierFlag::COMMAND_R; EXPECT_TRUE(ModifierFlag::isOn(flags, ModifierFlag::SHIFT_L)); EXPECT_FALSE(ModifierFlag::isOn(flags, ModifierFlag::SHIFT_R)); flags = ModifierFlag::NONE; EXPECT_TRUE(ModifierFlag::isOn(flags, ModifierFlag::NONE)); } namespace { unsigned int keypads[][2] = { { KeyCode::KEYPAD_0, KeyCode::M }, { KeyCode::KEYPAD_1, KeyCode::J }, { KeyCode::KEYPAD_2, KeyCode::K }, { KeyCode::KEYPAD_3, KeyCode::L }, { KeyCode::KEYPAD_4, KeyCode::U }, { KeyCode::KEYPAD_5, KeyCode::I }, { KeyCode::KEYPAD_6, KeyCode::O }, { KeyCode::KEYPAD_7, KeyCode::KEY_7 }, { KeyCode::KEYPAD_8, KeyCode::KEY_8 }, { KeyCode::KEYPAD_9, KeyCode::KEY_9 }, { KeyCode::KEYPAD_CLEAR, KeyCode::KEY_6 }, { KeyCode::KEYPAD_PLUS, KeyCode::SLASH }, { KeyCode::KEYPAD_MINUS, KeyCode::SEMICOLON }, { KeyCode::KEYPAD_MULTIPLY, KeyCode::P }, { KeyCode::KEYPAD_SLASH, KeyCode::KEY_0 }, { KeyCode::KEYPAD_EQUAL, KeyCode::MINUS }, { KeyCode::KEYPAD_DOT, KeyCode::DOT }, }; unsigned int cursors[][2] = { { KeyCode::PAGEUP, KeyCode::CURSOR_UP }, { KeyCode::PAGEDOWN, KeyCode::CURSOR_DOWN }, { KeyCode::HOME, KeyCode::CURSOR_LEFT }, { KeyCode::END, KeyCode::CURSOR_RIGHT }, }; } TEST(KeyCode, normalizeKey) { unsigned int key = 0; unsigned int flags = 0; unsigned int keyboardType = 0; // ENTER_POWERBOOK -> ENTER key = KeyCode::ENTER_POWERBOOK; flags = ModifierFlag::SHIFT_L; keyboardType = KeyboardType::POWERBOOK; KeyCode::normalizeKey(key, flags, keyboardType); EXPECT_EQ(key, static_cast<unsigned int>(KeyCode::ENTER)); EXPECT_EQ(flags, static_cast<unsigned int>(ModifierFlag::SHIFT_L)); // ENTER_POWERBOOK(+FN) -> ENTER(+FN) -> RETURN key = KeyCode::ENTER_POWERBOOK; flags = ModifierFlag::SHIFT_L | ModifierFlag::FN; keyboardType = KeyboardType::POWERBOOK; KeyCode::normalizeKey(key, flags, keyboardType); EXPECT_EQ(key, static_cast<unsigned int>(KeyCode::RETURN)); EXPECT_EQ(flags, static_cast<unsigned int>(ModifierFlag::SHIFT_L)); // normal key key = KeyCode::A; flags = ModifierFlag::SHIFT_L; keyboardType = KeyboardType::MACBOOK; KeyCode::normalizeKey(key, flags, keyboardType); EXPECT_EQ(key, static_cast<unsigned int>(KeyCode::A)); EXPECT_EQ(flags, static_cast<unsigned int>(ModifierFlag::SHIFT_L)); // KEYPAD for (size_t i = 0; i < sizeof(keypads) / sizeof(keypads[0]); ++i) { key = keypads[i][0]; flags = ModifierFlag::SHIFT_L | ModifierFlag::KEYPAD; keyboardType = KeyboardType::MACBOOK; KeyCode::normalizeKey(key, flags, keyboardType); EXPECT_EQ(key, keypads[i][0]); EXPECT_EQ(flags, static_cast<unsigned int>(ModifierFlag::SHIFT_L | ModifierFlag::KEYPAD)); } // PAGEUP for (size_t i = 0; i < sizeof(cursors) / sizeof(cursors[0]); ++i) { key = cursors[i][0]; flags = ModifierFlag::SHIFT_L; keyboardType = KeyboardType::MACBOOK; KeyCode::normalizeKey(key, flags, keyboardType); EXPECT_EQ(key, cursors[i][0]); EXPECT_EQ(flags, static_cast<unsigned int>(ModifierFlag::SHIFT_L)); } // ENTER key = KeyCode::ENTER; flags = ModifierFlag::SHIFT_L; keyboardType = KeyboardType::MACBOOK; KeyCode::normalizeKey(key, flags, keyboardType); EXPECT_EQ(key, static_cast<unsigned int>(KeyCode::ENTER)); EXPECT_EQ(flags, static_cast<unsigned int>(ModifierFlag::SHIFT_L)); // FORWARD_DELETE key = KeyCode::FORWARD_DELETE; flags = ModifierFlag::SHIFT_L; keyboardType = KeyboardType::MACBOOK; KeyCode::normalizeKey(key, flags, keyboardType); EXPECT_EQ(key, static_cast<unsigned int>(KeyCode::FORWARD_DELETE)); EXPECT_EQ(flags, static_cast<unsigned int>(ModifierFlag::SHIFT_L)); // normal key(+FN) key = KeyCode::A; flags = ModifierFlag::SHIFT_L | ModifierFlag::FN; keyboardType = KeyboardType::MACBOOK; KeyCode::normalizeKey(key, flags, keyboardType); EXPECT_EQ(key, static_cast<unsigned int>(KeyCode::A)); EXPECT_EQ(flags, static_cast<unsigned int>(ModifierFlag::SHIFT_L | ModifierFlag::FN)); // KEYPAD(+FN) for (size_t i = 0; i < sizeof(keypads) / sizeof(keypads[0]); ++i) { key = keypads[i][0]; flags = ModifierFlag::SHIFT_L | ModifierFlag::FN | ModifierFlag::KEYPAD; keyboardType = KeyboardType::MACBOOK; KeyCode::normalizeKey(key, flags, keyboardType); EXPECT_EQ(key, static_cast<unsigned int>(keypads[i][1])); EXPECT_EQ(flags, static_cast<unsigned int>(ModifierFlag::SHIFT_L | ModifierFlag::KEYPAD)); } // PAGEUP(+FN) for (size_t i = 0; i < sizeof(cursors) / sizeof(cursors[0]); ++i) { key = cursors[i][0]; flags = ModifierFlag::SHIFT_L | ModifierFlag::FN; keyboardType = KeyboardType::MACBOOK; KeyCode::normalizeKey(key, flags, keyboardType); EXPECT_EQ(key, cursors[i][1]); EXPECT_EQ(flags, static_cast<unsigned int>(ModifierFlag::SHIFT_L | ModifierFlag::CURSOR)); } // ENTER(+FN) key = KeyCode::ENTER; flags = ModifierFlag::SHIFT_L | ModifierFlag::FN; keyboardType = KeyboardType::MACBOOK; KeyCode::normalizeKey(key, flags, keyboardType); EXPECT_EQ(key, static_cast<unsigned int>(KeyCode::RETURN)); EXPECT_EQ(flags, static_cast<unsigned int>(ModifierFlag::SHIFT_L)); // FORWARD_DELETE(+FN) key = KeyCode::FORWARD_DELETE; flags = ModifierFlag::SHIFT_L | ModifierFlag::FN; keyboardType = KeyboardType::MACBOOK; KeyCode::normalizeKey(key, flags, keyboardType); EXPECT_EQ(key, static_cast<unsigned int>(KeyCode::DELETE)); EXPECT_EQ(flags, static_cast<unsigned int>(ModifierFlag::SHIFT_L)); } TEST(KeyCode, reverseNormalizeKey) { unsigned int key = 0; unsigned int flags = 0; unsigned int keyboardType = 0; // ENTER_POWERBOOK -> ENTER key = KeyCode::ENTER_POWERBOOK; flags = ModifierFlag::SHIFT_L; keyboardType = KeyboardType::POWERBOOK; KeyCode::normalizeKey(key, flags, keyboardType); KeyCode::reverseNormalizeKey(key, flags, keyboardType); EXPECT_EQ(key, static_cast<unsigned int>(KeyCode::ENTER_POWERBOOK)); EXPECT_EQ(flags, static_cast<unsigned int>(ModifierFlag::SHIFT_L)); // ENTER_POWERBOOK(+FN) -> ENTER(+FN) -> RETURN key = KeyCode::ENTER_POWERBOOK; flags = ModifierFlag::SHIFT_L | ModifierFlag::FN; keyboardType = KeyboardType::POWERBOOK; KeyCode::normalizeKey(key, flags, keyboardType); flags |= ModifierFlag::FN; KeyCode::reverseNormalizeKey(key, flags, keyboardType); EXPECT_EQ(key, static_cast<unsigned int>(KeyCode::ENTER_POWERBOOK)); EXPECT_EQ(flags, static_cast<unsigned int>(ModifierFlag::SHIFT_L | ModifierFlag::FN)); // normal key key = KeyCode::A; flags = ModifierFlag::SHIFT_L; keyboardType = KeyboardType::MACBOOK; KeyCode::normalizeKey(key, flags, keyboardType); KeyCode::reverseNormalizeKey(key, flags, keyboardType); EXPECT_EQ(key, static_cast<unsigned int>(KeyCode::A)); EXPECT_EQ(flags, static_cast<unsigned int>(ModifierFlag::SHIFT_L)); // KEYPAD for (size_t i = 0; i < sizeof(keypads) / sizeof(keypads[0]); ++i) { key = keypads[i][0]; flags = ModifierFlag::SHIFT_L | ModifierFlag::KEYPAD; keyboardType = KeyboardType::MACBOOK; KeyCode::normalizeKey(key, flags, keyboardType); KeyCode::reverseNormalizeKey(key, flags, keyboardType); EXPECT_EQ(key, keypads[i][0]); EXPECT_EQ(flags, static_cast<unsigned int>(ModifierFlag::SHIFT_L | ModifierFlag::KEYPAD)); } // PAGEUP for (size_t i = 0; i < sizeof(cursors) / sizeof(cursors[0]); ++i) { key = cursors[i][0]; flags = ModifierFlag::SHIFT_L; keyboardType = KeyboardType::MACBOOK; KeyCode::normalizeKey(key, flags, keyboardType); KeyCode::reverseNormalizeKey(key, flags, keyboardType); EXPECT_EQ(key, cursors[i][0]); EXPECT_EQ(flags, static_cast<unsigned int>(ModifierFlag::SHIFT_L)); } // ENTER key = KeyCode::ENTER; flags = ModifierFlag::SHIFT_L; keyboardType = KeyboardType::MACBOOK; KeyCode::normalizeKey(key, flags, keyboardType); KeyCode::reverseNormalizeKey(key, flags, keyboardType); EXPECT_EQ(key, static_cast<unsigned int>(KeyCode::ENTER)); EXPECT_EQ(flags, static_cast<unsigned int>(ModifierFlag::SHIFT_L)); // FORWARD_DELETE key = KeyCode::FORWARD_DELETE; flags = ModifierFlag::SHIFT_L; keyboardType = KeyboardType::MACBOOK; KeyCode::normalizeKey(key, flags, keyboardType); KeyCode::reverseNormalizeKey(key, flags, keyboardType); EXPECT_EQ(key, static_cast<unsigned int>(KeyCode::FORWARD_DELETE)); EXPECT_EQ(flags, static_cast<unsigned int>(ModifierFlag::SHIFT_L)); // CURSOR for (size_t i = 0; i < sizeof(cursors) / sizeof(cursors[0]); ++i) { key = cursors[i][1]; flags = ModifierFlag::CURSOR; keyboardType = KeyboardType::MACBOOK; KeyCode::normalizeKey(key, flags, keyboardType); KeyCode::reverseNormalizeKey(key, flags, keyboardType); EXPECT_EQ(key, static_cast<unsigned int>(cursors[i][1])); EXPECT_EQ(flags, static_cast<unsigned int>(ModifierFlag::CURSOR)); } // normal key(+FN) key = KeyCode::A; flags = ModifierFlag::SHIFT_L | ModifierFlag::FN; keyboardType = KeyboardType::MACBOOK; KeyCode::normalizeKey(key, flags, keyboardType); flags |= ModifierFlag::FN; KeyCode::reverseNormalizeKey(key, flags, keyboardType); EXPECT_EQ(key, static_cast<unsigned int>(KeyCode::A)); EXPECT_EQ(flags, static_cast<unsigned int>(ModifierFlag::SHIFT_L | ModifierFlag::FN)); // KEYPAD(+FN) for (size_t i = 0; i < sizeof(keypads) / sizeof(keypads[0]); ++i) { key = keypads[i][0]; flags = ModifierFlag::SHIFT_L | ModifierFlag::FN | ModifierFlag::KEYPAD; keyboardType = KeyboardType::MACBOOK; KeyCode::normalizeKey(key, flags, keyboardType); flags |= ModifierFlag::FN; KeyCode::reverseNormalizeKey(key, flags, keyboardType); EXPECT_EQ(key, static_cast<unsigned int>(keypads[i][0])); EXPECT_EQ(flags, static_cast<unsigned int>(ModifierFlag::SHIFT_L | ModifierFlag::FN | ModifierFlag::KEYPAD)); } // PAGEUP(+FN) for (size_t i = 0; i < sizeof(cursors) / sizeof(cursors[0]); ++i) { key = cursors[i][0]; flags = ModifierFlag::SHIFT_L | ModifierFlag::FN; keyboardType = KeyboardType::MACBOOK; KeyCode::normalizeKey(key, flags, keyboardType); flags |= ModifierFlag::FN; KeyCode::reverseNormalizeKey(key, flags, keyboardType); EXPECT_EQ(key, cursors[i][0]); EXPECT_EQ(flags, static_cast<unsigned int>(ModifierFlag::SHIFT_L | ModifierFlag::FN)); } // ENTER(+FN) key = KeyCode::ENTER; flags = ModifierFlag::SHIFT_L | ModifierFlag::FN; keyboardType = KeyboardType::MACBOOK; KeyCode::normalizeKey(key, flags, keyboardType); flags |= ModifierFlag::FN; KeyCode::reverseNormalizeKey(key, flags, keyboardType); EXPECT_EQ(key, static_cast<unsigned int>(KeyCode::ENTER)); EXPECT_EQ(flags, static_cast<unsigned int>(ModifierFlag::SHIFT_L | ModifierFlag::FN)); // FORWARD_DELETE(+FN) key = KeyCode::FORWARD_DELETE; flags = ModifierFlag::SHIFT_L | ModifierFlag::FN; keyboardType = KeyboardType::MACBOOK; KeyCode::normalizeKey(key, flags, keyboardType); flags |= ModifierFlag::FN; KeyCode::reverseNormalizeKey(key, flags, keyboardType); EXPECT_EQ(key, static_cast<unsigned int>(KeyCode::FORWARD_DELETE)); EXPECT_EQ(flags, static_cast<unsigned int>(ModifierFlag::SHIFT_L | ModifierFlag::FN)); } <commit_msg>update kext/Tests<commit_after>#include <gtest/gtest.h> #include "keycode.hpp" using namespace org_pqrs_KeyRemap4MacBook; TEST(ModifierFlag, stripFN) { unsigned int flags = ModifierFlag::SHIFT_L | ModifierFlag::CONTROL_R | ModifierFlag::COMMAND_R; EXPECT_EQ(ModifierFlag::stripFN(flags), flags); EXPECT_EQ(ModifierFlag::stripFN(flags | ModifierFlag::FN), flags); } TEST(ModifierFlag, stripCURSOR) { unsigned int flags = ModifierFlag::SHIFT_L | ModifierFlag::CONTROL_R | ModifierFlag::COMMAND_R; EXPECT_EQ(ModifierFlag::stripCURSOR(flags), flags); EXPECT_EQ(ModifierFlag::stripCURSOR(flags | ModifierFlag::CURSOR), flags); } TEST(ModifierFlag, stripKEYPAD) { unsigned int flags = ModifierFlag::SHIFT_L | ModifierFlag::CONTROL_R | ModifierFlag::COMMAND_R; EXPECT_EQ(ModifierFlag::stripKEYPAD(flags), flags); EXPECT_EQ(ModifierFlag::stripKEYPAD(flags | ModifierFlag::KEYPAD), flags); } TEST(ModifierFlag, stripNONE) { unsigned int flags = ModifierFlag::SHIFT_L | ModifierFlag::CONTROL_R | ModifierFlag::COMMAND_R; EXPECT_EQ(ModifierFlag::stripNONE(flags), flags); EXPECT_EQ(ModifierFlag::stripNONE(flags | ModifierFlag::NONE), flags); } TEST(ModifierFlag, isOn) { unsigned int flags = ModifierFlag::SHIFT_L | ModifierFlag::CONTROL_R | ModifierFlag::COMMAND_R; EXPECT_TRUE(ModifierFlag::isOn(flags, ModifierFlag::SHIFT_L)); EXPECT_FALSE(ModifierFlag::isOn(flags, ModifierFlag::SHIFT_R)); flags = ModifierFlag::NONE; EXPECT_TRUE(ModifierFlag::isOn(flags, ModifierFlag::NONE)); } namespace { unsigned int keypads[][2] = { { KeyCode::KEYPAD_0, KeyCode::M }, { KeyCode::KEYPAD_1, KeyCode::J }, { KeyCode::KEYPAD_2, KeyCode::K }, { KeyCode::KEYPAD_3, KeyCode::L }, { KeyCode::KEYPAD_4, KeyCode::U }, { KeyCode::KEYPAD_5, KeyCode::I }, { KeyCode::KEYPAD_6, KeyCode::O }, { KeyCode::KEYPAD_7, KeyCode::KEY_7 }, { KeyCode::KEYPAD_8, KeyCode::KEY_8 }, { KeyCode::KEYPAD_9, KeyCode::KEY_9 }, { KeyCode::KEYPAD_CLEAR, KeyCode::KEY_6 }, { KeyCode::KEYPAD_PLUS, KeyCode::SLASH }, { KeyCode::KEYPAD_MINUS, KeyCode::SEMICOLON }, { KeyCode::KEYPAD_MULTIPLY, KeyCode::P }, { KeyCode::KEYPAD_SLASH, KeyCode::KEY_0 }, { KeyCode::KEYPAD_EQUAL, KeyCode::MINUS }, { KeyCode::KEYPAD_DOT, KeyCode::DOT }, }; unsigned int cursors[][2] = { { KeyCode::PAGEUP, KeyCode::CURSOR_UP }, { KeyCode::PAGEDOWN, KeyCode::CURSOR_DOWN }, { KeyCode::HOME, KeyCode::CURSOR_LEFT }, { KeyCode::END, KeyCode::CURSOR_RIGHT }, }; } TEST(KeyCode, normalizeKey) { unsigned int key = 0; unsigned int flags = 0; unsigned int keyboardType = 0; // ENTER_POWERBOOK -> ENTER key = KeyCode::ENTER_POWERBOOK; flags = ModifierFlag::SHIFT_L; keyboardType = KeyboardType::POWERBOOK; KeyCode::normalizeKey(key, flags, keyboardType); EXPECT_EQ(key, static_cast<unsigned int>(KeyCode::ENTER)); EXPECT_EQ(flags, static_cast<unsigned int>(ModifierFlag::SHIFT_L)); // ENTER_POWERBOOK(+FN) -> ENTER(+FN) -> RETURN key = KeyCode::ENTER_POWERBOOK; flags = ModifierFlag::SHIFT_L | ModifierFlag::FN; keyboardType = KeyboardType::POWERBOOK; KeyCode::normalizeKey(key, flags, keyboardType); EXPECT_EQ(key, static_cast<unsigned int>(KeyCode::RETURN)); EXPECT_EQ(flags, static_cast<unsigned int>(ModifierFlag::SHIFT_L)); // normal key key = KeyCode::A; flags = ModifierFlag::SHIFT_L; keyboardType = KeyboardType::MACBOOK; KeyCode::normalizeKey(key, flags, keyboardType); EXPECT_EQ(key, static_cast<unsigned int>(KeyCode::A)); EXPECT_EQ(flags, static_cast<unsigned int>(ModifierFlag::SHIFT_L)); // KEYPAD for (size_t i = 0; i < sizeof(keypads) / sizeof(keypads[0]); ++i) { key = keypads[i][0]; flags = ModifierFlag::SHIFT_L | ModifierFlag::KEYPAD; keyboardType = KeyboardType::MACBOOK; KeyCode::normalizeKey(key, flags, keyboardType); EXPECT_EQ(key, keypads[i][0]); EXPECT_EQ(flags, static_cast<unsigned int>(ModifierFlag::SHIFT_L | ModifierFlag::KEYPAD)); } // PAGEUP for (size_t i = 0; i < sizeof(cursors) / sizeof(cursors[0]); ++i) { key = cursors[i][0]; flags = ModifierFlag::SHIFT_L; keyboardType = KeyboardType::MACBOOK; KeyCode::normalizeKey(key, flags, keyboardType); EXPECT_EQ(key, cursors[i][0]); EXPECT_EQ(flags, static_cast<unsigned int>(ModifierFlag::SHIFT_L)); } // ENTER key = KeyCode::ENTER; flags = ModifierFlag::SHIFT_L; keyboardType = KeyboardType::MACBOOK; KeyCode::normalizeKey(key, flags, keyboardType); EXPECT_EQ(key, static_cast<unsigned int>(KeyCode::ENTER)); EXPECT_EQ(flags, static_cast<unsigned int>(ModifierFlag::SHIFT_L)); // FORWARD_DELETE key = KeyCode::FORWARD_DELETE; flags = ModifierFlag::SHIFT_L; keyboardType = KeyboardType::MACBOOK; KeyCode::normalizeKey(key, flags, keyboardType); EXPECT_EQ(key, static_cast<unsigned int>(KeyCode::FORWARD_DELETE)); EXPECT_EQ(flags, static_cast<unsigned int>(ModifierFlag::SHIFT_L)); // normal key(+FN) key = KeyCode::A; flags = ModifierFlag::SHIFT_L | ModifierFlag::FN; keyboardType = KeyboardType::MACBOOK; KeyCode::normalizeKey(key, flags, keyboardType); EXPECT_EQ(key, static_cast<unsigned int>(KeyCode::A)); EXPECT_EQ(flags, static_cast<unsigned int>(ModifierFlag::SHIFT_L | ModifierFlag::FN)); // KEYPAD(+FN) for (size_t i = 0; i < sizeof(keypads) / sizeof(keypads[0]); ++i) { key = keypads[i][0]; flags = ModifierFlag::SHIFT_L | ModifierFlag::FN | ModifierFlag::KEYPAD; keyboardType = KeyboardType::MACBOOK; KeyCode::normalizeKey(key, flags, keyboardType); EXPECT_EQ(key, static_cast<unsigned int>(keypads[i][1])); EXPECT_EQ(flags, static_cast<unsigned int>(ModifierFlag::SHIFT_L)); } // PAGEUP(+FN) for (size_t i = 0; i < sizeof(cursors) / sizeof(cursors[0]); ++i) { key = cursors[i][0]; flags = ModifierFlag::SHIFT_L | ModifierFlag::FN; keyboardType = KeyboardType::MACBOOK; KeyCode::normalizeKey(key, flags, keyboardType); EXPECT_EQ(key, cursors[i][1]); EXPECT_EQ(flags, static_cast<unsigned int>(ModifierFlag::SHIFT_L | ModifierFlag::CURSOR)); } // ENTER(+FN) key = KeyCode::ENTER; flags = ModifierFlag::SHIFT_L | ModifierFlag::FN; keyboardType = KeyboardType::MACBOOK; KeyCode::normalizeKey(key, flags, keyboardType); EXPECT_EQ(key, static_cast<unsigned int>(KeyCode::RETURN)); EXPECT_EQ(flags, static_cast<unsigned int>(ModifierFlag::SHIFT_L)); // FORWARD_DELETE(+FN) key = KeyCode::FORWARD_DELETE; flags = ModifierFlag::SHIFT_L | ModifierFlag::FN; keyboardType = KeyboardType::MACBOOK; KeyCode::normalizeKey(key, flags, keyboardType); EXPECT_EQ(key, static_cast<unsigned int>(KeyCode::DELETE)); EXPECT_EQ(flags, static_cast<unsigned int>(ModifierFlag::SHIFT_L)); } TEST(KeyCode, reverseNormalizeKey) { unsigned int key = 0; unsigned int flags = 0; unsigned int keyboardType = 0; // ENTER_POWERBOOK -> ENTER key = KeyCode::ENTER_POWERBOOK; flags = ModifierFlag::SHIFT_L; keyboardType = KeyboardType::POWERBOOK; KeyCode::normalizeKey(key, flags, keyboardType); KeyCode::reverseNormalizeKey(key, flags, keyboardType); EXPECT_EQ(key, static_cast<unsigned int>(KeyCode::ENTER_POWERBOOK)); EXPECT_EQ(flags, static_cast<unsigned int>(ModifierFlag::SHIFT_L)); // ENTER_POWERBOOK(+FN) -> ENTER(+FN) -> RETURN key = KeyCode::ENTER_POWERBOOK; flags = ModifierFlag::SHIFT_L | ModifierFlag::FN; keyboardType = KeyboardType::POWERBOOK; KeyCode::normalizeKey(key, flags, keyboardType); flags |= ModifierFlag::FN; KeyCode::reverseNormalizeKey(key, flags, keyboardType); EXPECT_EQ(key, static_cast<unsigned int>(KeyCode::ENTER_POWERBOOK)); EXPECT_EQ(flags, static_cast<unsigned int>(ModifierFlag::SHIFT_L | ModifierFlag::FN)); // normal key key = KeyCode::A; flags = ModifierFlag::SHIFT_L; keyboardType = KeyboardType::MACBOOK; KeyCode::normalizeKey(key, flags, keyboardType); KeyCode::reverseNormalizeKey(key, flags, keyboardType); EXPECT_EQ(key, static_cast<unsigned int>(KeyCode::A)); EXPECT_EQ(flags, static_cast<unsigned int>(ModifierFlag::SHIFT_L)); // KEYPAD for (size_t i = 0; i < sizeof(keypads) / sizeof(keypads[0]); ++i) { key = keypads[i][0]; flags = ModifierFlag::SHIFT_L | ModifierFlag::KEYPAD; keyboardType = KeyboardType::MACBOOK; KeyCode::normalizeKey(key, flags, keyboardType); KeyCode::reverseNormalizeKey(key, flags, keyboardType); EXPECT_EQ(key, keypads[i][0]); EXPECT_EQ(flags, static_cast<unsigned int>(ModifierFlag::SHIFT_L | ModifierFlag::KEYPAD)); } // PAGEUP for (size_t i = 0; i < sizeof(cursors) / sizeof(cursors[0]); ++i) { key = cursors[i][0]; flags = ModifierFlag::SHIFT_L; keyboardType = KeyboardType::MACBOOK; KeyCode::normalizeKey(key, flags, keyboardType); KeyCode::reverseNormalizeKey(key, flags, keyboardType); EXPECT_EQ(key, cursors[i][0]); EXPECT_EQ(flags, static_cast<unsigned int>(ModifierFlag::SHIFT_L)); } // ENTER key = KeyCode::ENTER; flags = ModifierFlag::SHIFT_L; keyboardType = KeyboardType::MACBOOK; KeyCode::normalizeKey(key, flags, keyboardType); KeyCode::reverseNormalizeKey(key, flags, keyboardType); EXPECT_EQ(key, static_cast<unsigned int>(KeyCode::ENTER)); EXPECT_EQ(flags, static_cast<unsigned int>(ModifierFlag::SHIFT_L)); // FORWARD_DELETE key = KeyCode::FORWARD_DELETE; flags = ModifierFlag::SHIFT_L; keyboardType = KeyboardType::MACBOOK; KeyCode::normalizeKey(key, flags, keyboardType); KeyCode::reverseNormalizeKey(key, flags, keyboardType); EXPECT_EQ(key, static_cast<unsigned int>(KeyCode::FORWARD_DELETE)); EXPECT_EQ(flags, static_cast<unsigned int>(ModifierFlag::SHIFT_L)); // CURSOR for (size_t i = 0; i < sizeof(cursors) / sizeof(cursors[0]); ++i) { key = cursors[i][1]; flags = ModifierFlag::CURSOR; keyboardType = KeyboardType::MACBOOK; KeyCode::normalizeKey(key, flags, keyboardType); KeyCode::reverseNormalizeKey(key, flags, keyboardType); EXPECT_EQ(key, static_cast<unsigned int>(cursors[i][1])); EXPECT_EQ(flags, static_cast<unsigned int>(ModifierFlag::CURSOR)); } // normal key(+FN) key = KeyCode::A; flags = ModifierFlag::SHIFT_L | ModifierFlag::FN; keyboardType = KeyboardType::MACBOOK; KeyCode::normalizeKey(key, flags, keyboardType); flags |= ModifierFlag::FN; KeyCode::reverseNormalizeKey(key, flags, keyboardType); EXPECT_EQ(key, static_cast<unsigned int>(KeyCode::A)); EXPECT_EQ(flags, static_cast<unsigned int>(ModifierFlag::SHIFT_L | ModifierFlag::FN)); // KEYPAD(+FN) for (size_t i = 0; i < sizeof(keypads) / sizeof(keypads[0]); ++i) { key = keypads[i][0]; flags = ModifierFlag::SHIFT_L | ModifierFlag::FN | ModifierFlag::KEYPAD; keyboardType = KeyboardType::MACBOOK; KeyCode::normalizeKey(key, flags, keyboardType); flags |= ModifierFlag::FN; KeyCode::reverseNormalizeKey(key, flags, keyboardType); EXPECT_EQ(key, static_cast<unsigned int>(keypads[i][0])); EXPECT_EQ(flags, static_cast<unsigned int>(ModifierFlag::SHIFT_L | ModifierFlag::FN | ModifierFlag::KEYPAD)); } // PAGEUP(+FN) for (size_t i = 0; i < sizeof(cursors) / sizeof(cursors[0]); ++i) { key = cursors[i][0]; flags = ModifierFlag::SHIFT_L | ModifierFlag::FN; keyboardType = KeyboardType::MACBOOK; KeyCode::normalizeKey(key, flags, keyboardType); flags |= ModifierFlag::FN; KeyCode::reverseNormalizeKey(key, flags, keyboardType); EXPECT_EQ(key, cursors[i][0]); EXPECT_EQ(flags, static_cast<unsigned int>(ModifierFlag::SHIFT_L | ModifierFlag::FN)); } // ENTER(+FN) key = KeyCode::ENTER; flags = ModifierFlag::SHIFT_L | ModifierFlag::FN; keyboardType = KeyboardType::MACBOOK; KeyCode::normalizeKey(key, flags, keyboardType); flags |= ModifierFlag::FN; KeyCode::reverseNormalizeKey(key, flags, keyboardType); EXPECT_EQ(key, static_cast<unsigned int>(KeyCode::ENTER)); EXPECT_EQ(flags, static_cast<unsigned int>(ModifierFlag::SHIFT_L | ModifierFlag::FN)); // FORWARD_DELETE(+FN) key = KeyCode::FORWARD_DELETE; flags = ModifierFlag::SHIFT_L | ModifierFlag::FN; keyboardType = KeyboardType::MACBOOK; KeyCode::normalizeKey(key, flags, keyboardType); flags |= ModifierFlag::FN; KeyCode::reverseNormalizeKey(key, flags, keyboardType); EXPECT_EQ(key, static_cast<unsigned int>(KeyCode::FORWARD_DELETE)); EXPECT_EQ(flags, static_cast<unsigned int>(ModifierFlag::SHIFT_L | ModifierFlag::FN)); } <|endoftext|>
<commit_before>#include "core/physics/physics_manager.h" #include "core/physics/constraint.h" #include "core/rendering/render_manager.h" #include <glm/gtx/norm.hpp> #include <bitset> namespace eversim { namespace core { namespace physics { namespace { template <typename Constraints, typename Func, size_t... Is> void iterate(Constraints const& c, std::index_sequence<Is...>, Func&& fun) { std::initializer_list<int>{ (std::forward<Func>(fun)(std::get<Is>(c), Is), 0)... }; } } void physics_manager::add_particle(particle const& p) { particles.push_back(p); } void physics_manager::integrate(float dt) { apply_external_forces(dt); damp_velocities(); for (auto& p : particles) { p.projected_position = p.pos + dt * p.vel; } for (auto i = 0; i < solver_iterations; ++i) { project_constraints(); } for (auto& p : particles) { p.vel = (p.projected_position - p.pos) / dt; p.pos = p.projected_position; } } void physics_manager::atomic_step(float dt) { switch (current_state) { case simulation_state::external: apply_external_forces(dt); current_state = simulation_state::damp; break; case simulation_state::damp: damp_velocities(); current_state = simulation_state::apply_velocity; break; case simulation_state::apply_velocity: for (auto& p : particles) { p.projected_position = p.pos + dt * p.vel; } current_state = simulation_state::constraint_iteration; break; case simulation_state::constraint_iteration: if(current_iteration < solver_iterations) { project_constraints(); current_iteration++; }else { current_iteration = 0; current_state = simulation_state::apply_changes; } break; case simulation_state::apply_changes: for (auto& p : particles) { p.vel = (p.projected_position - p.pos) / dt; p.pos = p.projected_position; } current_state = simulation_state::external; break; default: ; assert(!"unknown state!"); } } void physics_manager::draw_constraints(std::bitset<max_constraint_arity> to_render) { iterate(constraints, std::make_index_sequence<max_constraint_arity>{}, [to_render](auto const& cs, size_t I) { if(to_render[I]) { for (auto const& c : cs) { for (int i = 0; i < c->arity(); ++i) { for (int j = 0; j < i; ++j) { auto p1 = c->particles[i]; auto p2 = c->particles[j]; rendering::draw_line(p1->projected_position, p2->projected_position); } } } } }); } void physics_manager::apply_external_forces(float dt) { for (auto& p : particles) { if (p.inv_mass == 0.f) continue; p.vel += dt * glm::vec2{0,-1}; } } void physics_manager::damp_velocities() { for (auto& p : particles) { p.vel *= 0.99; // TODO: improve } } namespace { template <size_t N> void project_single_constraint(constraint<N> const& c) { const auto err = c(); switch (c.get_type()) { case constraint_type::equality: { if (err == 0) return; break; } case constraint_type::inequality: { if (err >= 0) return; break; } default: { assert(!"Unhandled constraint type!"); } } const auto grad = c.grad(); const auto sum = [&] { auto sum = 0.f; for (auto i = 0; i < N; ++i) { sum += c.particles[i]->inv_mass * length2(grad[i]); } return sum; }(); const auto scale = err / sum; for (auto i = 0; i < N; ++i) { auto& p = c.particles[i]; const auto correction = -scale * p->inv_mass * grad[i]; rendering::draw_line(p->projected_position, p->projected_position + correction,60); p->projected_position += correction; } } } void physics_manager::project_constraints() { iterate(constraints, std::make_index_sequence<max_constraint_arity>{}, [](auto&& cs, auto){ for(auto const& c : cs) { project_single_constraint(*c); } }); } }}} <commit_msg>implemented missing code for stiffness parameter<commit_after>#include "core/physics/physics_manager.h" #include "core/physics/constraint.h" #include "core/rendering/render_manager.h" #include <glm/gtx/norm.hpp> #include <bitset> namespace eversim { namespace core { namespace physics { namespace { template <typename Constraints, typename Func, size_t... Is> void iterate(Constraints const& c, std::index_sequence<Is...>, Func&& fun) { std::initializer_list<int>{ (std::forward<Func>(fun)(std::get<Is>(c), Is), 0)... }; } } void physics_manager::add_particle(particle const& p) { particles.push_back(p); } void physics_manager::integrate(float dt) { apply_external_forces(dt); damp_velocities(); for (auto& p : particles) { p.projected_position = p.pos + dt * p.vel; } for (auto i = 0; i < solver_iterations; ++i) { project_constraints(); } for (auto& p : particles) { p.vel = (p.projected_position - p.pos) / dt; p.pos = p.projected_position; } } void physics_manager::atomic_step(float dt) { switch (current_state) { case simulation_state::external: apply_external_forces(dt); current_state = simulation_state::damp; break; case simulation_state::damp: damp_velocities(); current_state = simulation_state::apply_velocity; break; case simulation_state::apply_velocity: for (auto& p : particles) { p.projected_position = p.pos + dt * p.vel; } current_state = simulation_state::constraint_iteration; break; case simulation_state::constraint_iteration: if(current_iteration < solver_iterations) { project_constraints(); current_iteration++; }else { current_iteration = 0; current_state = simulation_state::apply_changes; } break; case simulation_state::apply_changes: for (auto& p : particles) { p.vel = (p.projected_position - p.pos) / dt; p.pos = p.projected_position; } current_state = simulation_state::external; break; default: ; assert(!"unknown state!"); } } void physics_manager::draw_constraints(std::bitset<max_constraint_arity> to_render) { iterate(constraints, std::make_index_sequence<max_constraint_arity>{}, [to_render](auto const& cs, size_t I) { if(to_render[I]) { for (auto const& c : cs) { for (int i = 0; i < c->arity(); ++i) { for (int j = 0; j < i; ++j) { auto p1 = c->particles[i]; auto p2 = c->particles[j]; rendering::draw_line(p1->projected_position, p2->projected_position); } } } } }); } void physics_manager::apply_external_forces(float dt) { for (auto& p : particles) { if (p.inv_mass == 0.f) continue; p.vel += dt * glm::vec2{0,-1}; } } void physics_manager::damp_velocities() { for (auto& p : particles) { p.vel *= 0.99; // TODO: improve } } namespace { template <size_t N> void project_single_constraint(constraint<N> const& c, int solver_iterations) { const auto err = c(); switch (c.get_type()) { case constraint_type::equality: { if (err == 0) return; break; } case constraint_type::inequality: { if (err >= 0) return; break; } default: { assert(!"Unhandled constraint type!"); } } const auto grad = c.grad(); const auto sum = [&] { auto sum = 0.f; for (auto i = 0; i < N; ++i) { sum += c.particles[i]->inv_mass * length2(grad[i]); } return sum; }(); const auto scale = err / sum; const auto k = 1.f - powf(1.f - c.stiffness, 1.f / solver_iterations); for (auto i = 0; i < N; ++i) { auto& p = c.particles[i]; const auto correction = -scale * p->inv_mass * grad[i] * k; rendering::draw_line(p->projected_position, p->projected_position + correction,60); p->projected_position += correction; } } } void physics_manager::project_constraints() { iterate(constraints, std::make_index_sequence<max_constraint_arity>{}, [this](auto&& cs, auto){ for(auto const& c : cs) { project_single_constraint(*c, solver_iterations); } }); } }}} <|endoftext|>
<commit_before>// // PROJECT CHRONO - http://projectchrono.org // // Copyright (c) 2013 Project Chrono // All rights reserved. // // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file at the top level of the distribution // and at http://projectchrono.org/license-chrono.txt. // // // Demo code about // // - FEA for 3D beams of 'cable' type (ANCF gradient-deficient beams) // uses the Chrono MKL module #include "chrono/timestepper/ChTimestepper.h" #include "chrono_irrlicht/ChIrrApp.h" #include "chrono_mkl/ChSolverMKL.h" #include "FEAcables.h" /* using namespace chrono; using namespace fea; using namespace irr; */ int main(int argc, char* argv[]) { // Create a Chrono::Engine physical system ChSystem my_system; // Create the Irrlicht visualization (open the Irrlicht device, // bind a simple user interface, etc. etc.) ChIrrApp application(&my_system, L"Cables FEM (MKL)", core::dimension2d<u32>(800, 600), false, true); // Easy shortcuts to add camera, lights, logo and sky in Irrlicht scene: application.AddTypicalLogo(); application.AddTypicalSky(); application.AddTypicalLights(); application.AddTypicalCamera(core::vector3df(0.f, 0.6f, -1.f)); // Create a mesh, that is a container for groups of elements and // their referenced nodes. auto my_mesh = std::make_shared<ChMesh>(); // Create the model (defined in FEAcables.h) model3(my_system, my_mesh); // Remember to add the mesh to the system! my_system.Add(my_mesh); // ==Asset== attach a visualization of the FEM mesh. // This will automatically update a triangle mesh (a ChTriangleMeshShape // asset that is internally managed) by setting proper // coordinates and vertex colours as in the FEM elements. // Such triangle mesh can be rendered by Irrlicht or POVray or whatever // postprocessor that can handle a coloured ChTriangleMeshShape). // Do not forget AddAsset() at the end! auto mvisualizebeamA = std::make_shared<ChVisualizationFEAmesh>(*(my_mesh.get())); mvisualizebeamA->SetFEMdataType(ChVisualizationFEAmesh::E_PLOT_ELEM_BEAM_MZ); mvisualizebeamA->SetColorscaleMinMax(-0.4, 0.4); mvisualizebeamA->SetSmoothFaces(true); mvisualizebeamA->SetWireframe(false); my_mesh->AddAsset(mvisualizebeamA); auto mvisualizebeamC = std::make_shared<ChVisualizationFEAmesh>(*(my_mesh.get())); mvisualizebeamC->SetFEMglyphType(ChVisualizationFEAmesh::E_GLYPH_NODE_CSYS); mvisualizebeamC->SetFEMdataType(ChVisualizationFEAmesh::E_PLOT_NONE); mvisualizebeamC->SetSymbolsThickness(0.006); mvisualizebeamC->SetSymbolsScale(0.01); mvisualizebeamC->SetZbufferHide(false); my_mesh->AddAsset(mvisualizebeamC); // ==IMPORTANT!== Use this function for adding a ChIrrNodeAsset to all items // in the system. These ChIrrNodeAsset assets are 'proxies' to the Irrlicht meshes. // If you need a finer control on which item really needs a visualization proxy in // Irrlicht, just use application.AssetBind(myitem); on a per-item basis. application.AssetBindAll(); // ==IMPORTANT!== Use this function for 'converting' into Irrlicht meshes the assets // that you added to the bodies into 3D shapes, they can be visualized by Irrlicht! application.AssetUpdateAll(); // Mark completion of system construction my_system.SetupInitial(); // Change solver to MKL ChSolverMKL<>* mkl_solver_stab = new ChSolverMKL<>; ChSolverMKL<>* mkl_solver_speed = new ChSolverMKL<>; my_system.ChangeSolverStab(mkl_solver_stab); my_system.ChangeSolverSpeed(mkl_solver_speed); mkl_solver_stab->SetSparsityPatternLock(true); mkl_solver_speed->SetSparsityPatternLock(true); application.GetSystem()->Update(); // Change type of integrator: my_system.SetIntegrationType(chrono::ChSystem::INT_EULER_IMPLICIT_LINEARIZED); // fast, less precise // my_system.SetIntegrationType(chrono::ChSystem::INT_HHT); // precise,slower, might iterate each step // if later you want to change integrator settings: if (auto mystepper = std::dynamic_pointer_cast<ChTimestepperHHT>(my_system.GetTimestepper())) { mystepper->SetAlpha(-0.2); mystepper->SetMaxiters(2); mystepper->SetAbsTolerances(1e-6); } // // THE SOFT-REAL-TIME CYCLE // application.SetTimestep(0.01); while (application.GetDevice()->run()) { application.BeginScene(); application.DrawAll(); application.DoStep(); application.EndScene(); } return 0; } <commit_msg>demo_FEAcablesMKL cannot use sparsity pattern lock (Pardiso bug)<commit_after>// // PROJECT CHRONO - http://projectchrono.org // // Copyright (c) 2013 Project Chrono // All rights reserved. // // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file at the top level of the distribution // and at http://projectchrono.org/license-chrono.txt. // // // Demo code about // // - FEA for 3D beams of 'cable' type (ANCF gradient-deficient beams) // uses the Chrono MKL module #include "chrono/timestepper/ChTimestepper.h" #include "chrono_irrlicht/ChIrrApp.h" #include "chrono_mkl/ChSolverMKL.h" #include "FEAcables.h" /* using namespace chrono; using namespace fea; using namespace irr; */ int main(int argc, char* argv[]) { // Create a Chrono::Engine physical system ChSystem my_system; // Create the Irrlicht visualization (open the Irrlicht device, // bind a simple user interface, etc. etc.) ChIrrApp application(&my_system, L"Cables FEM (MKL)", core::dimension2d<u32>(800, 600), false, true); // Easy shortcuts to add camera, lights, logo and sky in Irrlicht scene: application.AddTypicalLogo(); application.AddTypicalSky(); application.AddTypicalLights(); application.AddTypicalCamera(core::vector3df(0.f, 0.6f, -1.f)); // Create a mesh, that is a container for groups of elements and // their referenced nodes. auto my_mesh = std::make_shared<ChMesh>(); // Create the model (defined in FEAcables.h) model3(my_system, my_mesh); // Remember to add the mesh to the system! my_system.Add(my_mesh); // ==Asset== attach a visualization of the FEM mesh. // This will automatically update a triangle mesh (a ChTriangleMeshShape // asset that is internally managed) by setting proper // coordinates and vertex colours as in the FEM elements. // Such triangle mesh can be rendered by Irrlicht or POVray or whatever // postprocessor that can handle a coloured ChTriangleMeshShape). // Do not forget AddAsset() at the end! auto mvisualizebeamA = std::make_shared<ChVisualizationFEAmesh>(*(my_mesh.get())); mvisualizebeamA->SetFEMdataType(ChVisualizationFEAmesh::E_PLOT_ELEM_BEAM_MZ); mvisualizebeamA->SetColorscaleMinMax(-0.4, 0.4); mvisualizebeamA->SetSmoothFaces(true); mvisualizebeamA->SetWireframe(false); my_mesh->AddAsset(mvisualizebeamA); auto mvisualizebeamC = std::make_shared<ChVisualizationFEAmesh>(*(my_mesh.get())); mvisualizebeamC->SetFEMglyphType(ChVisualizationFEAmesh::E_GLYPH_NODE_CSYS); mvisualizebeamC->SetFEMdataType(ChVisualizationFEAmesh::E_PLOT_NONE); mvisualizebeamC->SetSymbolsThickness(0.006); mvisualizebeamC->SetSymbolsScale(0.01); mvisualizebeamC->SetZbufferHide(false); my_mesh->AddAsset(mvisualizebeamC); // ==IMPORTANT!== Use this function for adding a ChIrrNodeAsset to all items // in the system. These ChIrrNodeAsset assets are 'proxies' to the Irrlicht meshes. // If you need a finer control on which item really needs a visualization proxy in // Irrlicht, just use application.AssetBind(myitem); on a per-item basis. application.AssetBindAll(); // ==IMPORTANT!== Use this function for 'converting' into Irrlicht meshes the assets // that you added to the bodies into 3D shapes, they can be visualized by Irrlicht! application.AssetUpdateAll(); // Mark completion of system construction my_system.SetupInitial(); // Change solver to MKL auto mkl_solver_stab = new ChSolverMKL<>; auto mkl_solver_speed = new ChSolverMKL<>; my_system.ChangeSolverStab(mkl_solver_stab); my_system.ChangeSolverSpeed(mkl_solver_speed); mkl_solver_stab->SetSparsityPatternLock(false); mkl_solver_speed->SetSparsityPatternLock(false); // WARNING: due to known issues on MKL Pardiso, if CSR matrix is used, sparsity pattern lock should be put OFF // Look at ChCSR3Matrix::SetElement comments to further details. application.GetSystem()->Update(); // Change type of integrator: my_system.SetIntegrationType(chrono::ChSystem::INT_EULER_IMPLICIT_LINEARIZED); // fast, less precise // my_system.SetIntegrationType(chrono::ChSystem::INT_HHT); // precise,slower, might iterate each step // if later you want to change integrator settings: if (auto mystepper = std::dynamic_pointer_cast<ChTimestepperHHT>(my_system.GetTimestepper())) { mystepper->SetAlpha(-0.2); mystepper->SetMaxiters(2); mystepper->SetAbsTolerances(1e-6); } // // THE SOFT-REAL-TIME CYCLE // application.SetTimestep(0.01); while (application.GetDevice()->run()) { application.BeginScene(); application.DrawAll(); application.DoStep(); application.EndScene(); } return 0; } <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: layerupdatehandler.cxx,v $ * * $Revision: 1.9 $ * * last change: $Author: rt $ $Date: 2003-04-17 13:17:03 $ * * 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: 2002 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #include "layerupdatehandler.hxx" #ifndef CONFIGMGR_BACKEND_LAYERUPDATEMERGER_HXX #include "layerupdatemerger.hxx" #endif #ifndef CONFIGMGR_API_FACTORY_HXX_ #include "confapifactory.hxx" #endif #ifndef _COM_SUN_STAR_CONFIGURATION_BACKEND_XLAYERHANDLER_HPP_ #include <com/sun/star/configuration/backend/XLayerHandler.hpp> #endif #ifndef _COM_SUN_STAR_CONFIGURATION_BACKEND_XLAYER_HPP_ #include <com/sun/star/configuration/backend/XLayer.hpp> #endif #ifndef _COM_SUN_STAR_BEANS_PROPERTYEXISTEXCEPTION_HPP_ #include <com/sun/star/beans/PropertyExistException.hpp> #endif // ----------------------------------------------------------------------------- #define OUSTR( str ) OUString( RTL_CONSTASCII_USTRINGPARAM( str ) ) // ----------------------------------------------------------------------------- namespace configmgr { // ----------------------------------------------------------------------------- namespace backend { // ----------------------------------------------------------------------------- namespace uno = ::com::sun::star::uno; namespace lang = ::com::sun::star::lang; namespace backenduno = ::com::sun::star::configuration::backend; // ----------------------------------------------------------------------------- uno::Reference< uno::XInterface > SAL_CALL instantiateUpdateMerger ( CreationContext const& xContext ) { return * new LayerUpdateHandler( xContext ); } // ----------------------------------------------------------------------------- LayerUpdateHandler::LayerUpdateHandler(CreationArg _xContext) : UpdateService(_xContext) , m_aBuilder() { } // ----------------------------------------------------------------------------- LayerUpdateHandler::~LayerUpdateHandler() { } // ----------------------------------------------------------------------------- inline void LayerUpdateHandler::checkBuilder(bool _bForProperty) { if ( m_aBuilder.isEmpty() ) raiseMalformedDataException("LayerUpdateHandler: Illegal operation - no update is in progress"); if ( !m_aBuilder.isActive() ) raiseMalformedDataException("LayerUpdateHandler: Illegal operation - no context for update available"); if ( m_aBuilder.isPropertyActive() != _bForProperty ) raiseMalformedDataException("LayerUpdateHandler: Illegal operation - a property is in progress"); } // ----------------------------------------------------------------------------- void LayerUpdateHandler::raiseMalformedDataException(sal_Char const * pMsg) { OUString sMsg = OUString::createFromAscii(pMsg); throw backenduno::MalformedDataException(sMsg,*this,uno::Any()); } // ----------------------------------------------------------------------------- void LayerUpdateHandler::raiseNodeChangedBeforeException(sal_Char const * pMsg) { OUString sMsg = OUString::createFromAscii(pMsg); throw backenduno::MalformedDataException(sMsg,*this,uno::Any()); } // ----------------------------------------------------------------------------- void LayerUpdateHandler::raisePropChangedBeforeException(sal_Char const * pMsg) { OUString sMsg = OUString::createFromAscii(pMsg); throw backenduno::MalformedDataException(sMsg,*this,uno::Any()); } // ----------------------------------------------------------------------------- void LayerUpdateHandler::raisePropExistsException(sal_Char const * pMsg) { OUString sMsg = OUString::createFromAscii(pMsg); com::sun::star::beans::PropertyExistException e(sMsg,*this); throw backenduno::MalformedDataException(sMsg,*this, uno::makeAny(e)); } // ----------------------------------------------------------------------------- // XUpdateHandler void SAL_CALL LayerUpdateHandler::startUpdate( ) throw ( MalformedDataException, lang::IllegalAccessException, lang::WrappedTargetException, uno::RuntimeException) { this->checkSourceLayer(); if (!m_aBuilder.init()) raiseMalformedDataException("LayerUpdateHandler: Cannot start update - update is already in progress"); } // ----------------------------------------------------------------------------- void SAL_CALL LayerUpdateHandler::endUpdate( ) throw ( MalformedDataException, lang::IllegalAccessException, lang::WrappedTargetException, uno::RuntimeException) { checkBuilder(); if (!m_aBuilder.finish()) raiseMalformedDataException("LayerUpdateHandler: Cannot finish update - a node is still open."); uno::Reference< backenduno::XLayer > xMergedLayer( LayerUpdateMerger::getMergedLayer(this->getSourceLayer(), m_aBuilder.result()) ); m_aBuilder.clear(); this->writeUpdatedLayer(xMergedLayer); } // ----------------------------------------------------------------------------- void SAL_CALL LayerUpdateHandler::modifyNode( const OUString& aName, sal_Int16 aAttributes, sal_Int16 aAttributeMask, sal_Bool bReset ) throw (MalformedDataException, lang::WrappedTargetException, uno::RuntimeException) { checkBuilder(); if (!m_aBuilder.modifyNode(aName,aAttributes,aAttributeMask,bReset)) raiseNodeChangedBeforeException("LayerUpdateHandler: Cannot start node modification - node has already been changed."); } // ----------------------------------------------------------------------------- void SAL_CALL LayerUpdateHandler::addOrReplaceNode( const OUString& aName, sal_Int16 aAttributes ) throw (MalformedDataException, lang::WrappedTargetException, uno::RuntimeException) { checkBuilder(); if (!m_aBuilder.replaceNode(aName,aAttributes,NULL)) raiseNodeChangedBeforeException("LayerUpdateHandler: Cannot start added/replaced node - node has already been changed."); } // ----------------------------------------------------------------------------- void SAL_CALL LayerUpdateHandler::addOrReplaceNodeFromTemplate( const OUString& aName, sal_Int16 aAttributes, const TemplateIdentifier& aTemplate ) throw (MalformedDataException, lang::WrappedTargetException, uno::RuntimeException) { checkBuilder(); if (!m_aBuilder.replaceNode(aName,aAttributes,&aTemplate)) raiseNodeChangedBeforeException("LayerUpdateHandler: Cannot start added/replaced node - node has already been changed."); } // ----------------------------------------------------------------------------- void SAL_CALL LayerUpdateHandler::endNode( ) throw (MalformedDataException, lang::WrappedTargetException, uno::RuntimeException) { checkBuilder(); if (!m_aBuilder.finishNode()) { OSL_ENSURE(m_aBuilder.isPropertyActive() || !m_aBuilder.isActive(), "LayerUpdateHandler: Unexpected failure mode for finishNode"); if (m_aBuilder.isPropertyActive()) raiseMalformedDataException("LayerUpdateHandler: Cannot finish node update - open property has not been ended."); else raiseMalformedDataException("LayerUpdateHandler: Cannot finish node update - no node has been started."); } } // ----------------------------------------------------------------------------- void SAL_CALL LayerUpdateHandler::removeNode( const OUString& aName ) throw (MalformedDataException, lang::WrappedTargetException, uno::RuntimeException) { checkBuilder(); if (!m_aBuilder.removeNode(aName)) raiseNodeChangedBeforeException("LayerUpdateHandler: Cannot remove node - node has already been changed."); } // ----------------------------------------------------------------------------- void SAL_CALL LayerUpdateHandler:: modifyProperty( const OUString& aName, sal_Int16 aAttributes, sal_Int16 aAttributeMask, const uno::Type & aType ) throw (MalformedDataException, lang::WrappedTargetException, uno::RuntimeException) { checkBuilder(false); if (!m_aBuilder.modifyProperty(aName,aAttributes,aAttributeMask, aType)) raisePropChangedBeforeException("LayerUpdateHandler: Cannot start property modification - property has already been changed."); } // ----------------------------------------------------------------------------- void SAL_CALL LayerUpdateHandler:: setPropertyValue( const uno::Any& aValue ) throw (MalformedDataException, lang::WrappedTargetException, uno::RuntimeException) { checkBuilder(true); // already checks for open property OSL_VERIFY( m_aBuilder.setPropertyValue(aValue) ); } // ----------------------------------------------------------------------------- void SAL_CALL LayerUpdateHandler:: setPropertyValueForLocale( const uno::Any& aValue, const OUString& aLocale ) throw (MalformedDataException, lang::WrappedTargetException, uno::RuntimeException) { checkBuilder(true); // already checks for open property OSL_VERIFY( m_aBuilder.setPropertyValueForLocale(aValue,aLocale) ); } // ----------------------------------------------------------------------------- void SAL_CALL LayerUpdateHandler::resetPropertyValue( ) throw (MalformedDataException, lang::WrappedTargetException, uno::RuntimeException) { checkBuilder(true); // already checks for open property OSL_VERIFY( m_aBuilder.resetPropertyValue() ); } // ----------------------------------------------------------------------------- void SAL_CALL LayerUpdateHandler::resetPropertyValueForLocale( const OUString& aLocale ) throw (MalformedDataException, lang::WrappedTargetException, uno::RuntimeException) { checkBuilder(true); // already checks for open property OSL_VERIFY( m_aBuilder.resetPropertyValueForLocale(aLocale) ); } // ----------------------------------------------------------------------------- void SAL_CALL LayerUpdateHandler::endProperty( ) throw (MalformedDataException, lang::WrappedTargetException, uno::RuntimeException) { checkBuilder(true); // already checks for open property OSL_VERIFY ( m_aBuilder.finishProperty() ); } // ----------------------------------------------------------------------------- void SAL_CALL LayerUpdateHandler::resetProperty( const OUString& aName ) throw (MalformedDataException, lang::WrappedTargetException, uno::RuntimeException) { if (!m_aBuilder.resetProperty(aName)) raisePropChangedBeforeException("LayerUpdateHandler: Cannot reset property - property has already been changed."); } // ----------------------------------------------------------------------------- void SAL_CALL LayerUpdateHandler::addOrReplaceProperty( const OUString& aName, sal_Int16 aAttributes, const uno::Type& aType ) throw (MalformedDataException, lang::WrappedTargetException, uno::RuntimeException) { if (!m_aBuilder.addNullProperty(aName,aAttributes,aType)) raisePropExistsException("LayerUpdateHandler: Cannot add property - property exists (and has already been changed)."); } // ----------------------------------------------------------------------------- void SAL_CALL LayerUpdateHandler::addOrReplacePropertyWithValue( const OUString& aName, sal_Int16 aAttributes, const uno::Any& aValue ) throw (MalformedDataException, lang::WrappedTargetException, uno::RuntimeException) { if (!m_aBuilder.addProperty(aName,aAttributes,aValue)) raisePropExistsException("LayerUpdateHandler: Cannot add property - property exists (and has already been changed)."); } // ----------------------------------------------------------------------------- void SAL_CALL LayerUpdateHandler::removeProperty( const OUString& aName ) throw (MalformedDataException, lang::WrappedTargetException, uno::RuntimeException) { // treat 'remove' as 'reset'. (Note: does not verify that this actually amounts to dropping the property) if (!m_aBuilder.resetProperty(aName)) raisePropChangedBeforeException("LayerUpdateHandler: Cannot remove property - property has already been changed."); } // ----------------------------------------------------------------------------- // ----------------------------------------------------------------------------- // ----------------------------------------------------------------------------- } // namespace // ----------------------------------------------------------------------------- } // namespace <commit_msg>INTEGRATION: CWS ooo19126 (1.9.180); FILE MERGED 2005/09/05 17:04:01 rt 1.9.180.1: #i54170# Change license header: remove SISSL<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: layerupdatehandler.cxx,v $ * * $Revision: 1.10 $ * * last change: $Author: rt $ $Date: 2005-09-08 03:31:49 $ * * 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 "layerupdatehandler.hxx" #ifndef CONFIGMGR_BACKEND_LAYERUPDATEMERGER_HXX #include "layerupdatemerger.hxx" #endif #ifndef CONFIGMGR_API_FACTORY_HXX_ #include "confapifactory.hxx" #endif #ifndef _COM_SUN_STAR_CONFIGURATION_BACKEND_XLAYERHANDLER_HPP_ #include <com/sun/star/configuration/backend/XLayerHandler.hpp> #endif #ifndef _COM_SUN_STAR_CONFIGURATION_BACKEND_XLAYER_HPP_ #include <com/sun/star/configuration/backend/XLayer.hpp> #endif #ifndef _COM_SUN_STAR_BEANS_PROPERTYEXISTEXCEPTION_HPP_ #include <com/sun/star/beans/PropertyExistException.hpp> #endif // ----------------------------------------------------------------------------- #define OUSTR( str ) OUString( RTL_CONSTASCII_USTRINGPARAM( str ) ) // ----------------------------------------------------------------------------- namespace configmgr { // ----------------------------------------------------------------------------- namespace backend { // ----------------------------------------------------------------------------- namespace uno = ::com::sun::star::uno; namespace lang = ::com::sun::star::lang; namespace backenduno = ::com::sun::star::configuration::backend; // ----------------------------------------------------------------------------- uno::Reference< uno::XInterface > SAL_CALL instantiateUpdateMerger ( CreationContext const& xContext ) { return * new LayerUpdateHandler( xContext ); } // ----------------------------------------------------------------------------- LayerUpdateHandler::LayerUpdateHandler(CreationArg _xContext) : UpdateService(_xContext) , m_aBuilder() { } // ----------------------------------------------------------------------------- LayerUpdateHandler::~LayerUpdateHandler() { } // ----------------------------------------------------------------------------- inline void LayerUpdateHandler::checkBuilder(bool _bForProperty) { if ( m_aBuilder.isEmpty() ) raiseMalformedDataException("LayerUpdateHandler: Illegal operation - no update is in progress"); if ( !m_aBuilder.isActive() ) raiseMalformedDataException("LayerUpdateHandler: Illegal operation - no context for update available"); if ( m_aBuilder.isPropertyActive() != _bForProperty ) raiseMalformedDataException("LayerUpdateHandler: Illegal operation - a property is in progress"); } // ----------------------------------------------------------------------------- void LayerUpdateHandler::raiseMalformedDataException(sal_Char const * pMsg) { OUString sMsg = OUString::createFromAscii(pMsg); throw backenduno::MalformedDataException(sMsg,*this,uno::Any()); } // ----------------------------------------------------------------------------- void LayerUpdateHandler::raiseNodeChangedBeforeException(sal_Char const * pMsg) { OUString sMsg = OUString::createFromAscii(pMsg); throw backenduno::MalformedDataException(sMsg,*this,uno::Any()); } // ----------------------------------------------------------------------------- void LayerUpdateHandler::raisePropChangedBeforeException(sal_Char const * pMsg) { OUString sMsg = OUString::createFromAscii(pMsg); throw backenduno::MalformedDataException(sMsg,*this,uno::Any()); } // ----------------------------------------------------------------------------- void LayerUpdateHandler::raisePropExistsException(sal_Char const * pMsg) { OUString sMsg = OUString::createFromAscii(pMsg); com::sun::star::beans::PropertyExistException e(sMsg,*this); throw backenduno::MalformedDataException(sMsg,*this, uno::makeAny(e)); } // ----------------------------------------------------------------------------- // XUpdateHandler void SAL_CALL LayerUpdateHandler::startUpdate( ) throw ( MalformedDataException, lang::IllegalAccessException, lang::WrappedTargetException, uno::RuntimeException) { this->checkSourceLayer(); if (!m_aBuilder.init()) raiseMalformedDataException("LayerUpdateHandler: Cannot start update - update is already in progress"); } // ----------------------------------------------------------------------------- void SAL_CALL LayerUpdateHandler::endUpdate( ) throw ( MalformedDataException, lang::IllegalAccessException, lang::WrappedTargetException, uno::RuntimeException) { checkBuilder(); if (!m_aBuilder.finish()) raiseMalformedDataException("LayerUpdateHandler: Cannot finish update - a node is still open."); uno::Reference< backenduno::XLayer > xMergedLayer( LayerUpdateMerger::getMergedLayer(this->getSourceLayer(), m_aBuilder.result()) ); m_aBuilder.clear(); this->writeUpdatedLayer(xMergedLayer); } // ----------------------------------------------------------------------------- void SAL_CALL LayerUpdateHandler::modifyNode( const OUString& aName, sal_Int16 aAttributes, sal_Int16 aAttributeMask, sal_Bool bReset ) throw (MalformedDataException, lang::WrappedTargetException, uno::RuntimeException) { checkBuilder(); if (!m_aBuilder.modifyNode(aName,aAttributes,aAttributeMask,bReset)) raiseNodeChangedBeforeException("LayerUpdateHandler: Cannot start node modification - node has already been changed."); } // ----------------------------------------------------------------------------- void SAL_CALL LayerUpdateHandler::addOrReplaceNode( const OUString& aName, sal_Int16 aAttributes ) throw (MalformedDataException, lang::WrappedTargetException, uno::RuntimeException) { checkBuilder(); if (!m_aBuilder.replaceNode(aName,aAttributes,NULL)) raiseNodeChangedBeforeException("LayerUpdateHandler: Cannot start added/replaced node - node has already been changed."); } // ----------------------------------------------------------------------------- void SAL_CALL LayerUpdateHandler::addOrReplaceNodeFromTemplate( const OUString& aName, sal_Int16 aAttributes, const TemplateIdentifier& aTemplate ) throw (MalformedDataException, lang::WrappedTargetException, uno::RuntimeException) { checkBuilder(); if (!m_aBuilder.replaceNode(aName,aAttributes,&aTemplate)) raiseNodeChangedBeforeException("LayerUpdateHandler: Cannot start added/replaced node - node has already been changed."); } // ----------------------------------------------------------------------------- void SAL_CALL LayerUpdateHandler::endNode( ) throw (MalformedDataException, lang::WrappedTargetException, uno::RuntimeException) { checkBuilder(); if (!m_aBuilder.finishNode()) { OSL_ENSURE(m_aBuilder.isPropertyActive() || !m_aBuilder.isActive(), "LayerUpdateHandler: Unexpected failure mode for finishNode"); if (m_aBuilder.isPropertyActive()) raiseMalformedDataException("LayerUpdateHandler: Cannot finish node update - open property has not been ended."); else raiseMalformedDataException("LayerUpdateHandler: Cannot finish node update - no node has been started."); } } // ----------------------------------------------------------------------------- void SAL_CALL LayerUpdateHandler::removeNode( const OUString& aName ) throw (MalformedDataException, lang::WrappedTargetException, uno::RuntimeException) { checkBuilder(); if (!m_aBuilder.removeNode(aName)) raiseNodeChangedBeforeException("LayerUpdateHandler: Cannot remove node - node has already been changed."); } // ----------------------------------------------------------------------------- void SAL_CALL LayerUpdateHandler:: modifyProperty( const OUString& aName, sal_Int16 aAttributes, sal_Int16 aAttributeMask, const uno::Type & aType ) throw (MalformedDataException, lang::WrappedTargetException, uno::RuntimeException) { checkBuilder(false); if (!m_aBuilder.modifyProperty(aName,aAttributes,aAttributeMask, aType)) raisePropChangedBeforeException("LayerUpdateHandler: Cannot start property modification - property has already been changed."); } // ----------------------------------------------------------------------------- void SAL_CALL LayerUpdateHandler:: setPropertyValue( const uno::Any& aValue ) throw (MalformedDataException, lang::WrappedTargetException, uno::RuntimeException) { checkBuilder(true); // already checks for open property OSL_VERIFY( m_aBuilder.setPropertyValue(aValue) ); } // ----------------------------------------------------------------------------- void SAL_CALL LayerUpdateHandler:: setPropertyValueForLocale( const uno::Any& aValue, const OUString& aLocale ) throw (MalformedDataException, lang::WrappedTargetException, uno::RuntimeException) { checkBuilder(true); // already checks for open property OSL_VERIFY( m_aBuilder.setPropertyValueForLocale(aValue,aLocale) ); } // ----------------------------------------------------------------------------- void SAL_CALL LayerUpdateHandler::resetPropertyValue( ) throw (MalformedDataException, lang::WrappedTargetException, uno::RuntimeException) { checkBuilder(true); // already checks for open property OSL_VERIFY( m_aBuilder.resetPropertyValue() ); } // ----------------------------------------------------------------------------- void SAL_CALL LayerUpdateHandler::resetPropertyValueForLocale( const OUString& aLocale ) throw (MalformedDataException, lang::WrappedTargetException, uno::RuntimeException) { checkBuilder(true); // already checks for open property OSL_VERIFY( m_aBuilder.resetPropertyValueForLocale(aLocale) ); } // ----------------------------------------------------------------------------- void SAL_CALL LayerUpdateHandler::endProperty( ) throw (MalformedDataException, lang::WrappedTargetException, uno::RuntimeException) { checkBuilder(true); // already checks for open property OSL_VERIFY ( m_aBuilder.finishProperty() ); } // ----------------------------------------------------------------------------- void SAL_CALL LayerUpdateHandler::resetProperty( const OUString& aName ) throw (MalformedDataException, lang::WrappedTargetException, uno::RuntimeException) { if (!m_aBuilder.resetProperty(aName)) raisePropChangedBeforeException("LayerUpdateHandler: Cannot reset property - property has already been changed."); } // ----------------------------------------------------------------------------- void SAL_CALL LayerUpdateHandler::addOrReplaceProperty( const OUString& aName, sal_Int16 aAttributes, const uno::Type& aType ) throw (MalformedDataException, lang::WrappedTargetException, uno::RuntimeException) { if (!m_aBuilder.addNullProperty(aName,aAttributes,aType)) raisePropExistsException("LayerUpdateHandler: Cannot add property - property exists (and has already been changed)."); } // ----------------------------------------------------------------------------- void SAL_CALL LayerUpdateHandler::addOrReplacePropertyWithValue( const OUString& aName, sal_Int16 aAttributes, const uno::Any& aValue ) throw (MalformedDataException, lang::WrappedTargetException, uno::RuntimeException) { if (!m_aBuilder.addProperty(aName,aAttributes,aValue)) raisePropExistsException("LayerUpdateHandler: Cannot add property - property exists (and has already been changed)."); } // ----------------------------------------------------------------------------- void SAL_CALL LayerUpdateHandler::removeProperty( const OUString& aName ) throw (MalformedDataException, lang::WrappedTargetException, uno::RuntimeException) { // treat 'remove' as 'reset'. (Note: does not verify that this actually amounts to dropping the property) if (!m_aBuilder.resetProperty(aName)) raisePropChangedBeforeException("LayerUpdateHandler: Cannot remove property - property has already been changed."); } // ----------------------------------------------------------------------------- // ----------------------------------------------------------------------------- // ----------------------------------------------------------------------------- } // namespace // ----------------------------------------------------------------------------- } // namespace <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: MServices.cxx,v $ * * $Revision: 1.7 $ * * last change: $Author: vg $ $Date: 2007-10-15 12:31:00 $ * * 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_connectivity.hxx" #include "MDriver.hxx" #ifndef _CPPUHELPER_FACTORY_HXX_ #include <cppuhelper/factory.hxx> #endif #ifndef _OSL_DIAGNOSE_H_ #include <osl/diagnose.h> #endif #ifndef _COM_SUN_STAR_MOZILLA_XMOZILLABOOTSTRAP_HPP_ #include <com/sun/star/mozilla/XMozillaBootstrap.hpp> #endif #ifndef CONNECTIVITY_SMOZILLABOOTSTRAP_HXX #include "bootstrap/MMozillaBootstrap.hxx" #endif using namespace connectivity::mozab; using ::rtl::OUString; using ::com::sun::star::uno::Reference; using ::com::sun::star::uno::Sequence; using ::com::sun::star::registry::XRegistryKey; using ::com::sun::star::lang::XSingleServiceFactory; using ::com::sun::star::lang::XMultiServiceFactory; using ::com::sun::star::mozilla::XMozillaBootstrap; typedef Reference< XSingleServiceFactory > (SAL_CALL *createFactoryFunc) ( const Reference< XMultiServiceFactory > & rServiceManager, const OUString & rComponentName, ::cppu::ComponentInstantiation pCreateFunction, const Sequence< OUString > & rServiceNames, rtl_ModuleCount* _pTemp ); //*************************************************************************************** // // Die vorgeschriebene C-Api muss erfuellt werden! // Sie besteht aus drei Funktionen, die von dem Modul exportiert werden muessen. // //--------------------------------------------------------------------------------------- void REGISTER_PROVIDER( const OUString& aServiceImplName, const Sequence< OUString>& Services, const Reference< ::com::sun::star::registry::XRegistryKey > & xKey) { OUString aMainKeyName; aMainKeyName = OUString( RTL_CONSTASCII_USTRINGPARAM("/")); aMainKeyName += aServiceImplName; aMainKeyName += OUString( RTL_CONSTASCII_USTRINGPARAM("/UNO/SERVICES")); Reference< ::com::sun::star::registry::XRegistryKey > xNewKey( xKey->createKey(aMainKeyName) ); OSL_ENSURE(xNewKey.is(), "MOZAB::component_writeInfo : could not create a registry key !"); for (sal_Int32 i=0; i<Services.getLength(); ++i) xNewKey->createKey(Services[i]); } //--------------------------------------------------------------------------------------- struct ProviderRequest { Reference< XSingleServiceFactory > xRet; Reference< XMultiServiceFactory > const xServiceManager; OUString const sImplementationName; ProviderRequest( void* pServiceManager, sal_Char const* pImplementationName ) : xServiceManager(reinterpret_cast<XMultiServiceFactory*>(pServiceManager)) , sImplementationName(OUString::createFromAscii(pImplementationName)) { } inline sal_Bool CREATE_PROVIDER( const OUString& Implname, const Sequence< OUString > & Services, ::cppu::ComponentInstantiation Factory, createFactoryFunc creator ) { if (!xRet.is() && (Implname == sImplementationName)) try { xRet = creator( xServiceManager, sImplementationName,Factory, Services,0); } catch(...) { } return xRet.is(); } void* getProvider() const { return xRet.get(); } }; //--------------------------------------------------------------------------------------- extern "C" void SAL_CALL component_getImplementationEnvironment( const sal_Char **ppEnvTypeName, uno_Environment ** /*ppEnv*/ ) { *ppEnvTypeName = CPPU_CURRENT_LANGUAGE_BINDING_NAME; } //--------------------------------------------------------------------------------------- extern "C" sal_Bool SAL_CALL component_writeInfo( void* /*pServiceManager*/, void* pRegistryKey ) { if (pRegistryKey) try { Reference< ::com::sun::star::registry::XRegistryKey > xKey(reinterpret_cast< ::com::sun::star::registry::XRegistryKey*>(pRegistryKey)); REGISTER_PROVIDER( MozabDriver::getImplementationName_Static(), MozabDriver::getSupportedServiceNames_Static(), xKey); Sequence< ::rtl::OUString > aSNS( 1 ); aSNS[0] = ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM("com.sun.star.mozilla.MozillaBootstrap")); REGISTER_PROVIDER( ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM("com.sun.star.comp.mozilla.MozillaBootstrap")), aSNS, xKey); return sal_True; } catch (::com::sun::star::registry::InvalidRegistryException& ) { OSL_ENSURE(sal_False, "Mozab::component_writeInfo : could not create a registry key ! ## InvalidRegistryException !"); } return sal_False; } typedef void* (SAL_CALL * OMozillaBootstrap_CreateInstanceFunction)(const Reference< XMultiServiceFactory >& _rxFactory ); ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface > SAL_CALL createMozillaBootstrap(const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& _rxFactory) throw( ::com::sun::star::uno::Exception ) { const ::rtl::OUString sModuleName = ::rtl::OUString::createFromAscii(SAL_MODULENAME( "mozabdrv2" )); // load the dbtools library oslModule s_hModule = osl_loadModuleRelative( reinterpret_cast< oslGenericFunction >(&createMozillaBootstrap), sModuleName.pData, 0); OSL_ENSURE(NULL != s_hModule, "MozabDriver::registerClient: could not load the dbtools library!"); if (NULL != s_hModule) { // get the symbol for the method creating the factory const ::rtl::OUString sFactoryCreationFunc = ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM("OMozillaBootstrap_CreateInstance")); // reinterpret_cast<OMozabConnection_CreateInstanceFunction> removed GNU C OMozillaBootstrap_CreateInstanceFunction s_pCreationFunc = (OMozillaBootstrap_CreateInstanceFunction)osl_getFunctionSymbol(s_hModule, sFactoryCreationFunc.pData); if (NULL == s_pCreationFunc) { // did not find the symbol OSL_ENSURE(sal_False, "MozabDriver::registerClient: could not find the symbol for creating the factory!"); osl_unloadModule(s_hModule); s_hModule = NULL; } MozillaBootstrap * pBootstrap = reinterpret_cast<MozillaBootstrap*>((*s_pCreationFunc)(_rxFactory)); return *pBootstrap; } return NULL; } //--------------------------------------------------------------------------------------- extern "C" void* SAL_CALL component_getFactory( const sal_Char* pImplementationName, void* pServiceManager, void* /*pRegistryKey*/) { void* pRet = 0; if (pServiceManager) { OUString aImplName( OUString::createFromAscii( pImplementationName ) ); ProviderRequest aReq(pServiceManager,pImplementationName); if (aImplName.equals( MozabDriver::getImplementationName_Static() )) { aReq.CREATE_PROVIDER( MozabDriver::getImplementationName_Static(), MozabDriver::getSupportedServiceNames_Static(), MozabDriver_CreateInstance, ::cppu::createSingleFactory); } else if (aImplName.equals( ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM("com.sun.star.comp.mozilla.MozillaBootstrap")) )) { Sequence< ::rtl::OUString > aSNS( 1 ); aSNS[0] = ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM("com.sun.star.mozilla.MozillaBootstrap")); aReq.CREATE_PROVIDER( aImplName, aSNS, createMozillaBootstrap, ::cppu::createSingleFactory); } if(aReq.xRet.is()) aReq.xRet->acquire(); pRet = aReq.getProvider(); } return pRet; }; <commit_msg>INTEGRATION: CWS changefileheader (1.7.78); FILE MERGED 2008/04/01 15:08:58 thb 1.7.78.3: #i85898# Stripping all external header guards 2008/04/01 10:53:11 thb 1.7.78.2: #i85898# Stripping all external header guards 2008/03/28 15:23:51 rt 1.7.78.1: #i87441# Change license header to LPGL v3.<commit_after>/************************************************************************* * * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * Copyright 2008 by Sun Microsystems, Inc. * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: MServices.cxx,v $ * $Revision: 1.8 $ * * This file is part of OpenOffice.org. * * OpenOffice.org is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License version 3 * only, as published by the Free Software Foundation. * * OpenOffice.org is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License version 3 for more details * (a copy is included in the LICENSE file that accompanied this code). * * You should have received a copy of the GNU Lesser General Public License * version 3 along with OpenOffice.org. If not, see * <http://www.openoffice.org/license.html> * for a copy of the LGPLv3 License. * ************************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_connectivity.hxx" #include "MDriver.hxx" #include <cppuhelper/factory.hxx> #include <osl/diagnose.h> #include <com/sun/star/mozilla/XMozillaBootstrap.hpp> #include "bootstrap/MMozillaBootstrap.hxx" using namespace connectivity::mozab; using ::rtl::OUString; using ::com::sun::star::uno::Reference; using ::com::sun::star::uno::Sequence; using ::com::sun::star::registry::XRegistryKey; using ::com::sun::star::lang::XSingleServiceFactory; using ::com::sun::star::lang::XMultiServiceFactory; using ::com::sun::star::mozilla::XMozillaBootstrap; typedef Reference< XSingleServiceFactory > (SAL_CALL *createFactoryFunc) ( const Reference< XMultiServiceFactory > & rServiceManager, const OUString & rComponentName, ::cppu::ComponentInstantiation pCreateFunction, const Sequence< OUString > & rServiceNames, rtl_ModuleCount* _pTemp ); //*************************************************************************************** // // Die vorgeschriebene C-Api muss erfuellt werden! // Sie besteht aus drei Funktionen, die von dem Modul exportiert werden muessen. // //--------------------------------------------------------------------------------------- void REGISTER_PROVIDER( const OUString& aServiceImplName, const Sequence< OUString>& Services, const Reference< ::com::sun::star::registry::XRegistryKey > & xKey) { OUString aMainKeyName; aMainKeyName = OUString( RTL_CONSTASCII_USTRINGPARAM("/")); aMainKeyName += aServiceImplName; aMainKeyName += OUString( RTL_CONSTASCII_USTRINGPARAM("/UNO/SERVICES")); Reference< ::com::sun::star::registry::XRegistryKey > xNewKey( xKey->createKey(aMainKeyName) ); OSL_ENSURE(xNewKey.is(), "MOZAB::component_writeInfo : could not create a registry key !"); for (sal_Int32 i=0; i<Services.getLength(); ++i) xNewKey->createKey(Services[i]); } //--------------------------------------------------------------------------------------- struct ProviderRequest { Reference< XSingleServiceFactory > xRet; Reference< XMultiServiceFactory > const xServiceManager; OUString const sImplementationName; ProviderRequest( void* pServiceManager, sal_Char const* pImplementationName ) : xServiceManager(reinterpret_cast<XMultiServiceFactory*>(pServiceManager)) , sImplementationName(OUString::createFromAscii(pImplementationName)) { } inline sal_Bool CREATE_PROVIDER( const OUString& Implname, const Sequence< OUString > & Services, ::cppu::ComponentInstantiation Factory, createFactoryFunc creator ) { if (!xRet.is() && (Implname == sImplementationName)) try { xRet = creator( xServiceManager, sImplementationName,Factory, Services,0); } catch(...) { } return xRet.is(); } void* getProvider() const { return xRet.get(); } }; //--------------------------------------------------------------------------------------- extern "C" void SAL_CALL component_getImplementationEnvironment( const sal_Char **ppEnvTypeName, uno_Environment ** /*ppEnv*/ ) { *ppEnvTypeName = CPPU_CURRENT_LANGUAGE_BINDING_NAME; } //--------------------------------------------------------------------------------------- extern "C" sal_Bool SAL_CALL component_writeInfo( void* /*pServiceManager*/, void* pRegistryKey ) { if (pRegistryKey) try { Reference< ::com::sun::star::registry::XRegistryKey > xKey(reinterpret_cast< ::com::sun::star::registry::XRegistryKey*>(pRegistryKey)); REGISTER_PROVIDER( MozabDriver::getImplementationName_Static(), MozabDriver::getSupportedServiceNames_Static(), xKey); Sequence< ::rtl::OUString > aSNS( 1 ); aSNS[0] = ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM("com.sun.star.mozilla.MozillaBootstrap")); REGISTER_PROVIDER( ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM("com.sun.star.comp.mozilla.MozillaBootstrap")), aSNS, xKey); return sal_True; } catch (::com::sun::star::registry::InvalidRegistryException& ) { OSL_ENSURE(sal_False, "Mozab::component_writeInfo : could not create a registry key ! ## InvalidRegistryException !"); } return sal_False; } typedef void* (SAL_CALL * OMozillaBootstrap_CreateInstanceFunction)(const Reference< XMultiServiceFactory >& _rxFactory ); ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface > SAL_CALL createMozillaBootstrap(const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& _rxFactory) throw( ::com::sun::star::uno::Exception ) { const ::rtl::OUString sModuleName = ::rtl::OUString::createFromAscii(SAL_MODULENAME( "mozabdrv2" )); // load the dbtools library oslModule s_hModule = osl_loadModuleRelative( reinterpret_cast< oslGenericFunction >(&createMozillaBootstrap), sModuleName.pData, 0); OSL_ENSURE(NULL != s_hModule, "MozabDriver::registerClient: could not load the dbtools library!"); if (NULL != s_hModule) { // get the symbol for the method creating the factory const ::rtl::OUString sFactoryCreationFunc = ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM("OMozillaBootstrap_CreateInstance")); // reinterpret_cast<OMozabConnection_CreateInstanceFunction> removed GNU C OMozillaBootstrap_CreateInstanceFunction s_pCreationFunc = (OMozillaBootstrap_CreateInstanceFunction)osl_getFunctionSymbol(s_hModule, sFactoryCreationFunc.pData); if (NULL == s_pCreationFunc) { // did not find the symbol OSL_ENSURE(sal_False, "MozabDriver::registerClient: could not find the symbol for creating the factory!"); osl_unloadModule(s_hModule); s_hModule = NULL; } MozillaBootstrap * pBootstrap = reinterpret_cast<MozillaBootstrap*>((*s_pCreationFunc)(_rxFactory)); return *pBootstrap; } return NULL; } //--------------------------------------------------------------------------------------- extern "C" void* SAL_CALL component_getFactory( const sal_Char* pImplementationName, void* pServiceManager, void* /*pRegistryKey*/) { void* pRet = 0; if (pServiceManager) { OUString aImplName( OUString::createFromAscii( pImplementationName ) ); ProviderRequest aReq(pServiceManager,pImplementationName); if (aImplName.equals( MozabDriver::getImplementationName_Static() )) { aReq.CREATE_PROVIDER( MozabDriver::getImplementationName_Static(), MozabDriver::getSupportedServiceNames_Static(), MozabDriver_CreateInstance, ::cppu::createSingleFactory); } else if (aImplName.equals( ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM("com.sun.star.comp.mozilla.MozillaBootstrap")) )) { Sequence< ::rtl::OUString > aSNS( 1 ); aSNS[0] = ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM("com.sun.star.mozilla.MozillaBootstrap")); aReq.CREATE_PROVIDER( aImplName, aSNS, createMozillaBootstrap, ::cppu::createSingleFactory); } if(aReq.xRet.is()) aReq.xRet->acquire(); pRet = aReq.getProvider(); } return pRet; }; <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: stringtransfer.cxx,v $ * * $Revision: 1.7 $ * * last change: $Author: hr $ $Date: 2007-06-27 21:52:16 $ * * 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_svtools.hxx" #ifndef _SVTOOLS_STRINGTRANSFER_HXX_ #include <svtools/stringtransfer.hxx> #endif //........................................................................ namespace svt { //........................................................................ using namespace ::com::sun::star::uno; using namespace ::com::sun::star::datatransfer; //==================================================================== //= OStringTransferable //==================================================================== //-------------------------------------------------------------------- OStringTransferable::OStringTransferable(const ::rtl::OUString& _rContent) :TransferableHelper() ,m_sContent( _rContent ) { } //-------------------------------------------------------------------- void OStringTransferable::AddSupportedFormats() { AddFormat(SOT_FORMAT_STRING); } //-------------------------------------------------------------------- sal_Bool OStringTransferable::GetData( const DataFlavor& _rFlavor ) { sal_uInt32 nFormat = SotExchange::GetFormat( _rFlavor ); if (SOT_FORMAT_STRING == nFormat) return SetString( m_sContent, _rFlavor ); return sal_False; } //==================================================================== //= OStringTransfer //==================================================================== //-------------------------------------------------------------------- void OStringTransfer::CopyString( const ::rtl::OUString& _rContent, Window* _pWindow ) { OStringTransferable* pTransferable = new OStringTransferable( _rContent ); Reference< XTransferable > xTransfer = pTransferable; pTransferable->CopyToClipboard( _pWindow ); } //-------------------------------------------------------------------- sal_Bool OStringTransfer::PasteString( ::rtl::OUString& _rContent, Window* _pWindow ) { TransferableDataHelper aClipboardData = TransferableDataHelper::CreateFromSystemClipboard( _pWindow ); // check for a string format const DataFlavorExVector& rFormats = aClipboardData.GetDataFlavorExVector(); for ( DataFlavorExVector::const_iterator aSearch = rFormats.begin(); aSearch != rFormats.end(); ++aSearch ) { if (SOT_FORMAT_STRING == aSearch->mnSotId) { String sContent; sal_Bool bSuccess = aClipboardData.GetString( SOT_FORMAT_STRING, sContent ); _rContent = sContent; return bSuccess; } } return sal_False; } //-------------------------------------------------------------------- void OStringTransfer::StartStringDrag( const ::rtl::OUString& _rContent, Window* _pWindow, sal_Int8 _nDragSourceActions ) { OStringTransferable* pTransferable = new OStringTransferable( _rContent ); Reference< XTransferable > xTransfer = pTransferable; pTransferable->StartDrag(_pWindow, _nDragSourceActions); } //........................................................................ } // namespace svt //........................................................................ <commit_msg>INTEGRATION: CWS changefileheader (1.7.246); FILE MERGED 2008/04/01 12:43:48 thb 1.7.246.2: #i85898# Stripping all external header guards 2008/03/31 13:02:17 rt 1.7.246.1: #i87441# Change license header to LPGL v3.<commit_after>/************************************************************************* * * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * Copyright 2008 by Sun Microsystems, Inc. * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: stringtransfer.cxx,v $ * $Revision: 1.8 $ * * This file is part of OpenOffice.org. * * OpenOffice.org is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License version 3 * only, as published by the Free Software Foundation. * * OpenOffice.org is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License version 3 for more details * (a copy is included in the LICENSE file that accompanied this code). * * You should have received a copy of the GNU Lesser General Public License * version 3 along with OpenOffice.org. If not, see * <http://www.openoffice.org/license.html> * for a copy of the LGPLv3 License. * ************************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_svtools.hxx" #include <svtools/stringtransfer.hxx> //........................................................................ namespace svt { //........................................................................ using namespace ::com::sun::star::uno; using namespace ::com::sun::star::datatransfer; //==================================================================== //= OStringTransferable //==================================================================== //-------------------------------------------------------------------- OStringTransferable::OStringTransferable(const ::rtl::OUString& _rContent) :TransferableHelper() ,m_sContent( _rContent ) { } //-------------------------------------------------------------------- void OStringTransferable::AddSupportedFormats() { AddFormat(SOT_FORMAT_STRING); } //-------------------------------------------------------------------- sal_Bool OStringTransferable::GetData( const DataFlavor& _rFlavor ) { sal_uInt32 nFormat = SotExchange::GetFormat( _rFlavor ); if (SOT_FORMAT_STRING == nFormat) return SetString( m_sContent, _rFlavor ); return sal_False; } //==================================================================== //= OStringTransfer //==================================================================== //-------------------------------------------------------------------- void OStringTransfer::CopyString( const ::rtl::OUString& _rContent, Window* _pWindow ) { OStringTransferable* pTransferable = new OStringTransferable( _rContent ); Reference< XTransferable > xTransfer = pTransferable; pTransferable->CopyToClipboard( _pWindow ); } //-------------------------------------------------------------------- sal_Bool OStringTransfer::PasteString( ::rtl::OUString& _rContent, Window* _pWindow ) { TransferableDataHelper aClipboardData = TransferableDataHelper::CreateFromSystemClipboard( _pWindow ); // check for a string format const DataFlavorExVector& rFormats = aClipboardData.GetDataFlavorExVector(); for ( DataFlavorExVector::const_iterator aSearch = rFormats.begin(); aSearch != rFormats.end(); ++aSearch ) { if (SOT_FORMAT_STRING == aSearch->mnSotId) { String sContent; sal_Bool bSuccess = aClipboardData.GetString( SOT_FORMAT_STRING, sContent ); _rContent = sContent; return bSuccess; } } return sal_False; } //-------------------------------------------------------------------- void OStringTransfer::StartStringDrag( const ::rtl::OUString& _rContent, Window* _pWindow, sal_Int8 _nDragSourceActions ) { OStringTransferable* pTransferable = new OStringTransferable( _rContent ); Reference< XTransferable > xTransfer = pTransferable; pTransferable->StartDrag(_pWindow, _nDragSourceActions); } //........................................................................ } // namespace svt //........................................................................ <|endoftext|>
<commit_before>/************************************************************************* * * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * Copyright 2008 by Sun Microsystems, Inc. * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: displayinfo.cxx,v $ * $Revision: 1.15 $ * * This file is part of OpenOffice.org. * * OpenOffice.org is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License version 3 * only, as published by the Free Software Foundation. * * OpenOffice.org is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License version 3 for more details * (a copy is included in the LICENSE file that accompanied this code). * * You should have received a copy of the GNU Lesser General Public License * version 3 along with OpenOffice.org. If not, see * <http://www.openoffice.org/license.html> * for a copy of the LGPLv3 License. * ************************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_svx.hxx" #include <svx/sdr/contact/displayinfo.hxx> #include <vcl/outdev.hxx> #include <vcl/svapp.hxx> #include <svx/svdobj.hxx> #include <vcl/gdimtf.hxx> #include <svx/svdpagv.hxx> #define ALL_GHOSTED_DRAWMODES (DRAWMODE_GHOSTEDLINE|DRAWMODE_GHOSTEDFILL|DRAWMODE_GHOSTEDTEXT|DRAWMODE_GHOSTEDBITMAP|DRAWMODE_GHOSTEDGRADIENT) ////////////////////////////////////////////////////////////////////////////// namespace sdr { namespace contact { // This uses Application::AnyInput() and may change mbContinuePaint // to interrupt the paint void DisplayInfo::CheckContinuePaint() { // #111111# // INPUT_PAINT and INPUT_TIMER removed again since this leads to // problems under Linux and Solaris when painting slow objects // (e.g. bitmaps) // #114335# // INPUT_OTHER removed too, leads to problems with added controls // from the form layer. #ifndef SOLARIS if(Application::AnyInput(INPUT_KEYBOARD)) { mbContinuePaint = sal_False; } #endif } DisplayInfo::DisplayInfo(SdrPageView* pPageView) : mpPageView(pPageView), mpProcessedPage(0L), mpLastDisplayInfo(0L), maProcessLayers(sal_True), // init layer info with all bits set to draw everything on default mpOutputDevice(0L), mpExtOutputDevice(0L), mpPaintInfoRec(0L), mpRootVOC(0L), mbControlLayerPainting(sal_False), mbPagePainting(sal_True), mbGhostedDrawModeActive(sal_False), mbBufferingAllowed(sal_True), mbContinuePaint(sal_True), mbMasterPagePainting(sal_False) { } DisplayInfo::~DisplayInfo() { SetProcessedPage( 0L ); } // access to ProcessedPage, write for internal use only. void DisplayInfo::SetProcessedPage(SdrPage* pNew) { if(pNew != mpProcessedPage) { mpProcessedPage = pNew; if(mpPageView) { if( pNew == NULL ) { // DisplayInfo needs to be reset at PageView if set since DisplayInfo is no longer valid if(mpPageView && mpPageView->GetCurrentPaintingDisplayInfo()) { DBG_ASSERT( mpPageView->GetCurrentPaintingDisplayInfo() == this, "DisplayInfo::~DisplayInfo() : stack error!" ); // restore remembered DisplayInfo to build a stack, or delete mpPageView->SetCurrentPaintingDisplayInfo(mpLastDisplayInfo); } } else { // rescue current mpLastDisplayInfo = mpPageView->GetCurrentPaintingDisplayInfo(); // set at PageView when a page is set mpPageView->SetCurrentPaintingDisplayInfo(this); } } } } const SdrPage* DisplayInfo::GetProcessedPage() const { return mpProcessedPage; } // Access to LayerInfos (which layers to proccess) void DisplayInfo::SetProcessLayers(const SetOfByte& rSet) { maProcessLayers = rSet; } const SetOfByte& DisplayInfo::GetProcessLayers() const { return maProcessLayers; } // access to ExtendedOutputDevice void DisplayInfo::SetExtendedOutputDevice(XOutputDevice* pExtOut) { if(mpExtOutputDevice != pExtOut) { mpExtOutputDevice = pExtOut; } } XOutputDevice* DisplayInfo::GetExtendedOutputDevice() const { return mpExtOutputDevice; } // access to PaintInfoRec void DisplayInfo::SetPaintInfoRec(SdrPaintInfoRec* pInfoRec) { if(mpPaintInfoRec != pInfoRec) { mpPaintInfoRec = pInfoRec; } } SdrPaintInfoRec* DisplayInfo::GetPaintInfoRec() const { return mpPaintInfoRec; } // access to OutputDevice void DisplayInfo::SetOutputDevice(OutputDevice* pOutDev) { if(mpOutputDevice != pOutDev) { mpOutputDevice = pOutDev; } } OutputDevice* DisplayInfo::GetOutputDevice() const { return mpOutputDevice; } // access to RedrawArea void DisplayInfo::SetRedrawArea(const Region& rRegion) { maRedrawArea = rRegion; } const Region& DisplayInfo::GetRedrawArea() const { return maRedrawArea; } // Is OutDev a printer? sal_Bool DisplayInfo::OutputToPrinter() const { if(mpOutputDevice && OUTDEV_PRINTER == mpOutputDevice->GetOutDevType()) { return sal_True; } return sal_False; } // Is OutDev a window? sal_Bool DisplayInfo::OutputToWindow() const { if(mpOutputDevice && OUTDEV_WINDOW == mpOutputDevice->GetOutDevType()) { return sal_True; } return sal_False; } // Is OutDev a VirtualDevice? sal_Bool DisplayInfo::OutputToVirtualDevice() const { if(mpOutputDevice && OUTDEV_VIRDEV == mpOutputDevice->GetOutDevType()) { return sal_True; } return sal_False; } // Is OutDev a recording MetaFile? sal_Bool DisplayInfo::OutputToRecordingMetaFile() const { if(mpOutputDevice) { GDIMetaFile* pMetaFile = mpOutputDevice->GetConnectMetaFile(); if(pMetaFile) { sal_Bool bRecording = pMetaFile->IsRecord() && !pMetaFile->IsPause(); return bRecording; } } return sal_False; } void DisplayInfo::SetControlLayerPainting(sal_Bool bDoPaint) { if(mbControlLayerPainting != bDoPaint) { mbControlLayerPainting = bDoPaint; } } sal_Bool DisplayInfo::GetControlLayerPainting() const { return mbControlLayerPainting; } void DisplayInfo::SetPagePainting(sal_Bool bDoPaint) { if(mbPagePainting != bDoPaint) { mbPagePainting = bDoPaint; } } sal_Bool DisplayInfo::GetPagePainting() const { return mbPagePainting; } // Access to svtools::ColorConfig const svtools::ColorConfig& DisplayInfo::GetColorConfig() const { return maColorConfig; } sal_uInt32 DisplayInfo::GetOriginalDrawMode() const { // return DrawMode without ghosted stuff if(mpOutputDevice) { return (mpOutputDevice->GetDrawMode() & ~ALL_GHOSTED_DRAWMODES); } return 0L; } sal_uInt32 DisplayInfo::GetCurrentDrawMode() const { if(mpOutputDevice) { return mpOutputDevice->GetDrawMode(); } return 0L; } void DisplayInfo::ClearGhostedDrawMode() { if(mpOutputDevice) { mpOutputDevice->SetDrawMode(mpOutputDevice->GetDrawMode() & ~ALL_GHOSTED_DRAWMODES); } mbGhostedDrawModeActive = sal_False; } void DisplayInfo::SetGhostedDrawMode() { if(mpOutputDevice) { mpOutputDevice->SetDrawMode(mpOutputDevice->GetDrawMode() | ALL_GHOSTED_DRAWMODES); } mbGhostedDrawModeActive = sal_True; } sal_Bool DisplayInfo::IsGhostedDrawModeActive() const { return mbGhostedDrawModeActive; } // access to buffering allowed flag void DisplayInfo::SetBufferingAllowed(sal_Bool bNew) { if(mbBufferingAllowed != bNew) { mbBufferingAllowed = bNew; } } sal_Bool DisplayInfo::IsBufferingAllowed() const { return mbBufferingAllowed; } // Check if painting should be continued. If not, return from paint // as soon as possible. sal_Bool DisplayInfo::DoContinuePaint() { if(mbContinuePaint && mpOutputDevice && OUTDEV_WINDOW == mpOutputDevice->GetOutDevType()) { CheckContinuePaint(); } return mbContinuePaint; } sal_Bool DisplayInfo::GetMasterPagePainting() const { return mbMasterPagePainting; } void DisplayInfo::SetMasterPagePainting(sal_Bool bNew) { if(mbMasterPagePainting != bNew) { mbMasterPagePainting = bNew; } } } // end of namespace contact } // end of namespace sdr ////////////////////////////////////////////////////////////////////////////// // eof <commit_msg>INTEGRATION: CWS aw033 (1.8.14); FILE MERGED 2008/06/03 13:41:11 aw 1.8.14.12: corrections 2008/05/27 14:49:57 aw 1.8.14.11: #i39532# changes DEV300 m12 resync corrections 2008/05/14 14:00:23 aw 1.8.14.10: RESYNC: (1.14-1.15); FILE MERGED 2008/04/16 05:30:44 aw 1.8.14.9: diverse optimisations and fixes for primitives. Support for LazyInvalidation. 2008/01/29 10:27:31 aw 1.8.14.8: updated refresh for ActionChanged(), diverse removals 2008/01/22 12:29:29 aw 1.8.14.7: adaptions and 1st stripping 2007/12/03 16:39:59 aw 1.8.14.6: RESYNC: (1.13-1.14); FILE MERGED 2007/08/13 15:34:32 aw 1.8.14.5: #i39532# changes after resync 2007/08/09 18:45:41 aw 1.8.14.4: RESYNC: (1.12-1.13); FILE MERGED 2006/11/28 19:24:04 aw 1.8.14.3: RESYNC: (1.10-1.12); FILE MERGED 2006/09/26 19:19:49 aw 1.8.14.2: RESYNC: (1.8-1.10); FILE MERGED 2006/05/12 12:46:21 aw 1.8.14.1: code changes for primitive support<commit_after>/************************************************************************* * * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * Copyright 2008 by Sun Microsystems, Inc. * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: displayinfo.cxx,v $ * $Revision: 1.16 $ * * This file is part of OpenOffice.org. * * OpenOffice.org is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License version 3 * only, as published by the Free Software Foundation. * * OpenOffice.org is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License version 3 for more details * (a copy is included in the LICENSE file that accompanied this code). * * You should have received a copy of the GNU Lesser General Public License * version 3 along with OpenOffice.org. If not, see * <http://www.openoffice.org/license.html> * for a copy of the LGPLv3 License. * ************************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_svx.hxx" #include <svx/sdr/contact/displayinfo.hxx> #include <vcl/outdev.hxx> #include <vcl/svapp.hxx> #include <svx/svdobj.hxx> #include <vcl/gdimtf.hxx> #include <svx/svdpagv.hxx> #include <svx/svdview.hxx> #define ALL_GHOSTED_DRAWMODES (DRAWMODE_GHOSTEDLINE|DRAWMODE_GHOSTEDFILL|DRAWMODE_GHOSTEDTEXT|DRAWMODE_GHOSTEDBITMAP|DRAWMODE_GHOSTEDGRADIENT) ////////////////////////////////////////////////////////////////////////////// namespace sdr { namespace contact { DisplayInfo::DisplayInfo() : //mpProcessedPage(0), maProcessLayers(true), // init layer info with all bits set to draw everything on default maRedrawArea(), mbControlLayerProcessingActive(false), mbPageProcessingActive(true), mbGhostedDrawModeActive(false), mbSubContentActive(false) { } DisplayInfo::~DisplayInfo() { //SetProcessedPage(0); } // access to ProcessedPage, write for internal use only. //void DisplayInfo::SetProcessedPage(SdrPage* pNew) //{ // if(pNew != mpProcessedPage) // { // mpProcessedPage = pNew; // } //} //const SdrPage* DisplayInfo::GetProcessedPage() const //{ // return mpProcessedPage; //} // Access to LayerInfos (which layers to proccess) void DisplayInfo::SetProcessLayers(const SetOfByte& rSet) { maProcessLayers = rSet; } const SetOfByte& DisplayInfo::GetProcessLayers() const { return maProcessLayers; } // access to RedrawArea void DisplayInfo::SetRedrawArea(const Region& rRegion) { maRedrawArea = rRegion; } const Region& DisplayInfo::GetRedrawArea() const { return maRedrawArea; } void DisplayInfo::SetControlLayerProcessingActive(bool bDoProcess) { if((bool)mbControlLayerProcessingActive != bDoProcess) { mbControlLayerProcessingActive = bDoProcess; } } bool DisplayInfo::GetControlLayerProcessingActive() const { return mbControlLayerProcessingActive; } void DisplayInfo::SetPageProcessingActive(bool bDoProcess) { if((bool)mbPageProcessingActive != bDoProcess) { mbPageProcessingActive = bDoProcess; } } bool DisplayInfo::GetPageProcessingActive() const { return mbPageProcessingActive; } void DisplayInfo::ClearGhostedDrawMode() { mbGhostedDrawModeActive = false; } void DisplayInfo::SetGhostedDrawMode() { mbGhostedDrawModeActive = true; } bool DisplayInfo::IsGhostedDrawModeActive() const { return mbGhostedDrawModeActive; } bool DisplayInfo::GetSubContentActive() const { return mbSubContentActive; } void DisplayInfo::SetSubContentActive(bool bNew) { if((bool)mbSubContentActive != bNew) { mbSubContentActive = bNew; } } } // end of namespace contact } // end of namespace sdr ////////////////////////////////////////////////////////////////////////////// // eof <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: SwUndoPageDesc.cxx,v $ * * $Revision: 1.3 $ * * last change: $Author: hr $ $Date: 2004-09-08 14:57:59 $ * * 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 <tools/resid.hxx> #include <doc.hxx> #include <swundo.hxx> #include <pagedesc.hxx> #include <SwUndoPageDesc.hxx> #include <SwRewriter.hxx> #include <undobj.hxx> #include <comcore.hrc> SwUndoPageDesc::SwUndoPageDesc(const SwPageDesc & _aOld, const SwPageDesc & _aNew, SwDoc * _pDoc) : SwUndo(_aOld.GetName() != _aNew.GetName() ? UNDO_RENAME_PAGEDESC :UNDO_CHANGE_PAGEDESC), aOld(_aOld, _pDoc), aNew(_aNew, _pDoc), pDoc(_pDoc) { ASSERT(0 != pDoc, "no document?"); } SwUndoPageDesc::~SwUndoPageDesc() { } void SwUndoPageDesc::Undo(SwUndoIter & rIt) { BOOL bUndo = pDoc->DoesUndo(); pDoc->DoUndo(FALSE); pDoc->ChgPageDesc(aOld.GetName(), aOld); pDoc->DoUndo(bUndo); } void SwUndoPageDesc::Redo(SwUndoIter & rIt) { BOOL bUndo = pDoc->DoesUndo(); pDoc->DoUndo(FALSE); pDoc->ChgPageDesc(aNew.GetName(), aNew); pDoc->DoUndo(bUndo); } void SwUndoPageDesc::Repeat(SwUndoIter & rIt) { Redo(rIt); } SwRewriter SwUndoPageDesc::GetRewriter() const { SwRewriter aResult; aResult.AddRule(UNDO_ARG1, aOld.GetName()); aResult.AddRule(UNDO_ARG2, SW_RES(STR_YIELDS)); aResult.AddRule(UNDO_ARG3, aNew.GetName()); return aResult; } // #116530# SwUndoPageDescCreate::SwUndoPageDescCreate(const SwPageDesc * pNew, SwDoc * _pDoc) : SwUndo(UNDO_CREATE_PAGEDESC), pDesc(pNew), aNew(*pNew, _pDoc), pDoc(_pDoc) { ASSERT(0 != pDoc, "no document?"); } SwUndoPageDescCreate::~SwUndoPageDescCreate() { } void SwUndoPageDescCreate::Undo(SwUndoIter & rIt) { BOOL bUndo = pDoc->DoesUndo(); pDoc->DoUndo(FALSE); // -> #116530# if (pDesc) { aNew = *pDesc; pDesc = NULL; } // <- #116530# pDoc->DelPageDesc(aNew.GetName(), TRUE); pDoc->DoUndo(bUndo); } void SwUndoPageDescCreate::Redo(SwUndoIter & rIt) { BOOL bUndo = pDoc->DoesUndo(); pDoc->DoUndo(FALSE); SwPageDesc aPageDesc = aNew; pDoc->MakePageDesc(aNew.GetName(), &aPageDesc, FALSE, TRUE); // #116530# pDoc->DoUndo(bUndo); } void SwUndoPageDescCreate::Repeat(SwUndoIter & rIt) { Redo(rIt); } SwRewriter SwUndoPageDescCreate::GetRewriter() const { SwRewriter aResult; if (pDesc) aResult.AddRule(UNDO_ARG1, pDesc->GetName()); else aResult.AddRule(UNDO_ARG1, aNew.GetName()); return aResult; } SwUndoPageDescDelete::SwUndoPageDescDelete(const SwPageDesc & _aOld, SwDoc * _pDoc) : SwUndo(UNDO_DELETE_PAGEDESC), aOld(_aOld, _pDoc), pDoc(_pDoc) { ASSERT(0 != pDoc, "no document?"); } SwUndoPageDescDelete::~SwUndoPageDescDelete() { } void SwUndoPageDescDelete::Undo(SwUndoIter & rIt) { BOOL bUndo = pDoc->DoesUndo(); pDoc->DoUndo(FALSE); SwPageDesc aPageDesc = aOld; pDoc->MakePageDesc(aOld.GetName(), &aPageDesc, FALSE, TRUE); // #116530# pDoc->DoUndo(bUndo); } void SwUndoPageDescDelete::Redo(SwUndoIter & rIt) { BOOL bUndo = pDoc->DoesUndo(); pDoc->DoUndo(FALSE); pDoc->DelPageDesc(aOld.GetName(), TRUE); // #116530# pDoc->DoUndo(bUndo); } void SwUndoPageDescDelete::Repeat(SwUndoIter & rIt) { Redo(rIt); } SwRewriter SwUndoPageDescDelete::GetRewriter() const { SwRewriter aResult; aResult.AddRule(UNDO_ARG1, aOld.GetName()); return aResult; } <commit_msg>INTEGRATION: CWS swqcore08 (1.3.320); FILE MERGED 2005/03/01 18:06:23 dvo 1.3.320.1: #i43072# undo of header/footer creation/deletion<commit_after>/************************************************************************* * * $RCSfile: SwUndoPageDesc.cxx,v $ * * $Revision: 1.4 $ * * last change: $Author: rt $ $Date: 2005-03-29 14:38:59 $ * * 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 <tools/resid.hxx> #include <doc.hxx> #include <swundo.hxx> #include <pagedesc.hxx> #include <SwUndoPageDesc.hxx> #include <SwRewriter.hxx> #include <undobj.hxx> #include <comcore.hrc> #include <headerfooterhelper.hxx> SwUndoPageDesc::SwUndoPageDesc(const SwPageDesc & _aOld, const SwPageDesc & _aNew, SwDoc * _pDoc) : SwUndo(_aOld.GetName() != _aNew.GetName() ? UNDO_RENAME_PAGEDESC :UNDO_CHANGE_PAGEDESC), aOld(_aOld, _pDoc), aNew(_aNew, _pDoc), pDoc(_pDoc) { ASSERT(0 != pDoc, "no document?"); // The headers/footers from the two SwPageDesc saved by this undo // are still in the main document array. In order to preserve the // absolute indices, we need to move them into the undo nodes // array. SwNodes& rNodes = * const_cast<SwNodes*>( pDoc->GetUndoNds() ); saveHeaderFooterNodes( (SwPageDesc&)aOld, rNodes ); saveHeaderFooterNodes( (SwPageDesc&)aNew, rNodes ); } SwUndoPageDesc::~SwUndoPageDesc() { } void SwUndoPageDesc::Undo(SwUndoIter & rIt) { BOOL bUndo = pDoc->DoesUndo(); pDoc->DoUndo(FALSE); pDoc->ChgPageDesc(aOld.GetName(), aOld); pDoc->DoUndo(bUndo); } void SwUndoPageDesc::Redo(SwUndoIter & rIt) { BOOL bUndo = pDoc->DoesUndo(); pDoc->DoUndo(FALSE); pDoc->ChgPageDesc(aNew.GetName(), aNew); pDoc->DoUndo(bUndo); } void SwUndoPageDesc::Repeat(SwUndoIter & rIt) { Redo(rIt); } SwRewriter SwUndoPageDesc::GetRewriter() const { SwRewriter aResult; aResult.AddRule(UNDO_ARG1, aOld.GetName()); aResult.AddRule(UNDO_ARG2, SW_RES(STR_YIELDS)); aResult.AddRule(UNDO_ARG3, aNew.GetName()); return aResult; } // #116530# SwUndoPageDescCreate::SwUndoPageDescCreate(const SwPageDesc * pNew, SwDoc * _pDoc) : SwUndo(UNDO_CREATE_PAGEDESC), pDesc(pNew), aNew(*pNew, _pDoc), pDoc(_pDoc) { ASSERT(0 != pDoc, "no document?"); } SwUndoPageDescCreate::~SwUndoPageDescCreate() { } void SwUndoPageDescCreate::Undo(SwUndoIter & rIt) { BOOL bUndo = pDoc->DoesUndo(); pDoc->DoUndo(FALSE); // -> #116530# if (pDesc) { aNew = *pDesc; pDesc = NULL; } // <- #116530# pDoc->DelPageDesc(aNew.GetName(), TRUE); pDoc->DoUndo(bUndo); } void SwUndoPageDescCreate::Redo(SwUndoIter & rIt) { BOOL bUndo = pDoc->DoesUndo(); pDoc->DoUndo(FALSE); SwPageDesc aPageDesc = aNew; pDoc->MakePageDesc(aNew.GetName(), &aPageDesc, FALSE, TRUE); // #116530# pDoc->DoUndo(bUndo); } void SwUndoPageDescCreate::Repeat(SwUndoIter & rIt) { Redo(rIt); } SwRewriter SwUndoPageDescCreate::GetRewriter() const { SwRewriter aResult; if (pDesc) aResult.AddRule(UNDO_ARG1, pDesc->GetName()); else aResult.AddRule(UNDO_ARG1, aNew.GetName()); return aResult; } SwUndoPageDescDelete::SwUndoPageDescDelete(const SwPageDesc & _aOld, SwDoc * _pDoc) : SwUndo(UNDO_DELETE_PAGEDESC), aOld(_aOld, _pDoc), pDoc(_pDoc) { ASSERT(0 != pDoc, "no document?"); } SwUndoPageDescDelete::~SwUndoPageDescDelete() { } void SwUndoPageDescDelete::Undo(SwUndoIter & rIt) { BOOL bUndo = pDoc->DoesUndo(); pDoc->DoUndo(FALSE); SwPageDesc aPageDesc = aOld; pDoc->MakePageDesc(aOld.GetName(), &aPageDesc, FALSE, TRUE); // #116530# pDoc->DoUndo(bUndo); } void SwUndoPageDescDelete::Redo(SwUndoIter & rIt) { BOOL bUndo = pDoc->DoesUndo(); pDoc->DoUndo(FALSE); pDoc->DelPageDesc(aOld.GetName(), TRUE); // #116530# pDoc->DoUndo(bUndo); } void SwUndoPageDescDelete::Repeat(SwUndoIter & rIt) { Redo(rIt); } SwRewriter SwUndoPageDescDelete::GetRewriter() const { SwRewriter aResult; aResult.AddRule(UNDO_ARG1, aOld.GetName()); return aResult; } <|endoftext|>
<commit_before>#include "Node.h" int Node::s_current_id = 0; Node::Node() { // Status m_id = ++s_current_id; m_show = false; // Arrangement m_position = Vec2<double>(0.0, 0.0); m_anchor = Vec2<double>(0.5, 0.5); m_size = Vec2<double>(30.0, 30.0); // Texture m_texture = NULL; m_texture_src = NULL; m_texture_dst = NULL; } Node::~Node() { //SDL_DestroyTexture(m_texture); } int Node::getId() { return m_id; } void Node::show(bool p_show) { m_show = p_show; } bool Node::show() { return m_show; } void Node::setPosition(Vec2<double> pos) { m_position = pos; m_position.x -= (m_size.x * m_anchor.x); m_position.y -= (m_size.y * m_anchor.y); if(m_texture_dst != NULL) { m_texture_dst->x = m_position.x; m_texture_dst->y = m_position.y; } } void Node::moveBy(Vec2<double> p_movement) { m_position += p_movement; if(m_texture_dst != NULL) { m_texture_dst->x += p_movement.x; m_texture_dst->y += p_movement.y; } } Vec2<double> Node::getPosition() { return m_position; } void Node::setSize(Vec2<double> p_size) { // Arrangement m_size = p_size; // Texture m_texture_dst->w = m_size.x; m_texture_dst->h = m_size.y; } Vec2<double> Node::getSize() { return m_size; } void Node::setAnchor(Vec2<double> p_anchor) { m_anchor = p_anchor; } Vec2<double> Node::getAnchor() { return m_anchor; } void Node::setTexture(SDL_Texture* p_texture) { m_texture = p_texture; } SDL_Texture* Node::getTexture() { return m_texture; } SDL_Rect* Node::getTextureSrc() { return m_texture_src; } SDL_Rect* Node::getTextureDst() { return m_texture_dst; }<commit_msg>Fix texture displacement<commit_after>#include "Node.h" int Node::s_current_id = 0; Node::Node() { // Status m_id = ++s_current_id; m_show = false; // Arrangement m_position = Vec2<double>(0.0, 0.0); m_anchor = Vec2<double>(0.5, 0.5); m_size = Vec2<double>(30.0, 30.0); // Texture m_texture = NULL; m_texture_src = NULL; m_texture_dst = NULL; } Node::~Node() { //SDL_DestroyTexture(m_texture); } int Node::getId() { return m_id; } void Node::show(bool p_show) { m_show = p_show; } bool Node::show() { return m_show; } void Node::setPosition(Vec2<double> pos) { m_position = pos; m_position.x -= (m_size.x * m_anchor.x); m_position.y -= (m_size.y * m_anchor.y); if(m_texture_dst != NULL) { m_texture_dst->x = m_position.x; m_texture_dst->y = m_position.y; } } void Node::moveBy(Vec2<double> p_movement) { m_position += p_movement; if(m_texture_dst != NULL) { m_texture_dst->x = m_position.x; m_texture_dst->y = m_position.y; } } Vec2<double> Node::getPosition() { return m_position; } void Node::setSize(Vec2<double> p_size) { // Arrangement m_size = p_size; // Texture m_texture_dst->w = m_size.x; m_texture_dst->h = m_size.y; } Vec2<double> Node::getSize() { return m_size; } void Node::setAnchor(Vec2<double> p_anchor) { m_anchor = p_anchor; } Vec2<double> Node::getAnchor() { return m_anchor; } void Node::setTexture(SDL_Texture* p_texture) { m_texture = p_texture; } SDL_Texture* Node::getTexture() { return m_texture; } SDL_Rect* Node::getTextureSrc() { return m_texture_src; } SDL_Rect* Node::getTextureDst() { return m_texture_dst; }<|endoftext|>
<commit_before>/* * #%L * %% * Copyright (C) 2011 - 2016 BMW Car IT 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. * #L% */ #include <gtest/gtest.h> #include <gmock/gmock.h> #include <string> #include <vector> #include "joynr/MessagingQos.h" #include "joynr/JoynrMessage.h" #include "joynr/JoynrMessageFactory.h" #include "joynr/JoynrMessageSender.h" #include "joynr/Request.h" #include "joynr/Reply.h" #include "joynr/SubscriptionPublication.h" #include "joynr/PeriodicSubscriptionQos.h" #include "joynr/OnChangeSubscriptionQos.h" #include "tests/utils/MockObjects.h" #include "joynr/SingleThreadedIOService.h" using ::testing::A; using ::testing::_; using ::testing::A; using ::testing::Eq; using ::testing::NotNull; using ::testing::AllOf; using ::testing::Property; using namespace joynr; class JoynrMessageSenderTest : public ::testing::Test { public: JoynrMessageSenderTest() : messageFactory(), postFix(), senderID(), receiverID(), requestID(), qosSettings(), mockDispatcher(), mockMessagingStub(), callBack(), singleThreadedIOService() { singleThreadedIOService.start(); } void SetUp(){ postFix = "_" + util::createUuid(); senderID = "senderId" + postFix; receiverID = "receiverID" + postFix; requestID = "requestId" + postFix; qosSettings = MessagingQos(456000); } protected: JoynrMessageFactory messageFactory; std::string postFix; std::string senderID; std::string receiverID; std::string requestID; MessagingQos qosSettings; MockDispatcher mockDispatcher; MockMessaging mockMessagingStub; std::shared_ptr<IReplyCaller> callBack; SingleThreadedIOService singleThreadedIOService; }; typedef JoynrMessageSenderTest JoynrMessageSenderDeathTest; TEST_F(JoynrMessageSenderTest, sendRequest_normal){ MockDispatcher mockDispatcher; auto messagingStub = std::make_shared<MockMessageRouter>(singleThreadedIOService.getIOService()); Request request; request.setMethodName("methodName"); request.setParams(42, std::string("value")); std::vector<std::string> paramDatatypes; paramDatatypes.push_back("java.lang.Integer"); paramDatatypes.push_back("java.lang.String"); request.setParamDatatypes(paramDatatypes); JoynrMessage message = messageFactory.createRequest( senderID, receiverID, qosSettings, request ); EXPECT_CALL( *(messagingStub.get()), route(AllOf(Property(&JoynrMessage::getType, Eq(JoynrMessage::VALUE_MESSAGE_TYPE_REQUEST)), Property(&JoynrMessage::getPayload, Eq(message.getPayload()))),_)); JoynrMessageSender joynrMessageSender(messagingStub); joynrMessageSender.registerDispatcher(&mockDispatcher); joynrMessageSender.sendRequest(senderID, receiverID, qosSettings, request, callBack); } TEST_F(JoynrMessageSenderTest, sendOneWayRequest_normal){ MockDispatcher mockDispatcher; auto messagingStub = std::make_shared<MockMessageRouter>(singleThreadedIOService.getIOService()); OneWayRequest oneWayRequest; oneWayRequest.setMethodName("methodName"); oneWayRequest.setParams(42, std::string("value")); std::vector<std::string> paramDatatypes; paramDatatypes.push_back("java.lang.Integer"); paramDatatypes.push_back("java.lang.String"); oneWayRequest.setParamDatatypes(paramDatatypes); JoynrMessage message = messageFactory.createOneWayRequest( senderID, receiverID, qosSettings, oneWayRequest ); EXPECT_CALL( *(messagingStub.get()), route(AllOf(Property(&JoynrMessage::getType, Eq(JoynrMessage::VALUE_MESSAGE_TYPE_ONE_WAY)), Property(&JoynrMessage::getPayload, Eq(message.getPayload()))),_)); JoynrMessageSender joynrMessageSender(messagingStub); joynrMessageSender.registerDispatcher(&mockDispatcher); joynrMessageSender.sendOneWayRequest(senderID, receiverID, qosSettings, oneWayRequest); } TEST_F(JoynrMessageSenderDeathTest, DISABLED_sendRequest_nullPayloadFails_death){ MockDispatcher mockDispatcher; auto messagingStub = std::make_shared<MockMessageRouter>(singleThreadedIOService.getIOService()); EXPECT_CALL(*(messagingStub.get()), route(_,_)).Times(0); JoynrMessageSender joynrMessageSender(messagingStub); joynrMessageSender.registerDispatcher(&mockDispatcher); Request jsonRequest; ASSERT_DEATH(joynrMessageSender.sendRequest(senderID, receiverID, qosSettings, jsonRequest, callBack), "Assertion.*"); } TEST_F(JoynrMessageSenderTest, sendReply_normal){ MockDispatcher mockDispatcher; auto messagingStub = std::make_shared<MockMessageRouter>(singleThreadedIOService.getIOService()); JoynrMessageSender joynrMessageSender(messagingStub); joynrMessageSender.registerDispatcher(&mockDispatcher); Reply reply; reply.setRequestReplyId(util::createUuid()); reply.setResponse(std::string("response")); JoynrMessage message = messageFactory.createReply( senderID, receiverID, qosSettings, reply); EXPECT_CALL(*(messagingStub.get()), route(AllOf(Property(&JoynrMessage::getType, Eq(JoynrMessage::VALUE_MESSAGE_TYPE_REPLY)), Property(&JoynrMessage::getPayload, Eq(message.getPayload()))),_)); joynrMessageSender.sendReply(senderID, receiverID, qosSettings, reply); } TEST_F(JoynrMessageSenderTest, sendSubscriptionRequest_normal){ MockDispatcher mockDispatcher; auto messagingStub = std::make_shared<MockMessageRouter>(singleThreadedIOService.getIOService()); std::int64_t period = 2000; std::int64_t validity = 100000; std::int64_t alert = 4000; auto qos = std::make_shared<PeriodicSubscriptionQos>(validity, period, alert); SubscriptionRequest subscriptionRequest; subscriptionRequest.setSubscriptionId("subscriptionId"); subscriptionRequest.setSubscribeToName("attributeName"); subscriptionRequest.setQos(qos); JoynrMessage message = messageFactory.createSubscriptionRequest( senderID, receiverID, qosSettings, subscriptionRequest); EXPECT_CALL(*messagingStub, route(AllOf(Property(&JoynrMessage::getType, Eq(JoynrMessage::VALUE_MESSAGE_TYPE_SUBSCRIPTION_REQUEST)), Property(&JoynrMessage::getPayload, Eq(message.getPayload()))),_)); JoynrMessageSender joynrMessageSender(messagingStub); joynrMessageSender.registerDispatcher(&mockDispatcher); joynrMessageSender.sendSubscriptionRequest(senderID, receiverID, qosSettings, subscriptionRequest); } TEST_F(JoynrMessageSenderTest, sendBroadcastSubscriptionRequest_normal){ MockDispatcher mockDispatcher; auto messagingStub = std::make_shared<MockMessageRouter>(singleThreadedIOService.getIOService()); std::int64_t minInterval = 2000; std::int64_t validity = 100000; auto qos = std::make_shared<OnChangeSubscriptionQos>(validity, minInterval); BroadcastSubscriptionRequest subscriptionRequest; BroadcastFilterParameters filter; filter.setFilterParameter("MyParameter", "MyValue"); subscriptionRequest.setFilterParameters(filter); subscriptionRequest.setSubscriptionId("subscriptionId"); subscriptionRequest.setSubscribeToName("broadcastName"); subscriptionRequest.setQos(qos); JoynrMessage message = messageFactory.createBroadcastSubscriptionRequest( senderID, receiverID, qosSettings, subscriptionRequest); EXPECT_CALL(*messagingStub, route(AllOf(Property(&JoynrMessage::getType, Eq(JoynrMessage::VALUE_MESSAGE_TYPE_BROADCAST_SUBSCRIPTION_REQUEST)), Property(&JoynrMessage::getPayload, Eq(message.getPayload()))),_)); JoynrMessageSender joynrMessageSender(messagingStub); joynrMessageSender.registerDispatcher(&mockDispatcher); joynrMessageSender.sendBroadcastSubscriptionRequest(senderID, receiverID, qosSettings, subscriptionRequest); } //TODO implement sending a reply to a subscription request! TEST_F(JoynrMessageSenderTest, DISABLED_sendSubscriptionReply_normal){ MockDispatcher mockDispatcher; auto messagingStub = std::make_shared<MockMessageRouter>(singleThreadedIOService.getIOService()); std::string payload("subscriptionReply"); EXPECT_CALL(*(messagingStub.get()), route(AllOf(Property(&JoynrMessage::getType, Eq(JoynrMessage::VALUE_MESSAGE_TYPE_SUBSCRIPTION_REPLY)), Property(&JoynrMessage::getPayload, Eq(payload))),_)); JoynrMessageSender joynrMessageSender(messagingStub); joynrMessageSender.registerDispatcher(&mockDispatcher); // joynrMessageSender.sendSubscriptionReply(util::createUuid(), payload, senderID, receiverID, qosSettings); } TEST_F(JoynrMessageSenderTest, sendPublication_normal){ MockDispatcher mockDispatcher; auto messagingStub = std::make_shared<MockMessageRouter>(singleThreadedIOService.getIOService()); JoynrMessageSender joynrMessageSender(messagingStub); joynrMessageSender.registerDispatcher(&mockDispatcher); SubscriptionPublication publication; publication.setSubscriptionId("ignoresubscriptionid"); publication.setResponse(std::string("publication")); JoynrMessage message = messageFactory.createSubscriptionPublication( senderID, receiverID, qosSettings, publication); EXPECT_CALL(*(messagingStub.get()), route(AllOf(Property(&JoynrMessage::getType, Eq(JoynrMessage::VALUE_MESSAGE_TYPE_PUBLICATION)), Property(&JoynrMessage::getPayload, Eq(message.getPayload()))),_)); joynrMessageSender.sendSubscriptionPublication(senderID, receiverID, qosSettings, std::move(publication)); } <commit_msg>[C++] JoynrMessageSenderTest: Move common code into fixture<commit_after>/* * #%L * %% * Copyright (C) 2011 - 2016 BMW Car IT 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. * #L% */ #include <gtest/gtest.h> #include <gmock/gmock.h> #include <string> #include <vector> #include "joynr/MessagingQos.h" #include "joynr/JoynrMessage.h" #include "joynr/JoynrMessageFactory.h" #include "joynr/JoynrMessageSender.h" #include "joynr/Request.h" #include "joynr/Reply.h" #include "joynr/SubscriptionPublication.h" #include "joynr/PeriodicSubscriptionQos.h" #include "joynr/OnChangeSubscriptionQos.h" #include "tests/utils/MockObjects.h" #include "joynr/SingleThreadedIOService.h" using ::testing::A; using ::testing::_; using ::testing::A; using ::testing::Eq; using ::testing::NotNull; using ::testing::AllOf; using ::testing::Property; using namespace joynr; class JoynrMessageSenderTest : public ::testing::Test { public: JoynrMessageSenderTest() : messageFactory(), postFix(), senderID(), receiverID(), requestID(), qosSettings(), mockDispatcher(), mockMessagingStub(), callBack(), singleThreadedIOService(), messagingStub(std::make_shared<MockMessageRouter>(singleThreadedIOService.getIOService())) { singleThreadedIOService.start(); } void SetUp(){ postFix = "_" + util::createUuid(); senderID = "senderId" + postFix; receiverID = "receiverID" + postFix; requestID = "requestId" + postFix; qosSettings = MessagingQos(456000); } protected: JoynrMessageFactory messageFactory; std::string postFix; std::string senderID; std::string receiverID; std::string requestID; MessagingQos qosSettings; MockDispatcher mockDispatcher; MockMessaging mockMessagingStub; std::shared_ptr<IReplyCaller> callBack; SingleThreadedIOService singleThreadedIOService; std::shared_ptr<MockMessageRouter> messagingStub; }; typedef JoynrMessageSenderTest JoynrMessageSenderDeathTest; TEST_F(JoynrMessageSenderTest, sendRequest_normal){ Request request; request.setMethodName("methodName"); request.setParams(42, std::string("value")); std::vector<std::string> paramDatatypes; paramDatatypes.push_back("java.lang.Integer"); paramDatatypes.push_back("java.lang.String"); request.setParamDatatypes(paramDatatypes); JoynrMessage message = messageFactory.createRequest( senderID, receiverID, qosSettings, request ); EXPECT_CALL( *(messagingStub.get()), route(AllOf(Property(&JoynrMessage::getType, Eq(JoynrMessage::VALUE_MESSAGE_TYPE_REQUEST)), Property(&JoynrMessage::getPayload, Eq(message.getPayload()))),_)); JoynrMessageSender joynrMessageSender(messagingStub); joynrMessageSender.registerDispatcher(&mockDispatcher); joynrMessageSender.sendRequest(senderID, receiverID, qosSettings, request, callBack); } TEST_F(JoynrMessageSenderTest, sendOneWayRequest_normal){ OneWayRequest oneWayRequest; oneWayRequest.setMethodName("methodName"); oneWayRequest.setParams(42, std::string("value")); std::vector<std::string> paramDatatypes; paramDatatypes.push_back("java.lang.Integer"); paramDatatypes.push_back("java.lang.String"); oneWayRequest.setParamDatatypes(paramDatatypes); JoynrMessage message = messageFactory.createOneWayRequest( senderID, receiverID, qosSettings, oneWayRequest ); EXPECT_CALL( *(messagingStub.get()), route(AllOf(Property(&JoynrMessage::getType, Eq(JoynrMessage::VALUE_MESSAGE_TYPE_ONE_WAY)), Property(&JoynrMessage::getPayload, Eq(message.getPayload()))),_)); JoynrMessageSender joynrMessageSender(messagingStub); joynrMessageSender.registerDispatcher(&mockDispatcher); joynrMessageSender.sendOneWayRequest(senderID, receiverID, qosSettings, oneWayRequest); } TEST_F(JoynrMessageSenderDeathTest, DISABLED_sendRequest_nullPayloadFails_death){ EXPECT_CALL(*(messagingStub.get()), route(_,_)).Times(0); JoynrMessageSender joynrMessageSender(messagingStub); joynrMessageSender.registerDispatcher(&mockDispatcher); Request jsonRequest; ASSERT_DEATH(joynrMessageSender.sendRequest(senderID, receiverID, qosSettings, jsonRequest, callBack), "Assertion.*"); } TEST_F(JoynrMessageSenderTest, sendReply_normal){ JoynrMessageSender joynrMessageSender(messagingStub); joynrMessageSender.registerDispatcher(&mockDispatcher); Reply reply; reply.setRequestReplyId(util::createUuid()); reply.setResponse(std::string("response")); JoynrMessage message = messageFactory.createReply( senderID, receiverID, qosSettings, reply); EXPECT_CALL(*(messagingStub.get()), route(AllOf(Property(&JoynrMessage::getType, Eq(JoynrMessage::VALUE_MESSAGE_TYPE_REPLY)), Property(&JoynrMessage::getPayload, Eq(message.getPayload()))),_)); joynrMessageSender.sendReply(senderID, receiverID, qosSettings, reply); } TEST_F(JoynrMessageSenderTest, sendSubscriptionRequest_normal){ std::int64_t period = 2000; std::int64_t validity = 100000; std::int64_t alert = 4000; auto qos = std::make_shared<PeriodicSubscriptionQos>(validity, period, alert); SubscriptionRequest subscriptionRequest; subscriptionRequest.setSubscriptionId("subscriptionId"); subscriptionRequest.setSubscribeToName("attributeName"); subscriptionRequest.setQos(qos); JoynrMessage message = messageFactory.createSubscriptionRequest( senderID, receiverID, qosSettings, subscriptionRequest); EXPECT_CALL(*messagingStub, route(AllOf(Property(&JoynrMessage::getType, Eq(JoynrMessage::VALUE_MESSAGE_TYPE_SUBSCRIPTION_REQUEST)), Property(&JoynrMessage::getPayload, Eq(message.getPayload()))),_)); JoynrMessageSender joynrMessageSender(messagingStub); joynrMessageSender.registerDispatcher(&mockDispatcher); joynrMessageSender.sendSubscriptionRequest(senderID, receiverID, qosSettings, subscriptionRequest); } TEST_F(JoynrMessageSenderTest, sendBroadcastSubscriptionRequest_normal){ std::int64_t minInterval = 2000; std::int64_t validity = 100000; auto qos = std::make_shared<OnChangeSubscriptionQos>(validity, minInterval); BroadcastSubscriptionRequest subscriptionRequest; BroadcastFilterParameters filter; filter.setFilterParameter("MyParameter", "MyValue"); subscriptionRequest.setFilterParameters(filter); subscriptionRequest.setSubscriptionId("subscriptionId"); subscriptionRequest.setSubscribeToName("broadcastName"); subscriptionRequest.setQos(qos); JoynrMessage message = messageFactory.createBroadcastSubscriptionRequest( senderID, receiverID, qosSettings, subscriptionRequest); EXPECT_CALL(*messagingStub, route(AllOf(Property(&JoynrMessage::getType, Eq(JoynrMessage::VALUE_MESSAGE_TYPE_BROADCAST_SUBSCRIPTION_REQUEST)), Property(&JoynrMessage::getPayload, Eq(message.getPayload()))),_)); JoynrMessageSender joynrMessageSender(messagingStub); joynrMessageSender.registerDispatcher(&mockDispatcher); joynrMessageSender.sendBroadcastSubscriptionRequest(senderID, receiverID, qosSettings, subscriptionRequest); } //TODO implement sending a reply to a subscription request! TEST_F(JoynrMessageSenderTest, DISABLED_sendSubscriptionReply_normal){ std::string payload("subscriptionReply"); EXPECT_CALL(*(messagingStub.get()), route(AllOf(Property(&JoynrMessage::getType, Eq(JoynrMessage::VALUE_MESSAGE_TYPE_SUBSCRIPTION_REPLY)), Property(&JoynrMessage::getPayload, Eq(payload))),_)); JoynrMessageSender joynrMessageSender(messagingStub); joynrMessageSender.registerDispatcher(&mockDispatcher); // joynrMessageSender.sendSubscriptionReply(util::createUuid(), payload, senderID, receiverID, qosSettings); } TEST_F(JoynrMessageSenderTest, sendPublication_normal){ JoynrMessageSender joynrMessageSender(messagingStub); joynrMessageSender.registerDispatcher(&mockDispatcher); SubscriptionPublication publication; publication.setSubscriptionId("ignoresubscriptionid"); publication.setResponse(std::string("publication")); JoynrMessage message = messageFactory.createSubscriptionPublication( senderID, receiverID, qosSettings, publication); EXPECT_CALL(*(messagingStub.get()), route(AllOf(Property(&JoynrMessage::getType, Eq(JoynrMessage::VALUE_MESSAGE_TYPE_PUBLICATION)), Property(&JoynrMessage::getPayload, Eq(message.getPayload()))),_)); joynrMessageSender.sendSubscriptionPublication(senderID, receiverID, qosSettings, std::move(publication)); } <|endoftext|>
<commit_before>// RUN: %clang_cc1 -DSETNODEBUG=0 -emit-llvm -debug-info-kind=limited %s -o - | FileCheck %s --check-prefix=YESINFO // RUN: %clang_cc1 -DSETNODEBUG=1 -emit-llvm -debug-info-kind=limited %s -o - | FileCheck %s --check-prefix=NOINFO #if SETNODEBUG #define NODEBUG __attribute__((nodebug)) #else #define NODEBUG #endif // Const global variable. Use it so it gets emitted. NODEBUG static const int const_global_int_def = 1; void func1(int); void func2() { func1(const_global_int_def); } // YESINFO-DAG: !DIGlobalVariable(name: "const_global_int_def" // NOINFO-NOT: !DIGlobalVariable(name: "const_global_int_def" // Global variable with a more involved type. // If the variable has no debug info, the type should not appear either. struct S1 { int a; int b; }; NODEBUG S1 global_struct = { 2, 3 }; // YESINFO-DAG: !DICompositeType({{.*}} name: "S1" // NOINFO-NOT: !DICompositeType({{.*}} name: "S1" // YESINFO-DAG: !DIGlobalVariable(name: "global_struct" // NOINFO-NOT: !DIGlobalVariable(name: "global_struct" // Static data members. Const member needs a use. struct S2 { NODEBUG static int static_member; NODEBUG static const int static_const_member = 4; }; int S2::static_member = 5; void func3() { func1(S2::static_const_member); } // YESINFO-DAG: !DIGlobalVariable(name: "static_member" // NOINFO-NOT: !DIGlobalVariable(name: "static_member" // YESINFO-DAG: !DIDerivedType({{.*}} name: "static_const_member" // NOINFO-NOT: !DIDerivedType({{.*}} name: "static_const_member" // Function-local static variable. void func4() { NODEBUG static int static_local = 6; } // YESINFO-DAG: !DIGlobalVariable(name: "static_local" // NOINFO-NOT: !DIGlobalVariable(name: "static_local" <commit_msg>Make the test exercise all paths modified in r267746.<commit_after>// RUN: %clang_cc1 -DSETNODEBUG=0 -emit-llvm -debug-info-kind=limited %s -o - | FileCheck %s --check-prefix=YESINFO // RUN: %clang_cc1 -DSETNODEBUG=1 -emit-llvm -debug-info-kind=limited %s -o - | FileCheck %s --check-prefix=NOINFO #if SETNODEBUG #define NODEBUG __attribute__((nodebug)) #else #define NODEBUG #endif // Const global variable. Use it so it gets emitted. NODEBUG static const int const_global_int_def = 1; void func1(int); void func2() { func1(const_global_int_def); } // YESINFO-DAG: !DIGlobalVariable(name: "const_global_int_def" // NOINFO-NOT: !DIGlobalVariable(name: "const_global_int_def" // Global variable with a more involved type. // If the variable has no debug info, the type should not appear either. struct S1 { int a; int b; }; NODEBUG S1 global_struct = { 2, 3 }; // YESINFO-DAG: !DICompositeType({{.*}} name: "S1" // NOINFO-NOT: !DICompositeType({{.*}} name: "S1" // YESINFO-DAG: !DIGlobalVariable(name: "global_struct" // NOINFO-NOT: !DIGlobalVariable(name: "global_struct" // Static data members. Const member needs a use. // Also the class as a whole needs a use, so that we produce debug info for // the entire class (iterating over the members, demonstrably skipping those // with 'nodebug'). struct S2 { NODEBUG static int static_member; NODEBUG static const int static_const_member = 4; }; int S2::static_member = 5; void func3() { S2 junk; func1(S2::static_const_member); } // YESINFO-DAG: !DIGlobalVariable(name: "static_member" // NOINFO-NOT: !DIGlobalVariable(name: "static_member" // YESINFO-DAG: !DIDerivedType({{.*}} name: "static_const_member" // NOINFO-NOT: !DIDerivedType({{.*}} name: "static_const_member" // Function-local static variable. void func4() { NODEBUG static int static_local = 6; } // YESINFO-DAG: !DIGlobalVariable(name: "static_local" // NOINFO-NOT: !DIGlobalVariable(name: "static_local" <|endoftext|>
<commit_before>/* * Copyright 2019 The Open GEE Contributors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "AssetVersion.h" #include "gee_version.h" #include "StateUpdater.h" #include <algorithm> #include <assert.h> #include <gtest/gtest.h> #include <map> #include <string> using namespace std; // All refs must end with "?version=X" or the calls to AssetVersionRef::Bind // will try to load assets from disk. For simplicity, we force everything to // be version 1. When you write additional tests you have to remember to call // this function when working directly with the state updater. const string SUFFIX = "?version=1"; AssetKey fix(AssetKey ref) { return ref.toString() + SUFFIX; } class MockVersion : public AssetVersionImpl { public: bool stateSet; bool loadedMutable; vector<AssetKey> dependents; MockVersion() : stateSet(false), loadedMutable(false) { type = AssetDefs::Imagery; state = AssetDefs::Blocked; } MockVersion(const AssetKey & ref) : MockVersion() { name = fix(ref); } MockVersion(const MockVersion & that) : MockVersion() { name = that.name; // Don't add the suffix - the other MockVersion already did } void DependentChildren(vector<SharedString> & d) const { for(auto dependent : dependents) { d.push_back(dependent); } } bool NeedComputeState() const { return true; } AssetDefs::State CalcStateByInputsAndChildren( AssetDefs::State stateByInputs, AssetDefs::State stateByChildren, bool blockersAreOffline, uint32 numWaitingFor) const { return AssetDefs::InProgress; } void SetMyStateOnly(AssetDefs::State newState, bool sendNotifications) { stateSet = true; } // Not used - only included to make MockVersion non-virtual string PluginName(void) const { return string(); } void GetOutputFilenames(vector<string> &) const {} string GetOutputFilename(uint) const { return string(); } }; using VersionMap = map<AssetKey, shared_ptr<MockVersion>>; class MockStorageManager : public StorageManagerInterface<AssetVersionImpl> { private: VersionMap versions; PointerType GetFromMap(const AssetKey & ref) { auto versionIter = versions.find(ref); if (versionIter != versions.end()) { auto version = dynamic_pointer_cast<AssetVersionImpl>(versionIter->second); assert(version); return version; } assert(false); return nullptr; } public: void AddVersion(const AssetKey & key, const MockVersion & v) { versions[key] = make_shared<MockVersion>(v); } virtual AssetHandle<const AssetVersionImpl> Get(const AssetKey &ref) { return AssetHandle<const AssetVersionImpl>(GetFromMap(ref), nullptr); } virtual AssetHandle<AssetVersionImpl> GetMutable(const AssetKey &ref) { auto handle = AssetHandle<AssetVersionImpl>(GetFromMap(ref), nullptr); dynamic_cast<MockVersion*>(handle.operator->())->loadedMutable = true; return handle; } void ResetLoadedMutable() { for (auto & v : versions) { v.second->loadedMutable = false; } } }; class StateUpdaterTest : public testing::Test { protected: MockStorageManager sm; StateUpdater updater; public: StateUpdaterTest() : sm(), updater(&sm) {} }; void SetVersions(MockStorageManager & sm, vector<MockVersion> versions) { for (auto & version: versions) { sm.AddVersion(version.name, version); } } // This is bad because technically the object could be deleted before you use // it, but it works for unit tests. AssetHandle<const MockVersion> GetVersion(MockStorageManager & sm, const AssetKey & key) { return sm.Get(fix(key)); } void SetParentChild(MockStorageManager & sm, AssetKey parent, AssetKey child) { parent = fix(parent); child = fix(child); sm.GetMutable(parent)->children.push_back(child); sm.GetMutable(child)->parents.push_back(parent); } void SetListenerInput(MockStorageManager & sm, AssetKey listener, AssetKey input) { listener = fix(listener); input = fix(input); sm.GetMutable(listener)->inputs.push_back(input); sm.GetMutable(input)->listeners.push_back(listener); } void SetDependent(MockStorageManager & sm, AssetKey dependee, AssetKey dependent) { dependee = fix(dependee); dependent = fix(dependent); AssetHandle<MockVersion> dependeeHandle = sm.GetMutable(dependee); dependeeHandle->dependents.push_back(dependent); } void GetBigTree(MockStorageManager & sm) { SetVersions(sm, { MockVersion("gp"), MockVersion("p1"), MockVersion("p2"), MockVersion("gpi"), MockVersion("pi1"), MockVersion("c1"), MockVersion("c2"), MockVersion("c3"), MockVersion("c4"), MockVersion("ci1"), MockVersion("ci2"), MockVersion("ci3") }); SetParentChild(sm, "gp", "p1"); SetParentChild(sm, "gp", "p2"); SetListenerInput(sm, "gp", "gpi"); SetListenerInput(sm, "p1", "pi1"); SetParentChild(sm, "p1", "c1"); SetParentChild(sm, "p1", "c2"); SetParentChild(sm, "p2", "c3"); SetParentChild(sm, "p2", "c4"); SetListenerInput(sm, "c2", "ci3"); SetListenerInput(sm, "c4", "ci1"); SetListenerInput(sm, "c4", "ci2"); SetDependent(sm, "gp", "p1"); SetDependent(sm, "gp", "c2"); SetDependent(sm, "p1", "c1"); } TEST_F(StateUpdaterTest, SetStateSingleVersion) { AssetKey ref1 = "test1"; AssetKey ref2 = "test2"; AssetKey ref3 = "test3"; SetVersions(sm, {MockVersion(ref1), MockVersion(ref2), MockVersion(ref3)}); updater.SetStateForRefAndDependents(fix(ref1), AssetDefs::Bad, [](AssetDefs::State) { return true; }); ASSERT_TRUE(GetVersion(sm, ref1)->stateSet); ASSERT_FALSE(GetVersion(sm, ref2)->stateSet); ASSERT_FALSE(GetVersion(sm, ref3)->stateSet); updater.SetStateForRefAndDependents(fix(ref2), AssetDefs::Bad, [](AssetDefs::State) { return false; }); ASSERT_FALSE(GetVersion(sm, ref2)->stateSet); ASSERT_FALSE(GetVersion(sm, ref3)->stateSet); } TEST_F(StateUpdaterTest, SetStateMultipleVersions) { GetBigTree(sm); updater.SetStateForRefAndDependents(fix("gp"), AssetDefs::Canceled, [](AssetDefs::State) {return true; }); ASSERT_TRUE(GetVersion(sm, "gp")->stateSet); ASSERT_TRUE(GetVersion(sm, "p1")->stateSet); ASSERT_TRUE(GetVersion(sm, "c1")->stateSet); ASSERT_TRUE(GetVersion(sm, "c2")->stateSet); ASSERT_FALSE(GetVersion(sm, "gpi")->stateSet); ASSERT_FALSE(GetVersion(sm, "pi1")->stateSet); ASSERT_FALSE(GetVersion(sm, "c3")->stateSet); ASSERT_FALSE(GetVersion(sm, "c4")->stateSet); ASSERT_FALSE(GetVersion(sm, "ci1")->stateSet); ASSERT_FALSE(GetVersion(sm, "ci2")->stateSet); ASSERT_FALSE(GetVersion(sm, "ci3")->stateSet); } TEST_F(StateUpdaterTest, SetStateMultipleVersionsFromChild) { GetBigTree(sm); sm.ResetLoadedMutable(); updater.SetStateForRefAndDependents(fix("p1"), AssetDefs::Canceled, [](AssetDefs::State) {return true; }); ASSERT_TRUE(GetVersion(sm, "p1")->stateSet); ASSERT_TRUE(GetVersion(sm, "c1")->stateSet); ASSERT_FALSE(GetVersion(sm, "gp")->stateSet); ASSERT_FALSE(GetVersion(sm, "gpi")->stateSet); ASSERT_FALSE(GetVersion(sm, "pi1")->stateSet); ASSERT_FALSE(GetVersion(sm, "c2")->stateSet); ASSERT_FALSE(GetVersion(sm, "c3")->stateSet); ASSERT_FALSE(GetVersion(sm, "c4")->stateSet); ASSERT_FALSE(GetVersion(sm, "ci1")->stateSet); ASSERT_FALSE(GetVersion(sm, "ci2")->stateSet); ASSERT_FALSE(GetVersion(sm, "ci3")->stateSet); ASSERT_TRUE(GetVersion(sm, "p1")->loadedMutable); ASSERT_TRUE(GetVersion(sm, "c1")->loadedMutable); ASSERT_FALSE(GetVersion(sm, "gp")->loadedMutable); ASSERT_FALSE(GetVersion(sm, "gpi")->loadedMutable); ASSERT_FALSE(GetVersion(sm, "pi1")->loadedMutable); ASSERT_FALSE(GetVersion(sm, "c2")->loadedMutable); ASSERT_FALSE(GetVersion(sm, "c3")->loadedMutable); ASSERT_FALSE(GetVersion(sm, "c4")->loadedMutable); ASSERT_FALSE(GetVersion(sm, "ci1")->loadedMutable); ASSERT_FALSE(GetVersion(sm, "ci2")->loadedMutable); ASSERT_FALSE(GetVersion(sm, "ci3")->loadedMutable); } int main(int argc, char **argv) { testing::InitGoogleTest(&argc,argv); return RUN_ALL_TESTS(); } <commit_msg>Test states that do and don't change<commit_after>/* * Copyright 2019 The Open GEE Contributors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "AssetVersion.h" #include "gee_version.h" #include "StateUpdater.h" #include <algorithm> #include <assert.h> #include <gtest/gtest.h> #include <map> #include <string> using namespace std; // All refs must end with "?version=X" or the calls to AssetVersionRef::Bind // will try to load assets from disk. For simplicity, we force everything to // be version 1. When you write additional tests you have to remember to call // this function when working directly with the state updater. const string SUFFIX = "?version=1"; AssetKey fix(AssetKey ref) { return ref.toString() + SUFFIX; } class MockVersion : public AssetVersionImpl { public: bool stateSet; bool loadedMutable; vector<AssetKey> dependents; MockVersion() : stateSet(false), loadedMutable(false) { type = AssetDefs::Imagery; state = AssetDefs::Blocked; } MockVersion(const AssetKey & ref) : MockVersion() { name = fix(ref); } MockVersion(const MockVersion & that) : MockVersion() { name = that.name; // Don't add the suffix - the other MockVersion already did } void DependentChildren(vector<SharedString> & d) const { for(auto dependent : dependents) { d.push_back(dependent); } } bool NeedComputeState() const { return true; } AssetDefs::State CalcStateByInputsAndChildren( AssetDefs::State stateByInputs, AssetDefs::State stateByChildren, bool blockersAreOffline, uint32 numWaitingFor) const { return AssetDefs::InProgress; } void SetMyStateOnly(AssetDefs::State newState, bool sendNotifications) { stateSet = true; } // Not used - only included to make MockVersion non-virtual string PluginName(void) const { return string(); } void GetOutputFilenames(vector<string> &) const {} string GetOutputFilename(uint) const { return string(); } }; using VersionMap = map<AssetKey, shared_ptr<MockVersion>>; class MockStorageManager : public StorageManagerInterface<AssetVersionImpl> { private: VersionMap versions; PointerType GetFromMap(const AssetKey & ref) { auto versionIter = versions.find(ref); if (versionIter != versions.end()) { auto version = dynamic_pointer_cast<AssetVersionImpl>(versionIter->second); assert(version); return version; } assert(false); return nullptr; } public: void AddVersion(const AssetKey & key, const MockVersion & v) { versions[key] = make_shared<MockVersion>(v); } virtual AssetHandle<const AssetVersionImpl> Get(const AssetKey &ref) { return AssetHandle<const AssetVersionImpl>(GetFromMap(ref), nullptr); } virtual AssetHandle<AssetVersionImpl> GetMutable(const AssetKey &ref) { auto handle = AssetHandle<AssetVersionImpl>(GetFromMap(ref), nullptr); dynamic_cast<MockVersion*>(handle.operator->())->loadedMutable = true; return handle; } void ResetLoadedMutable() { for (auto & v : versions) { v.second->loadedMutable = false; } } }; class StateUpdaterTest : public testing::Test { protected: MockStorageManager sm; StateUpdater updater; public: StateUpdaterTest() : sm(), updater(&sm) {} }; void SetVersions(MockStorageManager & sm, vector<MockVersion> versions) { for (auto & version: versions) { sm.AddVersion(version.name, version); } } // This is bad because technically the object could be deleted before you use // it, but it works for unit tests. AssetHandle<const MockVersion> GetVersion(MockStorageManager & sm, const AssetKey & key) { return sm.Get(fix(key)); } void SetParentChild(MockStorageManager & sm, AssetKey parent, AssetKey child) { parent = fix(parent); child = fix(child); sm.GetMutable(parent)->children.push_back(child); sm.GetMutable(child)->parents.push_back(parent); } void SetListenerInput(MockStorageManager & sm, AssetKey listener, AssetKey input) { listener = fix(listener); input = fix(input); sm.GetMutable(listener)->inputs.push_back(input); sm.GetMutable(input)->listeners.push_back(listener); } void SetDependent(MockStorageManager & sm, AssetKey dependee, AssetKey dependent) { dependee = fix(dependee); dependent = fix(dependent); AssetHandle<MockVersion> dependeeHandle = sm.GetMutable(dependee); dependeeHandle->dependents.push_back(dependent); } void GetBigTree(MockStorageManager & sm) { SetVersions(sm, { MockVersion("gp"), MockVersion("p1"), MockVersion("p2"), MockVersion("gpi"), MockVersion("pi1"), MockVersion("c1"), MockVersion("c2"), MockVersion("c3"), MockVersion("c4"), MockVersion("ci1"), MockVersion("ci2"), MockVersion("ci3") }); SetParentChild(sm, "gp", "p1"); SetParentChild(sm, "gp", "p2"); SetListenerInput(sm, "gp", "gpi"); SetListenerInput(sm, "p1", "pi1"); SetParentChild(sm, "p1", "c1"); SetParentChild(sm, "p1", "c2"); SetParentChild(sm, "p2", "c3"); SetParentChild(sm, "p2", "c4"); SetListenerInput(sm, "c2", "ci3"); SetListenerInput(sm, "c4", "ci1"); SetListenerInput(sm, "c4", "ci2"); SetDependent(sm, "gp", "p1"); SetDependent(sm, "gp", "c2"); SetDependent(sm, "p1", "c1"); } TEST_F(StateUpdaterTest, SetStateSingleVersion) { AssetKey ref1 = "test1"; AssetKey ref2 = "test2"; AssetKey ref3 = "test3"; SetVersions(sm, {MockVersion(ref1), MockVersion(ref2), MockVersion(ref3)}); updater.SetStateForRefAndDependents(fix(ref1), AssetDefs::Bad, [](AssetDefs::State) { return true; }); ASSERT_TRUE(GetVersion(sm, ref1)->stateSet); ASSERT_FALSE(GetVersion(sm, ref2)->stateSet); ASSERT_FALSE(GetVersion(sm, ref3)->stateSet); updater.SetStateForRefAndDependents(fix(ref2), AssetDefs::Bad, [](AssetDefs::State) { return false; }); ASSERT_FALSE(GetVersion(sm, ref2)->stateSet); ASSERT_FALSE(GetVersion(sm, ref3)->stateSet); } TEST_F(StateUpdaterTest, SetStateMultipleVersions) { GetBigTree(sm); updater.SetStateForRefAndDependents(fix("gp"), AssetDefs::Canceled, [](AssetDefs::State) {return true; }); ASSERT_TRUE(GetVersion(sm, "gp")->stateSet); ASSERT_TRUE(GetVersion(sm, "p1")->stateSet); ASSERT_TRUE(GetVersion(sm, "c1")->stateSet); ASSERT_TRUE(GetVersion(sm, "c2")->stateSet); ASSERT_FALSE(GetVersion(sm, "gpi")->stateSet); ASSERT_FALSE(GetVersion(sm, "pi1")->stateSet); ASSERT_FALSE(GetVersion(sm, "c3")->stateSet); ASSERT_FALSE(GetVersion(sm, "c4")->stateSet); ASSERT_FALSE(GetVersion(sm, "ci1")->stateSet); ASSERT_FALSE(GetVersion(sm, "ci2")->stateSet); ASSERT_FALSE(GetVersion(sm, "ci3")->stateSet); } TEST_F(StateUpdaterTest, SetStateMultipleVersionsFromChild) { GetBigTree(sm); sm.ResetLoadedMutable(); updater.SetStateForRefAndDependents(fix("p1"), AssetDefs::Canceled, [](AssetDefs::State) { return true; }); ASSERT_TRUE(GetVersion(sm, "p1")->stateSet); ASSERT_TRUE(GetVersion(sm, "c1")->stateSet); ASSERT_FALSE(GetVersion(sm, "gp")->stateSet); ASSERT_FALSE(GetVersion(sm, "gpi")->stateSet); ASSERT_FALSE(GetVersion(sm, "pi1")->stateSet); ASSERT_FALSE(GetVersion(sm, "c2")->stateSet); ASSERT_FALSE(GetVersion(sm, "c3")->stateSet); ASSERT_FALSE(GetVersion(sm, "c4")->stateSet); ASSERT_FALSE(GetVersion(sm, "ci1")->stateSet); ASSERT_FALSE(GetVersion(sm, "ci2")->stateSet); ASSERT_FALSE(GetVersion(sm, "ci3")->stateSet); ASSERT_TRUE(GetVersion(sm, "p1")->loadedMutable); ASSERT_TRUE(GetVersion(sm, "c1")->loadedMutable); ASSERT_FALSE(GetVersion(sm, "gp")->loadedMutable); ASSERT_FALSE(GetVersion(sm, "gpi")->loadedMutable); ASSERT_FALSE(GetVersion(sm, "pi1")->loadedMutable); ASSERT_FALSE(GetVersion(sm, "c2")->loadedMutable); ASSERT_FALSE(GetVersion(sm, "c3")->loadedMutable); ASSERT_FALSE(GetVersion(sm, "c4")->loadedMutable); ASSERT_FALSE(GetVersion(sm, "ci1")->loadedMutable); ASSERT_FALSE(GetVersion(sm, "ci2")->loadedMutable); ASSERT_FALSE(GetVersion(sm, "ci3")->loadedMutable); } TEST_F(StateUpdaterTest, SetState_StateDoesAndDoesntChange) { const AssetDefs::State SET_TO_STATE = AssetDefs::InProgress; const AssetDefs::State STARTING_STATE = AssetDefs::Canceled; SetVersions(sm, {MockVersion("a"), MockVersion("b")}); sm.GetMutable(fix("a"))->state = SET_TO_STATE; sm.GetMutable(fix("b"))->state = STARTING_STATE; updater.SetStateForRefAndDependents(fix("a"), SET_TO_STATE, [](AssetDefs::State) { return true; }); ASSERT_FALSE(GetVersion(sm, "a")->stateSet); ASSERT_FALSE(GetVersion(sm, "b")->stateSet); updater.SetStateForRefAndDependents(fix("b"), SET_TO_STATE, [](AssetDefs::State) { return true; }); ASSERT_FALSE(GetVersion(sm, "a")->stateSet); ASSERT_TRUE(GetVersion(sm, "b")->stateSet); } int main(int argc, char **argv) { testing::InitGoogleTest(&argc,argv); return RUN_ALL_TESTS(); } <|endoftext|>
<commit_before>/* * Copyright 2019 The Open GEE Contributors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "AssetVersion.h" #include "gee_version.h" #include "StateUpdater.h" #include <algorithm> #include <assert.h> #include <gtest/gtest.h> #include <map> #include <string> using namespace std; // All refs must end with "?version=X" or the calls to AssetVersionRef::Bind // will try to load assets from disk. For simplicity, we force everything to // be version 1. When you write additional tests you have to remember to call // this function when working directly with the state updater. const string SUFFIX = "?version=1"; AssetKey fix(AssetKey ref) { return ref.toString() + SUFFIX; } const AssetDefs::State STARTING_STATE = AssetDefs::Blocked; const AssetDefs::State CALCULATED_STATE = AssetDefs::InProgress; class MockVersion : public AssetVersionImpl { public: bool stateSet; bool loadedMutable; bool notificationsSent; bool needComputeState; vector<AssetKey> dependents; MockVersion() : stateSet(false), loadedMutable(false), notificationsSent(false), needComputeState(true) { type = AssetDefs::Imagery; state = STARTING_STATE; } MockVersion(const AssetKey & ref) : MockVersion() { name = fix(ref); } MockVersion(const MockVersion & that) : MockVersion() { name = that.name; // Don't add the suffix - the other MockVersion already did } void DependentChildren(vector<SharedString> & d) const { for(auto dependent : dependents) { d.push_back(dependent); } } bool NeedComputeState() const { return needComputeState; } AssetDefs::State CalcStateByInputsAndChildren( AssetDefs::State stateByInputs, AssetDefs::State stateByChildren, bool blockersAreOffline, uint32 numWaitingFor) const { return CALCULATED_STATE; } void SetMyStateOnly(AssetDefs::State newState, bool sendNotifications) { stateSet = true; notificationsSent = sendNotifications; } // Not used - only included to make MockVersion non-virtual string PluginName(void) const { return string(); } void GetOutputFilenames(vector<string> &) const {} string GetOutputFilename(uint) const { return string(); } }; using VersionMap = map<AssetKey, shared_ptr<MockVersion>>; class MockStorageManager : public StorageManagerInterface<AssetVersionImpl> { private: VersionMap versions; PointerType GetFromMap(const AssetKey & ref) { auto versionIter = versions.find(ref); if (versionIter != versions.end()) { auto version = dynamic_pointer_cast<AssetVersionImpl>(versionIter->second); assert(version); return version; } assert(false); return nullptr; } public: void AddVersion(const AssetKey & key, const MockVersion & v) { versions[key] = make_shared<MockVersion>(v); } virtual AssetHandle<const AssetVersionImpl> Get(const AssetKey &ref) { return AssetHandle<const AssetVersionImpl>(GetFromMap(ref), nullptr); } virtual AssetHandle<AssetVersionImpl> GetMutable(const AssetKey &ref) { auto handle = AssetHandle<AssetVersionImpl>(GetFromMap(ref), nullptr); dynamic_cast<MockVersion*>(handle.operator->())->loadedMutable = true; return handle; } void ResetLoadedMutable() { for (auto & v : versions) { v.second->loadedMutable = false; } } }; class StateUpdaterTest : public testing::Test { protected: MockStorageManager sm; StateUpdater updater; public: StateUpdaterTest() : sm(), updater(&sm) {} }; void SetVersions(MockStorageManager & sm, vector<MockVersion> versions) { for (auto & version: versions) { sm.AddVersion(version.name, version); } } AssetHandle<const MockVersion> GetVersion(MockStorageManager & sm, const AssetKey & key) { return sm.Get(fix(key)); } AssetHandle<MockVersion> GetMutableVersion(MockStorageManager & sm, const AssetKey & key) { return sm.GetMutable(fix(key)); } void SetParentChild(MockStorageManager & sm, AssetKey parent, AssetKey child) { GetMutableVersion(sm, parent)->children.push_back(fix(child)); GetMutableVersion(sm, child)->parents.push_back(fix(parent)); } void SetListenerInput(MockStorageManager & sm, AssetKey listener, AssetKey input) { GetMutableVersion(sm, listener)->inputs.push_back(fix(input)); GetMutableVersion(sm, input)->listeners.push_back(fix(listener)); } void SetDependent(MockStorageManager & sm, AssetKey dependee, AssetKey dependent) { GetMutableVersion(sm, dependee)->dependents.push_back(fix(dependent)); } void GetBigTree(MockStorageManager & sm) { SetVersions(sm, { MockVersion("gp"), MockVersion("p1"), MockVersion("p2"), MockVersion("gpi"), MockVersion("pi1"), MockVersion("c1"), MockVersion("c2"), MockVersion("c3"), MockVersion("c4"), MockVersion("ci1"), MockVersion("ci2"), MockVersion("ci3") }); SetParentChild(sm, "gp", "p1"); SetParentChild(sm, "gp", "p2"); SetListenerInput(sm, "gp", "gpi"); SetListenerInput(sm, "p1", "pi1"); SetParentChild(sm, "p1", "c1"); SetParentChild(sm, "p1", "c2"); SetParentChild(sm, "p2", "c3"); SetParentChild(sm, "p2", "c4"); SetListenerInput(sm, "c2", "ci3"); SetListenerInput(sm, "c4", "ci1"); SetListenerInput(sm, "c4", "ci2"); SetDependent(sm, "gp", "p1"); SetDependent(sm, "gp", "c2"); SetDependent(sm, "p1", "c1"); } TEST_F(StateUpdaterTest, SetStateSingleVersion) { AssetKey ref1 = "test1"; AssetKey ref2 = "test2"; AssetKey ref3 = "test3"; SetVersions(sm, {MockVersion(ref1), MockVersion(ref2), MockVersion(ref3)}); updater.SetStateForRefAndDependents(fix(ref1), AssetDefs::Bad, [](AssetDefs::State) { return true; }); ASSERT_TRUE(GetVersion(sm, ref1)->stateSet); ASSERT_FALSE(GetVersion(sm, ref2)->stateSet); ASSERT_FALSE(GetVersion(sm, ref3)->stateSet); updater.SetStateForRefAndDependents(fix(ref2), AssetDefs::Bad, [](AssetDefs::State) { return false; }); ASSERT_FALSE(GetVersion(sm, ref2)->stateSet); ASSERT_FALSE(GetVersion(sm, ref3)->stateSet); } TEST_F(StateUpdaterTest, SetStateMultipleVersions) { GetBigTree(sm); updater.SetStateForRefAndDependents(fix("gp"), AssetDefs::Canceled, [](AssetDefs::State) {return true; }); ASSERT_TRUE(GetVersion(sm, "gp")->stateSet); ASSERT_TRUE(GetVersion(sm, "p1")->stateSet); ASSERT_TRUE(GetVersion(sm, "c1")->stateSet); ASSERT_TRUE(GetVersion(sm, "c2")->stateSet); ASSERT_FALSE(GetVersion(sm, "gpi")->stateSet); ASSERT_FALSE(GetVersion(sm, "pi1")->stateSet); ASSERT_FALSE(GetVersion(sm, "c3")->stateSet); ASSERT_FALSE(GetVersion(sm, "c4")->stateSet); ASSERT_FALSE(GetVersion(sm, "ci1")->stateSet); ASSERT_FALSE(GetVersion(sm, "ci2")->stateSet); ASSERT_FALSE(GetVersion(sm, "ci3")->stateSet); ASSERT_FALSE(GetVersion(sm, "gp")->notificationsSent); ASSERT_FALSE(GetVersion(sm, "p1")->notificationsSent); ASSERT_FALSE(GetVersion(sm, "c1")->notificationsSent); ASSERT_FALSE(GetVersion(sm, "c2")->notificationsSent); } TEST_F(StateUpdaterTest, SetStateMultipleVersionsFromChild) { GetBigTree(sm); sm.ResetLoadedMutable(); updater.SetStateForRefAndDependents(fix("p1"), AssetDefs::Canceled, [](AssetDefs::State) { return true; }); ASSERT_TRUE(GetVersion(sm, "p1")->stateSet); ASSERT_TRUE(GetVersion(sm, "c1")->stateSet); ASSERT_FALSE(GetVersion(sm, "gp")->stateSet); ASSERT_FALSE(GetVersion(sm, "gpi")->stateSet); ASSERT_FALSE(GetVersion(sm, "pi1")->stateSet); ASSERT_FALSE(GetVersion(sm, "c2")->stateSet); ASSERT_FALSE(GetVersion(sm, "c3")->stateSet); ASSERT_FALSE(GetVersion(sm, "c4")->stateSet); ASSERT_FALSE(GetVersion(sm, "ci1")->stateSet); ASSERT_FALSE(GetVersion(sm, "ci2")->stateSet); ASSERT_FALSE(GetVersion(sm, "ci3")->stateSet); ASSERT_TRUE(GetVersion(sm, "p1")->loadedMutable); ASSERT_TRUE(GetVersion(sm, "c1")->loadedMutable); ASSERT_FALSE(GetVersion(sm, "gp")->loadedMutable); ASSERT_FALSE(GetVersion(sm, "gpi")->loadedMutable); ASSERT_FALSE(GetVersion(sm, "pi1")->loadedMutable); ASSERT_FALSE(GetVersion(sm, "c2")->loadedMutable); ASSERT_FALSE(GetVersion(sm, "c3")->loadedMutable); ASSERT_FALSE(GetVersion(sm, "c4")->loadedMutable); ASSERT_FALSE(GetVersion(sm, "ci1")->loadedMutable); ASSERT_FALSE(GetVersion(sm, "ci2")->loadedMutable); ASSERT_FALSE(GetVersion(sm, "ci3")->loadedMutable); } TEST_F(StateUpdaterTest, SetState_StateDoesAndDoesntChange) { SetVersions(sm, {MockVersion("a"), MockVersion("b")}); GetMutableVersion(sm, "a")->state = CALCULATED_STATE; GetMutableVersion(sm, "b")->state = STARTING_STATE; updater.SetStateForRefAndDependents(fix("a"), CALCULATED_STATE, [](AssetDefs::State) { return true; }); ASSERT_FALSE(GetVersion(sm, "a")->stateSet); ASSERT_FALSE(GetVersion(sm, "b")->stateSet); updater.SetStateForRefAndDependents(fix("b"), CALCULATED_STATE, [](AssetDefs::State) { return true; }); ASSERT_FALSE(GetVersion(sm, "a")->stateSet); ASSERT_TRUE(GetVersion(sm, "b")->stateSet); } TEST_F(StateUpdaterTest, SetStatePredicate) { SetVersions(sm, {MockVersion("a"), MockVersion("b")}); GetMutableVersion(sm, "a")->state = AssetDefs::Bad; GetMutableVersion(sm, "b")->state = AssetDefs::Canceled; SetDependent(sm, "a", "b"); updater.SetStateForRefAndDependents(fix("a"), AssetDefs::Succeeded, [](AssetDefs::State state) { return state != AssetDefs::Canceled; }); ASSERT_TRUE(GetVersion(sm, "a")->stateSet); ASSERT_FALSE(GetVersion(sm, "b")->stateSet); } TEST_F(StateUpdaterTest, NeedComputeStateFalse) { SetVersions(sm, {MockVersion("a")}); updater.SetStateForRefAndDependents(fix("a"), AssetDefs::Canceled, [](AssetDefs::State) { return true; }); GetMutableVersion(sm, "a")->needComputeState = false; GetMutableVersion(sm, "a")->stateSet = false; updater.RecalculateAndSaveStates(); ASSERT_FALSE(GetVersion(sm, "a")->stateSet); GetMutableVersion(sm, "a")->needComputeState = true; updater.RecalculateAndSaveStates(); ASSERT_TRUE(GetVersion(sm, "a")->stateSet); ASSERT_TRUE(GetVersion(sm, "a")->notificationsSent); } TEST_F(StateUpdaterTest, RecalculateState_StateDoesAndDoesntChange) { SetVersions(sm, {MockVersion("a"), MockVersion("b")}); GetMutableVersion(sm, "a")->state = CALCULATED_STATE; GetMutableVersion(sm, "b")->state = STARTING_STATE; SetListenerInput(sm, "a", "b"); updater.SetStateForRefAndDependents(fix("a"), CALCULATED_STATE, [](AssetDefs::State) { return false; }); // Verify that the setup is correct ASSERT_FALSE(GetVersion(sm, "a")->stateSet); ASSERT_FALSE(GetVersion(sm, "b")->stateSet); updater.RecalculateAndSaveStates(); ASSERT_FALSE(GetVersion(sm, "a")->stateSet); ASSERT_TRUE(GetVersion(sm, "b")->stateSet); } int main(int argc, char **argv) { testing::InitGoogleTest(&argc,argv); return RUN_ALL_TESTS(); } <commit_msg>Make sure assets aren't unnecessarily loaded as mutable<commit_after>/* * Copyright 2019 The Open GEE Contributors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "AssetVersion.h" #include "gee_version.h" #include "StateUpdater.h" #include <algorithm> #include <assert.h> #include <gtest/gtest.h> #include <map> #include <string> using namespace std; // All refs must end with "?version=X" or the calls to AssetVersionRef::Bind // will try to load assets from disk. For simplicity, we force everything to // be version 1. When you write additional tests you have to remember to call // this function when working directly with the state updater. const string SUFFIX = "?version=1"; AssetKey fix(AssetKey ref) { return ref.toString() + SUFFIX; } const AssetDefs::State STARTING_STATE = AssetDefs::Blocked; const AssetDefs::State CALCULATED_STATE = AssetDefs::InProgress; class MockVersion : public AssetVersionImpl { public: bool stateSet; bool loadedMutable; bool notificationsSent; bool needComputeState; vector<AssetKey> dependents; MockVersion() : stateSet(false), loadedMutable(false), notificationsSent(false), needComputeState(true) { type = AssetDefs::Imagery; state = STARTING_STATE; } MockVersion(const AssetKey & ref) : MockVersion() { name = fix(ref); } MockVersion(const MockVersion & that) : MockVersion() { name = that.name; // Don't add the suffix - the other MockVersion already did } void DependentChildren(vector<SharedString> & d) const { for(auto dependent : dependents) { d.push_back(dependent); } } bool NeedComputeState() const { return needComputeState; } AssetDefs::State CalcStateByInputsAndChildren( AssetDefs::State stateByInputs, AssetDefs::State stateByChildren, bool blockersAreOffline, uint32 numWaitingFor) const { return CALCULATED_STATE; } void SetMyStateOnly(AssetDefs::State newState, bool sendNotifications) { stateSet = true; notificationsSent = sendNotifications; } // Not used - only included to make MockVersion non-virtual string PluginName(void) const { return string(); } void GetOutputFilenames(vector<string> &) const {} string GetOutputFilename(uint) const { return string(); } }; using VersionMap = map<AssetKey, shared_ptr<MockVersion>>; class MockStorageManager : public StorageManagerInterface<AssetVersionImpl> { private: VersionMap versions; PointerType GetFromMap(const AssetKey & ref) { auto versionIter = versions.find(ref); if (versionIter != versions.end()) { auto version = dynamic_pointer_cast<AssetVersionImpl>(versionIter->second); assert(version); return version; } assert(false); return nullptr; } public: void AddVersion(const AssetKey & key, const MockVersion & v) { versions[key] = make_shared<MockVersion>(v); } virtual AssetHandle<const AssetVersionImpl> Get(const AssetKey &ref) { return AssetHandle<const AssetVersionImpl>(GetFromMap(ref), nullptr); } virtual AssetHandle<AssetVersionImpl> GetMutable(const AssetKey &ref) { auto handle = AssetHandle<AssetVersionImpl>(GetFromMap(ref), nullptr); dynamic_cast<MockVersion*>(handle.operator->())->loadedMutable = true; return handle; } void ResetLoadedMutable() { for (auto & v : versions) { v.second->loadedMutable = false; } } }; class StateUpdaterTest : public testing::Test { protected: MockStorageManager sm; StateUpdater updater; public: StateUpdaterTest() : sm(), updater(&sm) {} }; void SetVersions(MockStorageManager & sm, vector<MockVersion> versions) { for (auto & version: versions) { sm.AddVersion(version.name, version); } } AssetHandle<const MockVersion> GetVersion(MockStorageManager & sm, const AssetKey & key) { return sm.Get(fix(key)); } AssetHandle<MockVersion> GetMutableVersion(MockStorageManager & sm, const AssetKey & key) { return sm.GetMutable(fix(key)); } void SetParentChild(MockStorageManager & sm, AssetKey parent, AssetKey child) { GetMutableVersion(sm, parent)->children.push_back(fix(child)); GetMutableVersion(sm, child)->parents.push_back(fix(parent)); } void SetListenerInput(MockStorageManager & sm, AssetKey listener, AssetKey input) { GetMutableVersion(sm, listener)->inputs.push_back(fix(input)); GetMutableVersion(sm, input)->listeners.push_back(fix(listener)); } void SetDependent(MockStorageManager & sm, AssetKey dependee, AssetKey dependent) { GetMutableVersion(sm, dependee)->dependents.push_back(fix(dependent)); } void GetBigTree(MockStorageManager & sm) { SetVersions(sm, { MockVersion("gp"), MockVersion("p1"), MockVersion("p2"), MockVersion("gpi"), MockVersion("pi1"), MockVersion("c1"), MockVersion("c2"), MockVersion("c3"), MockVersion("c4"), MockVersion("ci1"), MockVersion("ci2"), MockVersion("ci3") }); SetParentChild(sm, "gp", "p1"); SetParentChild(sm, "gp", "p2"); SetListenerInput(sm, "gp", "gpi"); SetListenerInput(sm, "p1", "pi1"); SetParentChild(sm, "p1", "c1"); SetParentChild(sm, "p1", "c2"); SetParentChild(sm, "p2", "c3"); SetParentChild(sm, "p2", "c4"); SetListenerInput(sm, "c2", "ci3"); SetListenerInput(sm, "c4", "ci1"); SetListenerInput(sm, "c4", "ci2"); SetDependent(sm, "gp", "p1"); SetDependent(sm, "gp", "c2"); SetDependent(sm, "p1", "c1"); } TEST_F(StateUpdaterTest, SetStateSingleVersion) { AssetKey ref1 = "test1"; AssetKey ref2 = "test2"; AssetKey ref3 = "test3"; SetVersions(sm, {MockVersion(ref1), MockVersion(ref2), MockVersion(ref3)}); updater.SetStateForRefAndDependents(fix(ref1), AssetDefs::Bad, [](AssetDefs::State) { return true; }); ASSERT_TRUE(GetVersion(sm, ref1)->stateSet); ASSERT_FALSE(GetVersion(sm, ref2)->stateSet); ASSERT_FALSE(GetVersion(sm, ref3)->stateSet); updater.SetStateForRefAndDependents(fix(ref2), AssetDefs::Bad, [](AssetDefs::State) { return false; }); ASSERT_FALSE(GetVersion(sm, ref2)->stateSet); ASSERT_FALSE(GetVersion(sm, ref3)->stateSet); } TEST_F(StateUpdaterTest, SetStateMultipleVersions) { GetBigTree(sm); updater.SetStateForRefAndDependents(fix("gp"), AssetDefs::Canceled, [](AssetDefs::State) {return true; }); ASSERT_TRUE(GetVersion(sm, "gp")->stateSet); ASSERT_TRUE(GetVersion(sm, "p1")->stateSet); ASSERT_TRUE(GetVersion(sm, "c1")->stateSet); ASSERT_TRUE(GetVersion(sm, "c2")->stateSet); ASSERT_FALSE(GetVersion(sm, "gpi")->stateSet); ASSERT_FALSE(GetVersion(sm, "pi1")->stateSet); ASSERT_FALSE(GetVersion(sm, "c3")->stateSet); ASSERT_FALSE(GetVersion(sm, "c4")->stateSet); ASSERT_FALSE(GetVersion(sm, "ci1")->stateSet); ASSERT_FALSE(GetVersion(sm, "ci2")->stateSet); ASSERT_FALSE(GetVersion(sm, "ci3")->stateSet); ASSERT_FALSE(GetVersion(sm, "gp")->notificationsSent); ASSERT_FALSE(GetVersion(sm, "p1")->notificationsSent); ASSERT_FALSE(GetVersion(sm, "c1")->notificationsSent); ASSERT_FALSE(GetVersion(sm, "c2")->notificationsSent); } TEST_F(StateUpdaterTest, SetStateMultipleVersionsFromChild) { GetBigTree(sm); sm.ResetLoadedMutable(); updater.SetStateForRefAndDependents(fix("p1"), AssetDefs::Canceled, [](AssetDefs::State) { return true; }); ASSERT_TRUE(GetVersion(sm, "p1")->stateSet); ASSERT_TRUE(GetVersion(sm, "c1")->stateSet); ASSERT_FALSE(GetVersion(sm, "gp")->stateSet); ASSERT_FALSE(GetVersion(sm, "gpi")->stateSet); ASSERT_FALSE(GetVersion(sm, "pi1")->stateSet); ASSERT_FALSE(GetVersion(sm, "c2")->stateSet); ASSERT_FALSE(GetVersion(sm, "c3")->stateSet); ASSERT_FALSE(GetVersion(sm, "c4")->stateSet); ASSERT_FALSE(GetVersion(sm, "ci1")->stateSet); ASSERT_FALSE(GetVersion(sm, "ci2")->stateSet); ASSERT_FALSE(GetVersion(sm, "ci3")->stateSet); ASSERT_TRUE(GetVersion(sm, "p1")->loadedMutable); ASSERT_TRUE(GetVersion(sm, "c1")->loadedMutable); ASSERT_FALSE(GetVersion(sm, "gp")->loadedMutable); ASSERT_FALSE(GetVersion(sm, "gpi")->loadedMutable); ASSERT_FALSE(GetVersion(sm, "pi1")->loadedMutable); ASSERT_FALSE(GetVersion(sm, "c2")->loadedMutable); ASSERT_FALSE(GetVersion(sm, "c3")->loadedMutable); ASSERT_FALSE(GetVersion(sm, "c4")->loadedMutable); ASSERT_FALSE(GetVersion(sm, "ci1")->loadedMutable); ASSERT_FALSE(GetVersion(sm, "ci2")->loadedMutable); ASSERT_FALSE(GetVersion(sm, "ci3")->loadedMutable); } TEST_F(StateUpdaterTest, SetState_StateDoesAndDoesntChange) { SetVersions(sm, {MockVersion("a"), MockVersion("b")}); GetMutableVersion(sm, "a")->state = CALCULATED_STATE; GetMutableVersion(sm, "b")->state = STARTING_STATE; updater.SetStateForRefAndDependents(fix("a"), CALCULATED_STATE, [](AssetDefs::State) { return true; }); ASSERT_FALSE(GetVersion(sm, "a")->stateSet); ASSERT_FALSE(GetVersion(sm, "b")->stateSet); updater.SetStateForRefAndDependents(fix("b"), CALCULATED_STATE, [](AssetDefs::State) { return true; }); ASSERT_FALSE(GetVersion(sm, "a")->stateSet); ASSERT_TRUE(GetVersion(sm, "b")->stateSet); } TEST_F(StateUpdaterTest, SetStatePredicate) { SetVersions(sm, {MockVersion("a"), MockVersion("b")}); GetMutableVersion(sm, "a")->state = AssetDefs::Bad; GetMutableVersion(sm, "b")->state = AssetDefs::Canceled; SetDependent(sm, "a", "b"); updater.SetStateForRefAndDependents(fix("a"), AssetDefs::Succeeded, [](AssetDefs::State state) { return state != AssetDefs::Canceled; }); ASSERT_TRUE(GetVersion(sm, "a")->stateSet); ASSERT_FALSE(GetVersion(sm, "b")->stateSet); } TEST_F(StateUpdaterTest, NeedComputeStateFalse) { SetVersions(sm, {MockVersion("a")}); updater.SetStateForRefAndDependents(fix("a"), AssetDefs::Canceled, [](AssetDefs::State) { return true; }); GetMutableVersion(sm, "a")->needComputeState = false; GetMutableVersion(sm, "a")->stateSet = false; updater.RecalculateAndSaveStates(); ASSERT_FALSE(GetVersion(sm, "a")->stateSet); GetMutableVersion(sm, "a")->needComputeState = true; updater.RecalculateAndSaveStates(); ASSERT_TRUE(GetVersion(sm, "a")->stateSet); ASSERT_TRUE(GetVersion(sm, "a")->notificationsSent); } TEST_F(StateUpdaterTest, RecalculateState_StateDoesAndDoesntChange) { SetVersions(sm, {MockVersion("a"), MockVersion("b")}); GetMutableVersion(sm, "a")->state = CALCULATED_STATE; GetMutableVersion(sm, "b")->state = STARTING_STATE; SetListenerInput(sm, "a", "b"); GetMutableVersion(sm, "a")->loadedMutable = false; updater.SetStateForRefAndDependents(fix("a"), CALCULATED_STATE, [](AssetDefs::State) { return false; }); // Verify that the setup is correct ASSERT_FALSE(GetVersion(sm, "a")->stateSet); ASSERT_FALSE(GetVersion(sm, "b")->stateSet); updater.RecalculateAndSaveStates(); ASSERT_FALSE(GetVersion(sm, "a")->stateSet); ASSERT_TRUE(GetVersion(sm, "b")->stateSet); ASSERT_FALSE(GetVersion(sm, "a")->loadedMutable); } int main(int argc, char **argv) { testing::InitGoogleTest(&argc,argv); return RUN_ALL_TESTS(); } <|endoftext|>
<commit_before>/* Copyright (c) 2003-2010 Sony Pictures Imageworks Inc., et al. All Rights Reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of Sony Pictures Imageworks nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include <OpenColorIO/OpenColorIO.h> #include "MatrixOps.h" #include "MathUtils.h" #include <cmath> #include <cstring> #include <sstream> OCIO_NAMESPACE_ENTER { namespace { void ApplyClampExponent(float* rgbaBuffer, long numPixels, const float* exp4) { for(long pixelIndex=0; pixelIndex<numPixels; ++pixelIndex) { rgbaBuffer[0] = powf( std::max(0.0f, rgbaBuffer[0]), exp4[0]); rgbaBuffer[1] = powf( std::max(0.0f, rgbaBuffer[1]), exp4[1]); rgbaBuffer[2] = powf( std::max(0.0f, rgbaBuffer[2]), exp4[2]); rgbaBuffer[3] = powf( std::max(0.0f, rgbaBuffer[3]), exp4[3]); rgbaBuffer += 4; } } const int FLOAT_DECIMALS = 7; } namespace { class ExponentOp : public Op { public: ExponentOp(const float * exp4, TransformDirection direction); virtual ~ExponentOp(); virtual OpRcPtr clone() const; virtual std::string getInfo() const; virtual std::string getCacheID() const; virtual bool isNoOp() const; virtual void finalize(); virtual void apply(float* rgbaBuffer, long numPixels) const; virtual bool supportsGpuShader() const; virtual void writeGpuShader(std::ostringstream & shader, const std::string & pixelName, const GpuShaderDesc & shaderDesc) const; virtual bool definesGpuAllocation() const; virtual GpuAllocationData getGpuAllocation() const; private: float m_exp4[4]; float m_finalExp4[4]; TransformDirection m_direction; std::string m_cacheID; }; ExponentOp::ExponentOp(const float * exp4, TransformDirection direction): Op(), m_direction(direction) { memcpy(m_exp4, exp4, 4*sizeof(float)); memset(m_finalExp4, 0, 4*sizeof(float)); } OpRcPtr ExponentOp::clone() const { OpRcPtr op = OpRcPtr(new ExponentOp(m_exp4, m_direction)); return op; } ExponentOp::~ExponentOp() { } std::string ExponentOp::getInfo() const { return "<ExponentOp>"; } std::string ExponentOp::getCacheID() const { return m_cacheID; } // TODO: compute real value for isNoOp bool ExponentOp::isNoOp() const { return false; } void ExponentOp::finalize() { if(m_direction == TRANSFORM_DIR_UNKNOWN) { throw Exception("Cannot apply ExponentOp op, unspecified transform direction."); } if(m_direction == TRANSFORM_DIR_INVERSE) { for(int i=0; i<4; ++i) { if(!IsScalarEqualToZero(m_exp4[i])) { m_finalExp4[i] = 1.0f / m_exp4[i]; } else { throw Exception("Cannot apply ExponentOp op, Cannot apply 0.0 exponent in the inverse."); } } } else { memcpy(m_finalExp4, m_exp4, 4*sizeof(float)); } // Create the cacheID std::ostringstream cacheIDStream; cacheIDStream << "<ExponentOp "; cacheIDStream.precision(FLOAT_DECIMALS); for(int i=0; i<4; ++i) { cacheIDStream << m_finalExp4[i] << " "; } cacheIDStream << ">"; m_cacheID = cacheIDStream.str(); } void ExponentOp::apply(float* rgbaBuffer, long numPixels) const { if(!rgbaBuffer) return; ApplyClampExponent(rgbaBuffer, numPixels, m_finalExp4); } bool ExponentOp::supportsGpuShader() const { return false; } void ExponentOp::writeGpuShader(std::ostringstream & /*shader*/, const std::string & /*pixelName*/, const GpuShaderDesc & /*shaderDesc*/) const { // TODO: Add Gpu Shader for exponent op throw Exception("ExponentOp does not support analytical shader generation."); } bool ExponentOp::definesGpuAllocation() const { return false; } GpuAllocationData ExponentOp::getGpuAllocation() const { throw Exception("ExponentOp does not define a Gpu Allocation."); } } // Anon namespace void CreateExponentOp(OpRcPtrVec & ops, const float * exp4, TransformDirection direction) { bool expIsIdentity = IsVecEqualToOne(exp4, 4); if(expIsIdentity) return; ops.push_back( OpRcPtr(new ExponentOp(exp4, direction)) ); } } OCIO_NAMESPACE_EXIT <commit_msg>exponentop implements gpu path<commit_after>/* Copyright (c) 2003-2010 Sony Pictures Imageworks Inc., et al. All Rights Reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of Sony Pictures Imageworks nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include <cmath> #include <cstring> #include <sstream> #include <OpenColorIO/OpenColorIO.h> #include "GpuShaderUtils.h" #include "MatrixOps.h" #include "MathUtils.h" OCIO_NAMESPACE_ENTER { namespace { void ApplyClampExponent(float* rgbaBuffer, long numPixels, const float* exp4) { for(long pixelIndex=0; pixelIndex<numPixels; ++pixelIndex) { rgbaBuffer[0] = powf( std::max(0.0f, rgbaBuffer[0]), exp4[0]); rgbaBuffer[1] = powf( std::max(0.0f, rgbaBuffer[1]), exp4[1]); rgbaBuffer[2] = powf( std::max(0.0f, rgbaBuffer[2]), exp4[2]); rgbaBuffer[3] = powf( std::max(0.0f, rgbaBuffer[3]), exp4[3]); rgbaBuffer += 4; } } const int FLOAT_DECIMALS = 7; } namespace { class ExponentOp : public Op { public: ExponentOp(const float * exp4, TransformDirection direction); virtual ~ExponentOp(); virtual OpRcPtr clone() const; virtual std::string getInfo() const; virtual std::string getCacheID() const; virtual bool isNoOp() const; virtual void finalize(); virtual void apply(float* rgbaBuffer, long numPixels) const; virtual bool supportsGpuShader() const; virtual void writeGpuShader(std::ostringstream & shader, const std::string & pixelName, const GpuShaderDesc & shaderDesc) const; virtual bool definesGpuAllocation() const; virtual GpuAllocationData getGpuAllocation() const; private: float m_exp4[4]; float m_finalExp4[4]; TransformDirection m_direction; std::string m_cacheID; }; ExponentOp::ExponentOp(const float * exp4, TransformDirection direction): Op(), m_direction(direction) { memcpy(m_exp4, exp4, 4*sizeof(float)); memset(m_finalExp4, 0, 4*sizeof(float)); } OpRcPtr ExponentOp::clone() const { OpRcPtr op = OpRcPtr(new ExponentOp(m_exp4, m_direction)); return op; } ExponentOp::~ExponentOp() { } std::string ExponentOp::getInfo() const { return "<ExponentOp>"; } std::string ExponentOp::getCacheID() const { return m_cacheID; } // TODO: compute real value for isNoOp bool ExponentOp::isNoOp() const { return false; } void ExponentOp::finalize() { if(m_direction == TRANSFORM_DIR_UNKNOWN) { throw Exception("Cannot apply ExponentOp op, unspecified transform direction."); } if(m_direction == TRANSFORM_DIR_INVERSE) { for(int i=0; i<4; ++i) { if(!IsScalarEqualToZero(m_exp4[i])) { m_finalExp4[i] = 1.0f / m_exp4[i]; } else { throw Exception("Cannot apply ExponentOp op, Cannot apply 0.0 exponent in the inverse."); } } } else { memcpy(m_finalExp4, m_exp4, 4*sizeof(float)); } // Create the cacheID std::ostringstream cacheIDStream; cacheIDStream << "<ExponentOp "; cacheIDStream.precision(FLOAT_DECIMALS); for(int i=0; i<4; ++i) { cacheIDStream << m_finalExp4[i] << " "; } cacheIDStream << ">"; m_cacheID = cacheIDStream.str(); } void ExponentOp::apply(float* rgbaBuffer, long numPixels) const { if(!rgbaBuffer) return; ApplyClampExponent(rgbaBuffer, numPixels, m_finalExp4); } bool ExponentOp::supportsGpuShader() const { return true; } void ExponentOp::writeGpuShader(std::ostringstream & shader, const std::string & pixelName, const GpuShaderDesc & shaderDesc) const { GpuLanguage lang = shaderDesc.getLanguage(); float zerovec[4] = { 0.0f, 0.0f, 0.0f, 0.0f }; shader << pixelName << " = pow("; shader << "max(" << pixelName << ", " << GpuTextHalf4(zerovec, lang) << ")"; shader << ", " << GpuTextHalf4(m_finalExp4, lang) << ");\n"; } bool ExponentOp::definesGpuAllocation() const { return false; } GpuAllocationData ExponentOp::getGpuAllocation() const { throw Exception("ExponentOp does not define a Gpu Allocation."); } } // Anon namespace void CreateExponentOp(OpRcPtrVec & ops, const float * exp4, TransformDirection direction) { bool expIsIdentity = IsVecEqualToOne(exp4, 4); if(expIsIdentity) return; ops.push_back( OpRcPtr(new ExponentOp(exp4, direction)) ); } } OCIO_NAMESPACE_EXIT <|endoftext|>
<commit_before>/** * @file rpc_manager.cpp * * @date Feb 7, 2017 */ #include <cassert> #include <iostream> #include <derecho/core/detail/rpc_manager.hpp> namespace derecho { namespace rpc { thread_local bool _in_rpc_handler = false; RPCManager::~RPCManager() { thread_shutdown = true; if(rpc_thread.joinable()) { rpc_thread.join(); } } void RPCManager::create_connections() { connections = std::make_unique<sst::P2PConnections>(sst::P2PParams{nid, {nid}, view_manager.view_max_window_size, view_manager.view_max_payload_size + sizeof(header)}); } void RPCManager::destroy_remote_invocable_class(uint32_t instance_id) { //Delete receiver functions that were added by this class/subgroup for(auto receivers_iterator = receivers->begin(); receivers_iterator != receivers->end();) { if(receivers_iterator->first.subgroup_id == instance_id) { receivers_iterator = receivers->erase(receivers_iterator); } else { receivers_iterator++; } } //Deliver a node_removed_from_shard_exception to the QueryResults for this class //Important: This only works because the Replicated destructor runs before the //wrapped_this member is destroyed; otherwise the PendingResults we're referencing //would already have been deleted. std::lock_guard<std::mutex> lock(pending_results_mutex); while(!pending_results_to_fulfill[instance_id].empty()) { pending_results_to_fulfill[instance_id].front().get().set_exception_for_caller_removed(); pending_results_to_fulfill[instance_id].pop(); } while(!fulfilled_pending_results[instance_id].empty()) { fulfilled_pending_results[instance_id].front().get().set_exception_for_caller_removed(); fulfilled_pending_results[instance_id].pop_front(); } } void RPCManager::start_listening() { std::lock_guard<std::mutex> lock(thread_start_mutex); thread_start = true; thread_start_cv.notify_all(); } std::exception_ptr RPCManager::receive_message( const Opcode& indx, const node_id_t& received_from, char const* const buf, std::size_t payload_size, const std::function<char*(int)>& out_alloc) { using namespace remote_invocation_utilities; assert(payload_size); auto receiver_function_entry = receivers->find(indx); if(receiver_function_entry == receivers->end()) { dbg_default_error("Received an RPC message with an invalid RPC opcode! Opcode was ({}, {}, {}, {}).", indx.class_id, indx.subgroup_id, indx.function_id, indx.is_reply); //TODO: We should reply with some kind of "no such method" error in this case return std::exception_ptr{}; } std::size_t reply_header_size = header_space(); recv_ret reply_return = receiver_function_entry->second( &rdv, received_from, buf, [&out_alloc, &reply_header_size](std::size_t size) { return out_alloc(size + reply_header_size) + reply_header_size; }); auto* reply_buf = reply_return.payload; if(reply_buf) { reply_buf -= reply_header_size; const auto id = reply_return.opcode; const auto size = reply_return.size; populate_header(reply_buf, size, id, nid, 0); } return reply_return.possible_exception; } std::exception_ptr RPCManager::parse_and_receive(char* buf, std::size_t size, const std::function<char*(int)>& out_alloc) { using namespace remote_invocation_utilities; assert(size >= header_space()); std::size_t payload_size = size; Opcode indx; node_id_t received_from; uint32_t flags; retrieve_header(&rdv, buf, payload_size, indx, received_from, flags); return receive_message(indx, received_from, buf + header_space(), payload_size, out_alloc); } void RPCManager::rpc_message_handler(subgroup_id_t subgroup_id, node_id_t sender_id, char* msg_buf, uint32_t buffer_size) { // WARNING: This assumes the current view doesn't change during execution! // (It accesses curr_view without a lock). // set the thread local rpc_handler context _in_rpc_handler = true; //Use the reply-buffer allocation lambda to detect whether parse_and_receive generated a reply size_t reply_size = 0; char* reply_buf; parse_and_receive(msg_buf, buffer_size, [this, &reply_buf, &reply_size, &sender_id](size_t size) -> char* { reply_size = size; if(reply_size <= connections->get_max_p2p_size()) { reply_buf = (char*)connections->get_sendbuffer_ptr( connections->get_node_rank(sender_id), sst::REQUEST_TYPE::RPC_REPLY); return reply_buf; } else { // the reply size is too large - not part of the design to handle it return nullptr; } }); if(sender_id == nid) { //This is a self-receive of an RPC message I sent, so I have a reply-map that needs fulfilling int my_shard = view_manager.curr_view->multicast_group->get_subgroup_settings().at(subgroup_id).shard_num; std::unique_lock<std::mutex> lock(pending_results_mutex); // because of a race condition, toFulfillQueue can genuinely be empty // so we shouldn't assert that it is empty // instead we should sleep on a condition variable and let the main thread that called the orderedSend signal us // although the race condition is infinitely rare pending_results_cv.wait(lock, [&]() { return !pending_results_to_fulfill[subgroup_id].empty(); }); //We now know the membership of "all nodes in my shard of the subgroup" in the current view pending_results_to_fulfill[subgroup_id].front().get().fulfill_map( view_manager.curr_view->subgroup_shard_views.at(subgroup_id).at(my_shard).members); fulfilled_pending_results[subgroup_id].push_back( std::move(pending_results_to_fulfill[subgroup_id].front())); pending_results_to_fulfill[subgroup_id].pop(); if(reply_size > 0) { //Since this was a self-receive, the reply also goes to myself parse_and_receive( reply_buf, reply_size, [](size_t size) -> char* { assert_always(false); }); } } else if(reply_size > 0) { //Otherwise, the only thing to do is send the reply (if there was one) connections->send(connections->get_node_rank(sender_id)); } // clear the thread local rpc_handler context _in_rpc_handler = false; } void RPCManager::p2p_message_handler(node_id_t sender_id, char* msg_buf, uint32_t buffer_size) { using namespace remote_invocation_utilities; const std::size_t header_size = header_space(); std::size_t payload_size; Opcode indx; node_id_t received_from; uint32_t flags; retrieve_header(nullptr, msg_buf, payload_size, indx, received_from, flags); size_t reply_size = 0; if(indx.is_reply) { // REPLYs can be handled here because they do not block. receive_message(indx, received_from, msg_buf + header_size, payload_size, [this, &msg_buf, &buffer_size, &reply_size, &sender_id](size_t _size) -> char* { reply_size = _size; if(reply_size <= buffer_size) { return (char*)connections->get_sendbuffer_ptr( connections->get_node_rank(sender_id), sst::REQUEST_TYPE::P2P_REPLY); } return nullptr; }); if(reply_size > 0) { connections->send(connections->get_node_rank(sender_id)); } } else if(RPC_HEADER_FLAG_TST(flags, CASCADE)) { // TODO: what is the lifetime of msg_buf? discuss with Sagar to make // sure the buffers are safely managed. // for cascading messages, we create a new thread. throw derecho::derecho_exception("Cascading P2P Send/Queries to be implemented!"); } else { // send to fifo queue. std::unique_lock<std::mutex> lock(fifo_queue_mutex); fifo_queue.emplace(sender_id, msg_buf, buffer_size); fifo_queue_cv.notify_one(); } } void RPCManager::new_view_callback(const View& new_view) { std::lock_guard<std::mutex> connections_lock(p2p_connections_mutex); connections = std::make_unique<sst::P2PConnections>(std::move(*connections), new_view.members); dbg_default_debug("Created new connections among the new view members"); std::lock_guard<std::mutex> lock(pending_results_mutex); for(auto& fulfilled_pending_results_pair : fulfilled_pending_results) { const subgroup_id_t subgroup_id = fulfilled_pending_results_pair.first; //For each PendingResults in this subgroup, check the departed list of each shard //the subgroup, and call set_exception_for_removed_node for the departed nodes for(auto pending_results_iter = fulfilled_pending_results_pair.second.begin(); pending_results_iter != fulfilled_pending_results_pair.second.end();) { //Garbage-collect PendingResults references that are obsolete if(pending_results_iter->get().all_responded()) { pending_results_iter = fulfilled_pending_results_pair.second.erase(pending_results_iter); } else { for(uint32_t shard_num = 0; shard_num < new_view.subgroup_shard_views[subgroup_id].size(); ++shard_num) { for(auto removed_id : new_view.subgroup_shard_views[subgroup_id][shard_num].departed) { //This will do nothing if removed_id was never in the //shard this PendingResult corresponds to dbg_default_debug("Setting exception for removed node {} on PendingResults for subgroup {}, shard {}", removed_id, subgroup_id, shard_num); pending_results_iter->get().set_exception_for_removed_node(removed_id); } } pending_results_iter++; } } } } bool RPCManager::finish_rpc_send(subgroup_id_t subgroup_id, PendingBase& pending_results_handle) { std::lock_guard<std::mutex> lock(pending_results_mutex); pending_results_to_fulfill[subgroup_id].push(pending_results_handle); pending_results_cv.notify_all(); return true; } volatile char* RPCManager::get_sendbuffer_ptr(uint32_t dest_id, sst::REQUEST_TYPE type) { auto dest_rank = connections->get_node_rank(dest_id); volatile char* buf; do { buf = connections->get_sendbuffer_ptr(dest_rank, type); } while(!buf); return buf; } void RPCManager::finish_p2p_send(node_id_t dest_id, subgroup_id_t dest_subgroup_id, PendingBase& pending_results_handle) { connections->send(connections->get_node_rank(dest_id)); pending_results_handle.fulfill_map({dest_id}); std::lock_guard<std::mutex> lock(pending_results_mutex); fulfilled_pending_results[dest_subgroup_id].push_back(pending_results_handle); } void RPCManager::fifo_worker() { pthread_setname_np(pthread_self(), "fifo_thread"); using namespace remote_invocation_utilities; const std::size_t header_size = header_space(); std::size_t payload_size; Opcode indx; node_id_t received_from; uint32_t flags; size_t reply_size = 0; fifo_req request; while(!thread_shutdown) { { std::unique_lock<std::mutex> lock(fifo_queue_mutex); fifo_queue_cv.wait(lock, [&]() { return !fifo_queue.empty() || thread_shutdown; }); if(thread_shutdown) { break; } request = fifo_queue.front(); fifo_queue.pop(); } retrieve_header(nullptr, request.msg_buf, payload_size, indx, received_from, flags); if(indx.is_reply || RPC_HEADER_FLAG_TST(flags, CASCADE)) { dbg_default_error("Invalid rpc message in fifo queue: is_reply={}, is_cascading={}", indx.is_reply, RPC_HEADER_FLAG_TST(flags, CASCADE)); throw derecho::derecho_exception("invalid rpc message in fifo queue...crash."); } receive_message(indx, received_from, request.msg_buf + header_size, payload_size, [this, &reply_size, &request](size_t _size) -> char* { reply_size = _size; if(reply_size <= request.buffer_size) { return (char*)connections->get_sendbuffer_ptr( connections->get_node_rank(request.sender_id), sst::REQUEST_TYPE::P2P_REPLY); } return nullptr; }); if(reply_size > 0) { connections->send(connections->get_node_rank(request.sender_id)); } else { // hack for now to "simulate" a reply for p2p_sends to functions that do not generate a reply char* buf = connections->get_sendbuffer_ptr(connections->get_node_rank(request.sender_id), sst::REQUEST_TYPE::P2P_REPLY); buf[0] = 0; connections->send(connections->get_node_rank(request.sender_id)); } } } void RPCManager::p2p_receive_loop() { pthread_setname_np(pthread_self(), "rpc_thread"); uint64_t max_payload_size = getConfUInt64(CONF_SUBGROUP_DEFAULT_MAX_PAYLOAD_SIZE); // set the thread local rpc_handler context _in_rpc_handler = true; while(!thread_start) { std::unique_lock<std::mutex> lock(thread_start_mutex); thread_start_cv.wait(lock, [this]() { return thread_start; }); } dbg_default_debug("P2P listening thread started"); // start the fifo worker thread fifo_worker_thread = std::thread(&RPCManager::fifo_worker, this); // loop event while(!thread_shutdown) { std::lock_guard<std::mutex> connections_lock(p2p_connections_mutex); auto optional_reply_pair = connections->probe_all(); if(optional_reply_pair) { auto reply_pair = optional_reply_pair.value(); p2p_message_handler(reply_pair.first, (char*)reply_pair.second, max_payload_size); } } // stop fifo worker. fifo_queue_cv.notify_one(); fifo_worker_thread.join(); } bool in_rpc_handler() { return _in_rpc_handler; } } // namespace rpc } // namespace derecho <commit_msg>Fixed a potential deadlock in rpc_message_handler<commit_after>/** * @file rpc_manager.cpp * * @date Feb 7, 2017 */ #include <cassert> #include <iostream> #include <derecho/core/detail/rpc_manager.hpp> namespace derecho { namespace rpc { thread_local bool _in_rpc_handler = false; RPCManager::~RPCManager() { thread_shutdown = true; if(rpc_thread.joinable()) { rpc_thread.join(); } } void RPCManager::create_connections() { connections = std::make_unique<sst::P2PConnections>(sst::P2PParams{nid, {nid}, view_manager.view_max_window_size, view_manager.view_max_payload_size + sizeof(header)}); } void RPCManager::destroy_remote_invocable_class(uint32_t instance_id) { //Delete receiver functions that were added by this class/subgroup for(auto receivers_iterator = receivers->begin(); receivers_iterator != receivers->end();) { if(receivers_iterator->first.subgroup_id == instance_id) { receivers_iterator = receivers->erase(receivers_iterator); } else { receivers_iterator++; } } //Deliver a node_removed_from_shard_exception to the QueryResults for this class //Important: This only works because the Replicated destructor runs before the //wrapped_this member is destroyed; otherwise the PendingResults we're referencing //would already have been deleted. std::lock_guard<std::mutex> lock(pending_results_mutex); while(!pending_results_to_fulfill[instance_id].empty()) { pending_results_to_fulfill[instance_id].front().get().set_exception_for_caller_removed(); pending_results_to_fulfill[instance_id].pop(); } while(!fulfilled_pending_results[instance_id].empty()) { fulfilled_pending_results[instance_id].front().get().set_exception_for_caller_removed(); fulfilled_pending_results[instance_id].pop_front(); } } void RPCManager::start_listening() { std::lock_guard<std::mutex> lock(thread_start_mutex); thread_start = true; thread_start_cv.notify_all(); } std::exception_ptr RPCManager::receive_message( const Opcode& indx, const node_id_t& received_from, char const* const buf, std::size_t payload_size, const std::function<char*(int)>& out_alloc) { using namespace remote_invocation_utilities; assert(payload_size); auto receiver_function_entry = receivers->find(indx); if(receiver_function_entry == receivers->end()) { dbg_default_error("Received an RPC message with an invalid RPC opcode! Opcode was ({}, {}, {}, {}).", indx.class_id, indx.subgroup_id, indx.function_id, indx.is_reply); //TODO: We should reply with some kind of "no such method" error in this case return std::exception_ptr{}; } std::size_t reply_header_size = header_space(); recv_ret reply_return = receiver_function_entry->second( &rdv, received_from, buf, [&out_alloc, &reply_header_size](std::size_t size) { return out_alloc(size + reply_header_size) + reply_header_size; }); auto* reply_buf = reply_return.payload; if(reply_buf) { reply_buf -= reply_header_size; const auto id = reply_return.opcode; const auto size = reply_return.size; populate_header(reply_buf, size, id, nid, 0); } return reply_return.possible_exception; } std::exception_ptr RPCManager::parse_and_receive(char* buf, std::size_t size, const std::function<char*(int)>& out_alloc) { using namespace remote_invocation_utilities; assert(size >= header_space()); std::size_t payload_size = size; Opcode indx; node_id_t received_from; uint32_t flags; retrieve_header(&rdv, buf, payload_size, indx, received_from, flags); return receive_message(indx, received_from, buf + header_space(), payload_size, out_alloc); } void RPCManager::rpc_message_handler(subgroup_id_t subgroup_id, node_id_t sender_id, char* msg_buf, uint32_t buffer_size) { // WARNING: This assumes the current view doesn't change during execution! // (It accesses curr_view without a lock). // set the thread local rpc_handler context _in_rpc_handler = true; //Use the reply-buffer allocation lambda to detect whether parse_and_receive generated a reply size_t reply_size = 0; char* reply_buf; parse_and_receive(msg_buf, buffer_size, [this, &reply_buf, &reply_size, &sender_id](size_t size) -> char* { reply_size = size; if(reply_size <= connections->get_max_p2p_size()) { reply_buf = (char*)connections->get_sendbuffer_ptr( connections->get_node_rank(sender_id), sst::REQUEST_TYPE::RPC_REPLY); return reply_buf; } else { // the reply size is too large - not part of the design to handle it return nullptr; } }); if(sender_id == nid) { //This is a self-receive of an RPC message I sent, so I have a reply-map that needs fulfilling const uint32_t my_shard = view_manager.curr_view->my_subgroups.at(subgroup_id); { std::unique_lock<std::mutex> lock(pending_results_mutex); // because of a race condition, pending_results_to_fulfill can genuinely be empty // so before accessing it we should sleep on a condition variable and let the main // thread that called the orderedSend signal us // although the race condition is infinitely rare pending_results_cv.wait(lock, [&]() { return !pending_results_to_fulfill[subgroup_id].empty(); }); //We now know the membership of "all nodes in my shard of the subgroup" in the current view pending_results_to_fulfill[subgroup_id].front().get().fulfill_map( view_manager.curr_view->subgroup_shard_views.at(subgroup_id).at(my_shard).members); fulfilled_pending_results[subgroup_id].push_back( std::move(pending_results_to_fulfill[subgroup_id].front())); pending_results_to_fulfill[subgroup_id].pop(); } //release pending_results_mutex if(reply_size > 0) { //Since this was a self-receive, the reply also goes to myself parse_and_receive( reply_buf, reply_size, [](size_t size) -> char* { assert_always(false); }); } } else if(reply_size > 0) { //Otherwise, the only thing to do is send the reply (if there was one) connections->send(connections->get_node_rank(sender_id)); } // clear the thread local rpc_handler context _in_rpc_handler = false; } void RPCManager::p2p_message_handler(node_id_t sender_id, char* msg_buf, uint32_t buffer_size) { using namespace remote_invocation_utilities; const std::size_t header_size = header_space(); std::size_t payload_size; Opcode indx; node_id_t received_from; uint32_t flags; retrieve_header(nullptr, msg_buf, payload_size, indx, received_from, flags); size_t reply_size = 0; if(indx.is_reply) { // REPLYs can be handled here because they do not block. receive_message(indx, received_from, msg_buf + header_size, payload_size, [this, &msg_buf, &buffer_size, &reply_size, &sender_id](size_t _size) -> char* { reply_size = _size; if(reply_size <= buffer_size) { return (char*)connections->get_sendbuffer_ptr( connections->get_node_rank(sender_id), sst::REQUEST_TYPE::P2P_REPLY); } return nullptr; }); if(reply_size > 0) { connections->send(connections->get_node_rank(sender_id)); } } else if(RPC_HEADER_FLAG_TST(flags, CASCADE)) { // TODO: what is the lifetime of msg_buf? discuss with Sagar to make // sure the buffers are safely managed. // for cascading messages, we create a new thread. throw derecho::derecho_exception("Cascading P2P Send/Queries to be implemented!"); } else { // send to fifo queue. std::unique_lock<std::mutex> lock(fifo_queue_mutex); fifo_queue.emplace(sender_id, msg_buf, buffer_size); fifo_queue_cv.notify_one(); } } void RPCManager::new_view_callback(const View& new_view) { std::lock_guard<std::mutex> connections_lock(p2p_connections_mutex); connections = std::make_unique<sst::P2PConnections>(std::move(*connections), new_view.members); dbg_default_debug("Created new connections among the new view members"); std::lock_guard<std::mutex> lock(pending_results_mutex); for(auto& fulfilled_pending_results_pair : fulfilled_pending_results) { const subgroup_id_t subgroup_id = fulfilled_pending_results_pair.first; //For each PendingResults in this subgroup, check the departed list of each shard //the subgroup, and call set_exception_for_removed_node for the departed nodes for(auto pending_results_iter = fulfilled_pending_results_pair.second.begin(); pending_results_iter != fulfilled_pending_results_pair.second.end();) { //Garbage-collect PendingResults references that are obsolete if(pending_results_iter->get().all_responded()) { pending_results_iter = fulfilled_pending_results_pair.second.erase(pending_results_iter); } else { for(uint32_t shard_num = 0; shard_num < new_view.subgroup_shard_views[subgroup_id].size(); ++shard_num) { for(auto removed_id : new_view.subgroup_shard_views[subgroup_id][shard_num].departed) { //This will do nothing if removed_id was never in the //shard this PendingResult corresponds to dbg_default_debug("Setting exception for removed node {} on PendingResults for subgroup {}, shard {}", removed_id, subgroup_id, shard_num); pending_results_iter->get().set_exception_for_removed_node(removed_id); } } pending_results_iter++; } } } } bool RPCManager::finish_rpc_send(subgroup_id_t subgroup_id, PendingBase& pending_results_handle) { std::lock_guard<std::mutex> lock(pending_results_mutex); pending_results_to_fulfill[subgroup_id].push(pending_results_handle); pending_results_cv.notify_all(); return true; } volatile char* RPCManager::get_sendbuffer_ptr(uint32_t dest_id, sst::REQUEST_TYPE type) { auto dest_rank = connections->get_node_rank(dest_id); volatile char* buf; do { buf = connections->get_sendbuffer_ptr(dest_rank, type); } while(!buf); return buf; } void RPCManager::finish_p2p_send(node_id_t dest_id, subgroup_id_t dest_subgroup_id, PendingBase& pending_results_handle) { connections->send(connections->get_node_rank(dest_id)); pending_results_handle.fulfill_map({dest_id}); std::lock_guard<std::mutex> lock(pending_results_mutex); fulfilled_pending_results[dest_subgroup_id].push_back(pending_results_handle); } void RPCManager::fifo_worker() { pthread_setname_np(pthread_self(), "fifo_thread"); using namespace remote_invocation_utilities; const std::size_t header_size = header_space(); std::size_t payload_size; Opcode indx; node_id_t received_from; uint32_t flags; size_t reply_size = 0; fifo_req request; while(!thread_shutdown) { { std::unique_lock<std::mutex> lock(fifo_queue_mutex); fifo_queue_cv.wait(lock, [&]() { return !fifo_queue.empty() || thread_shutdown; }); if(thread_shutdown) { break; } request = fifo_queue.front(); fifo_queue.pop(); } retrieve_header(nullptr, request.msg_buf, payload_size, indx, received_from, flags); if(indx.is_reply || RPC_HEADER_FLAG_TST(flags, CASCADE)) { dbg_default_error("Invalid rpc message in fifo queue: is_reply={}, is_cascading={}", indx.is_reply, RPC_HEADER_FLAG_TST(flags, CASCADE)); throw derecho::derecho_exception("invalid rpc message in fifo queue...crash."); } receive_message(indx, received_from, request.msg_buf + header_size, payload_size, [this, &reply_size, &request](size_t _size) -> char* { reply_size = _size; if(reply_size <= request.buffer_size) { return (char*)connections->get_sendbuffer_ptr( connections->get_node_rank(request.sender_id), sst::REQUEST_TYPE::P2P_REPLY); } return nullptr; }); if(reply_size > 0) { connections->send(connections->get_node_rank(request.sender_id)); } else { // hack for now to "simulate" a reply for p2p_sends to functions that do not generate a reply char* buf = connections->get_sendbuffer_ptr(connections->get_node_rank(request.sender_id), sst::REQUEST_TYPE::P2P_REPLY); buf[0] = 0; connections->send(connections->get_node_rank(request.sender_id)); } } } void RPCManager::p2p_receive_loop() { pthread_setname_np(pthread_self(), "rpc_thread"); uint64_t max_payload_size = getConfUInt64(CONF_SUBGROUP_DEFAULT_MAX_PAYLOAD_SIZE); // set the thread local rpc_handler context _in_rpc_handler = true; while(!thread_start) { std::unique_lock<std::mutex> lock(thread_start_mutex); thread_start_cv.wait(lock, [this]() { return thread_start; }); } dbg_default_debug("P2P listening thread started"); // start the fifo worker thread fifo_worker_thread = std::thread(&RPCManager::fifo_worker, this); // loop event while(!thread_shutdown) { std::lock_guard<std::mutex> connections_lock(p2p_connections_mutex); auto optional_reply_pair = connections->probe_all(); if(optional_reply_pair) { auto reply_pair = optional_reply_pair.value(); p2p_message_handler(reply_pair.first, (char*)reply_pair.second, max_payload_size); } } // stop fifo worker. fifo_queue_cv.notify_one(); fifo_worker_thread.join(); } bool in_rpc_handler() { return _in_rpc_handler; } } // namespace rpc } // namespace derecho <|endoftext|>
<commit_before>#include <cstdio> #include <dxjson/dxjson.h> int main() { using namespace dx; using namespace std; try { JSON j1(JSON_OBJECT); std::cout<<"Eps = "<<JSON::getEpsilon(); j1["key"] = 12; JSON j2(JSON_OBJECT); j2["blah"] = "sdsdsd"; j2["blah"] = "key"; j2["lala"] = j1[j2["blah"]]; std::cout<<"\nj2 = \n"<<j2.toString()<<"\n"; j2.erase("lala"); std::cout<<"\n j2 after erasing 'lala' = \n"<<j2.toString()<<"\n"; // JSON parse tests JSON j3 = JSON::parse("{\"blah\": [ 21,232,\"foo\" , {\"key\": \"val1\"}, true, false, null]}"); j3["blah"].push_back(1.23456789101112); j3["blah"].push_back("dsdsd"); j3["blah"].push_back(Null()); j3["blah"].push_back(12.212); j3["foo"] = vector<int>(5,5); std::map<std::string, int> mp; mp["lala"] = 12.11e-212; mp["dsdsd"] = 1212; j3["map"] = mp; std::cout<<"\nj3 = "<<j3.toString(); std::cout<<"\nj3[blah] = "<<j3["blah"].toString(); std::cout<<"\nj3[blah][2] = "<<j3["blah"][2].toString()<<"\n"; j3["blah"].erase(2); std::cout<<"\nBlah after erasing indx = 2\n"<<j3["blah"].toString()<<"\n"; JSON j4; std::string str = "{\"清华大学\": [\"this should look like second element\", \"\\u6e05\\u534e\\u5927\\u5b66\", \"\\n\\b\\t\\\"\"] }"; j4 = JSON::parse(str); std::cout<<"j4 = "<<j4.toString()<<"\n"; JSON j5(JSON_BOOLEAN); j5 = true; std::cout<<"\nj5 = "<<j5.toString()<<"\n"; // Equality tests std::cout<<"\nj4 == j5: "<<((j4==j5)?"true":"false"); JSON j5_copy = j5; std::cout<<"\nj5_copy == j5: "<<((j5_copy==j5) ? "true" : "false")<<"\n"; JSON j6 = 12.21; JSON j7 = 12.22; assert(j6 != j7); JSON j8(JSON_ARRAY); j8.push_back(12.21); j8.push_back("hello"); j8.push_back(j8); std::cout<<"\nj8 = "<<j8.toString()<<"\n"; JSON j9 = j8; assert(j9 == j8); j9.erase(2); assert(j9 != j8); assert(JSON(JSON_NULL) == JSON(JSON_NULL)); // JSON_UNDEFINED != JSON_UNDEFINED assert(JSON() != JSON()); // Iterator test int i=0; JSON j10(JSON_OBJECT); j10["key1"] = 12; j10["key2"] = 13; j10["key3"] = j8; j10["key4"] = j8; std::cout<<"\nChecking forward iterators now ... j10 = "<<j10.toString()<<"\n"; for (JSON::array_iterator it = j8.array_begin();it != j8.array_end(); ++it, ++i) { assert(j8[i] == *(it)); } for (JSON::object_iterator it = j10.object_begin();it != j10.object_end(); ++it) { assert(j10[it->first] == it->second); std::cout<<"Key = "<<it->first<<", Value = "<<it->second.toString()<<endl; } std::cout<<"\nChecking reverse now ...\n"; i = j8.size() - 1; for (JSON::array_reverse_iterator it = j8.array_rbegin();it != j8.array_rend(); ++it, --i) { assert(j8[i] == *(it)); } for (JSON::object_reverse_iterator it = j10.object_rbegin();it != j10.object_rend(); ++it) { assert(j10[it->first] == it->second); std::cout<<"Key = "<<it->first<<", Value = "<<it->second.toString()<<endl; } // //typedef std::map<std::string, JSON> ObjectIterator //ObjectIterator it = j4.ObjectBegin(); // JSON Iterators (different class); //for (; it != j4.end(); ++it) { // } // Check implicit cast operators JSON j11(JSON_OBJECT); j11["1"] = 1; j11["2"] = 12.33; j11["3"] = true; j11["4"] = 212l; j11["4.1"] = "blahh"; j11["5"] = vector<int>(5,0); j11["6"] = "1"; assert(j11["5"][0.9] == 0); assert(j11["5"][j11["1"]] == 0); assert(j11.has("1")); assert(!j11.has("random")); assert(j11["5"].has(0)); assert(j11["5"].has(1)); assert(j11["5"].has(j11["5"][0])); assert(j11.has(j11["6"]) && j11[j11["6"]] == 1); assert(j11["5"][j11["1"]] == 0); assert(double(j11["1"]) == 1); assert(double(j11["2"]) == 12.33); assert(bool(j11["3"]) == true); assert(j11["4.1"].toString() == "\"blahh\""); assert(long(j11["4"]) == 212l); assert(double(j11["1"]) < double(j11["2"])); const JSON j12(j11); assert(j12["5"][0.9] == 0); assert(j12["5"][j11["1"]] == 0); assert(j12["5"][j11["1"]] == 0); assert(double(j12["1"]) == 1); assert(double(j12["2"]) == 12.33); assert(bool(j12["3"]) == true); assert(j12["4.1"].toString() == "\"blahh\""); assert(long(j12["4"]) == 212l); assert(double(j12["1"]) < double(j11["2"])); JSON j13(JSON_OBJECT); j13["foo"] = "blah"; j13["foo2"] = 12; j13["foo3"] = 12.32; std::string str1 = j13["foo"].get<std::string>(); assert(str1 == "blah"); assert(j13["foo2"].get<int>() == 12); assert(j13["foo3"].get<double>() == 12.32); assert(j13["foo3"].get<bool>() == true); JSON j14(JSON_NULL); assert(j14 == JSON_NULL); std::cout<<"\nAll assertions performed succesfully\n"; } catch (exception &e) { std::cout<<"\nErrror occured: \n"<<e.what()<<"\n"; } return 0; } <commit_msg>Made dxjson/trial.cpp compilable on clang<commit_after>#include <cstdio> #include "dxjson.h" int main() { using namespace dx; using namespace std; try { JSON j1(JSON_OBJECT); std::cout<<"Eps = "<<JSON::getEpsilon(); j1["key"] = 12; JSON j2(JSON_OBJECT); j2["blah"] = "sdsdsd"; j2["blah"] = "key"; j2["lala"] = j1[j2["blah"]]; std::cout<<"\nj2 = \n"<<j2.toString()<<"\n"; j2.erase("lala"); std::cout<<"\n j2 after erasing 'lala' = \n"<<j2.toString()<<"\n"; // JSON parse tests JSON j3 = JSON::parse("{\"blah\": [ 21,232,\"foo\" , {\"key\": \"val1\"}, true, false, null]}"); j3["blah"].push_back(1.23456789101112); j3["blah"].push_back("dsdsd"); j3["blah"].push_back(Null()); j3["blah"].push_back(12.212); j3["foo"] = vector<int>(5,5); std::map<std::string, int> mp; mp["lala"] = 12.11e-212; mp["dsdsd"] = 1212; j3["map"] = mp; std::cout<<"\nj3 = "<<j3.toString(); std::cout<<"\nj3[blah] = "<<j3["blah"].toString(); std::cout<<"\nj3[blah][2] = "<<j3["blah"][2].toString()<<"\n"; j3["blah"].erase(2); std::cout<<"\nBlah after erasing indx = 2\n"<<j3["blah"].toString()<<"\n"; JSON j4; std::string str = "{\"清华大学\": [\"this should look like second element\", \"\\u6e05\\u534e\\u5927\\u5b66\", \"\\n\\b\\t\\\"\"] }"; j4 = JSON::parse(str); std::cout<<"j4 = "<<j4.toString()<<"\n"; JSON j5(JSON_BOOLEAN); j5 = true; std::cout<<"\nj5 = "<<j5.toString()<<"\n"; // Equality tests std::cout<<"\nj4 == j5: "<<((j4==j5)?"true":"false"); JSON j5_copy = j5; std::cout<<"\nj5_copy == j5: "<<((j5_copy==j5) ? "true" : "false")<<"\n"; JSON j6 = 12.21; JSON j7 = 12.22; assert(j6 != j7); JSON j8(JSON_ARRAY); j8.push_back(12.21); j8.push_back("hello"); j8.push_back(j8); std::cout<<"\nj8 = "<<j8.toString()<<"\n"; JSON j9 = j8; assert(j9 == j8); j9.erase(2); assert(j9 != j8); assert(JSON(JSON_NULL) == JSON(JSON_NULL)); // JSON_UNDEFINED != JSON_UNDEFINED assert(JSON() != JSON()); // Iterator test int i=0; JSON j10(JSON_OBJECT); j10["key1"] = 12; j10["key2"] = 13; j10["key3"] = j8; j10["key4"] = j8; std::cout<<"\nChecking forward iterators now ... j10 = "<<j10.toString()<<"\n"; for (JSON::array_iterator it = j8.array_begin();it != j8.array_end(); ++it, ++i) { assert(j8[i] == *(it)); } for (JSON::object_iterator it = j10.object_begin();it != j10.object_end(); ++it) { assert(j10[it->first] == it->second); std::cout<<"Key = "<<it->first<<", Value = "<<it->second.toString()<<endl; } std::cout<<"\nChecking reverse now ...\n"; i = j8.size() - 1; for (JSON::array_reverse_iterator it = j8.array_rbegin();it != j8.array_rend(); ++it, --i) { assert(j8[i] == *(it)); } for (JSON::object_reverse_iterator it = j10.object_rbegin();it != j10.object_rend(); ++it) { assert(j10[it->first] == it->second); std::cout<<"Key = "<<it->first<<", Value = "<<it->second.toString()<<endl; } // //typedef std::map<std::string, JSON> ObjectIterator //ObjectIterator it = j4.ObjectBegin(); // JSON Iterators (different class); //for (; it != j4.end(); ++it) { // } // Check implicit cast operators JSON j11(JSON_OBJECT); j11["1"] = 1; j11["2"] = 12.33; j11["3"] = true; j11["4"] = 212l; j11["4.1"] = "blahh"; j11["5"] = vector<int>(5,0); j11["6"] = "1"; assert(j11["5"][0.9].get<int>() == 0); assert(j11["5"][j11["1"]].get<int>() == 0); assert(j11.has("1")); assert(!j11.has("random")); assert(j11["5"].has(0)); assert(j11["5"].has(1)); assert(j11["5"].has(j11["5"][0])); assert(j11.has(j11["6"]) && j11[j11["6"]].get<int>() == 1); assert(j11["5"][j11["1"]].get<int>() == 0); assert(double(j11["1"]) == 1); assert(double(j11["2"]) == 12.33); assert(bool(j11["3"]) == true); assert(j11["4.1"].toString() == "\"blahh\""); assert(long(j11["4"]) == 212l); assert(double(j11["1"]) < double(j11["2"])); const JSON j12(j11); assert(j12["5"][0.9].get<int>() == 0); assert(j12["5"][j11["1"]].get<int>() == 0); assert(j12["5"][j11["1"]].get<int>() == 0); assert(double(j12["1"]) == 1); assert(double(j12["2"]) == 12.33); assert(bool(j12["3"]) == true); assert(j12["4.1"].toString() == "\"blahh\""); assert(long(j12["4"]) == 212l); assert(double(j12["1"]) < double(j11["2"])); JSON j13(JSON_OBJECT); j13["foo"] = "blah"; j13["foo2"] = 12; j13["foo3"] = 12.32; std::string str1 = j13["foo"].get<std::string>(); assert(str1 == "blah"); assert(j13["foo2"].get<int>() == 12); assert(j13["foo3"].get<double>() == 12.32); assert(j13["foo3"].get<bool>() == true); JSON j14(JSON_NULL); assert(j14 == JSON(JSON_NULL)); std::cout<<"\nAll assertions performed succesfully\n"; } catch (exception &e) { std::cout<<"\nErrror occured: \n"<<e.what()<<"\n"; } return 0; } <|endoftext|>
<commit_before>// // Created by Dawid Drozd aka Gelldur on 7/19/16. // #include "Preferences.h" #include<cstdio> #include <Poco/Data/Session.h> //#include <Poco/Data/SQLite/Connector.h> #include <log.h> #include <acme/MakeUnique.h> Preferences::Preferences(const std::string& databaseName, const std::string& tableName) : TABLE_NAME(tableName) , DATABSE_FILE_NAME(databaseName) { // Poco::Data::SQLite::Connector::registerConnector(); recreate(); } Preferences::~Preferences() { if (_session != nullptr) { _session->close(); } // Poco::Data::SQLite::Connector::unregisterConnector(); } void Preferences::setValue(const std::string& key, const std::string& value) { _cache[key] = value; if (_session == nullptr) { ELOG("Session not created\nNo storage"); return; } Poco::Data::Session& session = *_session; Poco::Data::Statement insert(session); insert << "INSERT OR REPLACE INTO " << TABLE_NAME << " VALUES(?, ?)", Poco::Data::Keywords::useRef(key), Poco::Data::Keywords::useRef(value); DLOG("Preferences: %s\n(%s)=(%s)", insert.toString().c_str(), key.c_str(), value.c_str()); insert.execute(); } std::string Preferences::getValue(const std::string& key, const std::string& defaultValue) { auto found = _cache.find(key); if (found != _cache.end()) { return found->second; } if (_session == nullptr) { ELOG("Session not created\nNo storage"); _cache[key] = defaultValue; return defaultValue; } std::string returnedValue = defaultValue; Poco::Data::Session& session = *_session; // a simple query Poco::Data::Statement select(session); select << "SELECT value FROM " << TABLE_NAME << " WHERE key=?", Poco::Data::Keywords::useRef(key), Poco::Data::Keywords::into(returnedValue); // iterate over result set one row at a time DLOG("Select: %s\nkey:%s", select.toString().c_str(), key.c_str()); select.execute(); _cache[key] = returnedValue; return returnedValue; } void Preferences::clean() { _cache.clear(); if (_session == nullptr) { ELOG("Session not created\nNo storage"); return; } _session->close(); if (std::remove(DATABSE_FILE_NAME.c_str()) != 0) { ELOG("Can't remove database: %s", DATABSE_FILE_NAME.c_str()); } recreate(); } void Preferences::recreate() { try { _session = std::make_unique<Poco::Data::Session>("SQLite", DATABSE_FILE_NAME.c_str()); } catch (const std::exception& ex) { ELOG("Can't create session: %s", ex.what()); } catch (...) { ELOG("Can't create session"); } if (_session == nullptr) { ELOG("Session not created\nNo storage"); return; } Poco::Data::Session& session = *_session; session << "CREATE TABLE IF NOT EXISTS `" << TABLE_NAME << "`(" "`key` TEXT NOT NULL UNIQUE," "`value` TEXT," "PRIMARY KEY(key)" ");", Poco::Data::Keywords::now; } <commit_msg>Fix Preferences (after android changes)<commit_after>// // Created by Dawid Drozd aka Gelldur on 7/19/16. // #include "Preferences.h" #include<cstdio> #include <Poco/Data/Session.h> #include <Poco/Data/SQLite/Connector.h> #include <log.h> #include <acme/MakeUnique.h> Preferences::Preferences(const std::string& databaseName, const std::string& tableName) : TABLE_NAME(tableName) , DATABSE_FILE_NAME(databaseName) { Poco::Data::SQLite::Connector::registerConnector(); recreate(); } Preferences::~Preferences() { if (_session != nullptr) { _session->close(); } Poco::Data::SQLite::Connector::unregisterConnector(); } void Preferences::setValue(const std::string& key, const std::string& value) { _cache[key] = value; if (_session == nullptr) { ELOG("Session not created\nNo storage"); return; } Poco::Data::Session& session = *_session; Poco::Data::Statement insert(session); insert << "INSERT OR REPLACE INTO " << TABLE_NAME << " VALUES(?, ?)", Poco::Data::Keywords::useRef(key), Poco::Data::Keywords::useRef(value); DLOG("Preferences: %s\n(%s)=(%s)", insert.toString().c_str(), key.c_str(), value.c_str()); insert.execute(); } std::string Preferences::getValue(const std::string& key, const std::string& defaultValue) { auto found = _cache.find(key); if (found != _cache.end()) { return found->second; } if (_session == nullptr) { ELOG("Session not created\nNo storage"); _cache[key] = defaultValue; return defaultValue; } std::string returnedValue = defaultValue; Poco::Data::Session& session = *_session; // a simple query Poco::Data::Statement select(session); select << "SELECT value FROM " << TABLE_NAME << " WHERE key=?", Poco::Data::Keywords::useRef(key), Poco::Data::Keywords::into(returnedValue); // iterate over result set one row at a time DLOG("Select: %s\nkey:%s", select.toString().c_str(), key.c_str()); select.execute(); _cache[key] = returnedValue; return returnedValue; } void Preferences::clean() { _cache.clear(); if (_session == nullptr) { ELOG("Session not created\nNo storage"); return; } _session->close(); if (std::remove(DATABSE_FILE_NAME.c_str()) != 0) { ELOG("Can't remove database: %s", DATABSE_FILE_NAME.c_str()); } recreate(); } void Preferences::recreate() { try { _session = std::make_unique<Poco::Data::Session>("SQLite", DATABSE_FILE_NAME.c_str()); } catch (const std::exception& ex) { ELOG("Can't create session: %s", ex.what()); } catch (...) { ELOG("Can't create session"); } if (_session == nullptr) { ELOG("Session not created\nNo storage"); return; } Poco::Data::Session& session = *_session; session << "CREATE TABLE IF NOT EXISTS `" << TABLE_NAME << "`(" "`key` TEXT NOT NULL UNIQUE," "`value` TEXT," "PRIMARY KEY(key)" ");", Poco::Data::Keywords::now; } <|endoftext|>
<commit_before>/***************************************************************************** * * This file is part of Mapnik (c++ mapping toolkit) * * Copyright (C) 2006 Artem Pavlenko * * 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 St, Fifth Floor, Boston, MA 02110-1301 USA * *****************************************************************************/ //$Id: datasource_cache.cpp 23 2005-03-22 22:16:34Z pavlenko $ // mapnik #include <mapnik/datasource_cache.hpp> #include <mapnik/config_error.hpp> // boost #include <boost/thread/mutex.hpp> #include <boost/filesystem/operations.hpp> #include <boost/algorithm/string.hpp> // ltdl #include <ltdl.h> // stl #include <algorithm> #include <stdexcept> namespace mapnik { using namespace std; using namespace boost; bool is_input_plugin (std::string const& filename) { return boost::algorithm::ends_with(filename,std::string(".input")); } datasource_cache::datasource_cache() { if (lt_dlinit()) throw std::runtime_error("lt_dlinit() failed"); } datasource_cache::~datasource_cache() { lt_dlexit(); } std::map<string,boost::shared_ptr<PluginInfo> > datasource_cache::plugins_; bool datasource_cache::registered_=false; datasource_ptr datasource_cache::create(const parameters& params) { boost::optional<std::string> type = params.get<std::string>("type"); if ( ! type) { throw config_error(string("Could not create datasource. Required ") + "parameter 'type' is missing"); } datasource_ptr ds; map<string,boost::shared_ptr<PluginInfo> >::iterator itr=plugins_.find(*type); if ( itr == plugins_.end() ) { throw config_error(string("Could not create datasource. No plugin ") + "found for type '" + * type + "'"); } if ( ! itr->second->handle()) { throw std::runtime_error(string("Cannot load library: ") + lt_dlerror()); } create_ds* create_datasource = (create_ds*) lt_dlsym(itr->second->handle(), "create"); if ( ! create_datasource) { throw std::runtime_error(string("Cannot load symbols: ") + lt_dlerror()); } std::cout << "size = " << params.size() << "\n"; parameters::const_iterator i = params.begin(); for (;i!=params.end();++i) { std::cout << i->first << "=" << i->second << "\n"; } ds=datasource_ptr(create_datasource(params), datasource_deleter()); #ifdef MAPNIK_DEBUG std::clog<<"datasource="<<ds<<" type="<<type<<std::endl; #endif return ds; } bool datasource_cache::insert(const std::string& type,const lt_dlhandle module) { return plugins_.insert(make_pair(type,boost::shared_ptr<PluginInfo> (new PluginInfo(type,module)))).second; } void datasource_cache::register_datasources(const std::string& str) { mutex::scoped_lock lock(mapnik::singleton<mapnik::datasource_cache, mapnik::CreateStatic>::mutex_); filesystem::path path(str); filesystem::directory_iterator end_itr; if (exists(path) && is_directory(path)) { for (filesystem::directory_iterator itr(path);itr!=end_itr;++itr ) { if (!is_directory( *itr ) && is_input_plugin(itr->leaf())) { try { lt_dlhandle module=lt_dlopen(itr->string().c_str()); if (module) { datasource_name* ds_name = (datasource_name*) lt_dlsym(module, "datasource_name"); if (ds_name && insert(ds_name(),module)) { #ifdef MAPNIK_DEBUG std::clog<<"registered datasource : "<<ds_name()<<std::endl; #endif registered_=true; } } else { std::clog << lt_dlerror() << "\n"; } } catch (...) {} } } } } } <commit_msg>only print to clog when MAPNIK_DEBUG is defined<commit_after>/***************************************************************************** * * This file is part of Mapnik (c++ mapping toolkit) * * Copyright (C) 2006 Artem Pavlenko * * 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 St, Fifth Floor, Boston, MA 02110-1301 USA * *****************************************************************************/ //$Id: datasource_cache.cpp 23 2005-03-22 22:16:34Z pavlenko $ // mapnik #include <mapnik/datasource_cache.hpp> #include <mapnik/config_error.hpp> // boost #include <boost/thread/mutex.hpp> #include <boost/filesystem/operations.hpp> #include <boost/algorithm/string.hpp> // ltdl #include <ltdl.h> // stl #include <algorithm> #include <stdexcept> namespace mapnik { using namespace std; using namespace boost; bool is_input_plugin (std::string const& filename) { return boost::algorithm::ends_with(filename,std::string(".input")); } datasource_cache::datasource_cache() { if (lt_dlinit()) throw std::runtime_error("lt_dlinit() failed"); } datasource_cache::~datasource_cache() { lt_dlexit(); } std::map<string,boost::shared_ptr<PluginInfo> > datasource_cache::plugins_; bool datasource_cache::registered_=false; datasource_ptr datasource_cache::create(const parameters& params) { boost::optional<std::string> type = params.get<std::string>("type"); if ( ! type) { throw config_error(string("Could not create datasource. Required ") + "parameter 'type' is missing"); } datasource_ptr ds; map<string,boost::shared_ptr<PluginInfo> >::iterator itr=plugins_.find(*type); if ( itr == plugins_.end() ) { throw config_error(string("Could not create datasource. No plugin ") + "found for type '" + * type + "'"); } if ( ! itr->second->handle()) { throw std::runtime_error(string("Cannot load library: ") + lt_dlerror()); } create_ds* create_datasource = (create_ds*) lt_dlsym(itr->second->handle(), "create"); if ( ! create_datasource) { throw std::runtime_error(string("Cannot load symbols: ") + lt_dlerror()); } #ifdef MAPNIK_DEBUG std::clog << "size = " << params.size() << "\n"; parameters::const_iterator i = params.begin(); for (;i!=params.end();++i) { std::clog << i->first << "=" << i->second << "\n"; } #endif ds=datasource_ptr(create_datasource(params), datasource_deleter()); #ifdef MAPNIK_DEBUG std::clog<<"datasource="<<ds<<" type="<<type<<std::endl; #endif return ds; } bool datasource_cache::insert(const std::string& type,const lt_dlhandle module) { return plugins_.insert(make_pair(type,boost::shared_ptr<PluginInfo> (new PluginInfo(type,module)))).second; } void datasource_cache::register_datasources(const std::string& str) { mutex::scoped_lock lock(mapnik::singleton<mapnik::datasource_cache, mapnik::CreateStatic>::mutex_); filesystem::path path(str); filesystem::directory_iterator end_itr; if (exists(path) && is_directory(path)) { for (filesystem::directory_iterator itr(path);itr!=end_itr;++itr ) { if (!is_directory( *itr ) && is_input_plugin(itr->leaf())) { try { lt_dlhandle module=lt_dlopen(itr->string().c_str()); if (module) { datasource_name* ds_name = (datasource_name*) lt_dlsym(module, "datasource_name"); if (ds_name && insert(ds_name(),module)) { #ifdef MAPNIK_DEBUG std::clog<<"registered datasource : "<<ds_name()<<std::endl; #endif registered_=true; } } else { std::clog << lt_dlerror() << "\n"; } } catch (...) {} } } } } } <|endoftext|>
<commit_before><commit_msg>Improve IAS Zone enrollment<commit_after><|endoftext|>
<commit_before>// Copyright (c) 2021 ASMlover. All rights reserved. // // ______ __ ___ // /\__ _\ /\ \ /\_ \ // \/_/\ \/ __ \_\ \ _____ ___\//\ \ __ // \ \ \ /'__`\ /'_` \/\ '__`\ / __`\\ \ \ /'__`\ // \ \ \/\ \L\.\_/\ \L\ \ \ \L\ \/\ \L\ \\_\ \_/\ __/ // \ \_\ \__/.\_\ \___,_\ \ ,__/\ \____//\____\ \____\ // \/_/\/__/\/_/\/__,_ /\ \ \/ \/___/ \/____/\/____/ // \ \_\ // \/_/ // // 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 ofconditions 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 materialsprovided 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 <Object/FunctionObject.hh> #include <Compiler/FunctionCompiler.hh> namespace Tadpole::Compiler { int FunctionCompiler::resolve_local(const Lex::Token& name, const ErrorFn& errfn) { for (int i = locals_count() - 1; i >= 0; --i) { const LocalVar& local = locals_[i]; if (local.name == name && local.depth == -1) errfn(Common::from_fmt("cannot load local variable `%s` in its own initializer", name.as_cstring())); } return -1; } int FunctionCompiler::add_upvalue(u8_t index, bool is_local) { for (sz_t i = 0; i < fn_->upvalues_count(); ++i) { if (upvalues_[i].is_equal(index, is_local)) return Common::as_type<int>(i); } upvalues_.push_back({index, is_local}); return Common::as_type<int>(fn_->inc_upvalues_count()); } int FunctionCompiler::resolve_upvalue(const Lex::Token& name, const ErrorFn& errfn) { if (enclosing_ == nullptr) return -1; if (int local = enclosing_->resolve_local(name, errfn); local != -1) { enclosing_->locals_[local].is_upvalue = true; return add_upvalue(Common::as_type<u8_t>(local), true); } if (int upvalue = enclosing_->resolve_upvalue(name, errfn); upvalue != -1) return add_upvalue(Common::as_type<u8_t>(upvalue), false); return -1; } void FunctionCompiler::declare_localvar(const Lex::Token& name, const ErrorFn& errfn) { // TODO: } } <commit_msg>:construction: chore(function-compiler): finished the implementation of function compiler<commit_after>// Copyright (c) 2021 ASMlover. All rights reserved. // // ______ __ ___ // /\__ _\ /\ \ /\_ \ // \/_/\ \/ __ \_\ \ _____ ___\//\ \ __ // \ \ \ /'__`\ /'_` \/\ '__`\ / __`\\ \ \ /'__`\ // \ \ \/\ \L\.\_/\ \L\ \ \ \L\ \/\ \L\ \\_\ \_/\ __/ // \ \_\ \__/.\_\ \___,_\ \ ,__/\ \____//\____\ \____\ // \/_/\/__/\/_/\/__,_ /\ \ \/ \/___/ \/____/\/____/ // \ \_\ // \/_/ // // 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 ofconditions 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 materialsprovided 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 <Object/FunctionObject.hh> #include <Compiler/FunctionCompiler.hh> namespace Tadpole::Compiler { int FunctionCompiler::resolve_local(const Lex::Token& name, const ErrorFn& errfn) { for (int i = locals_count() - 1; i >= 0; --i) { const LocalVar& local = locals_[i]; if (local.name == name && local.depth == -1) errfn(Common::from_fmt("cannot load local variable `%s` in its own initializer", name.as_cstring())); } return -1; } int FunctionCompiler::add_upvalue(u8_t index, bool is_local) { for (sz_t i = 0; i < fn_->upvalues_count(); ++i) { if (upvalues_[i].is_equal(index, is_local)) return Common::as_type<int>(i); } upvalues_.push_back({index, is_local}); return Common::as_type<int>(fn_->inc_upvalues_count()); } int FunctionCompiler::resolve_upvalue(const Lex::Token& name, const ErrorFn& errfn) { if (enclosing_ == nullptr) return -1; if (int local = enclosing_->resolve_local(name, errfn); local != -1) { enclosing_->locals_[local].is_upvalue = true; return add_upvalue(Common::as_type<u8_t>(local), true); } if (int upvalue = enclosing_->resolve_upvalue(name, errfn); upvalue != -1) return add_upvalue(Common::as_type<u8_t>(upvalue), false); return -1; } void FunctionCompiler::declare_localvar(const Lex::Token& name, const ErrorFn& errfn) { if (scope_depth_ == 0) return; for (auto it = locals_.rbegin(); it != locals_.rend(); ++it) { if (it->depth != -1 && it->depth < scope_depth_) break; if (it->name == name) errfn(Common::from_fmt("name `%s` is redefined", name.as_cstring())); } locals_.push_back({name, -1, false}); } } <|endoftext|>
<commit_before>/* * Copyright (C) 2019 The Android Open Source Project * * 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/trace_processor/sqlite/db_sqlite_table.h" #include "src/trace_processor/sqlite/sqlite_utils.h" namespace perfetto { namespace trace_processor { namespace { FilterOp SqliteOpToFilterOp(int sqlite_op) { switch (sqlite_op) { case SQLITE_INDEX_CONSTRAINT_EQ: case SQLITE_INDEX_CONSTRAINT_IS: return FilterOp::kEq; case SQLITE_INDEX_CONSTRAINT_GT: return FilterOp::kGt; case SQLITE_INDEX_CONSTRAINT_LT: return FilterOp::kLt; case SQLITE_INDEX_CONSTRAINT_ISNOT: case SQLITE_INDEX_CONSTRAINT_NE: return FilterOp::kNe; case SQLITE_INDEX_CONSTRAINT_GE: return FilterOp::kGe; case SQLITE_INDEX_CONSTRAINT_LE: return FilterOp::kLe; case SQLITE_INDEX_CONSTRAINT_ISNULL: return FilterOp::kIsNull; case SQLITE_INDEX_CONSTRAINT_ISNOTNULL: return FilterOp::kIsNotNull; case SQLITE_INDEX_CONSTRAINT_LIKE: return FilterOp::kLike; default: PERFETTO_FATAL("Currently unsupported constraint"); } } SqlValue SqliteValueToSqlValue(sqlite3_value* sqlite_val) { auto col_type = sqlite3_value_type(sqlite_val); SqlValue value; switch (col_type) { case SQLITE_INTEGER: value.type = SqlValue::kLong; value.long_value = sqlite3_value_int64(sqlite_val); break; case SQLITE_TEXT: value.type = SqlValue::kString; value.string_value = reinterpret_cast<const char*>(sqlite3_value_text(sqlite_val)); break; case SQLITE_FLOAT: value.type = SqlValue::kDouble; value.double_value = sqlite3_value_double(sqlite_val); break; case SQLITE_BLOB: value.type = SqlValue::kBytes; value.bytes_value = sqlite3_value_blob(sqlite_val); value.bytes_count = static_cast<size_t>(sqlite3_value_bytes(sqlite_val)); break; case SQLITE_NULL: value.type = SqlValue::kNull; break; } return value; } } // namespace DbSqliteTable::DbSqliteTable(sqlite3*, const Table* table) : table_(table) {} DbSqliteTable::~DbSqliteTable() = default; void DbSqliteTable::RegisterTable(sqlite3* db, const Table* table, const std::string& name) { SqliteTable::Register<DbSqliteTable, const Table*>(db, table, name); } util::Status DbSqliteTable::Init(int, const char* const*, Schema* schema) { std::vector<SqliteTable::Column> schema_cols; for (uint32_t i = 0; i < table_->GetColumnCount(); ++i) { const auto& col = table_->GetColumn(i); schema_cols.emplace_back(i, col.name(), col.type()); } // TODO(lalitm): this is hardcoded to be the id column but change this to be // more generic in the future. auto opt_idx = table_->FindColumnIdxByName("id"); if (!opt_idx) { PERFETTO_FATAL( "id column not found in %s. Currently all db Tables need to contain an " "id column; this constraint will be relaxed in the future.", name().c_str()); } std::vector<size_t> primary_keys; primary_keys.emplace_back(*opt_idx); *schema = Schema(std::move(schema_cols), std::move(primary_keys)); return util::OkStatus(); } int DbSqliteTable::BestIndex(const QueryConstraints& qc, BestIndexInfo* info) { // TODO(lalitm): investigate SQLITE_INDEX_SCAN_UNIQUE for id columns. auto cost_and_rows = EstimateCost(*table_, qc); info->estimated_cost = cost_and_rows.cost; info->estimated_rows = cost_and_rows.rows; return SQLITE_OK; } int DbSqliteTable::ModifyConstraints(QueryConstraints* qc) { using C = QueryConstraints::Constraint; // Reorder constraints to consider the constraints on columns which are // cheaper to filter first. auto* cs = qc->mutable_constraints(); std::sort(cs->begin(), cs->end(), [this](const C& a, const C& b) { uint32_t a_idx = static_cast<uint32_t>(a.column); uint32_t b_idx = static_cast<uint32_t>(b.column); const auto& a_col = table_->GetColumn(a_idx); const auto& b_col = table_->GetColumn(b_idx); // Id columns are always very cheap to filter on so try and get them // first. if (a_col.IsId() && !b_col.IsId()) return true; // Sorted columns are also quite cheap to filter so order them after // any id columns. if (a_col.IsSorted() && !b_col.IsSorted()) return true; // TODO(lalitm): introduce more orderings here based on empirical data. return false; }); // Remove any order by constraints which also have an equality constraint. auto* ob = qc->mutable_order_by(); { auto p = [&cs](const QueryConstraints::OrderBy& o) { auto inner_p = [&o](const QueryConstraints::Constraint& c) { return c.column == o.iColumn && sqlite_utils::IsOpEq(c.op); }; return std::any_of(cs->begin(), cs->end(), inner_p); }; auto remove_it = std::remove_if(ob->begin(), ob->end(), p); ob->erase(remove_it, ob->end()); } // Go through the order by constraints in reverse order and eliminate // constraints until the first non-sorted column or the first order by in // descending order. { auto p = [this](const QueryConstraints::OrderBy& o) { const auto& col = table_->GetColumn(static_cast<uint32_t>(o.iColumn)); return o.desc || !col.IsSorted(); }; auto first_non_sorted_it = std::find_if(ob->rbegin(), ob->rend(), p); auto pop_count = std::distance(ob->rbegin(), first_non_sorted_it); ob->resize(ob->size() - static_cast<uint32_t>(pop_count)); } return SQLITE_OK; } DbSqliteTable::QueryCost DbSqliteTable::EstimateCost( const Table& table, const QueryConstraints& qc) { // Currently our cost estimation algorithm is quite simplistic but is good // enough for the simplest cases. // TODO(lalitm): replace hardcoded constants with either more heuristics // based on the exact type of constraint or profiling the queries themselves. // We estimate the fixed cost of set-up and tear-down of a query in terms of // the number of rows scanned. constexpr double kFixedQueryCost = 1000.0; // Setup the variables for estimating the number of rows we will have at the // end of filtering. Note that |current_row_count| should always be at least 1 // unless we are absolutely certain that we will return no rows as otherwise // SQLite can make some bad choices. uint32_t current_row_count = table.size(); // If the table is empty, any constraint set only pays the fixed cost. Also we // can return 0 as the row count as we are certain that we will return no // rows. if (current_row_count == 0) return QueryCost{kFixedQueryCost, 0}; // Setup the variables for estimating the cost of filtering. double filter_cost = 0.0; const auto& cs = qc.constraints(); for (const auto& c : cs) { const auto& col = table.GetColumn(static_cast<uint32_t>(c.column)); if (sqlite_utils::IsOpEq(c.op) && col.IsId()) { // If we have an id equality constraint, it's a bit expensive to find // the exact row but it filters down to a single row. filter_cost += 100; current_row_count = 1; } else if (sqlite_utils::IsOpEq(c.op)) { // If there is only a single equality constraint, we have special logic // to sort by that column and then binary search if we see the constraint // set often. Model this by dividing but the log of the number of rows as // a good approximation. Otherwise, we'll need to do a full table scan. filter_cost += cs.size() == 1 ? (2 * current_row_count) / log2(current_row_count) : current_row_count; // We assume that an equalty constraint will cut down the number of rows // by approximate log of the number of rows. double estimated_rows = current_row_count / log2(current_row_count); current_row_count = std::max(static_cast<uint32_t>(estimated_rows), 1u); } else { // Otherwise, we will need to do a full table scan and we estimate we will // maybe (at best) halve the number of rows. filter_cost += current_row_count; current_row_count = std::max(current_row_count / 2u, 1u); } } // Now, to figure out the cost of sorting, multiply the final row count // by |qc.order_by().size()| * log(row count). This should act as a crude // estimation of the cost. double sort_cost = qc.order_by().size() * current_row_count * log2(current_row_count); // The cost of iterating rows is more expensive than filtering the rows // so multiply by an appropriate factor. double iteration_cost = current_row_count * 2.0; // To get the final cost, add up all the individual components. double final_cost = kFixedQueryCost + filter_cost + sort_cost + iteration_cost; return QueryCost{final_cost, current_row_count}; } std::unique_ptr<SqliteTable::Cursor> DbSqliteTable::CreateCursor() { return std::unique_ptr<Cursor>(new Cursor(this)); } DbSqliteTable::Cursor::Cursor(DbSqliteTable* table) : SqliteTable::Cursor(table), initial_db_table_(table->table_) {} int DbSqliteTable::Cursor::Filter(const QueryConstraints& qc, sqlite3_value** argv, FilterHistory history) { // Clear out the iterator before filtering to ensure the destructor is run // before the table's destructor. iterator_ = base::nullopt; if (history == FilterHistory::kSame && qc.constraints().size() == 1 && sqlite_utils::IsOpEq(qc.constraints().front().op)) { // If we've seen the same constraint set with a single equality constraint // more than |kRepeatedThreshold| times, we assume we will see it more // in the future and thus cache a table sorted on the column. That way, // future equality constraints can binary search for the value instead of // doing a full table scan. constexpr uint32_t kRepeatedThreshold = 3; if (!sorted_cache_table_ && repeated_cache_count_++ > kRepeatedThreshold) { const auto& c = qc.constraints().front(); uint32_t col = static_cast<uint32_t>(c.column); sorted_cache_table_ = initial_db_table_->Sort({Order{col, false}}); } } else { sorted_cache_table_ = base::nullopt; repeated_cache_count_ = 0; } // We reuse this vector to reduce memory allocations on nested subqueries. constraints_.resize(qc.constraints().size()); for (size_t i = 0; i < qc.constraints().size(); ++i) { const auto& cs = qc.constraints()[i]; uint32_t col = static_cast<uint32_t>(cs.column); FilterOp op = SqliteOpToFilterOp(cs.op); SqlValue value = SqliteValueToSqlValue(argv[i]); constraints_[i] = Constraint{col, op, value}; } // We reuse this vector to reduce memory allocations on nested subqueries. orders_.resize(qc.order_by().size()); for (size_t i = 0; i < qc.order_by().size(); ++i) { const auto& ob = qc.order_by()[i]; uint32_t col = static_cast<uint32_t>(ob.iColumn); orders_[i] = Order{col, static_cast<bool>(ob.desc)}; } // Try and use the sorted cache table (if it exists) to speed up the sorting. // Otherwise, just use the original table. auto* source = sorted_cache_table_ ? &*sorted_cache_table_ : &*initial_db_table_; db_table_ = source->Filter(constraints_).Sort(orders_); iterator_ = db_table_->IterateRows(); return SQLITE_OK; } int DbSqliteTable::Cursor::Next() { iterator_->Next(); return SQLITE_OK; } int DbSqliteTable::Cursor::Eof() { return !*iterator_; } int DbSqliteTable::Cursor::Column(sqlite3_context* ctx, int raw_col) { uint32_t column = static_cast<uint32_t>(raw_col); SqlValue value = iterator_->Get(column); switch (value.type) { case SqlValue::Type::kLong: sqlite3_result_int64(ctx, value.long_value); break; case SqlValue::Type::kDouble: sqlite3_result_double(ctx, value.double_value); break; case SqlValue::Type::kString: { // We can say kSqliteStatic here because all strings are expected to // come from the string pool and thus will be valid for the lifetime // of trace processor. sqlite3_result_text(ctx, value.string_value, -1, sqlite_utils::kSqliteStatic); break; } case SqlValue::Type::kBytes: { // We can say kSqliteStatic here because for our iterator will hold // onto the pointer as long as we don't call Next() but that only // happens with Next() is called on the Cursor itself at which point // SQLite no longer cares about the bytes pointer. sqlite3_result_blob(ctx, value.bytes_value, static_cast<int>(value.bytes_count), sqlite_utils::kSqliteStatic); break; } case SqlValue::Type::kNull: sqlite3_result_null(ctx); break; } return SQLITE_OK; } } // namespace trace_processor } // namespace perfetto <commit_msg>Fix cost estimation for single row am: 9faab56544<commit_after>/* * Copyright (C) 2019 The Android Open Source Project * * 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/trace_processor/sqlite/db_sqlite_table.h" #include "src/trace_processor/sqlite/sqlite_utils.h" namespace perfetto { namespace trace_processor { namespace { FilterOp SqliteOpToFilterOp(int sqlite_op) { switch (sqlite_op) { case SQLITE_INDEX_CONSTRAINT_EQ: case SQLITE_INDEX_CONSTRAINT_IS: return FilterOp::kEq; case SQLITE_INDEX_CONSTRAINT_GT: return FilterOp::kGt; case SQLITE_INDEX_CONSTRAINT_LT: return FilterOp::kLt; case SQLITE_INDEX_CONSTRAINT_ISNOT: case SQLITE_INDEX_CONSTRAINT_NE: return FilterOp::kNe; case SQLITE_INDEX_CONSTRAINT_GE: return FilterOp::kGe; case SQLITE_INDEX_CONSTRAINT_LE: return FilterOp::kLe; case SQLITE_INDEX_CONSTRAINT_ISNULL: return FilterOp::kIsNull; case SQLITE_INDEX_CONSTRAINT_ISNOTNULL: return FilterOp::kIsNotNull; case SQLITE_INDEX_CONSTRAINT_LIKE: return FilterOp::kLike; default: PERFETTO_FATAL("Currently unsupported constraint"); } } SqlValue SqliteValueToSqlValue(sqlite3_value* sqlite_val) { auto col_type = sqlite3_value_type(sqlite_val); SqlValue value; switch (col_type) { case SQLITE_INTEGER: value.type = SqlValue::kLong; value.long_value = sqlite3_value_int64(sqlite_val); break; case SQLITE_TEXT: value.type = SqlValue::kString; value.string_value = reinterpret_cast<const char*>(sqlite3_value_text(sqlite_val)); break; case SQLITE_FLOAT: value.type = SqlValue::kDouble; value.double_value = sqlite3_value_double(sqlite_val); break; case SQLITE_BLOB: value.type = SqlValue::kBytes; value.bytes_value = sqlite3_value_blob(sqlite_val); value.bytes_count = static_cast<size_t>(sqlite3_value_bytes(sqlite_val)); break; case SQLITE_NULL: value.type = SqlValue::kNull; break; } return value; } } // namespace DbSqliteTable::DbSqliteTable(sqlite3*, const Table* table) : table_(table) {} DbSqliteTable::~DbSqliteTable() = default; void DbSqliteTable::RegisterTable(sqlite3* db, const Table* table, const std::string& name) { SqliteTable::Register<DbSqliteTable, const Table*>(db, table, name); } util::Status DbSqliteTable::Init(int, const char* const*, Schema* schema) { std::vector<SqliteTable::Column> schema_cols; for (uint32_t i = 0; i < table_->GetColumnCount(); ++i) { const auto& col = table_->GetColumn(i); schema_cols.emplace_back(i, col.name(), col.type()); } // TODO(lalitm): this is hardcoded to be the id column but change this to be // more generic in the future. auto opt_idx = table_->FindColumnIdxByName("id"); if (!opt_idx) { PERFETTO_FATAL( "id column not found in %s. Currently all db Tables need to contain an " "id column; this constraint will be relaxed in the future.", name().c_str()); } std::vector<size_t> primary_keys; primary_keys.emplace_back(*opt_idx); *schema = Schema(std::move(schema_cols), std::move(primary_keys)); return util::OkStatus(); } int DbSqliteTable::BestIndex(const QueryConstraints& qc, BestIndexInfo* info) { // TODO(lalitm): investigate SQLITE_INDEX_SCAN_UNIQUE for id columns. auto cost_and_rows = EstimateCost(*table_, qc); info->estimated_cost = cost_and_rows.cost; info->estimated_rows = cost_and_rows.rows; return SQLITE_OK; } int DbSqliteTable::ModifyConstraints(QueryConstraints* qc) { using C = QueryConstraints::Constraint; // Reorder constraints to consider the constraints on columns which are // cheaper to filter first. auto* cs = qc->mutable_constraints(); std::sort(cs->begin(), cs->end(), [this](const C& a, const C& b) { uint32_t a_idx = static_cast<uint32_t>(a.column); uint32_t b_idx = static_cast<uint32_t>(b.column); const auto& a_col = table_->GetColumn(a_idx); const auto& b_col = table_->GetColumn(b_idx); // Id columns are always very cheap to filter on so try and get them // first. if (a_col.IsId() && !b_col.IsId()) return true; // Sorted columns are also quite cheap to filter so order them after // any id columns. if (a_col.IsSorted() && !b_col.IsSorted()) return true; // TODO(lalitm): introduce more orderings here based on empirical data. return false; }); // Remove any order by constraints which also have an equality constraint. auto* ob = qc->mutable_order_by(); { auto p = [&cs](const QueryConstraints::OrderBy& o) { auto inner_p = [&o](const QueryConstraints::Constraint& c) { return c.column == o.iColumn && sqlite_utils::IsOpEq(c.op); }; return std::any_of(cs->begin(), cs->end(), inner_p); }; auto remove_it = std::remove_if(ob->begin(), ob->end(), p); ob->erase(remove_it, ob->end()); } // Go through the order by constraints in reverse order and eliminate // constraints until the first non-sorted column or the first order by in // descending order. { auto p = [this](const QueryConstraints::OrderBy& o) { const auto& col = table_->GetColumn(static_cast<uint32_t>(o.iColumn)); return o.desc || !col.IsSorted(); }; auto first_non_sorted_it = std::find_if(ob->rbegin(), ob->rend(), p); auto pop_count = std::distance(ob->rbegin(), first_non_sorted_it); ob->resize(ob->size() - static_cast<uint32_t>(pop_count)); } return SQLITE_OK; } DbSqliteTable::QueryCost DbSqliteTable::EstimateCost( const Table& table, const QueryConstraints& qc) { // Currently our cost estimation algorithm is quite simplistic but is good // enough for the simplest cases. // TODO(lalitm): replace hardcoded constants with either more heuristics // based on the exact type of constraint or profiling the queries themselves. // We estimate the fixed cost of set-up and tear-down of a query in terms of // the number of rows scanned. constexpr double kFixedQueryCost = 1000.0; // Setup the variables for estimating the number of rows we will have at the // end of filtering. Note that |current_row_count| should always be at least 1 // unless we are absolutely certain that we will return no rows as otherwise // SQLite can make some bad choices. uint32_t current_row_count = table.size(); // If the table is empty, any constraint set only pays the fixed cost. Also we // can return 0 as the row count as we are certain that we will return no // rows. if (current_row_count == 0) return QueryCost{kFixedQueryCost, 0}; // Setup the variables for estimating the cost of filtering. double filter_cost = 0.0; const auto& cs = qc.constraints(); for (const auto& c : cs) { if (current_row_count < 2) break; const auto& col = table.GetColumn(static_cast<uint32_t>(c.column)); if (sqlite_utils::IsOpEq(c.op) && col.IsId()) { // If we have an id equality constraint, it's a bit expensive to find // the exact row but it filters down to a single row. filter_cost += 100; current_row_count = 1; } else if (sqlite_utils::IsOpEq(c.op)) { // If there is only a single equality constraint, we have special logic // to sort by that column and then binary search if we see the constraint // set often. Model this by dividing but the log of the number of rows as // a good approximation. Otherwise, we'll need to do a full table scan. filter_cost += cs.size() == 1 ? (2 * current_row_count) / log2(current_row_count) : current_row_count; // We assume that an equalty constraint will cut down the number of rows // by approximate log of the number of rows. double estimated_rows = current_row_count / log2(current_row_count); current_row_count = std::max(static_cast<uint32_t>(estimated_rows), 1u); } else { // Otherwise, we will need to do a full table scan and we estimate we will // maybe (at best) halve the number of rows. filter_cost += current_row_count; current_row_count = std::max(current_row_count / 2u, 1u); } } // Now, to figure out the cost of sorting, multiply the final row count // by |qc.order_by().size()| * log(row count). This should act as a crude // estimation of the cost. double sort_cost = qc.order_by().size() * current_row_count * log2(current_row_count); // The cost of iterating rows is more expensive than filtering the rows // so multiply by an appropriate factor. double iteration_cost = current_row_count * 2.0; // To get the final cost, add up all the individual components. double final_cost = kFixedQueryCost + filter_cost + sort_cost + iteration_cost; return QueryCost{final_cost, current_row_count}; } std::unique_ptr<SqliteTable::Cursor> DbSqliteTable::CreateCursor() { return std::unique_ptr<Cursor>(new Cursor(this)); } DbSqliteTable::Cursor::Cursor(DbSqliteTable* table) : SqliteTable::Cursor(table), initial_db_table_(table->table_) {} int DbSqliteTable::Cursor::Filter(const QueryConstraints& qc, sqlite3_value** argv, FilterHistory history) { // Clear out the iterator before filtering to ensure the destructor is run // before the table's destructor. iterator_ = base::nullopt; if (history == FilterHistory::kSame && qc.constraints().size() == 1 && sqlite_utils::IsOpEq(qc.constraints().front().op)) { // If we've seen the same constraint set with a single equality constraint // more than |kRepeatedThreshold| times, we assume we will see it more // in the future and thus cache a table sorted on the column. That way, // future equality constraints can binary search for the value instead of // doing a full table scan. constexpr uint32_t kRepeatedThreshold = 3; if (!sorted_cache_table_ && repeated_cache_count_++ > kRepeatedThreshold) { const auto& c = qc.constraints().front(); uint32_t col = static_cast<uint32_t>(c.column); sorted_cache_table_ = initial_db_table_->Sort({Order{col, false}}); } } else { sorted_cache_table_ = base::nullopt; repeated_cache_count_ = 0; } // We reuse this vector to reduce memory allocations on nested subqueries. constraints_.resize(qc.constraints().size()); for (size_t i = 0; i < qc.constraints().size(); ++i) { const auto& cs = qc.constraints()[i]; uint32_t col = static_cast<uint32_t>(cs.column); FilterOp op = SqliteOpToFilterOp(cs.op); SqlValue value = SqliteValueToSqlValue(argv[i]); constraints_[i] = Constraint{col, op, value}; } // We reuse this vector to reduce memory allocations on nested subqueries. orders_.resize(qc.order_by().size()); for (size_t i = 0; i < qc.order_by().size(); ++i) { const auto& ob = qc.order_by()[i]; uint32_t col = static_cast<uint32_t>(ob.iColumn); orders_[i] = Order{col, static_cast<bool>(ob.desc)}; } // Try and use the sorted cache table (if it exists) to speed up the sorting. // Otherwise, just use the original table. auto* source = sorted_cache_table_ ? &*sorted_cache_table_ : &*initial_db_table_; db_table_ = source->Filter(constraints_).Sort(orders_); iterator_ = db_table_->IterateRows(); return SQLITE_OK; } int DbSqliteTable::Cursor::Next() { iterator_->Next(); return SQLITE_OK; } int DbSqliteTable::Cursor::Eof() { return !*iterator_; } int DbSqliteTable::Cursor::Column(sqlite3_context* ctx, int raw_col) { uint32_t column = static_cast<uint32_t>(raw_col); SqlValue value = iterator_->Get(column); switch (value.type) { case SqlValue::Type::kLong: sqlite3_result_int64(ctx, value.long_value); break; case SqlValue::Type::kDouble: sqlite3_result_double(ctx, value.double_value); break; case SqlValue::Type::kString: { // We can say kSqliteStatic here because all strings are expected to // come from the string pool and thus will be valid for the lifetime // of trace processor. sqlite3_result_text(ctx, value.string_value, -1, sqlite_utils::kSqliteStatic); break; } case SqlValue::Type::kBytes: { // We can say kSqliteStatic here because for our iterator will hold // onto the pointer as long as we don't call Next() but that only // happens with Next() is called on the Cursor itself at which point // SQLite no longer cares about the bytes pointer. sqlite3_result_blob(ctx, value.bytes_value, static_cast<int>(value.bytes_count), sqlite_utils::kSqliteStatic); break; } case SqlValue::Type::kNull: sqlite3_result_null(ctx); break; } return SQLITE_OK; } } // namespace trace_processor } // namespace perfetto <|endoftext|>
<commit_before>/*----------------------------------------------------------------------------*/ /* Copyright (c) FIRST 2016. All Rights Reserved. */ /* Open Source Software - may be modified and shared by FRC teams. The code */ /* must be accompanied by the FIRST BSD license file in the root directory of */ /* the project. */ /*----------------------------------------------------------------------------*/ #include "HAL/AnalogGyro.h" #include <chrono> #include <thread> #include "AnalogInternal.h" #include "HAL/AnalogAccumulator.h" #include "HAL/AnalogInput.h" #include "HAL/handles/IndexedHandleResource.h" namespace { struct AnalogGyro { HAL_AnalogInputHandle handle; double voltsPerDegreePerSecond; double offset; int32_t center; }; } static constexpr uint32_t kOversampleBits = 10; static constexpr uint32_t kAverageBits = 0; static constexpr double kSamplesPerSecond = 50.0; static constexpr double kCalibrationSampleTime = 5.0; static constexpr double kDefaultVoltsPerDegreePerSecond = 0.007; using namespace hal; static IndexedHandleResource<HAL_GyroHandle, AnalogGyro, kNumAccumulators, HAL_HandleEnum::AnalogGyro> analogGyroHandles; static void Wait(double seconds) { if (seconds < 0.0) return; std::this_thread::sleep_for(std::chrono::duration<double>(seconds)); } extern "C" { HAL_GyroHandle HAL_InitializeAnalogGyro(HAL_AnalogInputHandle analog_handle, int32_t* status) { if (!HAL_IsAccumulatorChannel(analog_handle, status)) { if (*status == 0) { *status = HAL_INVALID_ACCUMULATOR_CHANNEL; } return HAL_kInvalidHandle; } // handle known to be correct, so no need to type check int16_t channel = getHandleIndex(analog_handle); auto handle = analogGyroHandles.Allocate(channel, status); if (*status != 0) return HAL_kInvalidHandle; // failed to allocate. Pass error back. // Initialize port structure auto gyro = analogGyroHandles.Get(handle); if (gyro == nullptr) { // would only error on thread issue *status = HAL_HANDLE_ERROR; return HAL_kInvalidHandle; } gyro->handle = analog_handle; gyro->voltsPerDegreePerSecond = 0; gyro->offset = 0; gyro->center = 0; return handle; } void HAL_SetupAnalogGyro(HAL_GyroHandle handle, int32_t* status) { auto gyro = analogGyroHandles.Get(handle); if (gyro == nullptr) { *status = HAL_HANDLE_ERROR; return; } gyro->voltsPerDegreePerSecond = kDefaultVoltsPerDegreePerSecond; HAL_SetAnalogAverageBits(gyro->handle, kAverageBits, status); if (*status != 0) return; HAL_SetAnalogOversampleBits(gyro->handle, kOversampleBits, status); if (*status != 0) return; float sampleRate = kSamplesPerSecond * (1 << (kAverageBits + kOversampleBits)); HAL_SetAnalogSampleRate(sampleRate, status); if (*status != 0) return; Wait(0.1); HAL_SetAnalogGyroDeadband(handle, 0.0f, status); if (*status != 0) return; } void HAL_FreeAnalogGyro(HAL_GyroHandle handle) { analogGyroHandles.Free(handle); } void HAL_SetAnalogGyroParameters(HAL_GyroHandle handle, double voltsPerDegreePerSecond, double offset, int32_t center, int32_t* status) { auto gyro = analogGyroHandles.Get(handle); if (gyro == nullptr) { *status = HAL_HANDLE_ERROR; return; } gyro->voltsPerDegreePerSecond = voltsPerDegreePerSecond; gyro->offset = offset; gyro->center = center; HAL_SetAccumulatorCenter(gyro->handle, center, status); } void HAL_SetAnalogGyroVoltsPerDegreePerSecond(HAL_GyroHandle handle, double voltsPerDegreePerSecond, int32_t* status) { auto gyro = analogGyroHandles.Get(handle); if (gyro == nullptr) { *status = HAL_HANDLE_ERROR; return; } gyro->voltsPerDegreePerSecond = voltsPerDegreePerSecond; } void HAL_ResetAnalogGyro(HAL_GyroHandle handle, int32_t* status) { auto gyro = analogGyroHandles.Get(handle); if (gyro == nullptr) { *status = HAL_HANDLE_ERROR; return; } HAL_ResetAccumulator(gyro->handle, status); if (*status != 0) return; const double sampleTime = 1.0 / HAL_GetAnalogSampleRate(status); const double overSamples = 1 << HAL_GetAnalogOversampleBits(gyro->handle, status); const double averageSamples = 1 << HAL_GetAnalogAverageBits(gyro->handle, status); if (*status != 0) return; Wait(sampleTime * overSamples * averageSamples); } void HAL_CalibrateAnalogGyro(HAL_GyroHandle handle, int32_t* status) { auto gyro = analogGyroHandles.Get(handle); if (gyro == nullptr) { *status = HAL_HANDLE_ERROR; return; } HAL_InitAccumulator(gyro->handle, status); if (*status != 0) return; Wait(kCalibrationSampleTime); int64_t value; int64_t count; HAL_GetAccumulatorOutput(gyro->handle, &value, &count, status); if (*status != 0) return; gyro->center = static_cast<int32_t>( static_cast<double>(value) / static_cast<double>(count) + .5); gyro->offset = static_cast<double>(value) / static_cast<double>(count) - static_cast<double>(gyro->center); HAL_SetAccumulatorCenter(gyro->handle, gyro->center, status); if (*status != 0) return; HAL_ResetAnalogGyro(handle, status); } void HAL_SetAnalogGyroDeadband(HAL_GyroHandle handle, double volts, int32_t* status) { auto gyro = analogGyroHandles.Get(handle); if (gyro == nullptr) { *status = HAL_HANDLE_ERROR; return; } int32_t deadband = static_cast<int32_t>( volts * 1e9 / HAL_GetAnalogLSBWeight(gyro->handle, status) * (1 << HAL_GetAnalogOversampleBits(gyro->handle, status))); if (*status != 0) return; HAL_SetAccumulatorDeadband(gyro->handle, deadband, status); } double HAL_GetAnalogGyroAngle(HAL_GyroHandle handle, int32_t* status) { auto gyro = analogGyroHandles.Get(handle); if (gyro == nullptr) { *status = HAL_HANDLE_ERROR; return 0; } int64_t rawValue = 0; int64_t count = 0; HAL_GetAccumulatorOutput(gyro->handle, &rawValue, &count, status); int64_t value = rawValue - static_cast<int64_t>(static_cast<double>(count) * gyro->offset); double scaledValue = value * 1e-9 * static_cast<double>(HAL_GetAnalogLSBWeight(gyro->handle, status)) * static_cast<double>(1 << HAL_GetAnalogAverageBits(gyro->handle, status)) / (HAL_GetAnalogSampleRate(status) * gyro->voltsPerDegreePerSecond); return static_cast<float>(scaledValue); } double HAL_GetAnalogGyroRate(HAL_GyroHandle handle, int32_t* status) { auto gyro = analogGyroHandles.Get(handle); if (gyro == nullptr) { *status = HAL_HANDLE_ERROR; return 0; } return (HAL_GetAnalogAverageValue(gyro->handle, status) - (static_cast<double>(gyro->center) + gyro->offset)) * 1e-9 * HAL_GetAnalogLSBWeight(gyro->handle, status) / ((1 << HAL_GetAnalogOversampleBits(gyro->handle, status)) * gyro->voltsPerDegreePerSecond); } double HAL_GetAnalogGyroOffset(HAL_GyroHandle handle, int32_t* status) { auto gyro = analogGyroHandles.Get(handle); if (gyro == nullptr) { *status = HAL_HANDLE_ERROR; return 0; } return gyro->offset; } int32_t HAL_GetAnalogGyroCenter(HAL_GyroHandle handle, int32_t* status) { auto gyro = analogGyroHandles.Get(handle); if (gyro == nullptr) { *status = HAL_HANDLE_ERROR; return 0; } return gyro->center; } } <commit_msg>Fixes analog gyro casting to float then returning double (#177)<commit_after>/*----------------------------------------------------------------------------*/ /* Copyright (c) FIRST 2016. All Rights Reserved. */ /* Open Source Software - may be modified and shared by FRC teams. The code */ /* must be accompanied by the FIRST BSD license file in the root directory of */ /* the project. */ /*----------------------------------------------------------------------------*/ #include "HAL/AnalogGyro.h" #include <chrono> #include <thread> #include "AnalogInternal.h" #include "HAL/AnalogAccumulator.h" #include "HAL/AnalogInput.h" #include "HAL/handles/IndexedHandleResource.h" namespace { struct AnalogGyro { HAL_AnalogInputHandle handle; double voltsPerDegreePerSecond; double offset; int32_t center; }; } static constexpr uint32_t kOversampleBits = 10; static constexpr uint32_t kAverageBits = 0; static constexpr double kSamplesPerSecond = 50.0; static constexpr double kCalibrationSampleTime = 5.0; static constexpr double kDefaultVoltsPerDegreePerSecond = 0.007; using namespace hal; static IndexedHandleResource<HAL_GyroHandle, AnalogGyro, kNumAccumulators, HAL_HandleEnum::AnalogGyro> analogGyroHandles; static void Wait(double seconds) { if (seconds < 0.0) return; std::this_thread::sleep_for(std::chrono::duration<double>(seconds)); } extern "C" { HAL_GyroHandle HAL_InitializeAnalogGyro(HAL_AnalogInputHandle analog_handle, int32_t* status) { if (!HAL_IsAccumulatorChannel(analog_handle, status)) { if (*status == 0) { *status = HAL_INVALID_ACCUMULATOR_CHANNEL; } return HAL_kInvalidHandle; } // handle known to be correct, so no need to type check int16_t channel = getHandleIndex(analog_handle); auto handle = analogGyroHandles.Allocate(channel, status); if (*status != 0) return HAL_kInvalidHandle; // failed to allocate. Pass error back. // Initialize port structure auto gyro = analogGyroHandles.Get(handle); if (gyro == nullptr) { // would only error on thread issue *status = HAL_HANDLE_ERROR; return HAL_kInvalidHandle; } gyro->handle = analog_handle; gyro->voltsPerDegreePerSecond = 0; gyro->offset = 0; gyro->center = 0; return handle; } void HAL_SetupAnalogGyro(HAL_GyroHandle handle, int32_t* status) { auto gyro = analogGyroHandles.Get(handle); if (gyro == nullptr) { *status = HAL_HANDLE_ERROR; return; } gyro->voltsPerDegreePerSecond = kDefaultVoltsPerDegreePerSecond; HAL_SetAnalogAverageBits(gyro->handle, kAverageBits, status); if (*status != 0) return; HAL_SetAnalogOversampleBits(gyro->handle, kOversampleBits, status); if (*status != 0) return; float sampleRate = kSamplesPerSecond * (1 << (kAverageBits + kOversampleBits)); HAL_SetAnalogSampleRate(sampleRate, status); if (*status != 0) return; Wait(0.1); HAL_SetAnalogGyroDeadband(handle, 0.0f, status); if (*status != 0) return; } void HAL_FreeAnalogGyro(HAL_GyroHandle handle) { analogGyroHandles.Free(handle); } void HAL_SetAnalogGyroParameters(HAL_GyroHandle handle, double voltsPerDegreePerSecond, double offset, int32_t center, int32_t* status) { auto gyro = analogGyroHandles.Get(handle); if (gyro == nullptr) { *status = HAL_HANDLE_ERROR; return; } gyro->voltsPerDegreePerSecond = voltsPerDegreePerSecond; gyro->offset = offset; gyro->center = center; HAL_SetAccumulatorCenter(gyro->handle, center, status); } void HAL_SetAnalogGyroVoltsPerDegreePerSecond(HAL_GyroHandle handle, double voltsPerDegreePerSecond, int32_t* status) { auto gyro = analogGyroHandles.Get(handle); if (gyro == nullptr) { *status = HAL_HANDLE_ERROR; return; } gyro->voltsPerDegreePerSecond = voltsPerDegreePerSecond; } void HAL_ResetAnalogGyro(HAL_GyroHandle handle, int32_t* status) { auto gyro = analogGyroHandles.Get(handle); if (gyro == nullptr) { *status = HAL_HANDLE_ERROR; return; } HAL_ResetAccumulator(gyro->handle, status); if (*status != 0) return; const double sampleTime = 1.0 / HAL_GetAnalogSampleRate(status); const double overSamples = 1 << HAL_GetAnalogOversampleBits(gyro->handle, status); const double averageSamples = 1 << HAL_GetAnalogAverageBits(gyro->handle, status); if (*status != 0) return; Wait(sampleTime * overSamples * averageSamples); } void HAL_CalibrateAnalogGyro(HAL_GyroHandle handle, int32_t* status) { auto gyro = analogGyroHandles.Get(handle); if (gyro == nullptr) { *status = HAL_HANDLE_ERROR; return; } HAL_InitAccumulator(gyro->handle, status); if (*status != 0) return; Wait(kCalibrationSampleTime); int64_t value; int64_t count; HAL_GetAccumulatorOutput(gyro->handle, &value, &count, status); if (*status != 0) return; gyro->center = static_cast<int32_t>( static_cast<double>(value) / static_cast<double>(count) + .5); gyro->offset = static_cast<double>(value) / static_cast<double>(count) - static_cast<double>(gyro->center); HAL_SetAccumulatorCenter(gyro->handle, gyro->center, status); if (*status != 0) return; HAL_ResetAnalogGyro(handle, status); } void HAL_SetAnalogGyroDeadband(HAL_GyroHandle handle, double volts, int32_t* status) { auto gyro = analogGyroHandles.Get(handle); if (gyro == nullptr) { *status = HAL_HANDLE_ERROR; return; } int32_t deadband = static_cast<int32_t>( volts * 1e9 / HAL_GetAnalogLSBWeight(gyro->handle, status) * (1 << HAL_GetAnalogOversampleBits(gyro->handle, status))); if (*status != 0) return; HAL_SetAccumulatorDeadband(gyro->handle, deadband, status); } double HAL_GetAnalogGyroAngle(HAL_GyroHandle handle, int32_t* status) { auto gyro = analogGyroHandles.Get(handle); if (gyro == nullptr) { *status = HAL_HANDLE_ERROR; return 0; } int64_t rawValue = 0; int64_t count = 0; HAL_GetAccumulatorOutput(gyro->handle, &rawValue, &count, status); int64_t value = rawValue - static_cast<int64_t>(static_cast<double>(count) * gyro->offset); double scaledValue = value * 1e-9 * static_cast<double>(HAL_GetAnalogLSBWeight(gyro->handle, status)) * static_cast<double>(1 << HAL_GetAnalogAverageBits(gyro->handle, status)) / (HAL_GetAnalogSampleRate(status) * gyro->voltsPerDegreePerSecond); return scaledValue; } double HAL_GetAnalogGyroRate(HAL_GyroHandle handle, int32_t* status) { auto gyro = analogGyroHandles.Get(handle); if (gyro == nullptr) { *status = HAL_HANDLE_ERROR; return 0; } return (HAL_GetAnalogAverageValue(gyro->handle, status) - (static_cast<double>(gyro->center) + gyro->offset)) * 1e-9 * HAL_GetAnalogLSBWeight(gyro->handle, status) / ((1 << HAL_GetAnalogOversampleBits(gyro->handle, status)) * gyro->voltsPerDegreePerSecond); } double HAL_GetAnalogGyroOffset(HAL_GyroHandle handle, int32_t* status) { auto gyro = analogGyroHandles.Get(handle); if (gyro == nullptr) { *status = HAL_HANDLE_ERROR; return 0; } return gyro->offset; } int32_t HAL_GetAnalogGyroCenter(HAL_GyroHandle handle, int32_t* status) { auto gyro = analogGyroHandles.Get(handle); if (gyro == nullptr) { *status = HAL_HANDLE_ERROR; return 0; } return gyro->center; } } <|endoftext|>
<commit_before>#pragma once #include <string> #include <vector> #include "rapidjson/writer.h" #include "rapidjson/prettywriter.h" #include "rapidjson/error/en.h" #include "rapidjson/stringbuffer.h" #include "acmacs-base/read-file.hh" // ---------------------------------------------------------------------- template <typename RW> class JsonWriterT : public RW { public: inline JsonWriterT(std::string aKeyword) : RW(mBuffer), mKeyword(aKeyword) {} inline operator std::string() const { return mBuffer.GetString(); } inline std::string keyword() const { return mKeyword; } private: rapidjson::StringBuffer mBuffer; std::string mKeyword; }; // template <> inline JsonWriterT<rapidjson::PrettyWriter<rapidjson::StringBuffer>>::JsonWriterT(std::string aKeyword) // : rapidjson::PrettyWriter<rapidjson::StringBuffer>(mBuffer), mKeyword(aKeyword) // { // SetIndent(' ', 1); // } typedef JsonWriterT<rapidjson::Writer<rapidjson::StringBuffer>> JsonWriter; typedef JsonWriterT<rapidjson::PrettyWriter<rapidjson::StringBuffer>> JsonPrettyWriter; // ---------------------------------------------------------------------- enum _StartArray { StartArray }; enum _EndArray { EndArray }; enum _StartObject { StartObject }; enum _EndObject { EndObject }; template <typename RW> inline JsonWriterT<RW>& operator <<(JsonWriterT<RW>& writer, _StartArray) { writer.StartArray(); return writer; } template <typename RW> inline JsonWriterT<RW>& operator <<(JsonWriterT<RW>& writer, _EndArray) { writer.EndArray(); return writer; } template <typename RW> inline JsonWriterT<RW>& operator <<(JsonWriterT<RW>& writer, _StartObject) { writer.StartObject(); return writer; } template <typename RW> inline JsonWriterT<RW>& operator <<(JsonWriterT<RW>& writer, _EndObject) { writer.EndObject(); return writer; } template <typename RW> inline JsonWriterT<RW>& operator <<(JsonWriterT<RW>& writer, std::string s) { writer.String(s.c_str(), static_cast<unsigned>(s.size())); return writer; } template <typename RW> inline JsonWriterT<RW>& operator <<(JsonWriterT<RW>& writer, int value) { writer.Int(value); return writer; } template <typename RW, typename T> inline JsonWriterT<RW>& operator <<(JsonWriterT<RW>& writer, const std::vector<T>& list) { writer << StartArray; for (const auto& e: list) writer << e; return writer << EndArray; } // ---------------------------------------------------------------------- template <typename RW> inline JsonWriterT<RW>& operator <<(JsonWriterT<RW>& writer, const std::vector<std::vector<std::string>>& list_list_strings) { writer << StartArray; for (const auto& e: list_list_strings) writer << e; return writer << EndArray; } // ---------------------------------------------------------------------- template <typename V> inline std::string pretty_json(const V& value, std::string keyword, size_t indent, bool insert_emacs_indent_hint) { JsonPrettyWriter writer(keyword); writer.SetIndent(' ', static_cast<unsigned int>(indent)); writer << value; std::string result = writer; if (insert_emacs_indent_hint && result[0] == '{') { const std::string ind(indent - 1, ' '); result.insert(1, ind + "\"_\": \"-*- js-indent-level: " + std::to_string(indent) + " -*-\","); } return result; } template <typename V> inline std::string compact_json(const V& value, std::string keyword) { JsonWriter writer(keyword); return writer << value; } template <typename V> inline std::string json(const V& value, std::string keyword, size_t indent, bool insert_emacs_indent_hint = true) { if (indent) return pretty_json(value, keyword, indent, insert_emacs_indent_hint); else return compact_json(value, keyword); } // ---------------------------------------------------------------------- template <typename V> inline void export_to_json(const V& value, std::string keyword, std::string filename, size_t indent, bool insert_emacs_indent_hint = true) { acmacs_base::write_file(filename, json(value, keyword, indent, insert_emacs_indent_hint)); } // ---------------------------------------------------------------------- /// Local Variables: /// eval: (if (fboundp 'eu-rename-buffer) (eu-rename-buffer)) /// End: <commit_msg>support for JsonObjectKey<commit_after>#pragma once #include <string> #include <vector> #include "rapidjson/writer.h" #include "rapidjson/prettywriter.h" #include "rapidjson/error/en.h" #include "rapidjson/stringbuffer.h" #include "acmacs-base/read-file.hh" // ---------------------------------------------------------------------- template <typename RW> class JsonWriterT : public RW { public: inline JsonWriterT(std::string aKeyword) : RW(mBuffer), mKeyword(aKeyword) {} inline operator std::string() const { return mBuffer.GetString(); } inline std::string keyword() const { return mKeyword; } private: rapidjson::StringBuffer mBuffer; std::string mKeyword; }; // template <> inline JsonWriterT<rapidjson::PrettyWriter<rapidjson::StringBuffer>>::JsonWriterT(std::string aKeyword) // : rapidjson::PrettyWriter<rapidjson::StringBuffer>(mBuffer), mKeyword(aKeyword) // { // SetIndent(' ', 1); // } typedef JsonWriterT<rapidjson::Writer<rapidjson::StringBuffer>> JsonWriter; typedef JsonWriterT<rapidjson::PrettyWriter<rapidjson::StringBuffer>> JsonPrettyWriter; // ---------------------------------------------------------------------- enum _StartArray { StartArray }; enum _EndArray { EndArray }; enum _StartObject { StartObject }; enum _EndObject { EndObject }; template <typename RW> inline JsonWriterT<RW>& operator <<(JsonWriterT<RW>& writer, _StartArray) { writer.StartArray(); return writer; } template <typename RW> inline JsonWriterT<RW>& operator <<(JsonWriterT<RW>& writer, _EndArray) { writer.EndArray(); return writer; } template <typename RW> inline JsonWriterT<RW>& operator <<(JsonWriterT<RW>& writer, _StartObject) { writer.StartObject(); return writer; } template <typename RW> inline JsonWriterT<RW>& operator <<(JsonWriterT<RW>& writer, _EndObject) { writer.EndObject(); return writer; } template <typename RW> inline JsonWriterT<RW>& operator <<(JsonWriterT<RW>& writer, const char* s) { writer.String(s, static_cast<unsigned>(strlen(s))); return writer; } template <typename RW> inline JsonWriterT<RW>& operator <<(JsonWriterT<RW>& writer, std::string s) { writer.String(s.c_str(), static_cast<unsigned>(s.size())); return writer; } template <typename RW> inline JsonWriterT<RW>& operator <<(JsonWriterT<RW>& writer, int value) { writer.Int(value); return writer; } class JsonObjectKey { public: inline JsonObjectKey(const char* v) : value(v) {} inline JsonObjectKey(std::string v) : value(v.c_str()) {} inline operator const char*() const { return value; } private: const char* value; }; template <typename RW> inline JsonWriterT<RW>& operator <<(JsonWriterT<RW>& writer, JsonObjectKey value) { writer.Key(value); return writer; } // ---------------------------------------------------------------------- template <typename RW, typename T> inline JsonWriterT<RW>& operator <<(JsonWriterT<RW>& writer, const std::vector<T>& list) { writer << StartArray; for (const auto& e: list) writer << e; return writer << EndArray; } // ---------------------------------------------------------------------- template <typename RW> inline JsonWriterT<RW>& operator <<(JsonWriterT<RW>& writer, const std::vector<std::vector<std::string>>& list_list_strings) { writer << StartArray; for (const auto& e: list_list_strings) writer << e; return writer << EndArray; } // ---------------------------------------------------------------------- template <typename V> inline std::string pretty_json(const V& value, std::string keyword, size_t indent, bool insert_emacs_indent_hint) { JsonPrettyWriter writer(keyword); writer.SetIndent(' ', static_cast<unsigned int>(indent)); writer << value; std::string result = writer; if (insert_emacs_indent_hint && result[0] == '{') { const std::string ind(indent - 1, ' '); result.insert(1, ind + "\"_\": \"-*- js-indent-level: " + std::to_string(indent) + " -*-\","); } return result; } template <typename V> inline std::string compact_json(const V& value, std::string keyword) { JsonWriter writer(keyword); return writer << value; } template <typename V> inline std::string json(const V& value, std::string keyword, size_t indent, bool insert_emacs_indent_hint = true) { if (indent) return pretty_json(value, keyword, indent, insert_emacs_indent_hint); else return compact_json(value, keyword); } // ---------------------------------------------------------------------- template <typename V> inline void export_to_json(const V& value, std::string keyword, std::string filename, size_t indent, bool insert_emacs_indent_hint = true) { acmacs_base::write_file(filename, json(value, keyword, indent, insert_emacs_indent_hint)); } // ---------------------------------------------------------------------- /// Local Variables: /// eval: (if (fboundp 'eu-rename-buffer) (eu-rename-buffer)) /// End: <|endoftext|>
<commit_before>/** ****************************************************************************** * Xenia : Xbox 360 Emulator Research Project * ****************************************************************************** * Copyright 2020 Ben Vanik. All rights reserved. * * Released under the BSD license - see LICENSE in the root for more details. * ****************************************************************************** */ #include "xenia/apu/xaudio2/xaudio2_audio_driver.h" // Must be included before xaudio2.h so we get the right windows.h include. #include "xenia/base/platform_win.h" #include "xenia/apu/apu_flags.h" #include "xenia/base/clock.h" #include "xenia/base/logging.h" namespace xe { namespace apu { namespace xaudio2 { class XAudio2AudioDriver::VoiceCallback : public api::IXAudio2VoiceCallback { public: explicit VoiceCallback(xe::threading::Semaphore* semaphore) : semaphore_(semaphore) {} ~VoiceCallback() {} void OnStreamEnd() {} void OnVoiceProcessingPassEnd() {} void OnVoiceProcessingPassStart(uint32_t samples_required) {} void OnBufferEnd(void* context) { auto ret = semaphore_->Release(1, nullptr); assert_true(ret); } void OnBufferStart(void* context) {} void OnLoopEnd(void* context) {} void OnVoiceError(void* context, HRESULT result) {} private: xe::threading::Semaphore* semaphore_ = nullptr; }; XAudio2AudioDriver::XAudio2AudioDriver(Memory* memory, xe::threading::Semaphore* semaphore) : AudioDriver(memory), semaphore_(semaphore) {} XAudio2AudioDriver::~XAudio2AudioDriver() = default; bool XAudio2AudioDriver::Initialize() { HRESULT hr; voice_callback_ = new VoiceCallback(semaphore_); // Load the XAudio2 DLL dynamically. Needed both for 2.7 and for // differentiating between 2.8 and later versions. Windows 8.1 SDK references // XAudio2_8.dll in xaudio2.lib, which is available on Windows 8.1, however, // Windows 10 SDK references XAudio2_9.dll in it, which is only available in // Windows 10, and XAudio2_8.dll is linked through a different .lib - // xaudio2_8.lib, so easier not to link the .lib at all. xaudio2_module_ = reinterpret_cast<void*>(LoadLibraryW(L"XAudio2_8.dll")); if (xaudio2_module_) { api_minor_version_ = 8; } else { xaudio2_module_ = reinterpret_cast<void*>(LoadLibraryW(L"XAudio2_7.dll")); if (xaudio2_module_) { api_minor_version_ = 7; } else { XELOGE("Failed to load XAudio 2.8 or 2.7 library DLL"); assert_always(); return false; } } // First CPU (2.8 default). XAUDIO2_ANY_PROCESSOR (2.7 default) steals too // much time from other things. Ideally should process audio on what roughly // represents thread 4 (5th) on the Xbox 360 (2.7 default on the console), or // even beyond the 6 guest cores. api::XAUDIO2_PROCESSOR processor = 0x00000001; if (api_minor_version_ >= 8) { union { // clang-format off HRESULT (__stdcall* xaudio2_create)( api::IXAudio2_8** xaudio2_out, UINT32 flags, api::XAUDIO2_PROCESSOR xaudio2_processor); // clang-format on FARPROC xaudio2_create_ptr; }; xaudio2_create_ptr = GetProcAddress( reinterpret_cast<HMODULE>(xaudio2_module_), "XAudio2Create"); if (!xaudio2_create_ptr) { XELOGE("XAudio2Create not found in XAudio2_8.dll"); assert_always(); return false; } hr = xaudio2_create(&objects_.api_2_8.audio, 0, processor); if (FAILED(hr)) { XELOGE("XAudio2Create failed with {:08X}", hr); assert_always(); return false; } return InitializeObjects(objects_.api_2_8); } else { hr = CoCreateInstance(__uuidof(api::XAudio2_7), NULL, CLSCTX_INPROC_SERVER, IID_PPV_ARGS(&objects_.api_2_7.audio)); if (FAILED(hr)) { XELOGE("CoCreateInstance for XAudio2 failed with {:08X}", hr); assert_always(); return false; } hr = objects_.api_2_7.audio->Initialize(0, processor); if (FAILED(hr)) { XELOGE("IXAudio2::Initialize failed with {:08X}", hr); assert_always(); return false; } return InitializeObjects(objects_.api_2_7); } } template <typename Objects> bool XAudio2AudioDriver::InitializeObjects(Objects& objects) { HRESULT hr; api::XAUDIO2_DEBUG_CONFIGURATION config; config.TraceMask = api::XE_XAUDIO2_LOG_ERRORS | api::XE_XAUDIO2_LOG_WARNINGS; config.BreakMask = 0; config.LogThreadID = FALSE; config.LogTiming = TRUE; config.LogFunctionName = TRUE; config.LogFileline = TRUE; objects.audio->SetDebugConfiguration(&config); hr = objects.audio->CreateMasteringVoice(&objects.mastering_voice); if (FAILED(hr)) { XELOGE("IXAudio2::CreateMasteringVoice failed with {:08X}", hr); assert_always(); return false; } WAVEFORMATIEEEFLOATEX waveformat; waveformat.Format.wFormatTag = WAVE_FORMAT_EXTENSIBLE; waveformat.Format.nChannels = frame_channels_; waveformat.Format.nSamplesPerSec = 48000; waveformat.Format.wBitsPerSample = 32; waveformat.Format.nBlockAlign = (waveformat.Format.nChannels * waveformat.Format.wBitsPerSample) / 8; waveformat.Format.nAvgBytesPerSec = waveformat.Format.nSamplesPerSec * waveformat.Format.nBlockAlign; waveformat.Format.cbSize = sizeof(WAVEFORMATIEEEFLOATEX) - sizeof(WAVEFORMATEX); waveformat.SubFormat = KSDATAFORMAT_SUBTYPE_IEEE_FLOAT; waveformat.Samples.wValidBitsPerSample = waveformat.Format.wBitsPerSample; static const DWORD kChannelMasks[] = { 0, 0, SPEAKER_FRONT_LEFT | SPEAKER_FRONT_RIGHT, 0, 0, 0, SPEAKER_FRONT_LEFT | SPEAKER_FRONT_CENTER | SPEAKER_FRONT_RIGHT | SPEAKER_LOW_FREQUENCY | SPEAKER_BACK_LEFT | SPEAKER_BACK_RIGHT, 0, }; waveformat.dwChannelMask = kChannelMasks[waveformat.Format.nChannels]; hr = objects.audio->CreateSourceVoice( &objects.pcm_voice, &waveformat.Format, 0, // api::XE_XAUDIO2_VOICE_NOSRC | api::XE_XAUDIO2_VOICE_NOPITCH, api::XE_XAUDIO2_MAX_FREQ_RATIO, voice_callback_); if (FAILED(hr)) { XELOGE("IXAudio2::CreateSourceVoice failed with {:08X}", hr); assert_always(); return false; } hr = objects.pcm_voice->Start(); if (FAILED(hr)) { XELOGE("IXAudio2SourceVoice::Start failed with {:08X}", hr); assert_always(); return false; } if (cvars::mute) { objects.pcm_voice->SetVolume(0.0f); } return true; } void XAudio2AudioDriver::SubmitFrame(uint32_t frame_ptr) { // Process samples! They are big-endian floats. HRESULT hr; api::XAUDIO2_VOICE_STATE state; if (api_minor_version_ >= 8) { objects_.api_2_8.pcm_voice->GetState(&state, api::XE_XAUDIO2_VOICE_NOSAMPLESPLAYED); } else { objects_.api_2_7.pcm_voice->GetState(&state); } assert_true(state.BuffersQueued < frame_count_); auto input_frame = memory_->TranslateVirtual<float*>(frame_ptr); auto output_frame = reinterpret_cast<float*>(frames_[current_frame_]); auto interleave_channels = frame_channels_; // interleave the data for (uint32_t index = 0, o = 0; index < channel_samples_; ++index) { for (uint32_t channel = 0, table = 0; channel < interleave_channels; ++channel, table += channel_samples_) { output_frame[o++] = xe::byte_swap(input_frame[table + index]); } } api::XAUDIO2_BUFFER buffer; buffer.Flags = 0; buffer.pAudioData = reinterpret_cast<BYTE*>(output_frame); buffer.AudioBytes = frame_size_; buffer.PlayBegin = 0; buffer.PlayLength = channel_samples_; buffer.LoopBegin = api::XE_XAUDIO2_NO_LOOP_REGION; buffer.LoopLength = 0; buffer.LoopCount = 0; buffer.pContext = 0; if (api_minor_version_ >= 8) { hr = objects_.api_2_8.pcm_voice->SubmitSourceBuffer(&buffer); } else { hr = objects_.api_2_7.pcm_voice->SubmitSourceBuffer(&buffer); } if (FAILED(hr)) { XELOGE("SubmitSourceBuffer failed with {:08X}", hr); assert_always(); return; } current_frame_ = (current_frame_ + 1) % frame_count_; // Update playback ratio to our time scalar. // This will keep audio in sync with the game clock. float frequency_ratio = static_cast<float>(xe::Clock::guest_time_scalar()); if (api_minor_version_ >= 8) { objects_.api_2_8.pcm_voice->SetFrequencyRatio(frequency_ratio); } else { objects_.api_2_7.pcm_voice->SetFrequencyRatio(frequency_ratio); } } void XAudio2AudioDriver::Shutdown() { if (api_minor_version_ >= 8) { ShutdownObjects(objects_.api_2_8); } else { ShutdownObjects(objects_.api_2_7); } if (xaudio2_module_) { FreeLibrary(reinterpret_cast<HMODULE>(xaudio2_module_)); xaudio2_module_ = nullptr; } if (voice_callback_) { delete voice_callback_; voice_callback_ = nullptr; } } template <typename Objects> void XAudio2AudioDriver::ShutdownObjects(Objects& objects) { if (objects.pcm_voice) { objects.pcm_voice->Stop(); objects.pcm_voice->DestroyVoice(); objects.pcm_voice = nullptr; } if (objects.mastering_voice) { objects.mastering_voice->DestroyVoice(); objects.mastering_voice = nullptr; } if (objects.audio) { objects.audio->StopEngine(); objects.audio->Release(); objects.audio = nullptr; } } } // namespace xaudio2 } // namespace apu } // namespace xe <commit_msg>[APU] Use vectorized converter in xaudio2 backend<commit_after>/** ****************************************************************************** * Xenia : Xbox 360 Emulator Research Project * ****************************************************************************** * Copyright 2020 Ben Vanik. All rights reserved. * * Released under the BSD license - see LICENSE in the root for more details. * ****************************************************************************** */ #include "xenia/apu/xaudio2/xaudio2_audio_driver.h" // Must be included before xaudio2.h so we get the right windows.h include. #include "xenia/base/platform_win.h" #include "xenia/apu/apu_flags.h" #include "xenia/apu/conversion.h" #include "xenia/base/clock.h" #include "xenia/base/logging.h" namespace xe { namespace apu { namespace xaudio2 { class XAudio2AudioDriver::VoiceCallback : public api::IXAudio2VoiceCallback { public: explicit VoiceCallback(xe::threading::Semaphore* semaphore) : semaphore_(semaphore) {} ~VoiceCallback() {} void OnStreamEnd() {} void OnVoiceProcessingPassEnd() {} void OnVoiceProcessingPassStart(uint32_t samples_required) {} void OnBufferEnd(void* context) { auto ret = semaphore_->Release(1, nullptr); assert_true(ret); } void OnBufferStart(void* context) {} void OnLoopEnd(void* context) {} void OnVoiceError(void* context, HRESULT result) {} private: xe::threading::Semaphore* semaphore_ = nullptr; }; XAudio2AudioDriver::XAudio2AudioDriver(Memory* memory, xe::threading::Semaphore* semaphore) : AudioDriver(memory), semaphore_(semaphore) {} XAudio2AudioDriver::~XAudio2AudioDriver() = default; bool XAudio2AudioDriver::Initialize() { HRESULT hr; voice_callback_ = new VoiceCallback(semaphore_); // Load the XAudio2 DLL dynamically. Needed both for 2.7 and for // differentiating between 2.8 and later versions. Windows 8.1 SDK references // XAudio2_8.dll in xaudio2.lib, which is available on Windows 8.1, however, // Windows 10 SDK references XAudio2_9.dll in it, which is only available in // Windows 10, and XAudio2_8.dll is linked through a different .lib - // xaudio2_8.lib, so easier not to link the .lib at all. xaudio2_module_ = reinterpret_cast<void*>(LoadLibraryW(L"XAudio2_8.dll")); if (xaudio2_module_) { api_minor_version_ = 8; } else { xaudio2_module_ = reinterpret_cast<void*>(LoadLibraryW(L"XAudio2_7.dll")); if (xaudio2_module_) { api_minor_version_ = 7; } else { XELOGE("Failed to load XAudio 2.8 or 2.7 library DLL"); assert_always(); return false; } } // First CPU (2.8 default). XAUDIO2_ANY_PROCESSOR (2.7 default) steals too // much time from other things. Ideally should process audio on what roughly // represents thread 4 (5th) on the Xbox 360 (2.7 default on the console), or // even beyond the 6 guest cores. api::XAUDIO2_PROCESSOR processor = 0x00000001; if (api_minor_version_ >= 8) { union { // clang-format off HRESULT (__stdcall* xaudio2_create)( api::IXAudio2_8** xaudio2_out, UINT32 flags, api::XAUDIO2_PROCESSOR xaudio2_processor); // clang-format on FARPROC xaudio2_create_ptr; }; xaudio2_create_ptr = GetProcAddress( reinterpret_cast<HMODULE>(xaudio2_module_), "XAudio2Create"); if (!xaudio2_create_ptr) { XELOGE("XAudio2Create not found in XAudio2_8.dll"); assert_always(); return false; } hr = xaudio2_create(&objects_.api_2_8.audio, 0, processor); if (FAILED(hr)) { XELOGE("XAudio2Create failed with {:08X}", hr); assert_always(); return false; } return InitializeObjects(objects_.api_2_8); } else { hr = CoCreateInstance(__uuidof(api::XAudio2_7), NULL, CLSCTX_INPROC_SERVER, IID_PPV_ARGS(&objects_.api_2_7.audio)); if (FAILED(hr)) { XELOGE("CoCreateInstance for XAudio2 failed with {:08X}", hr); assert_always(); return false; } hr = objects_.api_2_7.audio->Initialize(0, processor); if (FAILED(hr)) { XELOGE("IXAudio2::Initialize failed with {:08X}", hr); assert_always(); return false; } return InitializeObjects(objects_.api_2_7); } } template <typename Objects> bool XAudio2AudioDriver::InitializeObjects(Objects& objects) { HRESULT hr; api::XAUDIO2_DEBUG_CONFIGURATION config; config.TraceMask = api::XE_XAUDIO2_LOG_ERRORS | api::XE_XAUDIO2_LOG_WARNINGS; config.BreakMask = 0; config.LogThreadID = FALSE; config.LogTiming = TRUE; config.LogFunctionName = TRUE; config.LogFileline = TRUE; objects.audio->SetDebugConfiguration(&config); hr = objects.audio->CreateMasteringVoice(&objects.mastering_voice); if (FAILED(hr)) { XELOGE("IXAudio2::CreateMasteringVoice failed with {:08X}", hr); assert_always(); return false; } WAVEFORMATIEEEFLOATEX waveformat; waveformat.Format.wFormatTag = WAVE_FORMAT_EXTENSIBLE; waveformat.Format.nChannels = frame_channels_; waveformat.Format.nSamplesPerSec = 48000; waveformat.Format.wBitsPerSample = 32; waveformat.Format.nBlockAlign = (waveformat.Format.nChannels * waveformat.Format.wBitsPerSample) / 8; waveformat.Format.nAvgBytesPerSec = waveformat.Format.nSamplesPerSec * waveformat.Format.nBlockAlign; waveformat.Format.cbSize = sizeof(WAVEFORMATIEEEFLOATEX) - sizeof(WAVEFORMATEX); waveformat.SubFormat = KSDATAFORMAT_SUBTYPE_IEEE_FLOAT; waveformat.Samples.wValidBitsPerSample = waveformat.Format.wBitsPerSample; static const DWORD kChannelMasks[] = { 0, 0, SPEAKER_FRONT_LEFT | SPEAKER_FRONT_RIGHT, 0, 0, 0, SPEAKER_FRONT_LEFT | SPEAKER_FRONT_CENTER | SPEAKER_FRONT_RIGHT | SPEAKER_LOW_FREQUENCY | SPEAKER_BACK_LEFT | SPEAKER_BACK_RIGHT, 0, }; waveformat.dwChannelMask = kChannelMasks[waveformat.Format.nChannels]; hr = objects.audio->CreateSourceVoice( &objects.pcm_voice, &waveformat.Format, 0, // api::XE_XAUDIO2_VOICE_NOSRC | api::XE_XAUDIO2_VOICE_NOPITCH, api::XE_XAUDIO2_MAX_FREQ_RATIO, voice_callback_); if (FAILED(hr)) { XELOGE("IXAudio2::CreateSourceVoice failed with {:08X}", hr); assert_always(); return false; } hr = objects.pcm_voice->Start(); if (FAILED(hr)) { XELOGE("IXAudio2SourceVoice::Start failed with {:08X}", hr); assert_always(); return false; } if (cvars::mute) { objects.pcm_voice->SetVolume(0.0f); } return true; } void XAudio2AudioDriver::SubmitFrame(uint32_t frame_ptr) { // Process samples! They are big-endian floats. HRESULT hr; api::XAUDIO2_VOICE_STATE state; if (api_minor_version_ >= 8) { objects_.api_2_8.pcm_voice->GetState(&state, api::XE_XAUDIO2_VOICE_NOSAMPLESPLAYED); } else { objects_.api_2_7.pcm_voice->GetState(&state); } assert_true(state.BuffersQueued < frame_count_); auto input_frame = memory_->TranslateVirtual<float*>(frame_ptr); auto output_frame = reinterpret_cast<float*>(frames_[current_frame_]); auto interleave_channels = frame_channels_; // interleave the data conversion::sequential_6_BE_to_interleaved_6_LE(output_frame, input_frame, channel_samples_); api::XAUDIO2_BUFFER buffer; buffer.Flags = 0; buffer.pAudioData = reinterpret_cast<BYTE*>(output_frame); buffer.AudioBytes = frame_size_; buffer.PlayBegin = 0; buffer.PlayLength = channel_samples_; buffer.LoopBegin = api::XE_XAUDIO2_NO_LOOP_REGION; buffer.LoopLength = 0; buffer.LoopCount = 0; buffer.pContext = 0; if (api_minor_version_ >= 8) { hr = objects_.api_2_8.pcm_voice->SubmitSourceBuffer(&buffer); } else { hr = objects_.api_2_7.pcm_voice->SubmitSourceBuffer(&buffer); } if (FAILED(hr)) { XELOGE("SubmitSourceBuffer failed with {:08X}", hr); assert_always(); return; } current_frame_ = (current_frame_ + 1) % frame_count_; // Update playback ratio to our time scalar. // This will keep audio in sync with the game clock. float frequency_ratio = static_cast<float>(xe::Clock::guest_time_scalar()); if (api_minor_version_ >= 8) { objects_.api_2_8.pcm_voice->SetFrequencyRatio(frequency_ratio); } else { objects_.api_2_7.pcm_voice->SetFrequencyRatio(frequency_ratio); } } void XAudio2AudioDriver::Shutdown() { if (api_minor_version_ >= 8) { ShutdownObjects(objects_.api_2_8); } else { ShutdownObjects(objects_.api_2_7); } if (xaudio2_module_) { FreeLibrary(reinterpret_cast<HMODULE>(xaudio2_module_)); xaudio2_module_ = nullptr; } if (voice_callback_) { delete voice_callback_; voice_callback_ = nullptr; } } template <typename Objects> void XAudio2AudioDriver::ShutdownObjects(Objects& objects) { if (objects.pcm_voice) { objects.pcm_voice->Stop(); objects.pcm_voice->DestroyVoice(); objects.pcm_voice = nullptr; } if (objects.mastering_voice) { objects.mastering_voice->DestroyVoice(); objects.mastering_voice = nullptr; } if (objects.audio) { objects.audio->StopEngine(); objects.audio->Release(); objects.audio = nullptr; } } } // namespace xaudio2 } // namespace apu } // namespace xe <|endoftext|>
<commit_before>/** * \ file OutPointerFilter.cpp */ #include <cmath> #include <boost/math/constants/constants.hpp> #include <ATK/Core/InPointerFilter.h> #include <ATK/Core/OutPointerFilter.h> #define BOOST_TEST_DYN_LINK #define BOOST_TEST_NO_MAIN #include <boost/test/unit_test.hpp> #define PROCESSSIZE (10) BOOST_AUTO_TEST_CASE( OutPointerFloat_sin1k_test ) { std::array<float, PROCESSSIZE> data; for(ptrdiff_t i = 0; i < PROCESSSIZE; ++i) { data[i] = std::sin(2 * boost::math::constants::pi<float>() * (i+1.)/48000 * 1000); } ATK::InPointerFilter<float> generator(data.data(), 1, PROCESSSIZE, false); generator.set_output_sampling_rate(48000); std::array<float, PROCESSSIZE> outdata; ATK::OutPointerFilter<float> output(outdata.data(), 1, PROCESSSIZE, false); output.set_input_sampling_rate(48000); output.set_input_port(0, &generator, 0); output.process(2); output.process(PROCESSSIZE - 2); for(ptrdiff_t i = 0; i < PROCESSSIZE; ++i) { BOOST_REQUIRE_EQUAL(data[i], outdata[i]); } } BOOST_AUTO_TEST_CASE( OutPointerDouble_sin1k_test ) { std::array<double, PROCESSSIZE> data; for(ptrdiff_t i = 0; i < PROCESSSIZE; ++i) { data[i] = std::sin(2 * boost::math::constants::pi<float>() * (i+1.)/48000 * 1000); } ATK::InPointerFilter<double> generator(data.data(), 1, PROCESSSIZE, false); generator.set_output_sampling_rate(48000); std::array<double, PROCESSSIZE> outdata; ATK::OutPointerFilter<double> output(outdata.data(), 1, PROCESSSIZE, false); output.set_input_sampling_rate(48000); output.set_input_port(0, &generator, 0); output.process(2); output.process(PROCESSSIZE - 2); for(ptrdiff_t i = 0; i < PROCESSSIZE; ++i) { BOOST_REQUIRE_EQUAL(data[i], outdata[i]); } } BOOST_AUTO_TEST_CASE(OutPointerDouble_check_bound_test) { std::array<double, PROCESSSIZE> data; for (ptrdiff_t i = 0; i < PROCESSSIZE; ++i) { data[i] = std::sin(2 * boost::math::constants::pi<float>() * (i + 1.) / 48000 * 1000); } ATK::InPointerFilter<double> generator(data.data(), 1, PROCESSSIZE, false); generator.set_output_sampling_rate(48000); std::array<double, 2*PROCESSSIZE> outdata; std::fill(outdata.begin(), outdata.end(), -1); ATK::OutPointerFilter<double> output(outdata.data(), 1, 3*PROCESSSIZE/2, false); output.set_input_sampling_rate(48000); output.set_input_port(0, &generator, 0); output.process(2*PROCESSSIZE); for (ptrdiff_t i = 0; i < PROCESSSIZE; ++i) { BOOST_REQUIRE_EQUAL(data[i], outdata[i]); } for (ptrdiff_t i = 0; i < PROCESSSIZE / 2; ++i) { BOOST_REQUIRE_EQUAL(0, outdata[PROCESSSIZE + i]); // check that input is now 0 } for (ptrdiff_t i = 0; i < PROCESSSIZE / 2; ++i) { BOOST_REQUIRE_EQUAL(-1, outdata[3 * PROCESSSIZE /2 + i]); // check that we don't write after what we declare was allocated } } BOOST_AUTO_TEST_CASE( OutPointerFloat_sin1k2k_interleaved_test ) { std::array<float, 2*PROCESSSIZE> data; for(ptrdiff_t i = 0; i < PROCESSSIZE; ++i) { data[2*i] = std::sin(2 * boost::math::constants::pi<float>() * (i+1.)/48000 * 1000); data[2*i+1] = std::sin(2 * boost::math::constants::pi<float>() * (i+1.)/48000 * 2000); } ATK::InPointerFilter<float> generator(data.data(), PROCESSSIZE, 2, true); generator.set_output_sampling_rate(48000); std::array<double, 2*PROCESSSIZE> outdata; ATK::OutPointerFilter<double> output(outdata.data(), PROCESSSIZE, 2, true); output.set_input_sampling_rate(48000); output.set_input_port(0, &generator, 0); output.set_input_port(1, &generator, 1); output.process(2); output.process(PROCESSSIZE); output.process(PROCESSSIZE); output.process(PROCESSSIZE); for(ptrdiff_t i = 0; i < 2*PROCESSSIZE; ++i) { BOOST_REQUIRE_EQUAL(data[i], outdata[i]); } } BOOST_AUTO_TEST_CASE( OutPointerFloat_sin1k2k_noninterleaved_test ) { std::array<float, 2*PROCESSSIZE> data; for(ptrdiff_t i = 0; i < PROCESSSIZE; ++i) { data[i] = std::sin(2 * boost::math::constants::pi<float>() * (i+1.)/48000 * 1000); } for(ptrdiff_t i = 0; i < PROCESSSIZE; ++i) { data[i+PROCESSSIZE] = std::sin(2 * boost::math::constants::pi<float>() * (i+1.)/48000 * 2000); } ATK::InPointerFilter<float> generator(data.data(), 2, PROCESSSIZE, false); generator.set_output_sampling_rate(48000); std::array<double, 2*PROCESSSIZE> outdata; ATK::OutPointerFilter<double> output(outdata.data(), 2, PROCESSSIZE, false); output.set_input_sampling_rate(48000); output.set_input_port(0, &generator, 0); output.set_input_port(1, &generator, 1); output.process(2); output.process(PROCESSSIZE - 2); for(ptrdiff_t i = 0; i < 2*PROCESSSIZE; ++i) { BOOST_REQUIRE_EQUAL(data[i], outdata[i]); } } <commit_msg>Finally found the proper way of testing this line!!!!<commit_after>/** * \ file OutPointerFilter.cpp */ #include <cmath> #include <boost/math/constants/constants.hpp> #include <ATK/Core/InPointerFilter.h> #include <ATK/Core/OutPointerFilter.h> #define BOOST_TEST_DYN_LINK #define BOOST_TEST_NO_MAIN #include <boost/test/unit_test.hpp> #define PROCESSSIZE (10) BOOST_AUTO_TEST_CASE( OutPointerFloat_sin1k_test ) { std::array<float, PROCESSSIZE> data; for(ptrdiff_t i = 0; i < PROCESSSIZE; ++i) { data[i] = std::sin(2 * boost::math::constants::pi<float>() * (i+1.)/48000 * 1000); } ATK::InPointerFilter<float> generator(data.data(), 1, PROCESSSIZE, false); generator.set_output_sampling_rate(48000); std::array<float, PROCESSSIZE> outdata; ATK::OutPointerFilter<float> output(outdata.data(), 1, PROCESSSIZE, false); output.set_input_sampling_rate(48000); output.set_input_port(0, &generator, 0); output.process(2); output.process(PROCESSSIZE - 2); for(ptrdiff_t i = 0; i < PROCESSSIZE; ++i) { BOOST_REQUIRE_EQUAL(data[i], outdata[i]); } } BOOST_AUTO_TEST_CASE( OutPointerDouble_sin1k_test ) { std::array<double, PROCESSSIZE> data; for(ptrdiff_t i = 0; i < PROCESSSIZE; ++i) { data[i] = std::sin(2 * boost::math::constants::pi<float>() * (i+1.)/48000 * 1000); } ATK::InPointerFilter<double> generator(data.data(), 1, PROCESSSIZE, false); generator.set_output_sampling_rate(48000); std::array<double, PROCESSSIZE> outdata; ATK::OutPointerFilter<double> output(outdata.data(), 1, PROCESSSIZE, false); output.set_input_sampling_rate(48000); output.set_input_port(0, &generator, 0); output.process(2); output.process(PROCESSSIZE - 2); for(ptrdiff_t i = 0; i < PROCESSSIZE; ++i) { BOOST_REQUIRE_EQUAL(data[i], outdata[i]); } } BOOST_AUTO_TEST_CASE(OutPointerDouble_check_bound_test) { std::array<double, PROCESSSIZE> data; for (ptrdiff_t i = 0; i < PROCESSSIZE; ++i) { data[i] = std::sin(2 * boost::math::constants::pi<float>() * (i + 1.) / 48000 * 1000); } ATK::InPointerFilter<double> generator(data.data(), 1, PROCESSSIZE, false); generator.set_output_sampling_rate(48000); std::array<double, 2*PROCESSSIZE> outdata; std::fill(outdata.begin(), outdata.end(), -1); ATK::OutPointerFilter<double> output(outdata.data(), 1, 3*PROCESSSIZE/2, false); output.set_input_sampling_rate(48000); output.set_input_port(0, &generator, 0); output.process(2*PROCESSSIZE); for (ptrdiff_t i = 0; i < PROCESSSIZE; ++i) { BOOST_REQUIRE_EQUAL(data[i], outdata[i]); } for (ptrdiff_t i = 0; i < PROCESSSIZE / 2; ++i) { BOOST_REQUIRE_EQUAL(0, outdata[PROCESSSIZE + i]); // check that input is now 0 } for (ptrdiff_t i = 0; i < PROCESSSIZE / 2; ++i) { BOOST_REQUIRE_EQUAL(-1, outdata[3 * PROCESSSIZE /2 + i]); // check that we don't write after what we declare was allocated } } BOOST_AUTO_TEST_CASE( OutPointerFloat_sin1k2k_interleaved_test ) { std::array<float, 2*PROCESSSIZE> data; for(ptrdiff_t i = 0; i < PROCESSSIZE; ++i) { data[2*i] = std::sin(2 * boost::math::constants::pi<float>() * (i+1.)/48000 * 1000); data[2*i+1] = std::sin(2 * boost::math::constants::pi<float>() * (i+1.)/48000 * 2000); } ATK::InPointerFilter<float> generator(data.data(), PROCESSSIZE, 2, true); generator.set_output_sampling_rate(48000); std::array<double, 2*PROCESSSIZE> outdata; ATK::OutPointerFilter<double> output(outdata.data(), PROCESSSIZE, 2, true); output.set_input_sampling_rate(48000); output.set_input_port(0, &generator, 0); output.set_input_port(1, &generator, 1); output.process(2); output.process(PROCESSSIZE - 2); for(ptrdiff_t i = 0; i < 2*PROCESSSIZE; ++i) { BOOST_REQUIRE_EQUAL(data[i], outdata[i]); } } BOOST_AUTO_TEST_CASE( OutPointerFloat_sin1k2k_noninterleaved_test ) { std::array<float, 2*PROCESSSIZE> data; for(ptrdiff_t i = 0; i < PROCESSSIZE; ++i) { data[i] = std::sin(2 * boost::math::constants::pi<float>() * (i+1.)/48000 * 1000); } for(ptrdiff_t i = 0; i < PROCESSSIZE; ++i) { data[i+PROCESSSIZE] = std::sin(2 * boost::math::constants::pi<float>() * (i+1.)/48000 * 2000); } ATK::InPointerFilter<float> generator(data.data(), 2, PROCESSSIZE, false); generator.set_output_sampling_rate(48000); std::array<double, 2*PROCESSSIZE> outdata; ATK::OutPointerFilter<double> output(outdata.data(), 2, PROCESSSIZE, false); output.set_input_sampling_rate(48000); output.set_input_port(0, &generator, 0); output.set_input_port(1, &generator, 1); output.process(2); output.process(PROCESSSIZE); output.process(PROCESSSIZE); output.process(PROCESSSIZE); for(ptrdiff_t i = 0; i < 2*PROCESSSIZE; ++i) { BOOST_REQUIRE_EQUAL(data[i], outdata[i]); } } <|endoftext|>
<commit_before>// Copyright 2016 Yahoo Inc. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. #include <util/timer.h> #include <httpclient/httpclient.h> #include <util/filereader.h> #include "client.h" Client::Client(ClientArguments *args) : _args(args), _status(new ClientStatus()), _reqTimer(new Timer()), _cycleTimer(new Timer()), _masterTimer(new Timer()), _http(new HTTPClient(_args->_hostname, _args->_port, _args->_keepAlive, _args->_headerBenchmarkdataCoverage, _args->_extraHeaders, _args->_authority)), _reader(new FileReader()), _output(), _linebufsize(args->_maxLineSize), _linebuf(new char[_linebufsize]), _stop(false), _done(false), _thread() { assert(args != NULL); _cycleTimer->SetMax(_args->_cycle); } Client::~Client() { delete [] _linebuf; } void Client::runMe(Client * me) { me->run(); } class UrlReader { FileReader &_reader; const ClientArguments &_args; int _restarts; int _contentbufsize; int _leftOversLen; char *_contentbuf; const char *_leftOvers; public: UrlReader(FileReader& reader, const ClientArguments &args) : _reader(reader), _args(args), _restarts(0), _contentbufsize(0), _leftOversLen(0), _contentbuf(0), _leftOvers(0) { if (_args._usePostMode) { _contentbufsize = 16 * _args._maxLineSize; _contentbuf = new char[_contentbufsize]; } } bool reset(); int findUrl(char *buf, int buflen); int nextUrl(char *buf, int buflen); int getContent(); const char *content() const { return _contentbuf; } ~UrlReader() { delete [] _contentbuf; } }; bool UrlReader::reset() { if (_restarts == _args._restartLimit) { return false; } else if (_args._restartLimit > 0) { _restarts++; } _reader.Reset(); // Start reading from offset if (_args._singleQueryFile) { _reader.SetFilePos(_args._queryfileOffset); } return true; } int UrlReader::findUrl(char *buf, int buflen) { while (true) { if ( _args._singleQueryFile && _reader.GetFilePos() >= _args._queryfileEndOffset ) { // reached logical EOF return -1; } int ll = _reader.ReadLine(buf, buflen); if (ll < 0) { // reached physical EOF return ll; } if (ll > 0) { if (buf[0] == '/' || !_args._usePostMode) { // found URL return ll; } } } } int UrlReader::nextUrl(char *buf, int buflen) { if (_leftOvers) { int sz = std::min(_leftOversLen, buflen-1); strncpy(buf, _leftOvers, sz); buf[sz] = '\0'; _leftOvers = NULL; return _leftOversLen; } int ll = findUrl(buf, buflen); if (ll > 0) { return ll; } if (reset()) { // try again ll = findUrl(buf, buflen); } return ll; } int UrlReader::getContent() { char *buf = _contentbuf; int totLen = 0; while (totLen < _contentbufsize) { int left = _contentbufsize - totLen; int len = _reader.ReadLine(buf, left); if (len < 0) { // reached EOF return totLen; } if (len > 0 && buf[0] == '/') { // reached next URL _leftOvers = buf; _leftOversLen = len; return totLen; } buf += len; totLen += len; } return totLen; } void Client::run() { char inputFilename[1024]; char outputFilename[1024]; char timestr[64]; int linelen; /// int reslen; std::this_thread::sleep_for(std::chrono::milliseconds(_args->_delay)); // open query file snprintf(inputFilename, 1024, _args->_filenamePattern, _args->_myNum); if (!_reader->Open(inputFilename)) { printf("Client %d: ERROR: could not open file '%s' [read mode]\n", _args->_myNum, inputFilename); _status->SetError("Could not open query file."); return; } if (_args->_outputPattern != NULL) { snprintf(outputFilename, 1024, _args->_outputPattern, _args->_myNum); _output = std::make_unique<std::ofstream>(outputFilename, std::ofstream::out | std::ofstream::binary); if (_output->fail()) { printf("Client %d: ERROR: could not open file '%s' [write mode]\n", _args->_myNum, outputFilename); _status->SetError("Could not open output file."); return; } } if (_output) _output->write(FBENCH_DELIMITER + 1, strlen(FBENCH_DELIMITER) - 1); if (_args->_ignoreCount == 0) _masterTimer->Start(); // Start reading from offset if ( _args->_singleQueryFile ) _reader->SetFilePos(_args->_queryfileOffset); UrlReader urlSource(*_reader, *_args); size_t urlNumber = 0; // run queries while (!_stop) { _cycleTimer->Start(); linelen = urlSource.nextUrl(_linebuf, _linebufsize); if (linelen > 0) { ++urlNumber; } else { if (urlNumber == 0) { fprintf(stderr, "Client %d: ERROR: could not read any lines from '%s'\n", _args->_myNum, inputFilename); _status->SetError("Could not read any lines from query file."); } break; } if (linelen < _linebufsize) { if (_output) { _output->write("URL: ", strlen("URL: ")); _output->write(_linebuf, linelen); _output->write("\n\n", 2); } if (linelen + (int)_args->_queryStringToAppend.length() < _linebufsize) { strcat(_linebuf, _args->_queryStringToAppend.c_str()); } int cLen = _args->_usePostMode ? urlSource.getContent() : 0; _reqTimer->Start(); auto fetch_status = _http->Fetch(_linebuf, _output.get(), _args->_usePostMode, urlSource.content(), cLen); _reqTimer->Stop(); _status->AddRequestStatus(fetch_status.RequestStatus()); if (fetch_status.Ok() && fetch_status.TotalHitCount() == 0) ++_status->_zeroHitQueries; if (_output) { if (!fetch_status.Ok()) { _output->write("\nFBENCH: URL FETCH FAILED!\n", strlen("\nFBENCH: URL FETCH FAILED!\n")); _output->write(FBENCH_DELIMITER + 1, strlen(FBENCH_DELIMITER) - 1); } else { sprintf(timestr, "\nTIME USED: %0.4f s\n", _reqTimer->GetTimespan() / 1000.0); _output->write(timestr, strlen(timestr)); _output->write(FBENCH_DELIMITER + 1, strlen(FBENCH_DELIMITER) - 1); } } if (fetch_status.ResultSize() >= _args->_byteLimit) { if (_args->_ignoreCount == 0) _status->ResponseTime(_reqTimer->GetTimespan()); } else { if (_args->_ignoreCount == 0) _status->RequestFailed(); } } else { if (_args->_ignoreCount == 0) _status->SkippedRequest(); } _cycleTimer->Stop(); if (_args->_cycle < 0) { std::this_thread::sleep_for(std::chrono::milliseconds(int(_reqTimer->GetTimespan()))); } else { if (_cycleTimer->GetRemaining() > 0) { std::this_thread::sleep_for(std::chrono::milliseconds(int(_cycleTimer->GetRemaining()))); } else { if (_args->_ignoreCount == 0) _status->OverTime(); } } if (_args->_ignoreCount > 0) { _args->_ignoreCount--; if (_args->_ignoreCount == 0) _masterTimer->Start(); } // Update current time span to calculate Q/s _status->SetRealTime(_masterTimer->GetCurrent()); } _masterTimer->Stop(); _status->SetRealTime(_masterTimer->GetTimespan()); _status->SetReuseCount(_http->GetReuseCount()); printf("."); fflush(stdout); _done = true; } void Client::stop() { _stop = true; } bool Client::done() { return _done; } void Client::start() { _thread = std::thread(Client::runMe, this); } void Client::join() { _thread.join(); } <commit_msg>put newline between content lines<commit_after>// Copyright 2016 Yahoo Inc. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. #include <util/timer.h> #include <httpclient/httpclient.h> #include <util/filereader.h> #include "client.h" Client::Client(ClientArguments *args) : _args(args), _status(new ClientStatus()), _reqTimer(new Timer()), _cycleTimer(new Timer()), _masterTimer(new Timer()), _http(new HTTPClient(_args->_hostname, _args->_port, _args->_keepAlive, _args->_headerBenchmarkdataCoverage, _args->_extraHeaders, _args->_authority)), _reader(new FileReader()), _output(), _linebufsize(args->_maxLineSize), _linebuf(new char[_linebufsize]), _stop(false), _done(false), _thread() { assert(args != NULL); _cycleTimer->SetMax(_args->_cycle); } Client::~Client() { delete [] _linebuf; } void Client::runMe(Client * me) { me->run(); } class UrlReader { FileReader &_reader; const ClientArguments &_args; int _restarts; int _contentbufsize; int _leftOversLen; char *_contentbuf; const char *_leftOvers; public: UrlReader(FileReader& reader, const ClientArguments &args) : _reader(reader), _args(args), _restarts(0), _contentbufsize(0), _leftOversLen(0), _contentbuf(0), _leftOvers(0) { if (_args._usePostMode) { _contentbufsize = 16 * _args._maxLineSize; _contentbuf = new char[_contentbufsize]; } } bool reset(); int findUrl(char *buf, int buflen); int nextUrl(char *buf, int buflen); int nextContent(); const char *content() const { return _contentbuf; } ~UrlReader() { delete [] _contentbuf; } }; bool UrlReader::reset() { if (_restarts == _args._restartLimit) { return false; } else if (_args._restartLimit > 0) { _restarts++; } _reader.Reset(); // Start reading from offset if (_args._singleQueryFile) { _reader.SetFilePos(_args._queryfileOffset); } return true; } int UrlReader::findUrl(char *buf, int buflen) { while (true) { if ( _args._singleQueryFile && _reader.GetFilePos() >= _args._queryfileEndOffset ) { // reached logical EOF return -1; } int ll = _reader.ReadLine(buf, buflen); if (ll < 0) { // reached physical EOF return ll; } if (ll > 0) { if (buf[0] == '/' || !_args._usePostMode) { // found URL return ll; } } } } int UrlReader::nextUrl(char *buf, int buflen) { if (_leftOvers) { int sz = std::min(_leftOversLen, buflen-1); strncpy(buf, _leftOvers, sz); buf[sz] = '\0'; _leftOvers = NULL; return _leftOversLen; } int ll = findUrl(buf, buflen); if (ll > 0) { return ll; } if (reset()) { // try again ll = findUrl(buf, buflen); } return ll; } int UrlReader::nextContent() { char *buf = _contentbuf; int totLen = 0; int nl = 0; while (totLen + 1 < _contentbufsize) { int left = _contentbufsize - totLen; // allow space for newline: int len = _reader.ReadLine(buf, left - 1); if (len < 0) { // reached EOF return totLen; } if (len > 0 && buf[0] == '/') { // reached next URL _leftOvers = buf; _leftOversLen = len; return totLen; } buf += len; *buf++ = '\n'; totLen += nl + len; nl = 1; } return totLen; } void Client::run() { char inputFilename[1024]; char outputFilename[1024]; char timestr[64]; int linelen; /// int reslen; std::this_thread::sleep_for(std::chrono::milliseconds(_args->_delay)); // open query file snprintf(inputFilename, 1024, _args->_filenamePattern, _args->_myNum); if (!_reader->Open(inputFilename)) { printf("Client %d: ERROR: could not open file '%s' [read mode]\n", _args->_myNum, inputFilename); _status->SetError("Could not open query file."); return; } if (_args->_outputPattern != NULL) { snprintf(outputFilename, 1024, _args->_outputPattern, _args->_myNum); _output = std::make_unique<std::ofstream>(outputFilename, std::ofstream::out | std::ofstream::binary); if (_output->fail()) { printf("Client %d: ERROR: could not open file '%s' [write mode]\n", _args->_myNum, outputFilename); _status->SetError("Could not open output file."); return; } } if (_output) _output->write(FBENCH_DELIMITER + 1, strlen(FBENCH_DELIMITER) - 1); if (_args->_ignoreCount == 0) _masterTimer->Start(); // Start reading from offset if ( _args->_singleQueryFile ) _reader->SetFilePos(_args->_queryfileOffset); UrlReader urlSource(*_reader, *_args); size_t urlNumber = 0; // run queries while (!_stop) { _cycleTimer->Start(); linelen = urlSource.nextUrl(_linebuf, _linebufsize); if (linelen > 0) { ++urlNumber; } else { if (urlNumber == 0) { fprintf(stderr, "Client %d: ERROR: could not read any lines from '%s'\n", _args->_myNum, inputFilename); _status->SetError("Could not read any lines from query file."); } break; } if (linelen < _linebufsize) { if (_output) { _output->write("URL: ", strlen("URL: ")); _output->write(_linebuf, linelen); _output->write("\n\n", 2); } if (linelen + (int)_args->_queryStringToAppend.length() < _linebufsize) { strcat(_linebuf, _args->_queryStringToAppend.c_str()); } int cLen = _args->_usePostMode ? urlSource.nextContent() : 0; _reqTimer->Start(); auto fetch_status = _http->Fetch(_linebuf, _output.get(), _args->_usePostMode, urlSource.content(), cLen); _reqTimer->Stop(); _status->AddRequestStatus(fetch_status.RequestStatus()); if (fetch_status.Ok() && fetch_status.TotalHitCount() == 0) ++_status->_zeroHitQueries; if (_output) { if (!fetch_status.Ok()) { _output->write("\nFBENCH: URL FETCH FAILED!\n", strlen("\nFBENCH: URL FETCH FAILED!\n")); _output->write(FBENCH_DELIMITER + 1, strlen(FBENCH_DELIMITER) - 1); } else { sprintf(timestr, "\nTIME USED: %0.4f s\n", _reqTimer->GetTimespan() / 1000.0); _output->write(timestr, strlen(timestr)); _output->write(FBENCH_DELIMITER + 1, strlen(FBENCH_DELIMITER) - 1); } } if (fetch_status.ResultSize() >= _args->_byteLimit) { if (_args->_ignoreCount == 0) _status->ResponseTime(_reqTimer->GetTimespan()); } else { if (_args->_ignoreCount == 0) _status->RequestFailed(); } } else { if (_args->_ignoreCount == 0) _status->SkippedRequest(); } _cycleTimer->Stop(); if (_args->_cycle < 0) { std::this_thread::sleep_for(std::chrono::milliseconds(int(_reqTimer->GetTimespan()))); } else { if (_cycleTimer->GetRemaining() > 0) { std::this_thread::sleep_for(std::chrono::milliseconds(int(_cycleTimer->GetRemaining()))); } else { if (_args->_ignoreCount == 0) _status->OverTime(); } } if (_args->_ignoreCount > 0) { _args->_ignoreCount--; if (_args->_ignoreCount == 0) _masterTimer->Start(); } // Update current time span to calculate Q/s _status->SetRealTime(_masterTimer->GetCurrent()); } _masterTimer->Stop(); _status->SetRealTime(_masterTimer->GetTimespan()); _status->SetReuseCount(_http->GetReuseCount()); printf("."); fflush(stdout); _done = true; } void Client::stop() { _stop = true; } bool Client::done() { return _done; } void Client::start() { _thread = std::thread(Client::runMe, this); } void Client::join() { _thread.join(); } <|endoftext|>
<commit_before>#ifndef STAN_MATH_REV_FUNCTOR_APPLY_SCALAR_BINARY_HPP #define STAN_MATH_REV_FUNCTOR_APPLY_SCALAR_BINARY_HPP #include <stan/math/prim/fun/as_column_vector_or_scalar.hpp> #include <stan/math/rev/meta.hpp> #include <stan/math/prim/err/check_matching_dims.hpp> #include <stan/math/prim/err/check_matching_sizes.hpp> #include <stan/math/prim/fun/num_elements.hpp> #include <vector> namespace stan { namespace math { /** * Specialisation for use with combinations of * `Eigen::Matrix` and `var_value<Eigen::Matrix>` inputs. * Eigen's binaryExpr framework is used for more efficient indexing of both row- * and column-major inputs without separate loops. * * @tparam T1 Type of first argument to which functor is applied. * @tparam T2 Type of second argument to which functor is applied. * @tparam F Type of functor to apply. * @param x First Matrix input to which operation is applied. * @param y Second Matrix input to which operation is applied. * @param f functor to apply to Matrix inputs. * @return `var_value<Matrix>` with result of applying functor to inputs. */ template <typename T1, typename T2, typename F, require_any_var_matrix_t<T1, T2>* = nullptr, require_all_matrix_t<T1, T2>* = nullptr> inline auto apply_scalar_binary(const T1& x, const T2& y, const F& f) { check_matching_dims("Binary function", "x", x, "y", y); return f(x, y); } /** * Specialisation for use with one `var_value<Eigen vector>` (row or column) and * a one-dimensional std::vector of integer types * * @tparam T1 Type of first argument to which functor is applied. * @tparam T2 Type of second argument to which functor is applied. * @tparam F Type of functor to apply. * @param x Matrix input to which operation is applied. * @param y Integer std::vector input to which operation is applied. * @param f functor to apply to inputs. * @return var_value<Eigen> object with result of applying functor to inputs. */ template <typename T1, typename T2, typename F, require_any_var_matrix_t<T1, T2>* = nullptr, require_any_std_vector_vt<std::is_integral, T1, T2>* = nullptr> inline auto apply_scalar_binary(const T1& x, const T2& y, const F& f) { check_matching_sizes("Binary function", "x", x, "y", y); return f(x, y); } /** * Specialisation for use with a two-dimensional std::vector of integer types * and one `var_value<Matrix>`. * * @tparam T1 Type of first argument to which functor is applied. * @tparam T2 Type of second argument to which functor is applied. * @tparam F Type of functor to apply. * @param x Either a var matrix or nested integer std::vector input to which operation is applied. * @param x Either a var matrix or nested integer std::vector input to which operation is applied. * @param f functor to apply to inputs. * @return Eigen object with result of applying functor to inputs. */ template <typename T1, typename T2, typename F, require_any_std_vector_vt<is_std_vector, T1, T2>* = nullptr, require_any_std_vector_st<std::is_integral, T1, T2>* = nullptr, require_any_var_matrix_t<T1, T2>* = nullptr> inline auto apply_scalar_binary(const T1& x, const T2& y, const F& f) { return f(x, y); } /** * Specialisation for use when the one input is an `var_value<Eigen> type and * the other is a scalar. * * @tparam T1 Type of either `var_value<Matrix>` or scalar object to which functor is applied. * @tparam T2 Type of either `var_value<Matrix>` or scalar object to which functor is applied. * @tparam F Type of functor to apply. * @param x Matrix or Scalar input to which operation is applied. * @param x Matrix or Scalar input to which operation is applied. * @param f functor to apply to var matrix and scalar inputs. * @return `var_value<Matrix> object with result of applying functor to inputs. * */ template <typename T1, typename T2, typename F, require_any_stan_scalar_t<T1, T2>* = nullptr, require_any_var_matrix_t<T1, T2>* = nullptr> inline auto apply_scalar_binary(const T1& x, const T2& y, const F& f) { return f(x, y); } } // namespace math } // namespace stan #endif <commit_msg>[Jenkins] auto-formatting by clang-format version 6.0.0-1ubuntu2~16.04.1 (tags/RELEASE_600/final)<commit_after>#ifndef STAN_MATH_REV_FUNCTOR_APPLY_SCALAR_BINARY_HPP #define STAN_MATH_REV_FUNCTOR_APPLY_SCALAR_BINARY_HPP #include <stan/math/prim/fun/as_column_vector_or_scalar.hpp> #include <stan/math/rev/meta.hpp> #include <stan/math/prim/err/check_matching_dims.hpp> #include <stan/math/prim/err/check_matching_sizes.hpp> #include <stan/math/prim/fun/num_elements.hpp> #include <vector> namespace stan { namespace math { /** * Specialisation for use with combinations of * `Eigen::Matrix` and `var_value<Eigen::Matrix>` inputs. * Eigen's binaryExpr framework is used for more efficient indexing of both row- * and column-major inputs without separate loops. * * @tparam T1 Type of first argument to which functor is applied. * @tparam T2 Type of second argument to which functor is applied. * @tparam F Type of functor to apply. * @param x First Matrix input to which operation is applied. * @param y Second Matrix input to which operation is applied. * @param f functor to apply to Matrix inputs. * @return `var_value<Matrix>` with result of applying functor to inputs. */ template <typename T1, typename T2, typename F, require_any_var_matrix_t<T1, T2>* = nullptr, require_all_matrix_t<T1, T2>* = nullptr> inline auto apply_scalar_binary(const T1& x, const T2& y, const F& f) { check_matching_dims("Binary function", "x", x, "y", y); return f(x, y); } /** * Specialisation for use with one `var_value<Eigen vector>` (row or column) and * a one-dimensional std::vector of integer types * * @tparam T1 Type of first argument to which functor is applied. * @tparam T2 Type of second argument to which functor is applied. * @tparam F Type of functor to apply. * @param x Matrix input to which operation is applied. * @param y Integer std::vector input to which operation is applied. * @param f functor to apply to inputs. * @return var_value<Eigen> object with result of applying functor to inputs. */ template <typename T1, typename T2, typename F, require_any_var_matrix_t<T1, T2>* = nullptr, require_any_std_vector_vt<std::is_integral, T1, T2>* = nullptr> inline auto apply_scalar_binary(const T1& x, const T2& y, const F& f) { check_matching_sizes("Binary function", "x", x, "y", y); return f(x, y); } /** * Specialisation for use with a two-dimensional std::vector of integer types * and one `var_value<Matrix>`. * * @tparam T1 Type of first argument to which functor is applied. * @tparam T2 Type of second argument to which functor is applied. * @tparam F Type of functor to apply. * @param x Either a var matrix or nested integer std::vector input to which * operation is applied. * @param x Either a var matrix or nested integer std::vector input to which * operation is applied. * @param f functor to apply to inputs. * @return Eigen object with result of applying functor to inputs. */ template <typename T1, typename T2, typename F, require_any_std_vector_vt<is_std_vector, T1, T2>* = nullptr, require_any_std_vector_st<std::is_integral, T1, T2>* = nullptr, require_any_var_matrix_t<T1, T2>* = nullptr> inline auto apply_scalar_binary(const T1& x, const T2& y, const F& f) { return f(x, y); } /** * Specialisation for use when the one input is an `var_value<Eigen> type and * the other is a scalar. * * @tparam T1 Type of either `var_value<Matrix>` or scalar object to which * functor is applied. * @tparam T2 Type of either `var_value<Matrix>` or scalar object to which * functor is applied. * @tparam F Type of functor to apply. * @param x Matrix or Scalar input to which operation is applied. * @param x Matrix or Scalar input to which operation is applied. * @param f functor to apply to var matrix and scalar inputs. * @return `var_value<Matrix> object with result of applying functor to inputs. * */ template <typename T1, typename T2, typename F, require_any_stan_scalar_t<T1, T2>* = nullptr, require_any_var_matrix_t<T1, T2>* = nullptr> inline auto apply_scalar_binary(const T1& x, const T2& y, const F& f) { return f(x, y); } } // namespace math } // namespace stan #endif <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: elementparser.hxx,v $ * * $Revision: 1.3 $ * * last change: $Author: kz $ $Date: 2004-08-31 14:59:01 $ * * 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: 2002 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #ifndef CONFIGMGR_XML_ELEMENTPARSER_HXX #define CONFIGMGR_XML_ELEMENTPARSER_HXX #ifndef CONFIGMGR_XML_ELEMENTINFO_HXX #include "elementinfo.hxx" #endif #ifndef CONFIGMGR_LOGGER_HXX #include "logger.hxx" #endif #ifndef _COM_SUN_STAR_XML_SAX_XATTRIBUTELIST_HPP_ #include <com/sun/star/xml/sax/XAttributeList.hpp> #endif namespace configmgr { // ----------------------------------------------------------------------------- namespace xml { // ----------------------------------------------------------------------------- namespace uno = ::com::sun::star::uno; namespace sax = ::com::sun::star::xml::sax; using rtl::OUString; // ----------------------------------------------------------------------------- class ElementParser { Logger mLogger; public: typedef uno::Reference< sax::XAttributeList > SaxAttributeList; public: explicit ElementParser(Logger const & xLogger) : mLogger(xLogger) {} Logger const & logger() const { return mLogger; } /// reset the parser for a new document void reset() {} /// retrieve the (almost) complete information for an element ElementInfo parseElementInfo(OUString const& _sTag, SaxAttributeList const& _xAttribs) const; /// retrieve the node name for an element ElementType::Enum getNodeType(OUString const& _sTag, SaxAttributeList const& xAttribs) const; /// retrieve the node name for an element ElementName getName(OUString const& _sTag, SaxAttributeList const& xAttribs, ElementType::Enum eType = ElementType::unknown) const; /// query whether the node has an operation Operation::Enum getOperation(SaxAttributeList const& xAttribs, ElementType::Enum _eType) const; /// retrieve the language (if any) stored in the attribute list bool getLanguage(SaxAttributeList const& xAttribs, OUString & _rsLanguage) const; /// reads attributes for nodes from the attribute list ElementInfo::FlagsType getNodeFlags(SaxAttributeList const& xAttribs, ElementType::Enum _eType) const; /// retrieve element type and associated module name of a set, bool getSetElementType(SaxAttributeList const& _xAttribs, OUString& _rsElementType, OUString& _rsElementTypeModule) const; /// retrieve the instance type and associated module name of a instance, bool getInstanceType(SaxAttributeList const& _xAttribs, OUString& _rsElementType, OUString& _rsElementTypeModule) const; /// retrieve the component for an import or uses element, bool getImportComponent(SaxAttributeList const& _xAttribs, OUString& _rsComponent) const; /// retrieve element type and associated module name of a set, uno::Type getPropertyValueType(SaxAttributeList const& _xAttribs) const; /// reads a value attribute from the attribute list bool isNull(SaxAttributeList const& _xAttribs) const; /// reads a value attribute from the attribute list OUString getSeparator(SaxAttributeList const& _xAttribs) const; // low-level internal methods /// checks for presence of a boolean attribute and assigns its value if it exists (and is a bool) bool maybeGetAttribute(SaxAttributeList const& _xAttribs, OUString const& _aAttributeName, bool& _rbAttributeValue) const; /// checks for presence of an attribute and assigns its value if it exists bool maybeGetAttribute(SaxAttributeList const& _xAttribs, OUString const& _aAttributeName, OUString& _rsAttributeValue) const; /// assigns an attribute value or an empty string if it doesn't exist void alwaysGetAttribute(SaxAttributeList const& _xAttribs, OUString const& _aAttributeName, OUString& _rsAttributeValue) const; }; // ----------------------------------------------------------------------------- // ----------------------------------------------------------------------------- } // namespace xml // ----------------------------------------------------------------------------- } // namespace configmgr #endif <commit_msg>INTEGRATION: CWS cfglooseends (1.3.12); FILE MERGED 2004/11/05 10:25:10 jb 1.3.12.1: #115489# Raise an exception when encountering an invalid value type<commit_after>/************************************************************************* * * $RCSfile: elementparser.hxx,v $ * * $Revision: 1.4 $ * * last change: $Author: obo $ $Date: 2004-11-15 13:38: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: 2002 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #ifndef CONFIGMGR_XML_ELEMENTPARSER_HXX #define CONFIGMGR_XML_ELEMENTPARSER_HXX #ifndef CONFIGMGR_XML_ELEMENTINFO_HXX #include "elementinfo.hxx" #endif #ifndef CONFIGMGR_LOGGER_HXX #include "logger.hxx" #endif #ifndef _COM_SUN_STAR_XML_SAX_XATTRIBUTELIST_HPP_ #include <com/sun/star/xml/sax/XAttributeList.hpp> #endif namespace configmgr { // ----------------------------------------------------------------------------- namespace xml { // ----------------------------------------------------------------------------- namespace uno = ::com::sun::star::uno; namespace sax = ::com::sun::star::xml::sax; using rtl::OUString; // ----------------------------------------------------------------------------- class ElementParser { Logger mLogger; public: typedef uno::Reference< sax::XAttributeList > SaxAttributeList; class BadValueType { OUString mMessage; public: BadValueType(OUString const & aMessage) : mMessage(aMessage) {} OUString message() const { return mMessage.getStr(); } }; public: explicit ElementParser(Logger const & xLogger) : mLogger(xLogger) {} Logger const & logger() const { return mLogger; } /// reset the parser for a new document void reset() {} /// retrieve the (almost) complete information for an element ElementInfo parseElementInfo(OUString const& _sTag, SaxAttributeList const& _xAttribs) const; /// retrieve the node name for an element ElementType::Enum getNodeType(OUString const& _sTag, SaxAttributeList const& xAttribs) const; /// retrieve the node name for an element ElementName getName(OUString const& _sTag, SaxAttributeList const& xAttribs, ElementType::Enum eType = ElementType::unknown) const; /// query whether the node has an operation Operation::Enum getOperation(SaxAttributeList const& xAttribs, ElementType::Enum _eType) const; /// retrieve the language (if any) stored in the attribute list bool getLanguage(SaxAttributeList const& xAttribs, OUString & _rsLanguage) const; /// reads attributes for nodes from the attribute list ElementInfo::FlagsType getNodeFlags(SaxAttributeList const& xAttribs, ElementType::Enum _eType) const; /// retrieve element type and associated module name of a set, bool getSetElementType(SaxAttributeList const& _xAttribs, OUString& _rsElementType, OUString& _rsElementTypeModule) const; /// retrieve the instance type and associated module name of a instance, bool getInstanceType(SaxAttributeList const& _xAttribs, OUString& _rsElementType, OUString& _rsElementTypeModule) const; /// retrieve the component for an import or uses element, bool getImportComponent(SaxAttributeList const& _xAttribs, OUString& _rsComponent) const; /// retrieve element type and associated module name of a set, uno::Type getPropertyValueType(SaxAttributeList const& _xAttribs) const; // throw( BadValueType ) /// reads a value attribute from the attribute list bool isNull(SaxAttributeList const& _xAttribs) const; /// reads a value attribute from the attribute list OUString getSeparator(SaxAttributeList const& _xAttribs) const; // low-level internal methods /// checks for presence of a boolean attribute and assigns its value if it exists (and is a bool) bool maybeGetAttribute(SaxAttributeList const& _xAttribs, OUString const& _aAttributeName, bool& _rbAttributeValue) const; /// checks for presence of an attribute and assigns its value if it exists bool maybeGetAttribute(SaxAttributeList const& _xAttribs, OUString const& _aAttributeName, OUString& _rsAttributeValue) const; /// assigns an attribute value or an empty string if it doesn't exist void alwaysGetAttribute(SaxAttributeList const& _xAttribs, OUString const& _aAttributeName, OUString& _rsAttributeValue) const; }; // ----------------------------------------------------------------------------- // ----------------------------------------------------------------------------- } // namespace xml // ----------------------------------------------------------------------------- } // namespace configmgr #endif <|endoftext|>
<commit_before>//===--- RuntimeEntrySymbols.cpp - Define symbols for runtime entries --===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See http://swift.org/LICENSE.txt for license information // See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// // // This file defines function pointer symbols for runtime entries. // //===----------------------------------------------------------------------===// // Produce global symbols referencing runtime function implementations only for // those runtime entries that demand it. // // Each runtime function definition in RuntimeFunctions.def should // indicate if it requires a global referencing it. // // For example, all entries using the RegisterPreservingCC calling convention // need a global, because they are currently always invoked indirectly using a // client-side wrapper. // // Runtime entries using the DefaultCC calling convention do not // demand a global symbol by default. But they can optionally ask for it, in // case it is needed. For example, _swift_isDeallocating is required by // Instruments. #include "swift/Runtime/Config.h" // Entry points using a standard C calling convention or not using the new // calling convention do not need to have global symbols referring to their // implementations. #define FOR_CONV_DefaultCC(...) #define FOR_CONV_C_CC(...) // Entry points using the new calling convention require global symbols // referring to their implementations. #define FOR_CONV_RegisterPreservingCC(x) x typedef void (*RuntimeEntry)(); // Generate a forward declaration of the runtime entry implementation. // Define a global symbol referring to this implementation. #define DEFINE_SYMBOL(SymbolName, Name, CC) \ SWIFT_RT_ENTRY_VISIBILITY extern "C" void Name() \ SWIFT_CC(CC); \ SWIFT_RUNTIME_EXPORT extern "C" RuntimeEntry SymbolName = \ reinterpret_cast<RuntimeEntry>(Name); #define FUNCTION1(Id, Name, CC, ReturnTys, ArgTys, Attrs) \ DEFINE_SYMBOL(SWIFT_RT_ENTRY_REF(Name), Name, CC) #if defined(SWIFT_RT_USE_WRAPPERS) // Automatically generate a global symbol name if it is required by the calling // convention. #define FUNCTION(Id, Name, CC, ReturnTys, ArgTys, Attrs) \ FOR_CONV_##CC(FUNCTION1(Id, Name, CC, ReturnTys, ArgTys, Attrs)) #else // No need to generate any global symbols for entries that do not provide their // own symbols. #define FUNCTION(Id, Name, CC, ReturnTys, ArgTys, Attrs) #endif // Allow for a custom global symbol name and implementation. #define FUNCTION_WITH_GLOBAL_SYMBOL_AND_IMPL(Id, Name, GlobalSymbolName, Impl, \ CC, ReturnTys, ArgTys, Attrs) \ DEFINE_SYMBOL(GlobalSymbolName, Impl, CC) // Indicate that we are going to generate the global symbols for those runtime // functions that require it. #define SWIFT_RUNTIME_GENERATE_GLOBAL_SYMBOLS 1 namespace swift { // Generate global symbols which are function pointers to the actual // implementations of runtime entry points. // This is done only for entry points using a new calling convention or // for those entry points which explicitly require it. #include "swift/Runtime/RuntimeFunctions.def" } <commit_msg>Set proper linkage on external declarations of runtime functions implementations.<commit_after>//===--- RuntimeEntrySymbols.cpp - Define symbols for runtime entries --===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See http://swift.org/LICENSE.txt for license information // See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// // // This file defines function pointer symbols for runtime entries. // //===----------------------------------------------------------------------===// // Produce global symbols referencing runtime function implementations only for // those runtime entries that demand it. // // Each runtime function definition in RuntimeFunctions.def should // indicate if it requires a global referencing it. // // For example, all entries using the RegisterPreservingCC calling convention // need a global, because they are currently always invoked indirectly using a // client-side wrapper. // // Runtime entries using the DefaultCC calling convention do not // demand a global symbol by default. But they can optionally ask for it, in // case it is needed. For example, _swift_isDeallocating is required by // Instruments. #include "swift/Runtime/Config.h" // Entry points using a standard C calling convention or not using the new // calling convention do not need to have global symbols referring to their // implementations. #define FOR_CONV_DefaultCC(...) #define FOR_CONV_C_CC(...) // Entry points using the new calling convention require global symbols // referring to their implementations. #define FOR_CONV_RegisterPreservingCC(x) x typedef void (*RuntimeEntry)(); // Generate a forward declaration of the runtime entry implementation. // Define a global symbol referring to this implementation. #define DEFINE_SYMBOL(SymbolName, Name, CC) \ SWIFT_RT_ENTRY_IMPL_VISIBILITY extern "C" void Name() \ SWIFT_CC(CC); \ SWIFT_RUNTIME_EXPORT extern "C" RuntimeEntry SymbolName = \ reinterpret_cast<RuntimeEntry>(Name); #define FUNCTION1(Id, Name, CC, ReturnTys, ArgTys, Attrs) \ DEFINE_SYMBOL(SWIFT_RT_ENTRY_REF(Name), Name, CC) #if defined(SWIFT_RT_USE_WRAPPERS) // Automatically generate a global symbol name if it is required by the calling // convention. #define FUNCTION(Id, Name, CC, ReturnTys, ArgTys, Attrs) \ FOR_CONV_##CC(FUNCTION1(Id, Name, CC, ReturnTys, ArgTys, Attrs)) #else // No need to generate any global symbols for entries that do not provide their // own symbols. #define FUNCTION(Id, Name, CC, ReturnTys, ArgTys, Attrs) #endif // Allow for a custom global symbol name and implementation. #define FUNCTION_WITH_GLOBAL_SYMBOL_AND_IMPL(Id, Name, GlobalSymbolName, Impl, \ CC, ReturnTys, ArgTys, Attrs) \ DEFINE_SYMBOL(GlobalSymbolName, Impl, CC) // Indicate that we are going to generate the global symbols for those runtime // functions that require it. #define SWIFT_RUNTIME_GENERATE_GLOBAL_SYMBOLS 1 namespace swift { // Generate global symbols which are function pointers to the actual // implementations of runtime entry points. // This is done only for entry points using a new calling convention or // for those entry points which explicitly require it. #include "swift/Runtime/RuntimeFunctions.def" } <|endoftext|>
<commit_before>#include "selectsignaldialog.h" #include "ui_selectsignaldialog.h" #include "signaldescription.h" #include "signalhandler.h" #include "jointnames.h" #include <cstdio> #include <cassert> class SelectSignalDialog::Internal : public Ui::SelectSignalDialog { public: QList<QListWidget*> ArrayKeyWidgets; }; SelectSignalDialog::SelectSignalDialog(QWidget* parent) : QDialog(parent) { mInternal = new Internal; mInternal->setupUi(this); QStringList channels; channels << "ATLAS_COMMAND" << "ATLAS_FOOT_POS_EST" << "ATLAS_IMU_PACKET" << "ATLAS_IMU_PACKET_FILTERED" << "ATLAS_STATE" << "ATLAS_STATE_FILTERED" << "ATLAS_STATE_FILTERED_ALT" << "ATLAS_STATE_EXTRA" << "ATLAS_STATUS" << "EST_ROBOT_STATE" << "EST_ROBOT_STATE_KF" << "EST_ROBOT_STATE_LP" << "EST_ROBOT_STATE_ECHO" << "FOOT_CONTACT_ESTIMATE" << "FOOT_CONTACT_CLASSIFY" << "FORCE_PLATE_DATA" << "INS_ERR_UPDATE" << "MICROSTRAIN_INS" << "POSE_BDI" << "POSE_BODY" << "POSE_BODY_ALT" << "POSE_BODY_FOVIS_VELOCITY" << "POSE_BODY_LEGODO_VELOCITY" << "POSE_BODY_LEGODO_VELOCITY_FAIL" << "POSE_VICON" << "SCALED_ROBOT_STATE" << "SE_INS_POSE_STATE" << "SE_MATLAB_DATAFUSION_REQ" << "STATE_ESTIMATOR_POSE" << "STATE_ESTIMATOR_STATE" << "TRUE_ROBOT_STATE" << "VICON_ATLAS" << "CONTROLLER_DEBUG" << "ROBOTIQ_LEFT_STATUS" << "ROBOTIQ_RIGHT_STATUS" ; QStringList messageTypes = SignalHandlerFactory::instance().messageTypes(); QStringList messageFields; mInternal->ChannelListBox->addItems(channels); mInternal->MessageTypeListBox->addItems(messageTypes); mInternal->MessageFieldListBox->addItems(messageFields); mInternal->ChannelListBox->setCurrentRow(0); mInternal->MessageTypeListBox->setCurrentRow(0); mInternal->MessageFieldListBox->setCurrentRow(0); this->connect(mInternal->MessageTypeListBox, SIGNAL(currentRowChanged(int)), SLOT(onMessageTypeChanged())); this->connect(mInternal->MessageFieldListBox, SIGNAL(currentRowChanged(int)), SLOT(onFieldNameChanged())); this->onMessageTypeChanged(); } void SelectSignalDialog::onMessageTypeChanged() { if (!mInternal->MessageTypeListBox->currentItem()) { return; } QString messageType = mInternal->MessageTypeListBox->currentItem()->text(); QStringList fieldNames = SignalHandlerFactory::instance().fieldNames(messageType); fieldNames.sort(); mInternal->MessageFieldListBox->clear(); mInternal->MessageFieldListBox->addItems(fieldNames); mInternal->MessageFieldListBox->setCurrentRow(0); this->onFieldNameChanged(); } void SelectSignalDialog::onFieldNameChanged() { if (!mInternal->MessageFieldListBox->currentItem()) { return; } QString messageType = mInternal->MessageTypeListBox->currentItem()->text(); QString fieldName = mInternal->MessageFieldListBox->currentItem()->text(); foreach (QListWidget* listWidget, mInternal->ArrayKeyWidgets) { delete listWidget; } mInternal->ArrayKeyWidgets.clear(); const QList<QList<QString> >& validArrayKeys = SignalHandlerFactory::instance().validArrayKeys(messageType, fieldName); bool useArrayKeys = !validArrayKeys.empty(); mInternal->ArrayKeysLabel->setVisible(useArrayKeys); mInternal->ArrayKeysContainer->setVisible(useArrayKeys); foreach (const QList<QString> & keys, validArrayKeys) { assert(keys.size()); QListWidget* listWidget = new QListWidget; listWidget->addItems(keys); listWidget->setCurrentRow(0); mInternal->ArrayKeyWidgets.append(listWidget); mInternal->ArrayKeysContainer->layout()->addWidget(listWidget); } if (mInternal->ArrayKeyWidgets.size()) { mInternal->ArrayKeyWidgets.back()->setSelectionMode(QAbstractItemView::ExtendedSelection); } } SelectSignalDialog::~SelectSignalDialog() { delete mInternal; } QList<SignalHandler*> SelectSignalDialog::createSignalHandlers() const { QString channel = mInternal->ChannelListBox->currentItem()->text(); QString messageType = mInternal->MessageTypeListBox->currentItem()->text(); QString messageField = mInternal->MessageFieldListBox->currentItem()->text(); SignalDescription desc; desc.mChannel = channel; desc.mMessageType = messageType; desc.mFieldName = messageField; QList<SignalDescription> descriptions; if (mInternal->ArrayKeyWidgets.length()) { foreach (QListWidget* listWidget, mInternal->ArrayKeyWidgets) { if (listWidget == mInternal->ArrayKeyWidgets.back()) { foreach (QListWidgetItem* selectedItem, listWidget->selectedItems()) { QString arrayKey = selectedItem->text(); SignalDescription descCopy(desc); descCopy.mArrayKeys.append(arrayKey); descriptions.append(descCopy); } } else { QString arrayKey = listWidget->currentItem()->text(); desc.mArrayKeys.append(arrayKey); } } } else { descriptions.append(desc); } QList<SignalHandler*> signalHandlers; foreach (const SignalDescription& description, descriptions) { SignalHandler* signalHandler = SignalHandlerFactory::instance().createHandler(&description); assert(signalHandler); signalHandlers.append(signalHandler); } return signalHandlers; } <commit_msg>adding signal<commit_after>#include "selectsignaldialog.h" #include "ui_selectsignaldialog.h" #include "signaldescription.h" #include "signalhandler.h" #include "jointnames.h" #include <cstdio> #include <cassert> class SelectSignalDialog::Internal : public Ui::SelectSignalDialog { public: QList<QListWidget*> ArrayKeyWidgets; }; SelectSignalDialog::SelectSignalDialog(QWidget* parent) : QDialog(parent) { mInternal = new Internal; mInternal->setupUi(this); QStringList channels; channels << "ATLAS_COMMAND" << "ATLAS_FOOT_POS_EST" << "ATLAS_IMU_PACKET" << "ATLAS_IMU_PACKET_FILTERED" << "ATLAS_STATE" << "ATLAS_STATE_FILTERED" << "ATLAS_STATE_FILTERED_ALT" << "ATLAS_STATE_EXTRA" << "ATLAS_STATUS" << "EST_ROBOT_STATE" << "EST_ROBOT_STATE_KF" << "EST_ROBOT_STATE_LP" << "EST_ROBOT_STATE_ECHO" << "EXPD_ROBOT_STATE" << "FOOT_CONTACT_ESTIMATE" << "FOOT_CONTACT_CLASSIFY" << "FORCE_PLATE_DATA" << "INS_ERR_UPDATE" << "MICROSTRAIN_INS" << "POSE_BDI" << "POSE_BODY" << "POSE_BODY_ALT" << "POSE_BODY_FOVIS_VELOCITY" << "POSE_BODY_LEGODO_VELOCITY" << "POSE_BODY_LEGODO_VELOCITY_FAIL" << "POSE_VICON" << "SCALED_ROBOT_STATE" << "SE_INS_POSE_STATE" << "SE_MATLAB_DATAFUSION_REQ" << "STATE_ESTIMATOR_POSE" << "STATE_ESTIMATOR_STATE" << "TRUE_ROBOT_STATE" << "VICON_ATLAS" << "CONTROLLER_DEBUG" << "ROBOTIQ_LEFT_STATUS" << "ROBOTIQ_RIGHT_STATUS" ; QStringList messageTypes = SignalHandlerFactory::instance().messageTypes(); QStringList messageFields; mInternal->ChannelListBox->addItems(channels); mInternal->MessageTypeListBox->addItems(messageTypes); mInternal->MessageFieldListBox->addItems(messageFields); mInternal->ChannelListBox->setCurrentRow(0); mInternal->MessageTypeListBox->setCurrentRow(0); mInternal->MessageFieldListBox->setCurrentRow(0); this->connect(mInternal->MessageTypeListBox, SIGNAL(currentRowChanged(int)), SLOT(onMessageTypeChanged())); this->connect(mInternal->MessageFieldListBox, SIGNAL(currentRowChanged(int)), SLOT(onFieldNameChanged())); this->onMessageTypeChanged(); } void SelectSignalDialog::onMessageTypeChanged() { if (!mInternal->MessageTypeListBox->currentItem()) { return; } QString messageType = mInternal->MessageTypeListBox->currentItem()->text(); QStringList fieldNames = SignalHandlerFactory::instance().fieldNames(messageType); fieldNames.sort(); mInternal->MessageFieldListBox->clear(); mInternal->MessageFieldListBox->addItems(fieldNames); mInternal->MessageFieldListBox->setCurrentRow(0); this->onFieldNameChanged(); } void SelectSignalDialog::onFieldNameChanged() { if (!mInternal->MessageFieldListBox->currentItem()) { return; } QString messageType = mInternal->MessageTypeListBox->currentItem()->text(); QString fieldName = mInternal->MessageFieldListBox->currentItem()->text(); foreach (QListWidget* listWidget, mInternal->ArrayKeyWidgets) { delete listWidget; } mInternal->ArrayKeyWidgets.clear(); const QList<QList<QString> >& validArrayKeys = SignalHandlerFactory::instance().validArrayKeys(messageType, fieldName); bool useArrayKeys = !validArrayKeys.empty(); mInternal->ArrayKeysLabel->setVisible(useArrayKeys); mInternal->ArrayKeysContainer->setVisible(useArrayKeys); foreach (const QList<QString> & keys, validArrayKeys) { assert(keys.size()); QListWidget* listWidget = new QListWidget; listWidget->addItems(keys); listWidget->setCurrentRow(0); mInternal->ArrayKeyWidgets.append(listWidget); mInternal->ArrayKeysContainer->layout()->addWidget(listWidget); } if (mInternal->ArrayKeyWidgets.size()) { mInternal->ArrayKeyWidgets.back()->setSelectionMode(QAbstractItemView::ExtendedSelection); } } SelectSignalDialog::~SelectSignalDialog() { delete mInternal; } QList<SignalHandler*> SelectSignalDialog::createSignalHandlers() const { QString channel = mInternal->ChannelListBox->currentItem()->text(); QString messageType = mInternal->MessageTypeListBox->currentItem()->text(); QString messageField = mInternal->MessageFieldListBox->currentItem()->text(); SignalDescription desc; desc.mChannel = channel; desc.mMessageType = messageType; desc.mFieldName = messageField; QList<SignalDescription> descriptions; if (mInternal->ArrayKeyWidgets.length()) { foreach (QListWidget* listWidget, mInternal->ArrayKeyWidgets) { if (listWidget == mInternal->ArrayKeyWidgets.back()) { foreach (QListWidgetItem* selectedItem, listWidget->selectedItems()) { QString arrayKey = selectedItem->text(); SignalDescription descCopy(desc); descCopy.mArrayKeys.append(arrayKey); descriptions.append(descCopy); } } else { QString arrayKey = listWidget->currentItem()->text(); desc.mArrayKeys.append(arrayKey); } } } else { descriptions.append(desc); } QList<SignalHandler*> signalHandlers; foreach (const SignalDescription& description, descriptions) { SignalHandler* signalHandler = SignalHandlerFactory::instance().createHandler(&description); assert(signalHandler); signalHandlers.append(signalHandler); } return signalHandlers; } <|endoftext|>
<commit_before>#include "loader.h" #include<dlfcn.h> BVS::ModuleMap BVS::Loader::modules; BVS::ModuleVector BVS::Loader::masterModules; BVS::Loader::Loader(Control& control, Config& config) : control(control) , logger("Loader") , config(config) { } void BVS::Loader::registerModule(const std::string& id, Module* module) { modules[id] = std::shared_ptr<ModuleData>(new ModuleData{ \ id, \ std::string(), \ std::string(), \ module, \ nullptr, \ std::thread(), \ false, \ ModuleFlag::WAIT, \ Status::NONE, \ ConnectorMap()}); } BVS::Loader& BVS::Loader::load(const std::string& moduleTraits, const bool asThread) { /* algorithm: * SEPARATE id(library).options * CHECK for duplicate ids * LOAD the library and CHECK errors * LINK and execute register function, CHECK errors * SAVE metadata * MOVE connectors to metadata * START (un/)threaded module */ std::string id; std::string library; std::string options; // search for '.' in id and separate id and options size_t separator = moduleTraits.find_first_of('.'); if (separator!=std::string::npos) { id = moduleTraits.substr(0, separator); options = moduleTraits.substr(separator+1, std::string::npos); } else id = moduleTraits; // search for '(' in id and separate if necessary separator = id.find_first_of('('); if (separator!=std::string::npos) { library = id.substr(separator+1, std::string::npos); library.erase(library.length()-1); id = id.erase(separator, std::string::npos); } else library = id; // search for duplicate id in modules if (modules.find(id)!=modules.end()) { LOG(0, "Duplicate id: " << id); LOG(0, "If you try to load a module more than once, use unique ids and the id(library).options syntax!"); exit(-1); } // prepare path and load the lib std::string modulePath = "./lib" + library + ".so"; LOG(3, id << " will be loaded from " << modulePath); void* dlib = dlopen(modulePath.c_str(), RTLD_NOW); // check for errors if (dlib == NULL) { LOG(0, "While loading " << modulePath << ", following error occured: " << dlerror()); exit(-1); } // look for bvsRegisterModule in loaded lib, check for errors and execute register function typedef void (*bvsRegisterModule_t)(const std::string& id, const Config& config); bvsRegisterModule_t bvsRegisterModule; *reinterpret_cast<void**>(&bvsRegisterModule)=dlsym(dlib, "bvsRegisterModule"); // check for errors char* dlerr = dlerror(); if (dlerr) { LOG(0, "Loading function bvsRegisterModule() in " << modulePath << " resulted in: " << dlerr); exit(-1); } // register bvsRegisterModule(id, config); LOG(2, id << " loaded and registered!"); // save handle,library name and option string for later use modules[id]->dlib = dlib; modules[id]->library = library; modules[id]->options = options; // move connectors from temporary to metadata modules[id]->connectors = std::move(ConnectorDataCollector::connectors); // set metadata and start as thread if needed if (asThread==true) { LOG(3, id << " will be started in own thread!"); modules[id]->asThread = true; modules[id]->thread = std::thread(&Control::threadController, &control, modules[id]); Control::threadedModules++; } else { LOG(3, id << " will be executed by Control!"); modules[id]->asThread = false; masterModules.push_back(modules[id]); } return *this; } BVS::Loader& BVS::Loader::unload(const std::string& id, const bool eraseFromMap) { /* algorithm: * CHECK thread, signal exit * DISCONNECT connectors * DELETE module instance and connectors * CHECK library handle * CLOSE library * CHECK errors */ // wait for thread to join, first check if it is still running if (modules[id]->asThread == true) { if (modules[id]->thread.joinable()) { modules[id]->flag = ModuleFlag::QUIT; control.threadCond.notify_all(); LOG(3, "joining: " << id); modules[id]->thread.join(); } } // disconnect connectors for (auto& it: modules) { for (auto& con: it.second->connectors) { if (con.second->type==ConnectorType::INPUT) continue; // find and reset all inputs connected to output for (auto& mods: modules) { for (auto& modCon: mods.second->connectors) { if (con.second->pointer==modCon.second->pointer) { modCon.second->pointer = nullptr; modCon.second->active = false; } } } } } // delete module and connectors modules[id]->connectors.clear(); delete modules[id]->module; modules[id]->module = nullptr; // close lib and check for errors std::string modulePath = "./lib" + modules[id]->library + ".so"; LOG(3, id << " will be closed using " << modulePath); // get handle from internals void* dlib = modules[id]->dlib; if (dlib==nullptr) { LOG(0, "Requested module " << id << " not found!"); exit(-1); } // close the module dlclose(dlib); // check for errors char* dlerr = dlerror(); if (dlerr) { LOG(0, "While closing " << modulePath << " following error occured: " << dlerror()); exit(-1); } LOG(2, id << " unloaded and deregistered!"); if (eraseFromMap) { modules.erase(id); LOG(2, id << " erased from map!"); } return *this; } BVS::Loader& BVS::Loader::unloadAll() { for (auto& it: modules) unload(it.second->id, false); modules.clear(); return *this; } BVS::Loader& BVS::Loader::connectModules(bool connectorTypeMatching) { /* algorithm: * FOR EACH module * DO * SEPARATE input and remove parsed part * CHECK input exists * CHECK input type * SEPARATE module and output * CHECK module exists and self reference * CHECK output exists * CHECK output type * CHECK input typeid hash == output typeid hash * CHECK input already connected * CONNECT * DONE */ std::string options; std::string selection; std::string input; std::string module; std::string output; size_t separator; size_t separator2; // check options for each module for (auto& it: modules) { options = it.second->options; while (!options.empty()) { // get input name and selection separator = options.find_first_of('('); separator2 = options.find_first_of(')'); selection = options.substr(0, separator2+1); if (separator!=std::string::npos) { module= options.substr(separator+1, separator2-separator-1); input = options.substr(0, separator); } else { LOG(0, "no input selection found: " << selection); exit(1); } // remove parsed part options.erase(0, separator2+1); if (options[0] == '.') options.erase(options.begin()); // check if desired input exists if (it.second->connectors.find(input) == it.second->connectors.end()) { LOG(0, "selected input does not exist: " << selection); exit(1); } // check input type if (it.second->connectors[input]->type != ConnectorType::INPUT) { LOG(0, "selected input is not of input type: " << it.second->id << "." << selection); exit(1); } // search for '.' in selection and separate module and output separator = module.find_first_of('.'); if (separator!=std::string::npos) { output = module.substr(separator+1, std::string::npos); module = module.substr(0, separator); } else { LOG(0, "no module output selected: " << selection); exit(1); } // check if desired module exists if (modules.find(module) == modules.end()) { LOG(0, "could not find module: " << module); exit(1); } // check for sending data to oneself... if (module == it.second->id) { LOG(0, "can not request data from self: " << selection); exit(1); } // check if desired output exists if (modules[module]->connectors.find(output) == modules[module]->connectors.end()) { LOG(0, "selected output does not exist: " << selection); exit(1); } // check output type if (modules[module]->connectors[output]->type != ConnectorType::OUTPUT) { LOG(0, "selected output is not of output type: " << selection); exit(1); } // check input typeid hash == output typeid hash if (connectorTypeMatching && it.second->connectors[input]->typeIDHash != modules[module]->connectors[output]->typeIDHash) { LOG(0, "selected input and output connector template instantiations are of different type: " \ << it.second->id << "." << selection << " -> " \ << it.second->connectors[input]->typeIDName << "!=" << modules[module]->connectors[output]->typeIDName); exit(1); } // check if input is already connected if (it.second->connectors[input]->active) { LOG(0, "selected input is alreade connected to another output: " << selection); exit(1); } // connect it.second->connectors[input]->pointer = modules[module]->connectors[output]->pointer; it.second->connectors[input]->active = true; it.second->connectors[input]->mutex = modules[module]->connectors[output]->mutex; LOG(3, "connected: " << it.second->id << "." << it.second->connectors[input]->id << " <- " << modules[module]->id << "." << modules[module]->connectors[output]->id); } } // do maintenance for load/unload, e.g. remove all connections for unloaded module... return *this; } <commit_msg>loader: unset mutex when unloading<commit_after>#include "loader.h" #include<dlfcn.h> BVS::ModuleMap BVS::Loader::modules; BVS::ModuleVector BVS::Loader::masterModules; BVS::Loader::Loader(Control& control, Config& config) : control(control) , logger("Loader") , config(config) { } void BVS::Loader::registerModule(const std::string& id, Module* module) { modules[id] = std::shared_ptr<ModuleData>(new ModuleData{ \ id, \ std::string(), \ std::string(), \ module, \ nullptr, \ std::thread(), \ false, \ ModuleFlag::WAIT, \ Status::NONE, \ ConnectorMap()}); } BVS::Loader& BVS::Loader::load(const std::string& moduleTraits, const bool asThread) { /* algorithm: * SEPARATE id(library).options * CHECK for duplicate ids * LOAD the library and CHECK errors * LINK and execute register function, CHECK errors * SAVE metadata * MOVE connectors to metadata * START (un/)threaded module */ std::string id; std::string library; std::string options; // search for '.' in id and separate id and options size_t separator = moduleTraits.find_first_of('.'); if (separator!=std::string::npos) { id = moduleTraits.substr(0, separator); options = moduleTraits.substr(separator+1, std::string::npos); } else id = moduleTraits; // search for '(' in id and separate if necessary separator = id.find_first_of('('); if (separator!=std::string::npos) { library = id.substr(separator+1, std::string::npos); library.erase(library.length()-1); id = id.erase(separator, std::string::npos); } else library = id; // search for duplicate id in modules if (modules.find(id)!=modules.end()) { LOG(0, "Duplicate id: " << id); LOG(0, "If you try to load a module more than once, use unique ids and the id(library).options syntax!"); exit(-1); } // prepare path and load the lib std::string modulePath = "./lib" + library + ".so"; LOG(3, id << " will be loaded from " << modulePath); void* dlib = dlopen(modulePath.c_str(), RTLD_NOW); // check for errors if (dlib == NULL) { LOG(0, "While loading " << modulePath << ", following error occured: " << dlerror()); exit(-1); } // look for bvsRegisterModule in loaded lib, check for errors and execute register function typedef void (*bvsRegisterModule_t)(const std::string& id, const Config& config); bvsRegisterModule_t bvsRegisterModule; *reinterpret_cast<void**>(&bvsRegisterModule)=dlsym(dlib, "bvsRegisterModule"); // check for errors char* dlerr = dlerror(); if (dlerr) { LOG(0, "Loading function bvsRegisterModule() in " << modulePath << " resulted in: " << dlerr); exit(-1); } // register bvsRegisterModule(id, config); LOG(2, id << " loaded and registered!"); // save handle,library name and option string for later use modules[id]->dlib = dlib; modules[id]->library = library; modules[id]->options = options; // move connectors from temporary to metadata modules[id]->connectors = std::move(ConnectorDataCollector::connectors); // set metadata and start as thread if needed if (asThread==true) { LOG(3, id << " will be started in own thread!"); modules[id]->asThread = true; modules[id]->thread = std::thread(&Control::threadController, &control, modules[id]); Control::threadedModules++; } else { LOG(3, id << " will be executed by Control!"); modules[id]->asThread = false; masterModules.push_back(modules[id]); } return *this; } BVS::Loader& BVS::Loader::unload(const std::string& id, const bool eraseFromMap) { /* algorithm: * CHECK thread, signal exit * DISCONNECT connectors * DELETE module instance and connectors * CHECK library handle * CLOSE library * CHECK errors */ // wait for thread to join, first check if it is still running if (modules[id]->asThread == true) { if (modules[id]->thread.joinable()) { modules[id]->flag = ModuleFlag::QUIT; control.threadCond.notify_all(); LOG(3, "joining: " << id); modules[id]->thread.join(); } } // disconnect connectors for (auto& it: modules) { for (auto& con: it.second->connectors) { if (con.second->type==ConnectorType::INPUT) continue; // find and reset all inputs connected to output for (auto& mods: modules) { for (auto& modCon: mods.second->connectors) { if (con.second->pointer==modCon.second->pointer) { modCon.second->pointer = nullptr; modCon.second->active = false; modCon.second->mutex = nullptr; } } } } } // delete module and connectors modules[id]->connectors.clear(); delete modules[id]->module; modules[id]->module = nullptr; // close lib and check for errors std::string modulePath = "./lib" + modules[id]->library + ".so"; LOG(3, id << " will be closed using " << modulePath); // get handle from internals void* dlib = modules[id]->dlib; if (dlib==nullptr) { LOG(0, "Requested module " << id << " not found!"); exit(-1); } // close the module dlclose(dlib); // check for errors char* dlerr = dlerror(); if (dlerr) { LOG(0, "While closing " << modulePath << " following error occured: " << dlerror()); exit(-1); } LOG(2, id << " unloaded and deregistered!"); if (eraseFromMap) { modules.erase(id); LOG(2, id << " erased from map!"); } return *this; } BVS::Loader& BVS::Loader::unloadAll() { for (auto& it: modules) unload(it.second->id, false); modules.clear(); return *this; } BVS::Loader& BVS::Loader::connectModules(bool connectorTypeMatching) { /* algorithm: * FOR EACH module * DO * SEPARATE input and remove parsed part * CHECK input exists * CHECK input type * SEPARATE module and output * CHECK module exists and self reference * CHECK output exists * CHECK output type * CHECK input typeid hash == output typeid hash * CHECK input already connected * CONNECT * DONE */ std::string options; std::string selection; std::string input; std::string module; std::string output; size_t separator; size_t separator2; // check options for each module for (auto& it: modules) { options = it.second->options; while (!options.empty()) { // get input name and selection separator = options.find_first_of('('); separator2 = options.find_first_of(')'); selection = options.substr(0, separator2+1); if (separator!=std::string::npos) { module= options.substr(separator+1, separator2-separator-1); input = options.substr(0, separator); } else { LOG(0, "no input selection found: " << selection); exit(1); } // remove parsed part options.erase(0, separator2+1); if (options[0] == '.') options.erase(options.begin()); // check if desired input exists if (it.second->connectors.find(input) == it.second->connectors.end()) { LOG(0, "selected input does not exist: " << selection); exit(1); } // check input type if (it.second->connectors[input]->type != ConnectorType::INPUT) { LOG(0, "selected input is not of input type: " << it.second->id << "." << selection); exit(1); } // search for '.' in selection and separate module and output separator = module.find_first_of('.'); if (separator!=std::string::npos) { output = module.substr(separator+1, std::string::npos); module = module.substr(0, separator); } else { LOG(0, "no module output selected: " << selection); exit(1); } // check if desired module exists if (modules.find(module) == modules.end()) { LOG(0, "could not find module: " << module); exit(1); } // check for sending data to oneself... if (module == it.second->id) { LOG(0, "can not request data from self: " << selection); exit(1); } // check if desired output exists if (modules[module]->connectors.find(output) == modules[module]->connectors.end()) { LOG(0, "selected output does not exist: " << selection); exit(1); } // check output type if (modules[module]->connectors[output]->type != ConnectorType::OUTPUT) { LOG(0, "selected output is not of output type: " << selection); exit(1); } // check input typeid hash == output typeid hash if (connectorTypeMatching && it.second->connectors[input]->typeIDHash != modules[module]->connectors[output]->typeIDHash) { LOG(0, "selected input and output connector template instantiations are of different type: " \ << it.second->id << "." << selection << " -> " \ << it.second->connectors[input]->typeIDName << "!=" << modules[module]->connectors[output]->typeIDName); exit(1); } // check if input is already connected if (it.second->connectors[input]->active) { LOG(0, "selected input is alreade connected to another output: " << selection); exit(1); } // connect it.second->connectors[input]->pointer = modules[module]->connectors[output]->pointer; it.second->connectors[input]->active = true; it.second->connectors[input]->mutex = modules[module]->connectors[output]->mutex; LOG(3, "connected: " << it.second->id << "." << it.second->connectors[input]->id << " <- " << modules[module]->id << "." << modules[module]->connectors[output]->id); } } // do maintenance for load/unload, e.g. remove all connections for unloaded module... return *this; } <|endoftext|>
<commit_before>AliAnalysisTaskStrangenessVsMultiplicityMCRun2 *AddTaskStrangenessVsMultiplicityMCRun2( Bool_t lSaveEventTree = kTRUE, Bool_t lSaveV0 = kTRUE, Bool_t lSaveCascade = kTRUE, TString lExtraOptions = "", const TString lMasterJobSessionFlag = "", TString lExtraOutputName = "") { // Creates, configures and attaches to the train a cascades check task. // Get the pointer to the existing analysis manager via the static access method. //============================================================================== AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager(); if (!mgr) { ::Error("AddTaskStrangenessVsMultiplicity", "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("AddTaskStrangenessVsMultiplicity", "This task requires an input event handler"); return NULL; } TString type = mgr->GetInputEventHandler()->GetDataType(); // can be "ESD" or "AOD" // Create and configure the task AliAnalysisTaskStrangenessVsMultiplicityMCRun2 *taskAuxiliary = new AliAnalysisTaskStrangenessVsMultiplicityMCRun2(lSaveEventTree, lSaveV0, lSaveCascade, Form("taskAuxiliary%s",lExtraOutputName.Data()), lExtraOptions); mgr->AddTask(taskAuxiliary); TString outputFileName = AliAnalysisManager::GetCommonFileName(); outputFileName += ":PWGLF_StrVsMult"; if (mgr->GetMCtruthEventHandler()) outputFileName += "_MC"; outputFileName += lExtraOutputName.Data(); Printf("Set OutputFileName : \n %s\n", outputFileName.Data() ); TString lC[9]; lC[0] = "cList"; lC[1] = "cListV0"; lC[2] = "cListXiMinus"; lC[3] = "cListXiPlus"; lC[4] = "cListOmegaMinus"; lC[5] = "cListOmegaPlus"; lC[6] = "cTreeEvent"; lC[7] = "cTreeV0"; lC[8] = "cTreeCascade"; for(Int_t iname=0;iname<9;iname++) lC[iname] += lExtraOutputName.Data(); AliAnalysisDataContainer *coutputLists[6]; for(Int_t ilist=0;ilist<6;ilist++){ coutputLists[ilist] = mgr->CreateContainer(lC[ilist].Data(), TList::Class(), AliAnalysisManager::kOutputContainer, outputFileName ); } AliAnalysisDataContainer *coutputTree = 0x0; AliAnalysisDataContainer *coutputTreeV0 = 0x0; AliAnalysisDataContainer *coutputTreeCascade = 0x0; if( lSaveEventTree ){ AliAnalysisDataContainer *coutputTree = mgr->CreateContainer(Form("cTreeEvent%s",lExtraOutputName.Data()), TTree::Class(), AliAnalysisManager::kOutputContainer, outputFileName ); coutputTree->SetSpecialOutput(); } if( lSaveV0 ){ AliAnalysisDataContainer *coutputTreeV0 = mgr->CreateContainer(Form("cTreeV0%s",lExtraOutputName.Data()), TTree::Class(), AliAnalysisManager::kOutputContainer, outputFileName ); coutputTreeV0->SetSpecialOutput(); } if (lSaveCascade){ AliAnalysisDataContainer *coutputTreeCascade = mgr->CreateContainer(Form("cTreeCascade%s",lExtraOutputName.Data()), TTree::Class(), AliAnalysisManager::kOutputContainer, outputFileName ); coutputTreeCascade->SetSpecialOutput(); } //This one you should merge in file-resident ways... //Recommendation: Tree as a single output slot mgr->ConnectInput (taskAuxiliary, 0, mgr->GetCommonInputContainer()); for(Int_t ilist=0;ilist<6;ilist++){ mgr->ConnectOutput(taskAuxiliary, ilist+1, coutputLists[ilist]); if ( lSaveEventTree ) mgr->ConnectOutput(taskAuxiliary, 4, coutputTree); if ( lSaveV0 ) mgr->ConnectOutput(taskAuxiliary, 5, coutputTreeV0); if ( lSaveCascade ) mgr->ConnectOutput(taskAuxiliary, 6, coutputTreeCascade); return taskAuxiliary; } <commit_msg>Fix indices<commit_after>AliAnalysisTaskStrangenessVsMultiplicityMCRun2 *AddTaskStrangenessVsMultiplicityMCRun2( Bool_t lSaveEventTree = kTRUE, Bool_t lSaveV0 = kTRUE, Bool_t lSaveCascade = kTRUE, TString lExtraOptions = "", const TString lMasterJobSessionFlag = "", TString lExtraOutputName = "") { // Creates, configures and attaches to the train a cascades check task. // Get the pointer to the existing analysis manager via the static access method. //============================================================================== AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager(); if (!mgr) { ::Error("AddTaskStrangenessVsMultiplicity", "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("AddTaskStrangenessVsMultiplicity", "This task requires an input event handler"); return NULL; } TString type = mgr->GetInputEventHandler()->GetDataType(); // can be "ESD" or "AOD" // Create and configure the task AliAnalysisTaskStrangenessVsMultiplicityMCRun2 *taskAuxiliary = new AliAnalysisTaskStrangenessVsMultiplicityMCRun2(lSaveEventTree, lSaveV0, lSaveCascade, Form("taskAuxiliary%s",lExtraOutputName.Data()), lExtraOptions); mgr->AddTask(taskAuxiliary); TString outputFileName = AliAnalysisManager::GetCommonFileName(); outputFileName += ":PWGLF_StrVsMult"; if (mgr->GetMCtruthEventHandler()) outputFileName += "_MC"; outputFileName += lExtraOutputName.Data(); Printf("Set OutputFileName : \n %s\n", outputFileName.Data() ); TString lC[9]; lC[0] = "cList"; lC[1] = "cListV0"; lC[2] = "cListXiMinus"; lC[3] = "cListXiPlus"; lC[4] = "cListOmegaMinus"; lC[5] = "cListOmegaPlus"; lC[6] = "cTreeEvent"; lC[7] = "cTreeV0"; lC[8] = "cTreeCascade"; for(Int_t iname=0;iname<9;iname++) lC[iname] += lExtraOutputName.Data(); AliAnalysisDataContainer *coutputLists[6]; for(Int_t ilist=0;ilist<6;ilist++){ coutputLists[ilist] = mgr->CreateContainer(lC[ilist].Data(), TList::Class(), AliAnalysisManager::kOutputContainer, outputFileName ); } AliAnalysisDataContainer *coutputTree = 0x0; AliAnalysisDataContainer *coutputTreeV0 = 0x0; AliAnalysisDataContainer *coutputTreeCascade = 0x0; if( lSaveEventTree ){ AliAnalysisDataContainer *coutputTree = mgr->CreateContainer(Form("cTreeEvent%s",lExtraOutputName.Data()), TTree::Class(), AliAnalysisManager::kOutputContainer, outputFileName ); coutputTree->SetSpecialOutput(); } if( lSaveV0 ){ AliAnalysisDataContainer *coutputTreeV0 = mgr->CreateContainer(Form("cTreeV0%s",lExtraOutputName.Data()), TTree::Class(), AliAnalysisManager::kOutputContainer, outputFileName ); coutputTreeV0->SetSpecialOutput(); } if (lSaveCascade){ AliAnalysisDataContainer *coutputTreeCascade = mgr->CreateContainer(Form("cTreeCascade%s",lExtraOutputName.Data()), TTree::Class(), AliAnalysisManager::kOutputContainer, outputFileName ); coutputTreeCascade->SetSpecialOutput(); } //This one you should merge in file-resident ways... //Recommendation: Tree as a single output slot mgr->ConnectInput (taskAuxiliary, 0, mgr->GetCommonInputContainer()); for(Int_t ilist=0;ilist<6;ilist++){ mgr->ConnectOutput(taskAuxiliary, ilist+1, coutputLists[ilist]); if ( lSaveEventTree ) mgr->ConnectOutput(taskAuxiliary, 7, coutputTree); if ( lSaveV0 ) mgr->ConnectOutput(taskAuxiliary, 8, coutputTreeV0); if ( lSaveCascade ) mgr->ConnectOutput(taskAuxiliary, 9, coutputTreeCascade); return taskAuxiliary; } <|endoftext|>
<commit_before>/** * 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 <pthread.h> #include <cstdlib> #include <iostream> #include <tr1/functional> #include <mesos/executor.hpp> using namespace mesos; using std::cout; using std::endl; using std::string; void run(ExecutorDriver* driver, const TaskInfo& task) { sleep(100); TaskStatus status; status.mutable_task_id()->MergeFrom(task.task_id()); status.set_state(TASK_FINISHED); driver->sendStatusUpdate(status); } void* start(void* arg) { std::tr1::function<void(void)>* thunk = (std::tr1::function<void(void)>*) arg; (*thunk)(); delete thunk; return NULL; } class LongLivedExecutor : public Executor { public: virtual ~LongLivedExecutor() {} virtual void registered(ExecutorDriver* driver, const ExecutorInfo& executorInfo, const FrameworkInfo& frameworkInfo, const SlaveInfo& slaveInfo) { cout << "Registered executor on " << slaveInfo.hostname() << endl; } virtual void reregistered(ExecutorDriver* driver, const SlaveInfo& slaveInfo) { cout << "Re-registered executor on " << slaveInfo.hostname() << endl; } virtual void disconnected(ExecutorDriver* driver) {} virtual void launchTask(ExecutorDriver* driver, const TaskInfo& task) { cout << "Starting task " << task.task_id().value() << endl; std::tr1::function<void(void)>* thunk = new std::tr1::function<void(void)>(std::tr1::bind(&run, driver, task)); pthread_t pthread; if (pthread_create(&pthread, NULL, &start, thunk) != 0) { TaskStatus status; status.mutable_task_id()->MergeFrom(task.task_id()); status.set_state(TASK_FAILED); driver->sendStatusUpdate(status); } else { pthread_detach(pthread); TaskStatus status; status.mutable_task_id()->MergeFrom(task.task_id()); status.set_state(TASK_RUNNING); driver->sendStatusUpdate(status); } } virtual void killTask(ExecutorDriver* driver, const TaskID& taskId) {} virtual void frameworkMessage(ExecutorDriver* driver, const string& data) {} virtual void shutdown(ExecutorDriver* driver) {} virtual void error(ExecutorDriver* driver, const string& message) {} }; int main(int argc, char** argv) { LongLivedExecutor executor; MesosExecutorDriver driver(&executor); return driver.run() == DRIVER_STOPPED ? 0 : 1; } <commit_msg>Made tasks of the "long-lived-framework" have varying runtimes (https://reviews.apache.org/r/5267).<commit_after>/** * 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 <pthread.h> #include <stdlib.h> // For random. #include <cstdlib> #include <iostream> #include <tr1/functional> #include <mesos/executor.hpp> using namespace mesos; using std::cout; using std::endl; using std::string; void run(ExecutorDriver* driver, const TaskInfo& task) { sleep(random() % 10); TaskStatus status; status.mutable_task_id()->MergeFrom(task.task_id()); status.set_state(TASK_FINISHED); driver->sendStatusUpdate(status); } void* start(void* arg) { std::tr1::function<void(void)>* thunk = (std::tr1::function<void(void)>*) arg; (*thunk)(); delete thunk; return NULL; } class LongLivedExecutor : public Executor { public: virtual ~LongLivedExecutor() {} virtual void registered(ExecutorDriver* driver, const ExecutorInfo& executorInfo, const FrameworkInfo& frameworkInfo, const SlaveInfo& slaveInfo) { cout << "Registered executor on " << slaveInfo.hostname() << endl; } virtual void reregistered(ExecutorDriver* driver, const SlaveInfo& slaveInfo) { cout << "Re-registered executor on " << slaveInfo.hostname() << endl; } virtual void disconnected(ExecutorDriver* driver) {} virtual void launchTask(ExecutorDriver* driver, const TaskInfo& task) { cout << "Starting task " << task.task_id().value() << endl; std::tr1::function<void(void)>* thunk = new std::tr1::function<void(void)>(std::tr1::bind(&run, driver, task)); pthread_t pthread; if (pthread_create(&pthread, NULL, &start, thunk) != 0) { TaskStatus status; status.mutable_task_id()->MergeFrom(task.task_id()); status.set_state(TASK_FAILED); driver->sendStatusUpdate(status); } else { pthread_detach(pthread); TaskStatus status; status.mutable_task_id()->MergeFrom(task.task_id()); status.set_state(TASK_RUNNING); driver->sendStatusUpdate(status); } } virtual void killTask(ExecutorDriver* driver, const TaskID& taskId) {} virtual void frameworkMessage(ExecutorDriver* driver, const string& data) {} virtual void shutdown(ExecutorDriver* driver) {} virtual void error(ExecutorDriver* driver, const string& message) {} }; int main(int argc, char** argv) { LongLivedExecutor executor; MesosExecutorDriver driver(&executor); return driver.run() == DRIVER_STOPPED ? 0 : 1; } <|endoftext|>
<commit_before>#pragma once #ifndef DELEGATE_HPP # define DELEGATE_HPP #include <cassert> #include <memory> #include <new> #include <type_traits> #include <utility> template <typename T> class delegate; template<class R, class ...A> class delegate<R (A...)> { template <typename U, typename = void> struct is_functora : std::false_type { }; template <typename U> struct is_functora<U, typename std::enable_if<bool(sizeof((R (U::*)(A...)) &U::operator()))>::type > : std::true_type { }; template <typename U, typename = void> struct is_functorb : std::false_type { }; template <typename U> struct is_functorb<U, typename std::enable_if<bool(sizeof((R (U::*)(A...) const) &U::operator()))>::type > : std::true_type { }; template <typename U> struct is_functor { static constexpr bool const value = is_functora<U>::value || is_functorb<U>::value; }; typedef R (*stub_ptr_type)(void*, A...); constexpr delegate(void* const o, stub_ptr_type const m) : object_ptr_(o), stub_ptr_(m) { } public: constexpr delegate() = default; constexpr delegate(delegate const&) = default; constexpr delegate(delegate&&) = default; template <class C> constexpr delegate(C const* const o) : object_ptr_(const_cast<C*>(o)) { } template <class C> constexpr delegate(C const& o) : object_ptr_(const_cast<C*>(&o)) { } delegate(R (* const function_ptr)(A...)) { *this = from(function_ptr); } template <class C> delegate(C* const object_ptr_, R (C::* const method_ptr)(A...)) { *this = from(object_ptr_, method_ptr); } template <class C> delegate(C* const object_ptr_, R (C::* const method_ptr)(A...) const) { *this = from(object_ptr_, method_ptr); } template <class C> delegate(C& object, R (C::* const method_ptr)(A...)) { *this = from(object, method_ptr); } template <class C> delegate(C const& object, R (C::* const method_ptr)(A...) const) { *this = from(object, method_ptr); } template < typename T, typename = typename std::enable_if< !std::is_same<delegate, typename std::remove_const< typename std::remove_reference<T>::type>::type>::value && is_functor<typename std::remove_reference<T>::type>::value >::type > delegate(T&& f) : store_(operator new(sizeof(T)), functor_deleter<typename std::remove_reference<T>::type>), store_size_(sizeof(T)) { typedef typename std::remove_reference<T>::type functor_type; object_ptr_ = new (store_.get()) functor_type(std::forward<T>(f)); stub_ptr_ = functor_stub<functor_type>; deleter_ = destructor_stub<functor_type>; } delegate& operator=(delegate const&) = default; delegate& operator=(delegate&& rhs) = default; template <class C> delegate& operator=(R (C::* const rhs)(A...)) { return *this = from(static_cast<C*>(object_ptr_), rhs); } template <class C> delegate& operator=(R (C::* const rhs)(A...) const) { return *this = from(static_cast<C const*>(object_ptr_), rhs); } template < typename T, typename = typename std::enable_if< !std::is_same<delegate, typename std::remove_const< typename std::remove_reference<T>::type>::type>::value && is_functor<typename std::remove_reference<T>::type>::value >::type > delegate& operator=(T&& f) { typedef typename std::remove_reference<T>::type functor_type; if ((sizeof(T) > store_size_) || (decltype(store_.use_count())(1) != store_.use_count())) { store_.reset(operator new(sizeof(T)), functor_deleter<functor_type>); store_size_ = sizeof(T); } else { deleter_(store_.get()); } object_ptr_ = new (store_.get()) functor_type(std::forward<T>(f)); stub_ptr_ = functor_stub<functor_type>; deleter_ = destructor_stub<functor_type>; return *this; } template <R (*function_ptr)(A...)> static constexpr delegate from() { return { nullptr, function_stub<function_ptr> }; } template <class C, R (C::*method_ptr)(A...)> static constexpr delegate from(C* const object_ptr_) { return { object_ptr_, method_stub<C, method_ptr> }; } template <class C, R (C::*method_ptr)(A...) const> static constexpr delegate from(C const* const object_ptr_) { return { const_cast<C*>(object_ptr_), const_method_stub<C, method_ptr> }; } template <class C, R (C::*method_ptr)(A...)> static constexpr delegate from(C& object) { return { &object, method_stub<C, method_ptr> }; } template <class C, R (C::*method_ptr)(A...) const> static constexpr delegate from(C const& object) { return { const_cast<C*>(&object), const_method_stub<C, method_ptr> }; } template <typename T> static delegate from(T&& f) { return { std::forward<T>(f) }; } static constexpr delegate from(R (* const function_ptr)(A...)) { return { [function_ptr](A const... args){ return (*function_ptr)(args...); } }; } template <class C> static constexpr delegate from(C* const object_ptr_, R (C::* const method_ptr)(A...)) { return { [object_ptr_, method_ptr](A const... args){ return (object_ptr_->*method_ptr)(args...); } }; } template <class C> static constexpr delegate from(C const* const object_ptr_, R (C::* const method_ptr)(A...) const) { return { [object_ptr_, method_ptr](A const... args){ return (object_ptr_->*method_ptr)(args...); } }; } template <class C> static constexpr delegate from(C& object, R (C::* const method_ptr)(A...)) { return { [&object, method_ptr](A const... args){ return (object.*method_ptr)(args...); } }; } template <class C> static constexpr delegate from(C const& object, R (C::* const method_ptr)(A...) const) { return { [&object, method_ptr](A const... args){ return (object.*method_ptr)(args...); } }; } void reset() { stub_ptr_ = nullptr; } void swap(delegate& other) { std::swap(object_ptr_, other.object_ptr_); std::swap(stub_ptr_, other.stub_ptr_); } constexpr bool operator==(delegate const& rhs) const { return (stub_ptr_ == rhs.stub_ptr_) && (object_ptr_ == rhs.object_ptr_); } constexpr bool operator!=(delegate const& rhs) const { return !operator==(rhs); } constexpr bool operator<(delegate const& rhs) const { return (object_ptr_ < rhs.object_ptr_) || (stub_ptr_ < rhs.stub_ptr_); } constexpr explicit operator bool() const { return stub_ptr_; } template <typename ...B> constexpr R operator()(B&&... args) const { // assert(stub_ptr); return (*stub_ptr_)(object_ptr_, std::forward<B>(args)...); } private: friend class ::std::hash<delegate>; typedef void (*deleter_type)(void*); void* object_ptr_{}; stub_ptr_type stub_ptr_{}; deleter_type deleter_; std::shared_ptr<void> store_; std::size_t store_size_; template <class T> static void destructor_stub(void* const p) { static_cast<T*>(p)->~T(); } template <class T> static void functor_deleter(void* const p) { static_cast<T*>(p)->~T(); operator delete(p); } template <R (*function_ptr)(A...)> static constexpr R function_stub(void* const, A const... args) { return (*function_ptr)(args...); } template <class C, R (C::*method_ptr)(A...)> static constexpr R method_stub(void* const object_ptr_, A const... args) { return (static_cast<C*>(object_ptr_)->*method_ptr)(args...); } template <class C, R (C::*method_ptr)(A...) const> static constexpr R const_method_stub(void* const object_ptr_, A const... args) { return (static_cast<C const*>(object_ptr_)->*method_ptr)(args...); } template <typename T> static constexpr R functor_stub(void* const object_ptr_, A const... args) { return (*static_cast<T*>(object_ptr_))(args...); } }; namespace std { template <typename R, typename ...A> struct hash<delegate<R (A...)> > { size_t operator()(delegate<R (A...)> const& d) const { auto const seed(hash<void*>()(d.object_ptr_) + 0x9e3779b9); return hash<typename delegate<R (A...)>::stub_ptr_type>()(d.stub_ptr_) + 0x9e3779b9 + (seed << 6) + (seed >> 2); } }; } #endif // DELEGATE_HPP <commit_msg>hash added<commit_after>#pragma once #ifndef DELEGATE_HPP # define DELEGATE_HPP #include <cassert> #include <memory> #include <new> #include <type_traits> #include <utility> template <typename T> class delegate; template<class R, class ...A> class delegate<R (A...)> { template <typename U, typename = void> struct is_functora : std::false_type { }; template <typename U> struct is_functora<U, typename std::enable_if<bool(sizeof((R (U::*)(A...)) &U::operator()))>::type > : std::true_type { }; template <typename U, typename = void> struct is_functorb : std::false_type { }; template <typename U> struct is_functorb<U, typename std::enable_if<bool(sizeof((R (U::*)(A...) const) &U::operator()))>::type > : std::true_type { }; template <typename U> struct is_functor { static constexpr bool const value = is_functora<U>::value || is_functorb<U>::value; }; typedef R (*stub_ptr_type)(void*, A...); constexpr delegate(void* const o, stub_ptr_type const m) : object_ptr_(o), stub_ptr_(m) { } public: constexpr delegate() = default; constexpr delegate(delegate const&) = default; constexpr delegate(delegate&&) = default; template <class C> constexpr delegate(C const* const o) : object_ptr_(const_cast<C*>(o)) { } template <class C> constexpr delegate(C const& o) : object_ptr_(const_cast<C*>(&o)) { } delegate(R (* const function_ptr)(A...)) { *this = from(function_ptr); } template <class C> delegate(C* const object_ptr_, R (C::* const method_ptr)(A...)) { *this = from(object_ptr_, method_ptr); } template <class C> delegate(C* const object_ptr_, R (C::* const method_ptr)(A...) const) { *this = from(object_ptr_, method_ptr); } template <class C> delegate(C& object, R (C::* const method_ptr)(A...)) { *this = from(object, method_ptr); } template <class C> delegate(C const& object, R (C::* const method_ptr)(A...) const) { *this = from(object, method_ptr); } template < typename T, typename = typename std::enable_if< !std::is_same<delegate, typename std::remove_const< typename std::remove_reference<T>::type>::type>::value && is_functor<typename std::remove_reference<T>::type>::value >::type > delegate(T&& f) : store_(operator new(sizeof(T)), functor_deleter<typename std::remove_reference<T>::type>), store_size_(sizeof(T)) { typedef typename std::remove_reference<T>::type functor_type; object_ptr_ = new (store_.get()) functor_type(std::forward<T>(f)); stub_ptr_ = functor_stub<functor_type>; deleter_ = destructor_stub<functor_type>; } delegate& operator=(delegate const&) = default; delegate& operator=(delegate&& rhs) = default; template <class C> delegate& operator=(R (C::* const rhs)(A...)) { return *this = from(static_cast<C*>(object_ptr_), rhs); } template <class C> delegate& operator=(R (C::* const rhs)(A...) const) { return *this = from(static_cast<C const*>(object_ptr_), rhs); } template < typename T, typename = typename std::enable_if< !std::is_same<delegate, typename std::remove_const< typename std::remove_reference<T>::type>::type>::value && is_functor<typename std::remove_reference<T>::type>::value >::type > delegate& operator=(T&& f) { typedef typename std::remove_reference<T>::type functor_type; if ((sizeof(T) > store_size_) || (decltype(store_.use_count())(1) != store_.use_count())) { store_.reset(operator new(sizeof(T)), functor_deleter<functor_type>); store_size_ = sizeof(T); } else { deleter_(store_.get()); } object_ptr_ = new (store_.get()) functor_type(std::forward<T>(f)); stub_ptr_ = functor_stub<functor_type>; deleter_ = destructor_stub<functor_type>; return *this; } template <R (*function_ptr)(A...)> static constexpr delegate from() { return { nullptr, function_stub<function_ptr> }; } template <class C, R (C::*method_ptr)(A...)> static constexpr delegate from(C* const object_ptr_) { return { object_ptr_, method_stub<C, method_ptr> }; } template <class C, R (C::*method_ptr)(A...) const> static constexpr delegate from(C const* const object_ptr_) { return { const_cast<C*>(object_ptr_), const_method_stub<C, method_ptr> }; } template <class C, R (C::*method_ptr)(A...)> static constexpr delegate from(C& object) { return { &object, method_stub<C, method_ptr> }; } template <class C, R (C::*method_ptr)(A...) const> static constexpr delegate from(C const& object) { return { const_cast<C*>(&object), const_method_stub<C, method_ptr> }; } template <typename T> static delegate from(T&& f) { return { std::forward<T>(f) }; } static constexpr delegate from(R (* const function_ptr)(A...)) { return { [function_ptr](A const... args){ return (*function_ptr)(args...); } }; } template <class C> static constexpr delegate from(C* const object_ptr_, R (C::* const method_ptr)(A...)) { return { [object_ptr_, method_ptr](A const... args){ return (object_ptr_->*method_ptr)(args...); } }; } template <class C> static constexpr delegate from(C const* const object_ptr_, R (C::* const method_ptr)(A...) const) { return { [object_ptr_, method_ptr](A const... args){ return (object_ptr_->*method_ptr)(args...); } }; } template <class C> static constexpr delegate from(C& object, R (C::* const method_ptr)(A...)) { return { [&object, method_ptr](A const... args){ return (object.*method_ptr)(args...); } }; } template <class C> static constexpr delegate from(C const& object, R (C::* const method_ptr)(A...) const) { return { [&object, method_ptr](A const... args){ return (object.*method_ptr)(args...); } }; } void reset() { stub_ptr_ = nullptr; } void swap(delegate& other) { std::swap(*this, other); } constexpr bool operator==(delegate const& rhs) const { return (stub_ptr_ == rhs.stub_ptr_) && (object_ptr_ == rhs.object_ptr_); } constexpr bool operator!=(delegate const& rhs) const { return !operator==(rhs); } constexpr bool operator<(delegate const& rhs) const { return (object_ptr_ < rhs.object_ptr_) || (stub_ptr_ < rhs.stub_ptr_); } constexpr explicit operator bool() const { return stub_ptr_; } template <typename ...B> constexpr R operator()(B&&... args) const { // assert(stub_ptr); return (*stub_ptr_)(object_ptr_, std::forward<B>(args)...); } private: friend class ::std::hash<delegate>; typedef void (*deleter_type)(void*); void* object_ptr_{}; stub_ptr_type stub_ptr_{}; deleter_type deleter_; std::shared_ptr<void> store_; std::size_t store_size_; template <class T> static void destructor_stub(void* const p) { static_cast<T*>(p)->~T(); } template <class T> static void functor_deleter(void* const p) { static_cast<T*>(p)->~T(); operator delete(p); } template <R (*function_ptr)(A...)> static constexpr R function_stub(void* const, A const... args) { return (*function_ptr)(args...); } template <class C, R (C::*method_ptr)(A...)> static constexpr R method_stub(void* const object_ptr_, A const... args) { return (static_cast<C*>(object_ptr_)->*method_ptr)(args...); } template <class C, R (C::*method_ptr)(A...) const> static constexpr R const_method_stub(void* const object_ptr_, A const... args) { return (static_cast<C const*>(object_ptr_)->*method_ptr)(args...); } template <typename T> static constexpr R functor_stub(void* const object_ptr_, A const... args) { return (*static_cast<T*>(object_ptr_))(args...); } }; namespace std { template <typename R, typename ...A> struct hash<delegate<R (A...)> > { size_t operator()(delegate<R (A...)> const& d) const { auto const seed(hash<void*>()(d.object_ptr_) + 0x9e3779b9); return hash<typename delegate<R (A...)>::stub_ptr_type>()(d.stub_ptr_) + 0x9e3779b9 + (seed << 6) + (seed >> 2); } }; } #endif // DELEGATE_HPP <|endoftext|>
<commit_before>#include <gtest/gtest.h> #include "utTerm.h" int main( int argc , char **argv ) { testing :: InitGoogleTest( &argc , argv ) ; return RUN_ALL_TESTS( ) ; } <commit_msg>Delete MainTerm.cpp<commit_after><|endoftext|>
<commit_before>/*********************************************************************** filename: ItemViewRenderer.cpp created: Mon Jun 02 2014 author: Timotei Dolean <timotei21@gmail.com> *************************************************************************/ /*************************************************************************** * Copyright (C) 2004 - 2014 Paul D Turner & The CEGUI Development Team * * 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 BE LIABLE FOR ANY CLAIM, DAMAGES OR * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR * OTHER DEALINGS IN THE SOFTWARE. ***************************************************************************/ #include "CEGUI/WindowRendererSets/Core/ItemViewRenderer.h" #include "CEGUI/falagard/WidgetLookManager.h" namespace CEGUI { //----------------------------------------------------------------------------// ItemViewRenderer::ItemViewRenderer(const String& type) : WindowRenderer(type) { } //----------------------------------------------------------------------------// Rectf ItemViewRenderer::getItemRenderingArea(bool hscroll, bool vscroll) const { const WidgetLookFeel& wlf = getLookNFeel(); String scroll_suffix; if (vscroll) scroll_suffix += "V"; if (hscroll) scroll_suffix += "H"; if(!scroll_suffix.empty()) scroll_suffix += "Scroll"; const String area_names[] = { "ItemRenderingArea", "ItemRenderArea" }; const String suffixes[] = { scroll_suffix, "" }; for (size_t suffix_id = 0; suffix_id < 2; suffix_id++) { const String& suffix = suffixes[suffix_id]; for (size_t area_id = 0; area_id < 2; ++area_id) { const String& full_area_name = area_names[area_id] + suffix; if (wlf.isNamedAreaDefined(full_area_name)) return wlf.getNamedArea(full_area_name).getArea().getPixelRect(*d_window); } } CEGUI_THROW(UnknownObjectException("There is no item rendering area defined!")); } } <commit_msg>Fix the instantiating of a string<commit_after>/*********************************************************************** filename: ItemViewRenderer.cpp created: Mon Jun 02 2014 author: Timotei Dolean <timotei21@gmail.com> *************************************************************************/ /*************************************************************************** * Copyright (C) 2004 - 2014 Paul D Turner & The CEGUI Development Team * * 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 BE LIABLE FOR ANY CLAIM, DAMAGES OR * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR * OTHER DEALINGS IN THE SOFTWARE. ***************************************************************************/ #include "CEGUI/WindowRendererSets/Core/ItemViewRenderer.h" #include "CEGUI/falagard/WidgetLookManager.h" namespace CEGUI { //----------------------------------------------------------------------------// ItemViewRenderer::ItemViewRenderer(const String& type) : WindowRenderer(type) { } //----------------------------------------------------------------------------// Rectf ItemViewRenderer::getItemRenderingArea(bool hscroll, bool vscroll) const { const WidgetLookFeel& wlf = getLookNFeel(); String scroll_suffix; if (vscroll) scroll_suffix += "V"; if (hscroll) scroll_suffix += "H"; if(!scroll_suffix.empty()) scroll_suffix += "Scroll"; const String area_names[] = { "ItemRenderingArea", "ItemRenderArea" }; const String suffixes[] = { scroll_suffix, "" }; for (size_t suffix_id = 0; suffix_id < 2; suffix_id++) { const String& suffix = suffixes[suffix_id]; for (size_t area_id = 0; area_id < 2; ++area_id) { const String full_area_name(area_names[area_id] + suffix); if (wlf.isNamedAreaDefined(full_area_name)) return wlf.getNamedArea(full_area_name).getArea().getPixelRect(*d_window); } } CEGUI_THROW(UnknownObjectException("There is no item rendering area defined!")); } } <|endoftext|>
<commit_before>// Copyright (c) 2010 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "base/command_line.h" #include "chrome/browser/extensions/extension_apitest.h" #include "chrome/common/chrome_switches.h" #if defined(OS_WIN) #define MAYBE_Infobars Infobars #else // Need to finish port to Linux. See http://crbug.com/39916 for details. // Temporarily marked as DISABLED on OSX too. See http://crbug.com/60990 for details. #define MAYBE_Infobars DISABLED_Infobars #endif IN_PROC_BROWSER_TEST_F(ExtensionApiTest, MAYBE_Infobars) { // TODO(finnur): Remove once infobars are no longer experimental (bug 39511). CommandLine::ForCurrentProcess()->AppendSwitch( switches::kEnableExperimentalExtensionApis); ASSERT_TRUE(RunExtensionTest("infobars")) << message_; } <commit_msg>Marking ExtensionApiTest.Infobars as DISABLED on Windows.<commit_after>// Copyright (c) 2010 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "base/command_line.h" #include "chrome/browser/extensions/extension_apitest.h" #include "chrome/common/chrome_switches.h" #if defined(OS_WIN) // Also marking this as disabled on Windows. See http://crbug.com/75451. #define MAYBE_Infobars DISABLED_Infobars #else // Need to finish port to Linux. See http://crbug.com/39916 for details. // Temporarily marked as DISABLED on OSX too. See http://crbug.com/60990 for details. #define MAYBE_Infobars DISABLED_Infobars #endif IN_PROC_BROWSER_TEST_F(ExtensionApiTest, MAYBE_Infobars) { // TODO(finnur): Remove once infobars are no longer experimental (bug 39511). CommandLine::ForCurrentProcess()->AppendSwitch( switches::kEnableExperimentalExtensionApis); ASSERT_TRUE(RunExtensionTest("infobars")) << message_; } <|endoftext|>
<commit_before>// Copyright (c) 2010 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "base/command_line.h" #include "chrome/browser/extensions/extension_apitest.h" #include "chrome/common/chrome_switches.h" #if defined(TOOLKIT_VIEWS) #define MAYBE_Infobars Infobars #else // Need to finish port to Linux. See http://crbug.com/39916 for details. // Temporarily marked as DISABLED on OSX too. See http://crbug.com/60990 for details. #define MAYBE_Infobars DISABLED_Infobars #endif IN_PROC_BROWSER_TEST_F(ExtensionApiTest, MAYBE_Infobars) { // TODO(finnur): Remove once infobars are no longer experimental (bug 39511). CommandLine::ForCurrentProcess()->AppendSwitch( switches::kEnableExperimentalExtensionApis); ASSERT_TRUE(RunExtensionTest("infobars")) << message_; } <commit_msg>Marking ExtensionApiTest, Infobars as DISABLED on everything but Windows.<commit_after>// Copyright (c) 2010 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "base/command_line.h" #include "chrome/browser/extensions/extension_apitest.h" #include "chrome/common/chrome_switches.h" #if defined(OS_WIN) #define MAYBE_Infobars Infobars #else // Need to finish port to Linux. See http://crbug.com/39916 for details. // Temporarily marked as DISABLED on OSX too. See http://crbug.com/60990 for details. #define MAYBE_Infobars DISABLED_Infobars #endif IN_PROC_BROWSER_TEST_F(ExtensionApiTest, MAYBE_Infobars) { // TODO(finnur): Remove once infobars are no longer experimental (bug 39511). CommandLine::ForCurrentProcess()->AppendSwitch( switches::kEnableExperimentalExtensionApis); ASSERT_TRUE(RunExtensionTest("infobars")) << message_; } <|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/prerender/prerender_resource_handler.h" #include "chrome/browser/net/chrome_url_request_context.h" #include "content/common/resource_response.h" #include "net/base/load_flags.h" #include "net/http/http_response_headers.h" #include "net/url_request/url_request.h" namespace prerender { namespace { bool ShouldPrerenderURL(const GURL& url) { if (!url.is_valid()) return false; if (!url.SchemeIs("http")) { RecordFinalStatus(FINAL_STATUS_HTTPS); return false; } return true; } bool ValidateAliasURLs(const std::vector<GURL>& urls) { for (std::vector<GURL>::const_iterator it = urls.begin(); it != urls.end(); ++it) { if (!ShouldPrerenderURL(*it)) return false; } return true; } bool ShouldPrerender(const ResourceResponse* response) { if (!response) return false; const ResourceResponseHead& rrh = response->response_head; if (!rrh.headers) return false; if (rrh.mime_type != "text/html") return false; if (rrh.headers->response_code() != 200) return false; return true; } } // namespace PrerenderResourceHandler* PrerenderResourceHandler::MaybeCreate( const net::URLRequest& request, ChromeURLRequestContext* context, ResourceHandler* next_handler) { if (!context || !context->prerender_manager()) return NULL; if (request.load_flags() & net::LOAD_PRERENDER) { RecordFinalStatus(FINAL_STATUS_NESTED); return NULL; } if (!(request.load_flags() & net::LOAD_PREFETCH)) return NULL; if (!ShouldPrerenderURL(request.url())) return NULL; if (request.method() != "GET") return NULL; return new PrerenderResourceHandler(request, next_handler, context->prerender_manager()); } PrerenderResourceHandler::PrerenderResourceHandler( const net::URLRequest& request, ResourceHandler* next_handler, PrerenderManager* prerender_manager) : next_handler_(next_handler), prerender_manager_(prerender_manager), ALLOW_THIS_IN_INITIALIZER_LIST( prerender_callback_(NewCallback( this, &PrerenderResourceHandler::StartPrerender))), request_(request) { DCHECK(next_handler); DCHECK(prerender_manager); } PrerenderResourceHandler::PrerenderResourceHandler( const net::URLRequest& request, ResourceHandler* next_handler, PrerenderCallback* callback) : next_handler_(next_handler), prerender_callback_(callback), request_(request) { DCHECK(next_handler); DCHECK(callback); } PrerenderResourceHandler::~PrerenderResourceHandler() { } bool PrerenderResourceHandler::OnUploadProgress(int request_id, uint64 position, uint64 size) { return next_handler_->OnUploadProgress(request_id, position, size); } bool PrerenderResourceHandler::OnRequestRedirected(int request_id, const GURL& url, ResourceResponse* response, bool* defer) { bool will_redirect = next_handler_->OnRequestRedirected( request_id, url, response, defer); if (will_redirect) { if (!ShouldPrerenderURL(url)) return false; alias_urls_.push_back(url); url_ = url; } return will_redirect; } bool PrerenderResourceHandler::OnResponseStarted(int request_id, ResourceResponse* response) { if (ShouldPrerender(response)) { DCHECK(ValidateAliasURLs(alias_urls_)); BrowserThread::PostTask( BrowserThread::UI, FROM_HERE, NewRunnableMethod( this, &PrerenderResourceHandler::RunCallbackFromUIThread, url_, alias_urls_, GURL(request_.referrer()))); } return next_handler_->OnResponseStarted(request_id, response); } bool PrerenderResourceHandler::OnWillStart(int request_id, const GURL& url, bool* defer) { bool will_start = next_handler_->OnWillStart(request_id, url, defer); if (will_start) { if (!ShouldPrerenderURL(url)) return false; alias_urls_.push_back(url); url_ = url; } return will_start; } bool PrerenderResourceHandler::OnWillRead(int request_id, net::IOBuffer** buf, int* buf_size, int min_size) { return next_handler_->OnWillRead(request_id, buf, buf_size, min_size); } bool PrerenderResourceHandler::OnReadCompleted(int request_id, int* bytes_read) { return next_handler_->OnReadCompleted(request_id, bytes_read); } bool PrerenderResourceHandler::OnResponseCompleted( int request_id, const net::URLRequestStatus& status, const std::string& security_info) { return next_handler_->OnResponseCompleted(request_id, status, security_info); } void PrerenderResourceHandler::OnRequestClosed() { next_handler_->OnRequestClosed(); } void PrerenderResourceHandler::RunCallbackFromUIThread( const GURL& url, const std::vector<GURL>& alias_urls, const GURL& referrer) { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); prerender_callback_->Run(url, alias_urls, referrer); } void PrerenderResourceHandler::StartPrerender( const GURL& url, const std::vector<GURL>& alias_urls, const GURL& referrer) { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); prerender_manager_->AddPreload(url, alias_urls, referrer); } } // namespace prerender <commit_msg>Move FINAL_STATUS_NESTED later so it is not counted too heavily.<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/prerender/prerender_resource_handler.h" #include "chrome/browser/net/chrome_url_request_context.h" #include "content/common/resource_response.h" #include "net/base/load_flags.h" #include "net/http/http_response_headers.h" #include "net/url_request/url_request.h" namespace prerender { namespace { bool ShouldPrerenderURL(const GURL& url) { if (!url.is_valid()) return false; if (!url.SchemeIs("http")) { RecordFinalStatus(FINAL_STATUS_HTTPS); return false; } return true; } bool ValidateAliasURLs(const std::vector<GURL>& urls) { for (std::vector<GURL>::const_iterator it = urls.begin(); it != urls.end(); ++it) { if (!ShouldPrerenderURL(*it)) return false; } return true; } bool ShouldPrerender(const ResourceResponse* response) { if (!response) return false; const ResourceResponseHead& rrh = response->response_head; if (!rrh.headers) return false; if (rrh.mime_type != "text/html") return false; if (rrh.headers->response_code() != 200) return false; return true; } } // namespace PrerenderResourceHandler* PrerenderResourceHandler::MaybeCreate( const net::URLRequest& request, ChromeURLRequestContext* context, ResourceHandler* next_handler) { if (!context || !context->prerender_manager()) return NULL; if (!(request.load_flags() & net::LOAD_PREFETCH)) return NULL; if (!ShouldPrerenderURL(request.url())) return NULL; if (request.method() != "GET") return NULL; if (request.load_flags() & net::LOAD_PRERENDER) { RecordFinalStatus(FINAL_STATUS_NESTED); return NULL; } return new PrerenderResourceHandler(request, next_handler, context->prerender_manager()); } PrerenderResourceHandler::PrerenderResourceHandler( const net::URLRequest& request, ResourceHandler* next_handler, PrerenderManager* prerender_manager) : next_handler_(next_handler), prerender_manager_(prerender_manager), ALLOW_THIS_IN_INITIALIZER_LIST( prerender_callback_(NewCallback( this, &PrerenderResourceHandler::StartPrerender))), request_(request) { DCHECK(next_handler); DCHECK(prerender_manager); } PrerenderResourceHandler::PrerenderResourceHandler( const net::URLRequest& request, ResourceHandler* next_handler, PrerenderCallback* callback) : next_handler_(next_handler), prerender_callback_(callback), request_(request) { DCHECK(next_handler); DCHECK(callback); } PrerenderResourceHandler::~PrerenderResourceHandler() { } bool PrerenderResourceHandler::OnUploadProgress(int request_id, uint64 position, uint64 size) { return next_handler_->OnUploadProgress(request_id, position, size); } bool PrerenderResourceHandler::OnRequestRedirected(int request_id, const GURL& url, ResourceResponse* response, bool* defer) { bool will_redirect = next_handler_->OnRequestRedirected( request_id, url, response, defer); if (will_redirect) { if (!ShouldPrerenderURL(url)) return false; alias_urls_.push_back(url); url_ = url; } return will_redirect; } bool PrerenderResourceHandler::OnResponseStarted(int request_id, ResourceResponse* response) { if (ShouldPrerender(response)) { DCHECK(ValidateAliasURLs(alias_urls_)); BrowserThread::PostTask( BrowserThread::UI, FROM_HERE, NewRunnableMethod( this, &PrerenderResourceHandler::RunCallbackFromUIThread, url_, alias_urls_, GURL(request_.referrer()))); } return next_handler_->OnResponseStarted(request_id, response); } bool PrerenderResourceHandler::OnWillStart(int request_id, const GURL& url, bool* defer) { bool will_start = next_handler_->OnWillStart(request_id, url, defer); if (will_start) { if (!ShouldPrerenderURL(url)) return false; alias_urls_.push_back(url); url_ = url; } return will_start; } bool PrerenderResourceHandler::OnWillRead(int request_id, net::IOBuffer** buf, int* buf_size, int min_size) { return next_handler_->OnWillRead(request_id, buf, buf_size, min_size); } bool PrerenderResourceHandler::OnReadCompleted(int request_id, int* bytes_read) { return next_handler_->OnReadCompleted(request_id, bytes_read); } bool PrerenderResourceHandler::OnResponseCompleted( int request_id, const net::URLRequestStatus& status, const std::string& security_info) { return next_handler_->OnResponseCompleted(request_id, status, security_info); } void PrerenderResourceHandler::OnRequestClosed() { next_handler_->OnRequestClosed(); } void PrerenderResourceHandler::RunCallbackFromUIThread( const GURL& url, const std::vector<GURL>& alias_urls, const GURL& referrer) { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); prerender_callback_->Run(url, alias_urls, referrer); } void PrerenderResourceHandler::StartPrerender( const GURL& url, const std::vector<GURL>& alias_urls, const GURL& referrer) { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); prerender_manager_->AddPreload(url, alias_urls, referrer); } } // namespace prerender <|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 "base/file_path.h" #include "chrome/browser/browser_list.h" #include "chrome/browser/defaults.h" #include "chrome/browser/profiles/profile.h" #include "chrome/browser/sessions/tab_restore_service.h" #include "chrome/browser/tabs/tab_strip_model.h" #include "chrome/browser/ui/browser.h" #include "chrome/browser/ui/browser_list.h" #include "chrome/browser/ui/browser_window.h" #include "chrome/test/in_process_browser_test.h" #include "chrome/test/ui_test_utils.h" #include "content/browser/tab_contents/tab_contents.h" #include "content/common/page_transition_types.h" namespace { // BrowserList::Observer implementation that waits for a browser to be // removed. class BrowserListObserverImpl : public BrowserList::Observer { public: BrowserListObserverImpl() : did_remove_(false), running_(false) { BrowserList::AddObserver(this); } ~BrowserListObserverImpl() { BrowserList::RemoveObserver(this); } // Returns when a browser has been removed. void Run() { running_ = true; if (!did_remove_) ui_test_utils::RunMessageLoop(); } // BrowserList::Observer virtual void OnBrowserAdded(const Browser* browser) OVERRIDE { } virtual void OnBrowserRemoved(const Browser* browser) OVERRIDE { did_remove_ = true; if (running_) MessageLoop::current()->Quit(); } private: // Was OnBrowserRemoved invoked? bool did_remove_; // Was Run invoked? bool running_; DISALLOW_COPY_AND_ASSIGN(BrowserListObserverImpl); }; } // namespace typedef InProcessBrowserTest SessionRestoreTest; #if defined(OS_LINUX) && defined(TOOLKIT_VIEWS) // Crashes on Linux Views: http://crbug.com/39476 #define MAYBE_RestoreOnNewWindowWithNoTabbedBrowsers \ DISABLED_RestoreOnNewWindowWithNoTabbedBrowsers #else #define MAYBE_RestoreOnNewWindowWithNoTabbedBrowsers \ RestoreOnNewWindowWithNoTabbedBrowsers #endif // Makes sure when session restore is triggered in the same process we don't end // up with an extra tab. IN_PROC_BROWSER_TEST_F(SessionRestoreTest, MAYBE_RestoreOnNewWindowWithNoTabbedBrowsers) { if (browser_defaults::kRestorePopups) return; const FilePath::CharType* kTitle1File = FILE_PATH_LITERAL("title1.html"); GURL url(ui_test_utils::GetTestUrl(FilePath(FilePath::kCurrentDirectory), FilePath(kTitle1File))); ui_test_utils::NavigateToURL(browser(), url); // Turn on session restore. SessionStartupPref::SetStartupPref( browser()->profile(), SessionStartupPref(SessionStartupPref::LAST)); // Create a new popup. Profile* profile = browser()->profile(); Browser* popup = Browser::CreateForType(Browser::TYPE_POPUP, profile); popup->window()->Show(); // Close the browser. browser()->window()->Close(); // Create a new window, which should trigger session restore. popup->NewWindow(); Browser* new_browser = ui_test_utils::WaitForNewBrowser(); ASSERT_TRUE(new_browser != NULL); // The browser should only have one tab. ASSERT_EQ(1, new_browser->tab_count()); // And the first url should be url. EXPECT_EQ(url, new_browser->GetTabContentsAt(0)->GetURL()); } IN_PROC_BROWSER_TEST_F(SessionRestoreTest, RestoreIndividualTabFromWindow) { GURL url1(ui_test_utils::GetTestUrl( FilePath(FilePath::kCurrentDirectory), FilePath(FILE_PATH_LITERAL("title1.html")))); GURL url2(ui_test_utils::GetTestUrl( FilePath(FilePath::kCurrentDirectory), FilePath(FILE_PATH_LITERAL("title2.html")))); GURL url3(ui_test_utils::GetTestUrl( FilePath(FilePath::kCurrentDirectory), FilePath(FILE_PATH_LITERAL("title3.html")))); // Add and navigate three tabs. ui_test_utils::NavigateToURL(browser(), url1); browser()->AddSelectedTabWithURL(url2, PageTransition::LINK); ui_test_utils::WaitForNavigationInCurrentTab(browser()); browser()->AddSelectedTabWithURL(url3, PageTransition::LINK); ui_test_utils::WaitForNavigationInCurrentTab(browser()); TabRestoreService* service = browser()->profile()->GetTabRestoreService(); service->ClearEntries(); browser()->window()->Close(); // Expect a window with three tabs. EXPECT_EQ(1U, service->entries().size()); ASSERT_EQ(TabRestoreService::WINDOW, service->entries().front()->type); const TabRestoreService::Window* window = static_cast<TabRestoreService::Window*>(service->entries().front()); EXPECT_EQ(3U, window->tabs.size()); // Find the SessionID for entry2. Since the session service was destroyed, // there is no guarantee that the SessionID for the tab has remained the same. std::vector<TabRestoreService::Tab>::const_iterator it = window->tabs.begin(); for ( ; it != window->tabs.end(); ++it) { const TabRestoreService::Tab& tab = *it; // If this tab held url2, then restore this single tab. if (tab.navigations[0].virtual_url() == url2) { service->RestoreEntryById(NULL, tab.id, false); break; } } // Make sure that the Window got updated. EXPECT_EQ(1U, service->entries().size()); ASSERT_EQ(TabRestoreService::WINDOW, service->entries().front()->type); window = static_cast<TabRestoreService::Window*>(service->entries().front()); EXPECT_EQ(2U, window->tabs.size()); } IN_PROC_BROWSER_TEST_F(SessionRestoreTest, WindowWithOneTab) { GURL url(ui_test_utils::GetTestUrl( FilePath(FilePath::kCurrentDirectory), FilePath(FILE_PATH_LITERAL("title1.html")))); // Add a single tab. ui_test_utils::NavigateToURL(browser(), url); TabRestoreService* service = browser()->profile()->GetTabRestoreService(); service->ClearEntries(); EXPECT_EQ(0U, service->entries().size()); // Close the window. browser()->window()->Close(); // Expect the window to be converted to a tab by the TRS. EXPECT_EQ(1U, service->entries().size()); ASSERT_EQ(TabRestoreService::TAB, service->entries().front()->type); const TabRestoreService::Tab* tab = static_cast<TabRestoreService::Tab*>(service->entries().front()); // Restore the tab. service->RestoreEntryById(NULL, tab->id, false); // Make sure the restore was successful. EXPECT_EQ(0U, service->entries().size()); } // Verifies we remember the last browser window when closing the last // non-incognito window while an incognito window is open. IN_PROC_BROWSER_TEST_F(SessionRestoreTest, IncognitotoNonIncognito) { // Turn on session restore. SessionStartupPref pref(SessionStartupPref::LAST); SessionStartupPref::SetStartupPref(browser()->profile(), pref); GURL url(ui_test_utils::GetTestUrl( FilePath(FilePath::kCurrentDirectory), FilePath(FILE_PATH_LITERAL("title1.html")))); // Add a single tab. ui_test_utils::NavigateToURL(browser(), url); // Create a new incognito window. Browser* incognito_browser = CreateIncognitoBrowser(); incognito_browser->AddBlankTab(true); incognito_browser->window()->Show(); // Close the normal browser. After this we only have the incognito window // open. We wait until the window closes as window closing is async. { BrowserListObserverImpl observer; browser()->window()->Close(); observer.Run(); } // Create a new window, which should trigger session restore. incognito_browser->NewWindow(); // The first tab should have 'url' as its url. Browser* new_browser = ui_test_utils::WaitForNewBrowser(); ASSERT_TRUE(new_browser); EXPECT_EQ(url, new_browser->GetTabContentsAt(0)->GetURL()); } <commit_msg>Fix header include for reals.<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 "base/file_path.h" #include "chrome/browser/defaults.h" #include "chrome/browser/profiles/profile.h" #include "chrome/browser/sessions/tab_restore_service.h" #include "chrome/browser/tabs/tab_strip_model.h" #include "chrome/browser/ui/browser.h" #include "chrome/browser/ui/browser_list.h" #include "chrome/browser/ui/browser_window.h" #include "chrome/test/in_process_browser_test.h" #include "chrome/test/ui_test_utils.h" #include "content/browser/tab_contents/tab_contents.h" #include "content/common/page_transition_types.h" namespace { // BrowserList::Observer implementation that waits for a browser to be // removed. class BrowserListObserverImpl : public BrowserList::Observer { public: BrowserListObserverImpl() : did_remove_(false), running_(false) { BrowserList::AddObserver(this); } ~BrowserListObserverImpl() { BrowserList::RemoveObserver(this); } // Returns when a browser has been removed. void Run() { running_ = true; if (!did_remove_) ui_test_utils::RunMessageLoop(); } // BrowserList::Observer virtual void OnBrowserAdded(const Browser* browser) OVERRIDE { } virtual void OnBrowserRemoved(const Browser* browser) OVERRIDE { did_remove_ = true; if (running_) MessageLoop::current()->Quit(); } private: // Was OnBrowserRemoved invoked? bool did_remove_; // Was Run invoked? bool running_; DISALLOW_COPY_AND_ASSIGN(BrowserListObserverImpl); }; } // namespace typedef InProcessBrowserTest SessionRestoreTest; #if defined(OS_LINUX) && defined(TOOLKIT_VIEWS) // Crashes on Linux Views: http://crbug.com/39476 #define MAYBE_RestoreOnNewWindowWithNoTabbedBrowsers \ DISABLED_RestoreOnNewWindowWithNoTabbedBrowsers #else #define MAYBE_RestoreOnNewWindowWithNoTabbedBrowsers \ RestoreOnNewWindowWithNoTabbedBrowsers #endif // Makes sure when session restore is triggered in the same process we don't end // up with an extra tab. IN_PROC_BROWSER_TEST_F(SessionRestoreTest, MAYBE_RestoreOnNewWindowWithNoTabbedBrowsers) { if (browser_defaults::kRestorePopups) return; const FilePath::CharType* kTitle1File = FILE_PATH_LITERAL("title1.html"); GURL url(ui_test_utils::GetTestUrl(FilePath(FilePath::kCurrentDirectory), FilePath(kTitle1File))); ui_test_utils::NavigateToURL(browser(), url); // Turn on session restore. SessionStartupPref::SetStartupPref( browser()->profile(), SessionStartupPref(SessionStartupPref::LAST)); // Create a new popup. Profile* profile = browser()->profile(); Browser* popup = Browser::CreateForType(Browser::TYPE_POPUP, profile); popup->window()->Show(); // Close the browser. browser()->window()->Close(); // Create a new window, which should trigger session restore. popup->NewWindow(); Browser* new_browser = ui_test_utils::WaitForNewBrowser(); ASSERT_TRUE(new_browser != NULL); // The browser should only have one tab. ASSERT_EQ(1, new_browser->tab_count()); // And the first url should be url. EXPECT_EQ(url, new_browser->GetTabContentsAt(0)->GetURL()); } IN_PROC_BROWSER_TEST_F(SessionRestoreTest, RestoreIndividualTabFromWindow) { GURL url1(ui_test_utils::GetTestUrl( FilePath(FilePath::kCurrentDirectory), FilePath(FILE_PATH_LITERAL("title1.html")))); GURL url2(ui_test_utils::GetTestUrl( FilePath(FilePath::kCurrentDirectory), FilePath(FILE_PATH_LITERAL("title2.html")))); GURL url3(ui_test_utils::GetTestUrl( FilePath(FilePath::kCurrentDirectory), FilePath(FILE_PATH_LITERAL("title3.html")))); // Add and navigate three tabs. ui_test_utils::NavigateToURL(browser(), url1); browser()->AddSelectedTabWithURL(url2, PageTransition::LINK); ui_test_utils::WaitForNavigationInCurrentTab(browser()); browser()->AddSelectedTabWithURL(url3, PageTransition::LINK); ui_test_utils::WaitForNavigationInCurrentTab(browser()); TabRestoreService* service = browser()->profile()->GetTabRestoreService(); service->ClearEntries(); browser()->window()->Close(); // Expect a window with three tabs. EXPECT_EQ(1U, service->entries().size()); ASSERT_EQ(TabRestoreService::WINDOW, service->entries().front()->type); const TabRestoreService::Window* window = static_cast<TabRestoreService::Window*>(service->entries().front()); EXPECT_EQ(3U, window->tabs.size()); // Find the SessionID for entry2. Since the session service was destroyed, // there is no guarantee that the SessionID for the tab has remained the same. std::vector<TabRestoreService::Tab>::const_iterator it = window->tabs.begin(); for ( ; it != window->tabs.end(); ++it) { const TabRestoreService::Tab& tab = *it; // If this tab held url2, then restore this single tab. if (tab.navigations[0].virtual_url() == url2) { service->RestoreEntryById(NULL, tab.id, false); break; } } // Make sure that the Window got updated. EXPECT_EQ(1U, service->entries().size()); ASSERT_EQ(TabRestoreService::WINDOW, service->entries().front()->type); window = static_cast<TabRestoreService::Window*>(service->entries().front()); EXPECT_EQ(2U, window->tabs.size()); } IN_PROC_BROWSER_TEST_F(SessionRestoreTest, WindowWithOneTab) { GURL url(ui_test_utils::GetTestUrl( FilePath(FilePath::kCurrentDirectory), FilePath(FILE_PATH_LITERAL("title1.html")))); // Add a single tab. ui_test_utils::NavigateToURL(browser(), url); TabRestoreService* service = browser()->profile()->GetTabRestoreService(); service->ClearEntries(); EXPECT_EQ(0U, service->entries().size()); // Close the window. browser()->window()->Close(); // Expect the window to be converted to a tab by the TRS. EXPECT_EQ(1U, service->entries().size()); ASSERT_EQ(TabRestoreService::TAB, service->entries().front()->type); const TabRestoreService::Tab* tab = static_cast<TabRestoreService::Tab*>(service->entries().front()); // Restore the tab. service->RestoreEntryById(NULL, tab->id, false); // Make sure the restore was successful. EXPECT_EQ(0U, service->entries().size()); } // Verifies we remember the last browser window when closing the last // non-incognito window while an incognito window is open. IN_PROC_BROWSER_TEST_F(SessionRestoreTest, IncognitotoNonIncognito) { // Turn on session restore. SessionStartupPref pref(SessionStartupPref::LAST); SessionStartupPref::SetStartupPref(browser()->profile(), pref); GURL url(ui_test_utils::GetTestUrl( FilePath(FilePath::kCurrentDirectory), FilePath(FILE_PATH_LITERAL("title1.html")))); // Add a single tab. ui_test_utils::NavigateToURL(browser(), url); // Create a new incognito window. Browser* incognito_browser = CreateIncognitoBrowser(); incognito_browser->AddBlankTab(true); incognito_browser->window()->Show(); // Close the normal browser. After this we only have the incognito window // open. We wait until the window closes as window closing is async. { BrowserListObserverImpl observer; browser()->window()->Close(); observer.Run(); } // Create a new window, which should trigger session restore. incognito_browser->NewWindow(); // The first tab should have 'url' as its url. Browser* new_browser = ui_test_utils::WaitForNewBrowser(); ASSERT_TRUE(new_browser); EXPECT_EQ(url, new_browser->GetTabContentsAt(0)->GetURL()); } <|endoftext|>
<commit_before>// Copyright (c) 2010 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/tab_contents/tab_contents_ssl_helper.h" #include "app/l10n_util.h" #include "app/resource_bundle.h" #include "base/basictypes.h" #include "base/string_number_conversions.h" #include "base/utf_string_conversions.h" #include "chrome/browser/certificate_viewer.h" #include "chrome/browser/ssl/ssl_add_cert_handler.h" #include "chrome/browser/ssl/ssl_client_auth_handler.h" #include "chrome/browser/ssl_client_certificate_selector.h" #include "chrome/browser/tab_contents/infobar_delegate.h" #include "chrome/browser/tab_contents/tab_contents.h" #include "chrome/common/notification_service.h" #include "grit/generated_resources.h" #include "grit/theme_resources.h" #include "net/base/net_errors.h" namespace { SkBitmap* GetCertIcon() { // TODO(davidben): use a more appropriate icon. return ResourceBundle::GetSharedInstance().GetBitmapNamed( IDR_INFOBAR_SAVE_PASSWORD); } class SSLCertAddedInfoBarDelegate : public ConfirmInfoBarDelegate { public: SSLCertAddedInfoBarDelegate(TabContents* tab_contents, net::X509Certificate* cert) : ConfirmInfoBarDelegate(tab_contents), tab_contents_(tab_contents), cert_(cert) { } virtual ~SSLCertAddedInfoBarDelegate() { } // Overridden from ConfirmInfoBarDelegate: virtual string16 GetMessageText() const { // TODO(evanm): GetDisplayName should return UTF-16. return l10n_util::GetStringFUTF16( IDS_ADD_CERT_SUCCESS_INFOBAR_LABEL, UTF8ToUTF16(cert_->issuer().GetDisplayName())); } virtual SkBitmap* GetIcon() const { return GetCertIcon(); } virtual int GetButtons() const { return BUTTON_OK; } virtual string16 GetButtonLabel(InfoBarButton button) const { switch (button) { case BUTTON_OK: return l10n_util::GetStringUTF16(IDS_ADD_CERT_SUCCESS_INFOBAR_BUTTON); default: return string16(); } } virtual Type GetInfoBarType() { return PAGE_ACTION_TYPE; } virtual bool Accept() { ShowCertificateViewer(tab_contents_->GetMessageBoxRootWindow(), cert_); return false; // Hiding the infobar just as the dialog opens looks weird. } virtual void InfoBarClosed() { // ConfirmInfoBarDelegate doesn't delete itself. delete this; } private: // The TabContents we are attached to TabContents* tab_contents_; // The cert we added. scoped_refptr<net::X509Certificate> cert_; }; } // namespace class TabContentsSSLHelper::SSLAddCertData : public NotificationObserver { public: SSLAddCertData(TabContents* tab, SSLAddCertHandler* handler) : tab_(tab), handler_(handler), infobar_delegate_(NULL) { // Listen for disappearing InfoBars. Source<TabContents> tc_source(tab_); registrar_.Add(this, NotificationType::TAB_CONTENTS_INFOBAR_REMOVED, tc_source); registrar_.Add(this, NotificationType::TAB_CONTENTS_INFOBAR_REPLACED, tc_source); } ~SSLAddCertData() {} // Displays |delegate| as an infobar in |tab_|, replacing our current one if // still active. void ShowInfoBar(InfoBarDelegate* delegate) { if (infobar_delegate_) { tab_->ReplaceInfoBar(infobar_delegate_, delegate); } else { tab_->AddInfoBar(delegate); } infobar_delegate_ = delegate; } void ShowErrorInfoBar(const std::wstring& message) { ShowInfoBar( new SimpleAlertInfoBarDelegate(tab_, WideToUTF16(message), GetCertIcon(), true)); } // NotificationObserver implementation. virtual void Observe(NotificationType type, const NotificationSource& source, const NotificationDetails& details) { switch (type.value) { case NotificationType::TAB_CONTENTS_INFOBAR_REMOVED: InfoBarClosed(Details<InfoBarDelegate>(details).ptr()); break; case NotificationType::TAB_CONTENTS_INFOBAR_REPLACED: typedef std::pair<InfoBarDelegate*, InfoBarDelegate*> InfoBarDelegatePair; InfoBarClosed(Details<InfoBarDelegatePair>(details).ptr()->first); break; default: NOTREACHED(); break; } } private: void InfoBarClosed(InfoBarDelegate* delegate) { if (infobar_delegate_ == delegate) infobar_delegate_ = NULL; } // The TabContents we are attached to. TabContents* tab_; // The handler we call back to. scoped_refptr<SSLAddCertHandler> handler_; // The current InfoBarDelegate we're displaying. InfoBarDelegate* infobar_delegate_; NotificationRegistrar registrar_; DISALLOW_COPY_AND_ASSIGN(SSLAddCertData); }; TabContentsSSLHelper::TabContentsSSLHelper(TabContents* tab_contents) : tab_contents_(tab_contents) { } TabContentsSSLHelper::~TabContentsSSLHelper() { } void TabContentsSSLHelper::ShowClientCertificateRequestDialog( scoped_refptr<SSLClientAuthHandler> handler) { browser::ShowSSLClientCertificateSelector( tab_contents_, handler->cert_request_info(), handler); } void TabContentsSSLHelper::OnVerifyClientCertificateError( scoped_refptr<SSLAddCertHandler> handler, int error_code) { SSLAddCertData* add_cert_data = GetAddCertData(handler); // Display an infobar with the error message. // TODO(davidben): Display a more user-friendly error string. add_cert_data->ShowErrorInfoBar( l10n_util::GetStringF(IDS_ADD_CERT_ERR_INVALID_CERT, UTF8ToWide(base::IntToString(-error_code)), ASCIIToWide(net::ErrorToString(error_code)))); } void TabContentsSSLHelper::AskToAddClientCertificate( scoped_refptr<SSLAddCertHandler> handler) { NOTREACHED(); // Not implemented yet. } void TabContentsSSLHelper::OnAddClientCertificateSuccess( scoped_refptr<SSLAddCertHandler> handler) { SSLAddCertData* add_cert_data = GetAddCertData(handler); // Display an infobar to inform the user. add_cert_data->ShowInfoBar( new SSLCertAddedInfoBarDelegate(tab_contents_, handler->cert())); } void TabContentsSSLHelper::OnAddClientCertificateError( scoped_refptr<SSLAddCertHandler> handler, int error_code) { SSLAddCertData* add_cert_data = GetAddCertData(handler); // Display an infobar with the error message. // TODO(davidben): Display a more user-friendly error string. add_cert_data->ShowErrorInfoBar( l10n_util::GetStringF(IDS_ADD_CERT_ERR_FAILED, UTF8ToWide(base::IntToString(-error_code)), ASCIIToWide(net::ErrorToString(error_code)))); } void TabContentsSSLHelper::OnAddClientCertificateFinished( scoped_refptr<SSLAddCertHandler> handler) { // Clean up. request_id_to_add_cert_data_.erase(handler->network_request_id()); } TabContentsSSLHelper::SSLAddCertData* TabContentsSSLHelper::GetAddCertData( SSLAddCertHandler* handler) { // Find/create the slot. linked_ptr<SSLAddCertData>& ptr_ref = request_id_to_add_cert_data_[handler->network_request_id()]; // Fill it if necessary. if (!ptr_ref.get()) ptr_ref.reset(new SSLAddCertData(tab_contents_, handler)); return ptr_ref.get(); } <commit_msg>Rmeove another wstring from infobar code.<commit_after>// Copyright (c) 2010 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/tab_contents/tab_contents_ssl_helper.h" #include "app/l10n_util.h" #include "app/resource_bundle.h" #include "base/basictypes.h" #include "base/string_number_conversions.h" #include "base/utf_string_conversions.h" #include "chrome/browser/certificate_viewer.h" #include "chrome/browser/ssl/ssl_add_cert_handler.h" #include "chrome/browser/ssl/ssl_client_auth_handler.h" #include "chrome/browser/ssl_client_certificate_selector.h" #include "chrome/browser/tab_contents/infobar_delegate.h" #include "chrome/browser/tab_contents/tab_contents.h" #include "chrome/common/notification_service.h" #include "grit/generated_resources.h" #include "grit/theme_resources.h" #include "net/base/net_errors.h" namespace { SkBitmap* GetCertIcon() { // TODO(davidben): use a more appropriate icon. return ResourceBundle::GetSharedInstance().GetBitmapNamed( IDR_INFOBAR_SAVE_PASSWORD); } class SSLCertAddedInfoBarDelegate : public ConfirmInfoBarDelegate { public: SSLCertAddedInfoBarDelegate(TabContents* tab_contents, net::X509Certificate* cert) : ConfirmInfoBarDelegate(tab_contents), tab_contents_(tab_contents), cert_(cert) { } virtual ~SSLCertAddedInfoBarDelegate() { } // Overridden from ConfirmInfoBarDelegate: virtual string16 GetMessageText() const { // TODO(evanm): GetDisplayName should return UTF-16. return l10n_util::GetStringFUTF16( IDS_ADD_CERT_SUCCESS_INFOBAR_LABEL, UTF8ToUTF16(cert_->issuer().GetDisplayName())); } virtual SkBitmap* GetIcon() const { return GetCertIcon(); } virtual int GetButtons() const { return BUTTON_OK; } virtual string16 GetButtonLabel(InfoBarButton button) const { switch (button) { case BUTTON_OK: return l10n_util::GetStringUTF16(IDS_ADD_CERT_SUCCESS_INFOBAR_BUTTON); default: return string16(); } } virtual Type GetInfoBarType() { return PAGE_ACTION_TYPE; } virtual bool Accept() { ShowCertificateViewer(tab_contents_->GetMessageBoxRootWindow(), cert_); return false; // Hiding the infobar just as the dialog opens looks weird. } virtual void InfoBarClosed() { // ConfirmInfoBarDelegate doesn't delete itself. delete this; } private: // The TabContents we are attached to TabContents* tab_contents_; // The cert we added. scoped_refptr<net::X509Certificate> cert_; }; } // namespace class TabContentsSSLHelper::SSLAddCertData : public NotificationObserver { public: SSLAddCertData(TabContents* tab, SSLAddCertHandler* handler) : tab_(tab), handler_(handler), infobar_delegate_(NULL) { // Listen for disappearing InfoBars. Source<TabContents> tc_source(tab_); registrar_.Add(this, NotificationType::TAB_CONTENTS_INFOBAR_REMOVED, tc_source); registrar_.Add(this, NotificationType::TAB_CONTENTS_INFOBAR_REPLACED, tc_source); } ~SSLAddCertData() {} // Displays |delegate| as an infobar in |tab_|, replacing our current one if // still active. void ShowInfoBar(InfoBarDelegate* delegate) { if (infobar_delegate_) { tab_->ReplaceInfoBar(infobar_delegate_, delegate); } else { tab_->AddInfoBar(delegate); } infobar_delegate_ = delegate; } void ShowErrorInfoBar(const string16& message) { ShowInfoBar( new SimpleAlertInfoBarDelegate(tab_, message, GetCertIcon(), true)); } // NotificationObserver implementation. virtual void Observe(NotificationType type, const NotificationSource& source, const NotificationDetails& details) { switch (type.value) { case NotificationType::TAB_CONTENTS_INFOBAR_REMOVED: InfoBarClosed(Details<InfoBarDelegate>(details).ptr()); break; case NotificationType::TAB_CONTENTS_INFOBAR_REPLACED: typedef std::pair<InfoBarDelegate*, InfoBarDelegate*> InfoBarDelegatePair; InfoBarClosed(Details<InfoBarDelegatePair>(details).ptr()->first); break; default: NOTREACHED(); break; } } private: void InfoBarClosed(InfoBarDelegate* delegate) { if (infobar_delegate_ == delegate) infobar_delegate_ = NULL; } // The TabContents we are attached to. TabContents* tab_; // The handler we call back to. scoped_refptr<SSLAddCertHandler> handler_; // The current InfoBarDelegate we're displaying. InfoBarDelegate* infobar_delegate_; NotificationRegistrar registrar_; DISALLOW_COPY_AND_ASSIGN(SSLAddCertData); }; TabContentsSSLHelper::TabContentsSSLHelper(TabContents* tab_contents) : tab_contents_(tab_contents) { } TabContentsSSLHelper::~TabContentsSSLHelper() { } void TabContentsSSLHelper::ShowClientCertificateRequestDialog( scoped_refptr<SSLClientAuthHandler> handler) { browser::ShowSSLClientCertificateSelector( tab_contents_, handler->cert_request_info(), handler); } void TabContentsSSLHelper::OnVerifyClientCertificateError( scoped_refptr<SSLAddCertHandler> handler, int error_code) { SSLAddCertData* add_cert_data = GetAddCertData(handler); // Display an infobar with the error message. // TODO(davidben): Display a more user-friendly error string. add_cert_data->ShowErrorInfoBar( l10n_util::GetStringFUTF16(IDS_ADD_CERT_ERR_INVALID_CERT, base::IntToString16(-error_code), ASCIIToUTF16(net::ErrorToString(error_code)))); } void TabContentsSSLHelper::AskToAddClientCertificate( scoped_refptr<SSLAddCertHandler> handler) { NOTREACHED(); // Not implemented yet. } void TabContentsSSLHelper::OnAddClientCertificateSuccess( scoped_refptr<SSLAddCertHandler> handler) { SSLAddCertData* add_cert_data = GetAddCertData(handler); // Display an infobar to inform the user. add_cert_data->ShowInfoBar( new SSLCertAddedInfoBarDelegate(tab_contents_, handler->cert())); } void TabContentsSSLHelper::OnAddClientCertificateError( scoped_refptr<SSLAddCertHandler> handler, int error_code) { SSLAddCertData* add_cert_data = GetAddCertData(handler); // Display an infobar with the error message. // TODO(davidben): Display a more user-friendly error string. add_cert_data->ShowErrorInfoBar( l10n_util::GetStringFUTF16(IDS_ADD_CERT_ERR_FAILED, base::IntToString16(-error_code), ASCIIToUTF16(net::ErrorToString(error_code)))); } void TabContentsSSLHelper::OnAddClientCertificateFinished( scoped_refptr<SSLAddCertHandler> handler) { // Clean up. request_id_to_add_cert_data_.erase(handler->network_request_id()); } TabContentsSSLHelper::SSLAddCertData* TabContentsSSLHelper::GetAddCertData( SSLAddCertHandler* handler) { // Find/create the slot. linked_ptr<SSLAddCertData>& ptr_ref = request_id_to_add_cert_data_[handler->network_request_id()]; // Fill it if necessary. if (!ptr_ref.get()) ptr_ref.reset(new SSLAddCertData(tab_contents_, handler)); return ptr_ref.get(); } <|endoftext|>
<commit_before>/** * This file is part of the CernVM File System. * * Fills an internal map of key-value pairs from ASCII files in key=value * style. Parameters can be overwritten. Used to read configuration from * /etc/cvmfs/... */ #include "cvmfs_config.h" #include "options.h" #include <fcntl.h> #include <sys/wait.h> #include <unistd.h> #include <cassert> #include <cstdio> #include <cstdlib> #include <utility> #include "logging.h" #include "sanitizer.h" #include "util.h" using namespace std; // NOLINT #ifdef CVMFS_NAMESPACE_GUARD namespace CVMFS_NAMESPACE_GUARD { #endif static string EscapeShell(const std::string &raw) { for (unsigned i = 0, l = raw.length(); i < l; ++i) { if (!(((raw[i] >= '0') && (raw[i] <= '9')) || ((raw[i] >= 'A') && (raw[i] <= 'Z')) || ((raw[i] >= 'a') && (raw[i] <= 'z')) || (raw[i] == '/') || (raw[i] == ':') || (raw[i] == '.') || (raw[i] == '_') || (raw[i] == '-') || (raw[i] == ','))) { goto escape_shell_quote; } } return raw; escape_shell_quote: string result = "'"; for (unsigned i = 0, l = raw.length(); i < l; ++i) { if (raw[i] == '\'') result += "\\"; result += raw[i]; } result += "'"; return result; } void SimpleOptionsParser::ParsePath(const string &config_file, const bool external __attribute__((unused))) { LogCvmfs(kLogCvmfs, kLogDebug, "Fast-parsing config file %s", config_file.c_str()); int retval; string line; FILE *fconfig = fopen(config_file.c_str(), "r"); if (fconfig == NULL) return; // Read line by line and extract parameters while (GetLineFile(fconfig, &line)) { line = Trim(line); if (line.empty() || line[0] == '#' || line.find(" ") < string::npos) continue; vector<string> tokens = SplitString(line, '='); if (tokens.size() < 2 || tokens.size() > 2) continue; ConfigValue value; value.source = config_file; value.value = tokens[1]; string parameter = tokens[0]; config_[parameter] = value; retval = setenv(parameter.c_str(), value.value.c_str(), 1); assert(retval == 0); } fclose(fconfig); } void BashOptionsManager::ParsePath(const string &config_file, const bool external) { LogCvmfs(kLogCvmfs, kLogDebug, "Parsing config file %s", config_file.c_str()); int retval; int pipe_open[2]; int pipe_quit[2]; pid_t pid_child = 0; if (external) { // cvmfs can run in the process group of automount in which case // autofs won't mount an additional config repository. We create a // short-lived process that detaches from the process group and triggers // autofs to mount the config repository, if necessary. It holds a file // handle to the config file until the main process opened the file, too. MakePipe(pipe_open); MakePipe(pipe_quit); switch (pid_child = fork()) { case -1: abort(); case 0: { // Child close(pipe_open[0]); close(pipe_quit[1]); // If this is not a process group leader, create a new session if (getpgrp() != getpid()) { pid_t new_session = setsid(); assert(new_session != (pid_t)-1); } (void)open(config_file.c_str(), O_RDONLY); char ready = 'R'; WritePipe(pipe_open[1], &ready, 1); read(pipe_quit[0], &ready, 1); _exit(0); // Don't flush shared file descriptors } } // Parent close(pipe_open[1]); close(pipe_quit[0]); char ready = 0; ReadPipe(pipe_open[0], &ready, 1); assert(ready == 'R'); close(pipe_open[0]); } const string config_path = GetParentPath(config_file); FILE *fconfig = fopen(config_file.c_str(), "r"); if (pid_child > 0) { char c = 'C'; WritePipe(pipe_quit[1], &c, 1); int statloc; waitpid(pid_child, &statloc, 0); close(pipe_quit[1]); } if (!fconfig) { if (external && !DirectoryExists(config_path)) { LogCvmfs(kLogCvmfs, kLogDebug | kLogSyslogWarn, "external location for configuration files does not exist: %s", config_path.c_str()); } return; } int fd_stdin; int fd_stdout; int fd_stderr; retval = Shell(&fd_stdin, &fd_stdout, &fd_stderr); assert(retval); // Let the shell read the file string line; const string newline = "\n"; const string cd = "cd \"" + ((config_path == "") ? "/" : config_path) + "\"" + newline; WritePipe(fd_stdin, cd.data(), cd.length()); while (GetLineFile(fconfig, &line)) { WritePipe(fd_stdin, line.data(), line.length()); WritePipe(fd_stdin, newline.data(), newline.length()); } rewind(fconfig); // Read line by line and extract parameters while (GetLineFile(fconfig, &line)) { line = Trim(line); if (line.empty() || line[0] == '#' || line.find("if ") == 0) continue; vector<string> tokens = SplitString(line, '='); if (tokens.size() < 2) continue; ConfigValue value; value.source = config_file; string parameter = tokens[0]; // Strip "readonly" if (parameter.find("readonly") == 0) { parameter = parameter.substr(8); parameter = Trim(parameter); } // Strip export if (parameter.find("export") == 0) { parameter = parameter.substr(6); parameter = Trim(parameter); } // Strip eval if (parameter.find("eval") == 0) { parameter = parameter.substr(4); parameter = Trim(parameter); } const string sh_echo = "echo $" + parameter + "\n"; WritePipe(fd_stdin, sh_echo.data(), sh_echo.length()); GetLineFd(fd_stdout, &value.value); config_[parameter] = value; retval = setenv(parameter.c_str(), value.value.c_str(), 1); assert(retval == 0); } close(fd_stderr); close(fd_stdout); close(fd_stdin); fclose(fconfig); } bool OptionsManager::HasConfigRepository(const string &fqrn, string *config_path) { string cvmfs_mount_dir; if (!GetValue("CVMFS_MOUNT_DIR", &cvmfs_mount_dir)) { LogCvmfs(kLogCvmfs, kLogDebug | kLogSyslogErr, "CVMFS_MOUNT_DIR missing"); return false; } string config_repository; if (GetValue("CVMFS_CONFIG_REPOSITORY", &config_repository)) { if (config_repository.empty() || (config_repository == fqrn)) return false; sanitizer::RepositorySanitizer repository_sanitizer; if (!repository_sanitizer.IsValid(config_repository)) { LogCvmfs(kLogCvmfs, kLogDebug | kLogSyslogErr, "invalid CVMFS_CONFIG_REPOSITORY: %s", config_repository.c_str()); return false; } *config_path = cvmfs_mount_dir + "/" + config_repository + "/etc/cvmfs/"; return true; } return false; } void OptionsManager::ParseDefault(const string &fqrn) { int retval = setenv("CVMFS_FQRN", fqrn.c_str(), 1); assert(retval == 0); ParsePath("/etc/cvmfs/default.conf", false); vector<string> dist_defaults = FindFiles("/etc/cvmfs/default.d", ".conf"); for (unsigned i = 0; i < dist_defaults.size(); ++i) { ParsePath(dist_defaults[i], false); } ParsePath("/etc/cvmfs/default.local", false); if (fqrn != "") { string domain; vector<string> tokens = SplitString(fqrn, '.'); assert(tokens.size() > 1); tokens.erase(tokens.begin()); domain = JoinStrings(tokens, "."); string external_config_path; if (HasConfigRepository(fqrn, &external_config_path)) ParsePath(external_config_path + "domain.d/" + domain + ".conf", true); ParsePath("/etc/cvmfs/domain.d/" + domain + ".conf", false); ParsePath("/etc/cvmfs/domain.d/" + domain + ".local", false); if (HasConfigRepository(fqrn, &external_config_path)) ParsePath(external_config_path + "config.d/" + fqrn + ".conf", true); ParsePath("/etc/cvmfs/config.d/" + fqrn + ".conf", false); ParsePath("/etc/cvmfs/config.d/" + fqrn + ".local", false); } } void OptionsManager::ClearConfig() { config_.clear(); } bool OptionsManager::IsDefined(const std::string &key) { map<string, ConfigValue>::const_iterator iter = config_.find(key); return iter != config_.end(); } bool OptionsManager::GetValue(const string &key, string *value) { map<string, ConfigValue>::const_iterator iter = config_.find(key); if (iter != config_.end()) { *value = iter->second.value; return true; } *value = ""; return false; } bool OptionsManager::GetSource(const string &key, string *value) { map<string, ConfigValue>::const_iterator iter = config_.find(key); if (iter != config_.end()) { *value = iter->second.source; return true; } *value = ""; return false; } bool OptionsManager::IsOn(const std::string &param_value) { const string uppercase = ToUpper(param_value); return ((uppercase == "YES") || (uppercase == "ON") || (uppercase == "1")); } vector<string> OptionsManager::GetAllKeys() { vector<string> result; for (map<string, ConfigValue>::const_iterator i = config_.begin(), iEnd = config_.end(); i != iEnd; ++i) { result.push_back(i->first); } return result; } string OptionsManager::Dump() { string result; vector<string> keys = GetAllKeys(); for (unsigned i = 0, l = keys.size(); i < l; ++i) { bool retval; string value; string source; retval = GetValue(keys[i], &value); assert(retval); retval = GetSource(keys[i], &source); assert(retval); result += keys[i] + "=" + EscapeShell(value) + " # from " + source + "\n"; } return result; } #ifdef CVMFS_NAMESPACE_GUARD } // namespace CVMFS_NAMESPACE_GUARD #endif <commit_msg>add looking for default.conf in config repo<commit_after>/** * This file is part of the CernVM File System. * * Fills an internal map of key-value pairs from ASCII files in key=value * style. Parameters can be overwritten. Used to read configuration from * /etc/cvmfs/... */ #include "cvmfs_config.h" #include "options.h" #include <fcntl.h> #include <sys/wait.h> #include <unistd.h> #include <cassert> #include <cstdio> #include <cstdlib> #include <utility> #include "logging.h" #include "sanitizer.h" #include "util.h" using namespace std; // NOLINT #ifdef CVMFS_NAMESPACE_GUARD namespace CVMFS_NAMESPACE_GUARD { #endif static string EscapeShell(const std::string &raw) { for (unsigned i = 0, l = raw.length(); i < l; ++i) { if (!(((raw[i] >= '0') && (raw[i] <= '9')) || ((raw[i] >= 'A') && (raw[i] <= 'Z')) || ((raw[i] >= 'a') && (raw[i] <= 'z')) || (raw[i] == '/') || (raw[i] == ':') || (raw[i] == '.') || (raw[i] == '_') || (raw[i] == '-') || (raw[i] == ','))) { goto escape_shell_quote; } } return raw; escape_shell_quote: string result = "'"; for (unsigned i = 0, l = raw.length(); i < l; ++i) { if (raw[i] == '\'') result += "\\"; result += raw[i]; } result += "'"; return result; } void SimpleOptionsParser::ParsePath(const string &config_file, const bool external __attribute__((unused))) { LogCvmfs(kLogCvmfs, kLogDebug, "Fast-parsing config file %s", config_file.c_str()); int retval; string line; FILE *fconfig = fopen(config_file.c_str(), "r"); if (fconfig == NULL) return; // Read line by line and extract parameters while (GetLineFile(fconfig, &line)) { line = Trim(line); if (line.empty() || line[0] == '#' || line.find(" ") < string::npos) continue; vector<string> tokens = SplitString(line, '='); if (tokens.size() < 2 || tokens.size() > 2) continue; ConfigValue value; value.source = config_file; value.value = tokens[1]; string parameter = tokens[0]; config_[parameter] = value; retval = setenv(parameter.c_str(), value.value.c_str(), 1); assert(retval == 0); } fclose(fconfig); } void BashOptionsManager::ParsePath(const string &config_file, const bool external) { LogCvmfs(kLogCvmfs, kLogDebug, "Parsing config file %s", config_file.c_str()); int retval; int pipe_open[2]; int pipe_quit[2]; pid_t pid_child = 0; if (external) { // cvmfs can run in the process group of automount in which case // autofs won't mount an additional config repository. We create a // short-lived process that detaches from the process group and triggers // autofs to mount the config repository, if necessary. It holds a file // handle to the config file until the main process opened the file, too. MakePipe(pipe_open); MakePipe(pipe_quit); switch (pid_child = fork()) { case -1: abort(); case 0: { // Child close(pipe_open[0]); close(pipe_quit[1]); // If this is not a process group leader, create a new session if (getpgrp() != getpid()) { pid_t new_session = setsid(); assert(new_session != (pid_t)-1); } (void)open(config_file.c_str(), O_RDONLY); char ready = 'R'; WritePipe(pipe_open[1], &ready, 1); read(pipe_quit[0], &ready, 1); _exit(0); // Don't flush shared file descriptors } } // Parent close(pipe_open[1]); close(pipe_quit[0]); char ready = 0; ReadPipe(pipe_open[0], &ready, 1); assert(ready == 'R'); close(pipe_open[0]); } const string config_path = GetParentPath(config_file); FILE *fconfig = fopen(config_file.c_str(), "r"); if (pid_child > 0) { char c = 'C'; WritePipe(pipe_quit[1], &c, 1); int statloc; waitpid(pid_child, &statloc, 0); close(pipe_quit[1]); } if (!fconfig) { if (external && !DirectoryExists(config_path)) { LogCvmfs(kLogCvmfs, kLogDebug | kLogSyslogWarn, "external location for configuration files does not exist: %s", config_path.c_str()); } return; } int fd_stdin; int fd_stdout; int fd_stderr; retval = Shell(&fd_stdin, &fd_stdout, &fd_stderr); assert(retval); // Let the shell read the file string line; const string newline = "\n"; const string cd = "cd \"" + ((config_path == "") ? "/" : config_path) + "\"" + newline; WritePipe(fd_stdin, cd.data(), cd.length()); while (GetLineFile(fconfig, &line)) { WritePipe(fd_stdin, line.data(), line.length()); WritePipe(fd_stdin, newline.data(), newline.length()); } rewind(fconfig); // Read line by line and extract parameters while (GetLineFile(fconfig, &line)) { line = Trim(line); if (line.empty() || line[0] == '#' || line.find("if ") == 0) continue; vector<string> tokens = SplitString(line, '='); if (tokens.size() < 2) continue; ConfigValue value; value.source = config_file; string parameter = tokens[0]; // Strip "readonly" if (parameter.find("readonly") == 0) { parameter = parameter.substr(8); parameter = Trim(parameter); } // Strip export if (parameter.find("export") == 0) { parameter = parameter.substr(6); parameter = Trim(parameter); } // Strip eval if (parameter.find("eval") == 0) { parameter = parameter.substr(4); parameter = Trim(parameter); } const string sh_echo = "echo $" + parameter + "\n"; WritePipe(fd_stdin, sh_echo.data(), sh_echo.length()); GetLineFd(fd_stdout, &value.value); config_[parameter] = value; retval = setenv(parameter.c_str(), value.value.c_str(), 1); assert(retval == 0); } close(fd_stderr); close(fd_stdout); close(fd_stdin); fclose(fconfig); } bool OptionsManager::HasConfigRepository(const string &fqrn, string *config_path) { string cvmfs_mount_dir; if (!GetValue("CVMFS_MOUNT_DIR", &cvmfs_mount_dir)) { LogCvmfs(kLogCvmfs, kLogDebug | kLogSyslogErr, "CVMFS_MOUNT_DIR missing"); return false; } string config_repository; if (GetValue("CVMFS_CONFIG_REPOSITORY", &config_repository)) { if (config_repository.empty() || (config_repository == fqrn)) return false; sanitizer::RepositorySanitizer repository_sanitizer; if (!repository_sanitizer.IsValid(config_repository)) { LogCvmfs(kLogCvmfs, kLogDebug | kLogSyslogErr, "invalid CVMFS_CONFIG_REPOSITORY: %s", config_repository.c_str()); return false; } *config_path = cvmfs_mount_dir + "/" + config_repository + "/etc/cvmfs/"; return true; } return false; } void OptionsManager::ParseDefault(const string &fqrn) { int retval = setenv("CVMFS_FQRN", fqrn.c_str(), 1); assert(retval == 0); ParsePath("/etc/cvmfs/default.conf", false); vector<string> dist_defaults = FindFiles("/etc/cvmfs/default.d", ".conf"); for (unsigned i = 0; i < dist_defaults.size(); ++i) { ParsePath(dist_defaults[i], false); } string external_config_path; if ((fqrn != "") && HasConfigRepository(fqrn, &external_config_path)) ParsePath(external_config_path + "default.conf", true); ParsePath("/etc/cvmfs/default.local", false); if (fqrn != "") { string domain; vector<string> tokens = SplitString(fqrn, '.'); assert(tokens.size() > 1); tokens.erase(tokens.begin()); domain = JoinStrings(tokens, "."); if (HasConfigRepository(fqrn, &external_config_path)) ParsePath(external_config_path + "domain.d/" + domain + ".conf", true); ParsePath("/etc/cvmfs/domain.d/" + domain + ".conf", false); ParsePath("/etc/cvmfs/domain.d/" + domain + ".local", false); if (HasConfigRepository(fqrn, &external_config_path)) ParsePath(external_config_path + "config.d/" + fqrn + ".conf", true); ParsePath("/etc/cvmfs/config.d/" + fqrn + ".conf", false); ParsePath("/etc/cvmfs/config.d/" + fqrn + ".local", false); } } void OptionsManager::ClearConfig() { config_.clear(); } bool OptionsManager::IsDefined(const std::string &key) { map<string, ConfigValue>::const_iterator iter = config_.find(key); return iter != config_.end(); } bool OptionsManager::GetValue(const string &key, string *value) { map<string, ConfigValue>::const_iterator iter = config_.find(key); if (iter != config_.end()) { *value = iter->second.value; return true; } *value = ""; return false; } bool OptionsManager::GetSource(const string &key, string *value) { map<string, ConfigValue>::const_iterator iter = config_.find(key); if (iter != config_.end()) { *value = iter->second.source; return true; } *value = ""; return false; } bool OptionsManager::IsOn(const std::string &param_value) { const string uppercase = ToUpper(param_value); return ((uppercase == "YES") || (uppercase == "ON") || (uppercase == "1")); } vector<string> OptionsManager::GetAllKeys() { vector<string> result; for (map<string, ConfigValue>::const_iterator i = config_.begin(), iEnd = config_.end(); i != iEnd; ++i) { result.push_back(i->first); } return result; } string OptionsManager::Dump() { string result; vector<string> keys = GetAllKeys(); for (unsigned i = 0, l = keys.size(); i < l; ++i) { bool retval; string value; string source; retval = GetValue(keys[i], &value); assert(retval); retval = GetSource(keys[i], &source); assert(retval); result += keys[i] + "=" + EscapeShell(value) + " # from " + source + "\n"; } return result; } #ifdef CVMFS_NAMESPACE_GUARD } // namespace CVMFS_NAMESPACE_GUARD #endif <|endoftext|>
<commit_before>#include "StdAfxUnitTests.h" #include "DnsUnitTests.h" CPPUNIT_TEST_SUITE_REGISTRATION(AppSecInc::UnitTests::TcpIp::DNS::DnsUnitTests); using namespace AppSecInc::UnitTests::TcpIp::DNS; void DnsUnitTests::testGetHostByAddress() { AppSecInc::TcpIp::CWSAStartup wsa; struct TestData { LPCSTR ip; LPCSTR host; }; TestData testdata[] = { { "65.55.11.218", "*.codeplex.com" } }; for (int i = 0; i < ARRAYSIZE(testdata); i++) { std::string host = AppSecInc::TcpIp::DNS::GetHostByAddress(testdata[i].ip); std::cout << std::endl << testdata[i].ip << " -> " << host; CPPUNIT_ASSERT(host == testdata[i].host); } } void DnsUnitTests::testGetHostByInvalidAddress() { AppSecInc::TcpIp::CWSAStartup wsa; LPCSTR testdata[] = { { "abcdefgh" }, }; for (int i = 0; i < ARRAYSIZE(testdata); i++) { try { AppSecInc::TcpIp::DNS::GetHostByAddress(testdata[i]); throw "Expected std::exception"; } catch(std::exception& ex) { std::cout << std::endl << "Expected exception for " << testdata[i] << ": " << ex.what(); } } } void DnsUnitTests::testGetHostByName() { AppSecInc::TcpIp::CWSAStartup wsa; struct TestData { LPCSTR ip; LPCSTR host; }; TestData testdata[] = { { "65.55.11.218", "*.codeplex.com" }, { "www.codeplex.com", "lb.codeplex.com.microsoft.akadns.net" }, }; for (int i = 0; i < ARRAYSIZE(testdata); i++) { std::string host = AppSecInc::TcpIp::DNS::GetHostByName(testdata[i].ip); std::cout << std::endl << testdata[i].ip << " -> " << host; CPPUNIT_ASSERT(host == testdata[i].host); } } void DnsUnitTests::testGetHostIpAddresses() { AppSecInc::TcpIp::CWSAStartup wsa; struct TestData { LPCSTR host; LPCSTR ip; }; TestData testdata[] = { { "65.55.11.218", "65.55.11.218" }, { "www.codeplex.com", "65.55.11.218" }, }; for (int i = 0; i < ARRAYSIZE(testdata); i++) { std::string ip = AppSecInc::TcpIp::DNS::GetHostIpAddresses(testdata[i].ip)[0]; std::cout << std::endl << testdata[i].host << " -> " << ip; CPPUNIT_ASSERT(ip == testdata[i].ip); } } void DnsUnitTests::testGetHostInfo() { AppSecInc::TcpIp::CWSAStartup wsa; struct TestData { LPCSTR host; LPCSTR hostname; // expected host name }; TestData testdata[] = { { "www.codeplex.com", "lb.codeplex.com.microsoft.akadns.net" }, }; for (int i = 0; i < ARRAYSIZE(testdata); i++) { std::string hostname; std::vector<std::string> aliases; std::vector<std::string> addresses; AppSecInc::TcpIp::DNS::GetHostInfo(testdata[i].host, hostname, aliases, addresses); std::cout << std::endl << testdata[i].host << " -> " << hostname; CPPUNIT_ASSERT(hostname == testdata[i].hostname); for each (const std::string& alias in aliases) std::cout << std::endl << " alias: " << alias; for each (const std::string& address in addresses) std::cout << std::endl << " address: " << address; } } void DnsUnitTests::testGetLocal() { AppSecInc::TcpIp::CWSAStartup wsa; char computername[MAX_COMPUTERNAME_LENGTH + 1] = { 0 }; DWORD size = MAX_COMPUTERNAME_LENGTH; CPPUNIT_ASSERT(::GetComputerNameA(computername, & size)); std::cout << std::endl << "Host: " << computername; std::string tcpaddress = AppSecInc::TcpIp::DNS::GetHostIpAddresses(computername)[0]; std::cout << std::endl << "Ip: " << tcpaddress; CPPUNIT_ASSERT(! tcpaddress.empty()); std::string host = AppSecInc::TcpIp::DNS::GetHostByName(computername); std::cout << std::endl << "Host: " << host; CPPUNIT_ASSERT(! host.empty()); } void DnsUnitTests::testGetHostName() { wchar_t computername[MAX_COMPUTERNAME_LENGTH + 1] = { 0 }; DWORD size = MAX_COMPUTERNAME_LENGTH; CPPUNIT_ASSERT(::GetComputerNameW(computername, & size)); std::wcout << std::endl << L"Computer: " << computername; std::wstring hostname = AppSecInc::TcpIp::DNS::GetHostNameW(); std::wcout << std::endl << L"Host: " << hostname; CPPUNIT_ASSERT(0 == ::_wcsicmp(computername, hostname.c_str())); } void DnsUnitTests::testIsIpAddress() { AppSecInc::TcpIp::CWSAStartup wsa; struct TestData { LPCSTR ip; bool isIp; // expected true/false }; TestData testdata[] = { { "", false }, { "127.0.0.1", true }, { "localhost", false }, { "0", false }, { "192.168.0.1", true }, { "10.10.10.10", true }, { "fe80::8081:ade5:e522:4a3c%14", false }, // IPv6 is not supported by this function }; for (int i = 0; i < ARRAYSIZE(testdata); i++) { bool ip = AppSecInc::TcpIp::DNS::IsIpAddress(testdata[i].ip); std::cout << std::endl << testdata[i].ip << " -> " << (ip ? "ip" : "not ip"); CPPUNIT_ASSERT(ip == testdata[i].isIp); } }<commit_msg>Changed sample IPs in test.<commit_after>#include "StdAfxUnitTests.h" #include "DnsUnitTests.h" CPPUNIT_TEST_SUITE_REGISTRATION(AppSecInc::UnitTests::TcpIp::DNS::DnsUnitTests); using namespace AppSecInc::UnitTests::TcpIp::DNS; void DnsUnitTests::testGetHostByAddress() { AppSecInc::TcpIp::CWSAStartup wsa; struct TestData { LPCSTR ip; LPCSTR host; }; TestData testdata[] = { { "207.97.227.239", "github.com" } }; for (int i = 0; i < ARRAYSIZE(testdata); i++) { std::string host = AppSecInc::TcpIp::DNS::GetHostByAddress(testdata[i].ip); std::cout << std::endl << testdata[i].ip << " -> " << host; CPPUNIT_ASSERT(host == testdata[i].host); } } void DnsUnitTests::testGetHostByInvalidAddress() { AppSecInc::TcpIp::CWSAStartup wsa; LPCSTR testdata[] = { { "abcdefgh" }, }; for (int i = 0; i < ARRAYSIZE(testdata); i++) { try { AppSecInc::TcpIp::DNS::GetHostByAddress(testdata[i]); throw "Expected std::exception"; } catch(std::exception& ex) { std::cout << std::endl << "Expected exception for " << testdata[i] << ": " << ex.what(); } } } void DnsUnitTests::testGetHostByName() { AppSecInc::TcpIp::CWSAStartup wsa; struct TestData { LPCSTR ip; LPCSTR host; }; TestData testdata[] = { { "207.97.227.239", "github.com" }, { "www.codeplex.com", "lb.codeplex.com.microsoft.akadns.net" }, }; for (int i = 0; i < ARRAYSIZE(testdata); i++) { std::string host = AppSecInc::TcpIp::DNS::GetHostByName(testdata[i].ip); std::cout << std::endl << testdata[i].ip << " -> " << host; CPPUNIT_ASSERT(host == testdata[i].host); } } void DnsUnitTests::testGetHostIpAddresses() { AppSecInc::TcpIp::CWSAStartup wsa; struct TestData { LPCSTR host; LPCSTR ip; }; TestData testdata[] = { { "207.97.227.239", "207.97.227.239" }, { "www.github.com", "207.97.227.239" }, }; for (int i = 0; i < ARRAYSIZE(testdata); i++) { std::string ip = AppSecInc::TcpIp::DNS::GetHostIpAddresses(testdata[i].ip)[0]; std::cout << std::endl << testdata[i].host << " -> " << ip; CPPUNIT_ASSERT(ip == testdata[i].ip); } } void DnsUnitTests::testGetHostInfo() { AppSecInc::TcpIp::CWSAStartup wsa; struct TestData { LPCSTR host; LPCSTR hostname; // expected host name }; TestData testdata[] = { { "www.codeplex.com", "lb.codeplex.com.microsoft.akadns.net" }, }; for (int i = 0; i < ARRAYSIZE(testdata); i++) { std::string hostname; std::vector<std::string> aliases; std::vector<std::string> addresses; AppSecInc::TcpIp::DNS::GetHostInfo(testdata[i].host, hostname, aliases, addresses); std::cout << std::endl << testdata[i].host << " -> " << hostname; CPPUNIT_ASSERT(hostname == testdata[i].hostname); for each (const std::string& alias in aliases) std::cout << std::endl << " alias: " << alias; for each (const std::string& address in addresses) std::cout << std::endl << " address: " << address; } } void DnsUnitTests::testGetLocal() { AppSecInc::TcpIp::CWSAStartup wsa; char computername[MAX_COMPUTERNAME_LENGTH + 1] = { 0 }; DWORD size = MAX_COMPUTERNAME_LENGTH; CPPUNIT_ASSERT(::GetComputerNameA(computername, & size)); std::cout << std::endl << "Host: " << computername; std::string tcpaddress = AppSecInc::TcpIp::DNS::GetHostIpAddresses(computername)[0]; std::cout << std::endl << "Ip: " << tcpaddress; CPPUNIT_ASSERT(! tcpaddress.empty()); std::string host = AppSecInc::TcpIp::DNS::GetHostByName(computername); std::cout << std::endl << "Host: " << host; CPPUNIT_ASSERT(! host.empty()); } void DnsUnitTests::testGetHostName() { wchar_t computername[MAX_COMPUTERNAME_LENGTH + 1] = { 0 }; DWORD size = MAX_COMPUTERNAME_LENGTH; CPPUNIT_ASSERT(::GetComputerNameW(computername, & size)); std::wcout << std::endl << L"Computer: " << computername; std::wstring hostname = AppSecInc::TcpIp::DNS::GetHostNameW(); std::wcout << std::endl << L"Host: " << hostname; CPPUNIT_ASSERT(0 == ::_wcsicmp(computername, hostname.c_str())); } void DnsUnitTests::testIsIpAddress() { AppSecInc::TcpIp::CWSAStartup wsa; struct TestData { LPCSTR ip; bool isIp; // expected true/false }; TestData testdata[] = { { "", false }, { "127.0.0.1", true }, { "localhost", false }, { "0", false }, { "192.168.0.1", true }, { "10.10.10.10", true }, { "fe80::8081:ade5:e522:4a3c%14", false }, // IPv6 is not supported by this function }; for (int i = 0; i < ARRAYSIZE(testdata); i++) { bool ip = AppSecInc::TcpIp::DNS::IsIpAddress(testdata[i].ip); std::cout << std::endl << testdata[i].ip << " -> " << (ip ? "ip" : "not ip"); CPPUNIT_ASSERT(ip == testdata[i].isIp); } }<|endoftext|>
<commit_before>#undef isnan #undef isfinite #include "kfusion.h" #include "helpers.h" #include <iostream> #include <sstream> #include <iomanip> #include <cvd/glwindow.h> #include "perfstats.h" using namespace std; using namespace TooN; #include <libfreenect/libfreenect.h> freenect_context *f_ctx; freenect_device *f_dev; bool gotDepth; void depth_cb(freenect_device *dev, void *v_depth, uint32_t timestamp) { gotDepth = true; } int InitKinect( uint16_t * buffer ){ if (freenect_init(&f_ctx, NULL) < 0) { cout << "freenect_init() failed" << endl; return 1; } freenect_set_log_level(f_ctx, FREENECT_LOG_WARNING); freenect_select_subdevices(f_ctx, (freenect_device_flags)(FREENECT_DEVICE_MOTOR | FREENECT_DEVICE_CAMERA)); int nr_devices = freenect_num_devices (f_ctx); cout << "Number of devices found: " << nr_devices << endl; if (nr_devices < 1) return 1; if (freenect_open_device(f_ctx, &f_dev, 0) < 0) { cout << "Could not open device" << endl; return 1; } freenect_set_depth_callback(f_dev, depth_cb); freenect_set_depth_mode(f_dev, freenect_find_depth_mode(FREENECT_RESOLUTION_MEDIUM, FREENECT_DEPTH_11BIT)); freenect_set_depth_buffer(f_dev, buffer); freenect_start_depth(f_dev); gotDepth = false; return 0; } void CloseKinect(){ freenect_stop_depth(f_dev); freenect_close_device(f_dev); freenect_shutdown(f_ctx); } void DepthFrameKinect() { while (!gotDepth && freenect_process_events(f_ctx) >= 0){ } gotDepth = false; } int main(int argc, char ** argv) { const float size = (argc > 1) ? atof(argv[1]) : 2.f; KFusionConfig config; // it is enough now to set the volume resolution once. // everything else is derived from that. // config.volumeSize = make_uint3(64); config.volumeSize = make_uint3(128); // config.volumeSize = make_uint3(256); // these are physical dimensions in meters config.volumeDimensions = make_float3(size); config.nearPlane = 0.4f; config.farPlane = 5.0f; config.mu = 0.1; config.combinedTrackAndReduce = false; config.camera = make_float4(297.12732, 296.24240, 169.89365, 121.25151); config.iterations[0] = 10; config.iterations[1] = 5; config.iterations[2] = 4; config.dist_threshold = (argc > 2 ) ? atof(argv[2]) : config.dist_threshold; config.normal_threshold = (argc > 3 ) ? atof(argv[3]) : config.normal_threshold; const uint2 imageSize = config.renderSize(); CVD::GLWindow window(CVD::ImageRef(imageSize.x * 2, imageSize.y * 2)); CVD::GLWindow::EventSummary events; glDisable(GL_DEPTH_TEST); KFusion kfusion; kfusion.Init(config); if(printCUDAError()){ kfusion.Clear(); cudaDeviceReset(); return 1; } Image<uchar4, HostDevice> lightScene(imageSize), depth(imageSize), lightModel(imageSize); Image<uint16_t, HostDevice> depthImage(make_uint2(640, 480)); const float3 light = make_float3(1.0, -2, 1.0); const float3 ambient = make_float3(0.1, 0.1, 0.1); const float4 renderCamera = make_float4(297.12732, 296.24240, 169.89365+160, 121.25151); SE3<float> initPose(makeVector(size/2, size/2, 0, 0, 0, 0)); kfusion.setPose(toMatrix4(initPose), toMatrix4(initPose.inverse())); if(InitKinect(depthImage.data())) return 1; bool integrate = true; bool reset = true; int counter = 0; while(!events.should_quit()){ glClear( GL_COLOR_BUFFER_BIT ); const double startFrame = Stats.start(); ++counter; DepthFrameKinect(); const double startProcessing = Stats.sample("kinect"); kfusion.setKinectDeviceDepth(depthImage.getDeviceImage()); Stats.sample("raw to cooked"); integrate = kfusion.Track(); Stats.sample("track"); if(integrate || reset ){ kfusion.Integrate(); Stats.sample("integrate"); reset = false; } renderLight( lightModel.getDeviceImage(), kfusion.vertex, kfusion.normal, light, ambient); renderLight( lightScene.getDeviceImage(), kfusion.inputVertex[0], kfusion.inputNormal[0], light, ambient ); renderTrackResult( depth.getDeviceImage(), kfusion.reduction ); cudaDeviceSynchronize(); Stats.sample("render"); glClear( GL_COLOR_BUFFER_BIT ); glRasterPos2i(0,imageSize.y * 0); glDrawPixels(lightScene); glRasterPos2i(imageSize.x, imageSize.y * 0); glDrawPixels(depth); glRasterPos2i(0,imageSize.y * 1); glDrawPixels(lightModel); Stats.sample("draw"); window.swap_buffers(); events.clear(); window.get_events(events); if(events.key_up.count('c')){ kfusion.Reset(); kfusion.setPose(toMatrix4(initPose), toMatrix4(initPose.inverse())); reset = true; } if(counter % 50 == 0){ Stats.print(); Stats.reset(); cout << endl; } if(printCUDAError()) break; const double endProcessing = Stats.sample("events"); Stats.sample("total", endProcessing - startFrame, PerfStats::TIME); Stats.sample("total_proc", endProcessing - startProcessing, PerfStats::TIME); } CloseKinect(); kfusion.Clear(); cudaDeviceReset(); return 0; } <commit_msg>vectors instead of arrays, to make config copyable etc and everything more flexible, missed a file<commit_after>#undef isnan #undef isfinite #include "kfusion.h" #include "helpers.h" #include <iostream> #include <sstream> #include <iomanip> #include <cvd/glwindow.h> #include "perfstats.h" using namespace std; using namespace TooN; #include <libfreenect/libfreenect.h> freenect_context *f_ctx; freenect_device *f_dev; bool gotDepth; void depth_cb(freenect_device *dev, void *v_depth, uint32_t timestamp) { gotDepth = true; } int InitKinect( uint16_t * buffer ){ if (freenect_init(&f_ctx, NULL) < 0) { cout << "freenect_init() failed" << endl; return 1; } freenect_set_log_level(f_ctx, FREENECT_LOG_WARNING); freenect_select_subdevices(f_ctx, (freenect_device_flags)(FREENECT_DEVICE_MOTOR | FREENECT_DEVICE_CAMERA)); int nr_devices = freenect_num_devices (f_ctx); cout << "Number of devices found: " << nr_devices << endl; if (nr_devices < 1) return 1; if (freenect_open_device(f_ctx, &f_dev, 0) < 0) { cout << "Could not open device" << endl; return 1; } freenect_set_depth_callback(f_dev, depth_cb); freenect_set_depth_mode(f_dev, freenect_find_depth_mode(FREENECT_RESOLUTION_MEDIUM, FREENECT_DEPTH_11BIT)); freenect_set_depth_buffer(f_dev, buffer); freenect_start_depth(f_dev); gotDepth = false; return 0; } void CloseKinect(){ freenect_stop_depth(f_dev); freenect_close_device(f_dev); freenect_shutdown(f_ctx); } void DepthFrameKinect() { while (!gotDepth && freenect_process_events(f_ctx) >= 0){ } gotDepth = false; } int main(int argc, char ** argv) { const float size = (argc > 1) ? atof(argv[1]) : 2.f; KFusionConfig config; // it is enough now to set the volume resolution once. // everything else is derived from that. // config.volumeSize = make_uint3(64); config.volumeSize = make_uint3(128); // config.volumeSize = make_uint3(256); // these are physical dimensions in meters config.volumeDimensions = make_float3(size); config.nearPlane = 0.4f; config.farPlane = 5.0f; config.mu = 0.1; config.combinedTrackAndReduce = false; config.camera = make_float4(297.12732, 296.24240, 169.89365, 121.25151); // config.iterations is a vector<int>, the length determines // the number of levels to be used in tracking // push back more then 3 iteraton numbers to get more levels. config.iterations[0] = 10; config.iterations[1] = 5; config.iterations[2] = 4; config.dist_threshold = (argc > 2 ) ? atof(argv[2]) : config.dist_threshold; config.normal_threshold = (argc > 3 ) ? atof(argv[3]) : config.normal_threshold; const uint2 imageSize = config.renderSize(); CVD::GLWindow window(CVD::ImageRef(imageSize.x * 2, imageSize.y * 2)); CVD::GLWindow::EventSummary events; glDisable(GL_DEPTH_TEST); KFusion kfusion; kfusion.Init(config); if(printCUDAError()){ kfusion.Clear(); cudaDeviceReset(); return 1; } Image<uchar4, HostDevice> lightScene(imageSize), depth(imageSize), lightModel(imageSize); Image<uint16_t, HostDevice> depthImage(make_uint2(640, 480)); const float3 light = make_float3(1.0, -2, 1.0); const float3 ambient = make_float3(0.1, 0.1, 0.1); const float4 renderCamera = make_float4(297.12732, 296.24240, 169.89365+160, 121.25151); SE3<float> initPose(makeVector(size/2, size/2, 0, 0, 0, 0)); kfusion.setPose(toMatrix4(initPose), toMatrix4(initPose.inverse())); if(InitKinect(depthImage.data())) return 1; bool integrate = true; bool reset = true; int counter = 0; while(!events.should_quit()){ glClear( GL_COLOR_BUFFER_BIT ); const double startFrame = Stats.start(); ++counter; DepthFrameKinect(); const double startProcessing = Stats.sample("kinect"); kfusion.setKinectDeviceDepth(depthImage.getDeviceImage()); Stats.sample("raw to cooked"); integrate = kfusion.Track(); Stats.sample("track"); if(integrate || reset ){ kfusion.Integrate(); Stats.sample("integrate"); reset = false; } renderLight( lightModel.getDeviceImage(), kfusion.vertex, kfusion.normal, light, ambient); renderLight( lightScene.getDeviceImage(), kfusion.inputVertex[0], kfusion.inputNormal[0], light, ambient ); renderTrackResult( depth.getDeviceImage(), kfusion.reduction ); cudaDeviceSynchronize(); Stats.sample("render"); glClear( GL_COLOR_BUFFER_BIT ); glRasterPos2i(0,imageSize.y * 0); glDrawPixels(lightScene); glRasterPos2i(imageSize.x, imageSize.y * 0); glDrawPixels(depth); glRasterPos2i(0,imageSize.y * 1); glDrawPixels(lightModel); Stats.sample("draw"); window.swap_buffers(); events.clear(); window.get_events(events); if(events.key_up.count('c')){ kfusion.Reset(); kfusion.setPose(toMatrix4(initPose), toMatrix4(initPose.inverse())); reset = true; } if(counter % 50 == 0){ Stats.print(); Stats.reset(); cout << endl; } if(printCUDAError()) break; const double endProcessing = Stats.sample("events"); Stats.sample("total", endProcessing - startFrame, PerfStats::TIME); Stats.sample("total_proc", endProcessing - startProcessing, PerfStats::TIME); } CloseKinect(); kfusion.Clear(); cudaDeviceReset(); return 0; } <|endoftext|>
<commit_before>/* <one line to give the program's name and a brief idea of what it does.> Copyright (C) <year> <name of author> 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 "componentprivate.h" using namespace Gluon; ComponentPrivate::ComponentPrivate() { } ComponentPrivate::ComponentPrivate(const ComponentPrivate &other) : QSharedData(other) { } ComponentPrivate::~ComponentPrivate() { } <commit_msg>Initialize variables<commit_after>/* <one line to give the program's name and a brief idea of what it does.> Copyright (C) <year> <name of author> 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 "componentprivate.h" using namespace Gluon; ComponentPrivate::ComponentPrivate() { enabled = true; gameObject = 0; } ComponentPrivate::ComponentPrivate(const ComponentPrivate &other) : QSharedData(other) , enabled(other.enabled) , gameObject(other.gameObject) { } ComponentPrivate::~ComponentPrivate() { } <|endoftext|>
<commit_before>/* * Copyright (C) 2017 Rene Herthel * * This file is subject to the terms and conditions of the MIT License. * See the file LICENSE in the top level directory for more details. */ /** * @ingroup error_handler * @{ * * @brief Function declaration of the ErrorHandler. * * @author Rene Herthel <rene.herthel@haw-hamburg.de> */ #include "ErrorHandler.h" #include "DistanceObservable.h" #include "DistanceEnum.h" #include "Signals.h" #include "CodeDefinition.h" #include "SerialProtocoll.h" #include "Signals.h" #include <iostream> using namespace std; using namespace HAL; ErrorHandler::ErrorHandler( int chid, ConveyorBeltService *conveyorBeltService, LightSystemService *lightSystemService, SerialService *serialService, PuckManager *puckManager) : m_hasError(false) , m_resetPressed(false) , m_conveyorBeltService(conveyorBeltService) , m_lightSystemService(lightSystemService) , m_serialService(serialService) , m_puckManager(puckManager) { m_lightSystemService->setWarningLevel(Level::OPERATING); } ErrorHandler::~ErrorHandler() { // Nothing todo so far. } void ErrorHandler::process(PuckManager::ManagerReturn &manager) { LOG_DEBUG << "[ErrorHandler] Demux Manager return \n"; LOG_DEBUG << "[ErrorHandler] Actor Flag " << manager.actorFlag << " actorSignal " << (int)manager.actorSignal << "\n"; //if slide full return a warning if (manager.actorFlag && manager.actorSignal == PuckManager::ActorSignal::SEND_SLIDE_FULL){ m_lightSystemService->setWarningLevel(Level::WARNING_OCCURED); LOG_DEBUG << "[ErrorHandler] Slide is full \n"; } if (manager.actorFlag && manager.actorSignal == PuckManager::ActorSignal::SEND_SLIDE_EMPTY){ m_lightSystemService->setWarningLevel(Level::CLEAR_WARNING); m_lightSystemService->setWarningLevel(Level::OPERATING); LOG_DEBUG << "[ErrorHandler] Slide is empty \n"; } //Only handle when error code if (manager.errorFlag) { m_hasError = true; m_lightSystemService->setWarningLevel(Level::ERROR_OCCURED); DistanceObservable &distO = DistanceObservable::getInstance(); distO.updateSpeed(DistanceSpeed::STOP); m_conveyorBeltService->changeState(ConveyorBeltState::STOP); m_serialService->sendMsg(Serial_n::ser_proto_msg::STOP_SER); switch (manager.errorSignal) { case PuckManager::ErrorSignal::PUCK_LOST: cout << "[ErrorHandler] PUCK_LOST - Late Timer" << endl; LOG_DEBUG << "[ErrorHandler] PUCK_LOST - Late Timer" << endl; break; case PuckManager::ErrorSignal::PUCK_MOVED: cout << "[ErrorHandler] PUCK_MOVED - Puck triggered light barrier before early timer" << endl; LOG_DEBUG << "[ErrorHandler] PUCK_MOVED - Puck triggered light barrier before early timer" << endl; break; case PuckManager::ErrorSignal::UNEXPECTED_SIGNAL: cout << "[ErrorHandler] UNEXPECTED_SIGNAL - Signal could not be processed" << endl; LOG_DEBUG << "[ErrorHandler] UNEXPECTED_SIGNAL - Signal could not be processed" << endl; break; case PuckManager::ErrorSignal::MULTIPLE_ACCEPT: cout << "[ErrorHandler] MULTIPLE_ACCEPT - Shouldn't happen - multiple pucks were triggered" << endl; LOG_DEBUG << "[ErrorHandler] MULTIPLE_ACCEPT - Shouldn't happen - multiple pucks were triggered" << endl; break; case PuckManager::ErrorSignal::MULTIPLE_WARNING: cout << "[ErrorHandler] MULTIPLE_WARNING" << endl; LOG_DEBUG << "[ErrorHandler] MULTIPLE_WARNING" << endl; break; case PuckManager::ErrorSignal::BOTH_SLIDES_FULL: cout << "[ErrorHandler] BOTH_SLIDES_FULL" << endl; LOG_DEBUG << "[ErrorHandler] BOTH_SLIDES_FULL" << endl; break; default: LOG_DEBUG << "[ErrorHandler] Unkown Error !!!" << endl; break; } } } bool ErrorHandler::hasError() { LOG_DEBUG << "[ErrorHandler] Error: " << m_hasError << "\n"; return m_hasError; } void ErrorHandler::handleEvent(rcv::msg_t event) { LOG_DEBUG << "[ErrorHandler] Trying to demux " << event.code << " " << event.value << "\n"; switch(event.code){ case CodeDefinition::SER_IN : if( event.value == Serial_n::ser_proto_msg::ESTOP_SER || event.value == Serial_n::ser_proto_msg::ERROR_SER || event.value == Serial_n::ser_proto_msg::NO_CON_SER ){ LOG_DEBUG << "[ErrorHandler] Got error from serial \n"; m_lightSystemService->setWarningLevel(Level::ERROR_OCCURED); m_conveyorBeltService->changeState(ConveyorBeltState::STOP); m_hasError = true; m_resetPressed = false; } break; case CodeDefinition::ISR : if(event.value == interrupts::BUTTON_ESTOP_IN){ LOG_DEBUG << "[ErrorHandler] Got Estop from ISR \n"; m_lightSystemService->setWarningLevel(Level::ERROR_OCCURED); m_serialService->sendMsg(Serial_n::ser_proto_msg::ESTOP_SER); m_conveyorBeltService->changeState(ConveyorBeltState::STOP); m_hasError = true; m_resetPressed = false; } break; default : //Nothing to do break; } if(m_hasError){ bool buttonReset = false; bool buttonStart = false; if (event.code != 5) { // 5 is hardcoded in the ISR. TODO Serial signal needs to get through when error is acknowledged on other machine return; // Do not do anything without code 5! } switch(event.value) { case interrupts::BUTTON_RESET: buttonReset = true; break; case interrupts::BUTTON_START: buttonStart = true; break; default: // Nothing todo so far. break; } if (buttonReset && m_hasError) { m_resetPressed = true; cout << "Error acknowledged" << endl; m_lightSystemService->setWarningLevel(Level::ERROR_ACKNOWLEDGED); } else if (buttonStart && m_resetPressed && m_hasError) { // Only go further when reset was pressed before. m_puckManager->reset(); cout << "Clear error" << endl; m_lightSystemService->setWarningLevel(Level::OPERATING); m_resetPressed = false; m_hasError = false; } } } /** @} */ <commit_msg>ErrorHandler Distributes signals now<commit_after>/* * Copyright (C) 2017 Rene Herthel * * This file is subject to the terms and conditions of the MIT License. * See the file LICENSE in the top level directory for more details. */ /** * @ingroup error_handler * @{ * * @brief Function declaration of the ErrorHandler. * * @author Rene Herthel <rene.herthel@haw-hamburg.de> */ #include "ErrorHandler.h" #include "DistanceObservable.h" #include "DistanceEnum.h" #include "Signals.h" #include "CodeDefinition.h" #include "SerialProtocoll.h" #include "Signals.h" #include <iostream> using namespace std; using namespace HAL; ErrorHandler::ErrorHandler( int chid, ConveyorBeltService *conveyorBeltService, LightSystemService *lightSystemService, SerialService *serialService, PuckManager *puckManager) : m_hasError(false) , m_resetPressed(false) , m_conveyorBeltService(conveyorBeltService) , m_lightSystemService(lightSystemService) , m_serialService(serialService) , m_puckManager(puckManager) { m_lightSystemService->setWarningLevel(Level::OPERATING); } ErrorHandler::~ErrorHandler() { // Nothing todo so far. } void ErrorHandler::process(PuckManager::ManagerReturn &manager) { LOG_DEBUG << "[ErrorHandler] Demux Manager return \n"; LOG_DEBUG << "[ErrorHandler] Actor Flag " << manager.actorFlag << " actorSignal " << (int)manager.actorSignal << "\n"; //if slide full return a warning if (manager.actorFlag && manager.actorSignal == PuckManager::ActorSignal::SEND_SLIDE_FULL){ m_lightSystemService->setWarningLevel(Level::WARNING_OCCURED); LOG_DEBUG << "[ErrorHandler] Slide is full \n"; } if (manager.actorFlag && manager.actorSignal == PuckManager::ActorSignal::SEND_SLIDE_EMPTY){ m_lightSystemService->setWarningLevel(Level::CLEAR_WARNING); m_lightSystemService->setWarningLevel(Level::OPERATING); LOG_DEBUG << "[ErrorHandler] Slide is empty \n"; } //Only handle when error code if (manager.errorFlag) { m_hasError = true; m_lightSystemService->setWarningLevel(Level::ERROR_OCCURED); DistanceObservable &distO = DistanceObservable::getInstance(); distO.updateSpeed(DistanceSpeed::STOP); m_conveyorBeltService->changeState(ConveyorBeltState::STOP); m_serialService->sendMsg(Serial_n::ser_proto_msg::STOP_SER); switch (manager.errorSignal) { case PuckManager::ErrorSignal::PUCK_LOST: cout << "[ErrorHandler] PUCK_LOST - Late Timer" << endl; LOG_DEBUG << "[ErrorHandler] PUCK_LOST - Late Timer" << endl; break; case PuckManager::ErrorSignal::PUCK_MOVED: cout << "[ErrorHandler] PUCK_MOVED - Puck triggered light barrier before early timer" << endl; LOG_DEBUG << "[ErrorHandler] PUCK_MOVED - Puck triggered light barrier before early timer" << endl; break; case PuckManager::ErrorSignal::UNEXPECTED_SIGNAL: cout << "[ErrorHandler] UNEXPECTED_SIGNAL - Signal could not be processed" << endl; LOG_DEBUG << "[ErrorHandler] UNEXPECTED_SIGNAL - Signal could not be processed" << endl; break; case PuckManager::ErrorSignal::MULTIPLE_ACCEPT: cout << "[ErrorHandler] MULTIPLE_ACCEPT - Shouldn't happen - multiple pucks were triggered" << endl; LOG_DEBUG << "[ErrorHandler] MULTIPLE_ACCEPT - Shouldn't happen - multiple pucks were triggered" << endl; break; case PuckManager::ErrorSignal::MULTIPLE_WARNING: cout << "[ErrorHandler] MULTIPLE_WARNING" << endl; LOG_DEBUG << "[ErrorHandler] MULTIPLE_WARNING" << endl; break; default: LOG_DEBUG << "[ErrorHandler] Unkown Error !!!" << endl; break; } } } bool ErrorHandler::hasError() { LOG_DEBUG << "[ErrorHandler] Error: " << m_hasError << "\n"; return m_hasError; } void ErrorHandler::handleEvent(rcv::msg_t event) { LOG_DEBUG << "[ErrorHandler] Trying to demux " << event.code << " " << event.value << "\n"; switch(event.code){ case CodeDefinition::SER_IN : if( event.value == Serial_n::ser_proto_msg::ESTOP_SER || event.value == Serial_n::ser_proto_msg::ERROR_SER || event.value == Serial_n::ser_proto_msg::NO_CON_SER ){ LOG_DEBUG << "[ErrorHandler] Got error from serial \n"; m_lightSystemService->setWarningLevel(Level::ERROR_OCCURED); m_conveyorBeltService->changeState(ConveyorBeltState::STOP); m_hasError = true; m_resetPressed = false; } break; case CodeDefinition::ISR : if(event.value == interrupts::BUTTON_ESTOP_IN){ LOG_DEBUG << "[ErrorHandler] Got Estop from ISR \n"; m_lightSystemService->setWarningLevel(Level::ERROR_OCCURED); m_serialService->sendMsg(Serial_n::ser_proto_msg::ESTOP_SER); m_conveyorBeltService->changeState(ConveyorBeltState::STOP); m_hasError = true; m_resetPressed = false; } break; default : //Nothing to do break; } if(m_hasError){ bool buttonReset = false; bool buttonStart = false; if (event.code != 5) { // 5 is hardcoded in the ISR. TODO Serial signal needs to get through when error is acknowledged on other machine return; // Do not do anything without code 5! } switch(event.value) { case interrupts::BUTTON_RESET: buttonReset = true; break; case interrupts::BUTTON_START: buttonStart = true; break; case interrupts::SLIDE_OUT: PuckSignal::Signal signal; signal.signalType = PuckSignal::SignalType::INTERRUPT_SIGNAL; signal.interruptSignal = event.value; m_puckManager->process(signal); break; default: // Nothing todo so far. break; } if (buttonReset && m_hasError) { m_resetPressed = true; cout << "Error acknowledged" << endl; m_lightSystemService->setWarningLevel(Level::ERROR_ACKNOWLEDGED); } else if (buttonStart && m_resetPressed && m_hasError) { // Only go further when reset was pressed before. m_puckManager->reset(); cout << "Clear error" << endl; m_lightSystemService->setWarningLevel(Level::OPERATING); m_resetPressed = false; m_hasError = false; } } } /** @} */ <|endoftext|>
<commit_before> /* * Copyright 2011 Google Inc. * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include "SkColorMatrixFilter.h" #include "SkColorMatrix.h" #include "SkColorPriv.h" #include "SkUnPreMultiply.h" static int32_t rowmul4(const int32_t array[], unsigned r, unsigned g, unsigned b, unsigned a) { return array[0] * r + array[1] * g + array[2] * b + array[3] * a + array[4]; } static int32_t rowmul3(const int32_t array[], unsigned r, unsigned g, unsigned b) { return array[0] * r + array[1] * g + array[2] * b + array[4]; } static void General(SkColorMatrixFilter::State* state, unsigned r, unsigned g, unsigned b, unsigned a) { const int32_t* SK_RESTRICT array = state->fArray; const int shift = state->fShift; int32_t* SK_RESTRICT result = state->fResult; result[0] = rowmul4(&array[0], r, g, b, a) >> shift; result[1] = rowmul4(&array[5], r, g, b, a) >> shift; result[2] = rowmul4(&array[10], r, g, b, a) >> shift; result[3] = rowmul4(&array[15], r, g, b, a) >> shift; } static void General16(SkColorMatrixFilter::State* state, unsigned r, unsigned g, unsigned b, unsigned a) { const int32_t* SK_RESTRICT array = state->fArray; int32_t* SK_RESTRICT result = state->fResult; result[0] = rowmul4(&array[0], r, g, b, a) >> 16; result[1] = rowmul4(&array[5], r, g, b, a) >> 16; result[2] = rowmul4(&array[10], r, g, b, a) >> 16; result[3] = rowmul4(&array[15], r, g, b, a) >> 16; } static void AffineAdd(SkColorMatrixFilter::State* state, unsigned r, unsigned g, unsigned b, unsigned a) { const int32_t* SK_RESTRICT array = state->fArray; const int shift = state->fShift; int32_t* SK_RESTRICT result = state->fResult; result[0] = rowmul3(&array[0], r, g, b) >> shift; result[1] = rowmul3(&array[5], r, g, b) >> shift; result[2] = rowmul3(&array[10], r, g, b) >> shift; result[3] = a; } static void AffineAdd16(SkColorMatrixFilter::State* state, unsigned r, unsigned g, unsigned b, unsigned a) { const int32_t* SK_RESTRICT array = state->fArray; int32_t* SK_RESTRICT result = state->fResult; result[0] = rowmul3(&array[0], r, g, b) >> 16; result[1] = rowmul3(&array[5], r, g, b) >> 16; result[2] = rowmul3(&array[10], r, g, b) >> 16; result[3] = a; } static void ScaleAdd(SkColorMatrixFilter::State* state, unsigned r, unsigned g, unsigned b, unsigned a) { const int32_t* SK_RESTRICT array = state->fArray; const int shift = state->fShift; int32_t* SK_RESTRICT result = state->fResult; // cast to (int) to keep the expression signed for the shift result[0] = (array[0] * (int)r + array[4]) >> shift; result[1] = (array[6] * (int)g + array[9]) >> shift; result[2] = (array[12] * (int)b + array[14]) >> shift; result[3] = a; } static void ScaleAdd16(SkColorMatrixFilter::State* state, unsigned r, unsigned g, unsigned b, unsigned a) { const int32_t* SK_RESTRICT array = state->fArray; int32_t* SK_RESTRICT result = state->fResult; // cast to (int) to keep the expression signed for the shift result[0] = (array[0] * (int)r + array[4]) >> 16; result[1] = (array[6] * (int)g + array[9]) >> 16; result[2] = (array[12] * (int)b + array[14]) >> 16; result[3] = a; } static void Add(SkColorMatrixFilter::State* state, unsigned r, unsigned g, unsigned b, unsigned a) { const int32_t* SK_RESTRICT array = state->fArray; const int shift = state->fShift; int32_t* SK_RESTRICT result = state->fResult; result[0] = r + (array[4] >> shift); result[1] = g + (array[9] >> shift); result[2] = b + (array[14] >> shift); result[3] = a; } static void Add16(SkColorMatrixFilter::State* state, unsigned r, unsigned g, unsigned b, unsigned a) { const int32_t* SK_RESTRICT array = state->fArray; int32_t* SK_RESTRICT result = state->fResult; result[0] = r + (array[4] >> 16); result[1] = g + (array[9] >> 16); result[2] = b + (array[14] >> 16); result[3] = a; } #define kNO_ALPHA_FLAGS (SkColorFilter::kAlphaUnchanged_Flag | \ SkColorFilter::kHasFilter16_Flag) // src is [20] but some compilers won't accept __restrict__ on anything // but an raw pointer or reference void SkColorMatrixFilter::setup(const SkScalar* SK_RESTRICT src) { if (NULL == src) { fProc = NULL; // signals identity fFlags = kNO_ALPHA_FLAGS; // fState is undefined, but that is OK, since we shouldn't look at it return; } int32_t* SK_RESTRICT array = fState.fArray; int i; SkFixed max = 0; for (int i = 0; i < 20; i++) { SkFixed value = SkScalarToFixed(src[i]); array[i] = value; value = SkAbs32(value); max = SkMax32(max, value); } /* All of fArray[] values must fit in 23 bits, to safely allow me to multiply them by 8bit unsigned values, and get a signed answer without overflow. This means clz needs to be 9 or bigger */ int bits = SkCLZ(max); int32_t one = SK_Fixed1; fState.fShift = 16; // we are starting out as fixed 16.16 if (bits < 9) { bits = 9 - bits; fState.fShift -= bits; for (i = 0; i < 20; i++) { array[i] >>= bits; } one >>= bits; } // check if we have to munge Alpha int32_t changesAlpha = (array[15] | array[16] | array[17] | (array[18] - one) | array[19]); int32_t usesAlpha = (array[3] | array[8] | array[13]); bool shiftIs16 = (16 == fState.fShift); if (changesAlpha | usesAlpha) { fProc = shiftIs16 ? General16 : General; fFlags = changesAlpha ? 0 : SkColorFilter::kAlphaUnchanged_Flag; } else { fFlags = kNO_ALPHA_FLAGS; int32_t needsScale = (array[0] - one) | // red axis (array[6] - one) | // green axis (array[12] - one); // blue axis int32_t needs3x3 = array[1] | array[2] | // red off-axis array[5] | array[7] | // green off-axis array[10] | array[11]; // blue off-axis if (needs3x3) { fProc = shiftIs16 ? AffineAdd16 : AffineAdd; } else if (needsScale) { fProc = shiftIs16 ? ScaleAdd16 : ScaleAdd; } else if (array[4] | array[9] | array[14]) { // needs add fProc = shiftIs16 ? Add16 : Add; } else { fProc = NULL; // identity } } /* preround our add values so we get a rounded shift. We do this after we analyze the array, so we don't miss the case where the caller has zeros which could make us accidentally take the General or Add case. */ if (NULL != fProc) { int32_t add = 1 << (fState.fShift - 1); array[4] += add; array[9] += add; array[14] += add; array[19] += add; } } /////////////////////////////////////////////////////////////////////////////// static int32_t pin(int32_t value, int32_t max) { if (value < 0) { value = 0; } if (value > max) { value = max; } return value; } SkColorMatrixFilter::SkColorMatrixFilter() { this->setup(NULL); } SkColorMatrixFilter::SkColorMatrixFilter(const SkColorMatrix& cm) { this->setup(cm.fMat); } SkColorMatrixFilter::SkColorMatrixFilter(const SkScalar array[20]) { this->setup(array); } uint32_t SkColorMatrixFilter::getFlags() { return this->INHERITED::getFlags() | fFlags; } void SkColorMatrixFilter::filterSpan(const SkPMColor src[], int count, SkPMColor dst[]) { Proc proc = fProc; State* state = &fState; int32_t* SK_RESTRICT result = state->fResult; if (NULL == proc) { if (src != dst) { memcpy(dst, src, count * sizeof(SkPMColor)); } return; } const SkUnPreMultiply::Scale* table = SkUnPreMultiply::GetScaleTable(); for (int i = 0; i < count; i++) { SkPMColor c = src[i]; unsigned r = SkGetPackedR32(c); unsigned g = SkGetPackedG32(c); unsigned b = SkGetPackedB32(c); unsigned a = SkGetPackedA32(c); // need our components to be un-premultiplied if (255 != a) { SkUnPreMultiply::Scale scale = table[a]; r = SkUnPreMultiply::ApplyScale(scale, r); g = SkUnPreMultiply::ApplyScale(scale, g); b = SkUnPreMultiply::ApplyScale(scale, b); SkASSERT(r <= 255); SkASSERT(g <= 255); SkASSERT(b <= 255); } proc(state, r, g, b, a); r = pin(result[0], SK_R32_MASK); g = pin(result[1], SK_G32_MASK); b = pin(result[2], SK_B32_MASK); a = pin(result[3], SK_A32_MASK); // re-prepremultiply if needed if (255 != a) { int scale = SkAlpha255To256(a); r = SkAlphaMul(r, scale); g = SkAlphaMul(g, scale); b = SkAlphaMul(b, scale); } dst[i] = SkPackARGB32(a, r, g, b); } } void SkColorMatrixFilter::filterSpan16(const uint16_t src[], int count, uint16_t dst[]) { SkASSERT(fFlags & SkColorFilter::kHasFilter16_Flag); Proc proc = fProc; State* state = &fState; int32_t* SK_RESTRICT result = state->fResult; if (NULL == proc) { if (src != dst) { memcpy(dst, src, count * sizeof(uint16_t)); } return; } for (int i = 0; i < count; i++) { uint16_t c = src[i]; // expand to 8bit components (since our matrix translate is 8bit biased unsigned r = SkPacked16ToR32(c); unsigned g = SkPacked16ToG32(c); unsigned b = SkPacked16ToB32(c); proc(state, r, g, b, 0); r = pin(result[0], SK_R32_MASK); g = pin(result[1], SK_G32_MASK); b = pin(result[2], SK_B32_MASK); // now packed it back down to 16bits (hmmm, could dither...) dst[i] = SkPack888ToRGB16(r, g, b); } } /////////////////////////////////////////////////////////////////////////////// void SkColorMatrixFilter::flatten(SkFlattenableWriteBuffer& buffer) { this->INHERITED::flatten(buffer); buffer.writeFunctionPtr((void*)fProc); buffer.writeMul4(&fState, sizeof(fState)); buffer.write32(fFlags); } SkFlattenable::Factory SkColorMatrixFilter::getFactory() { return CreateProc; } SkColorMatrixFilter::SkColorMatrixFilter(SkFlattenableReadBuffer& buffer) : INHERITED(buffer) { fProc = (Proc)buffer.readFunctionPtr(); buffer.read(&fState, sizeof(fState)); fFlags = buffer.readU32(); } bool SkColorMatrixFilter::asColorMatrix(SkScalar matrix[20]) { int32_t* SK_RESTRICT array = fState.fArray; int unshift = 16 - fState.fShift; for (int i = 0; i < 20; i++) { matrix[i] = SkFixedToScalar(array[i] << unshift); } if (NULL != fProc) { // Undo the offset applied to the constant column in setup(). SkFixed offset = 1 << (fState.fShift - 1); matrix[4] = SkFixedToScalar((array[4] - offset) << unshift); matrix[9] = SkFixedToScalar((array[9] - offset) << unshift); matrix[14] = SkFixedToScalar((array[14] - offset) << unshift); matrix[19] = SkFixedToScalar((array[19] - offset) << unshift); } return true; } SkFlattenable* SkColorMatrixFilter::CreateProc(SkFlattenableReadBuffer& buf) { return SkNEW_ARGS(SkColorMatrixFilter, (buf)); } void SkColorMatrixFilter::setMatrix(const SkColorMatrix& matrix) { setup(matrix.fMat); } void SkColorMatrixFilter::setArray(const SkScalar array[20]) { setup(array); } SK_DEFINE_FLATTENABLE_REGISTRAR(SkColorMatrixFilter) <commit_msg>Improve the quality of color matrix filters by using SkPremultiplyARGBInline. This is closer (but not exactly the same as) WebKit's implementation.<commit_after> /* * Copyright 2011 Google Inc. * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include "SkColorMatrixFilter.h" #include "SkColorMatrix.h" #include "SkColorPriv.h" #include "SkUnPreMultiply.h" static int32_t rowmul4(const int32_t array[], unsigned r, unsigned g, unsigned b, unsigned a) { return array[0] * r + array[1] * g + array[2] * b + array[3] * a + array[4]; } static int32_t rowmul3(const int32_t array[], unsigned r, unsigned g, unsigned b) { return array[0] * r + array[1] * g + array[2] * b + array[4]; } static void General(SkColorMatrixFilter::State* state, unsigned r, unsigned g, unsigned b, unsigned a) { const int32_t* SK_RESTRICT array = state->fArray; const int shift = state->fShift; int32_t* SK_RESTRICT result = state->fResult; result[0] = rowmul4(&array[0], r, g, b, a) >> shift; result[1] = rowmul4(&array[5], r, g, b, a) >> shift; result[2] = rowmul4(&array[10], r, g, b, a) >> shift; result[3] = rowmul4(&array[15], r, g, b, a) >> shift; } static void General16(SkColorMatrixFilter::State* state, unsigned r, unsigned g, unsigned b, unsigned a) { const int32_t* SK_RESTRICT array = state->fArray; int32_t* SK_RESTRICT result = state->fResult; result[0] = rowmul4(&array[0], r, g, b, a) >> 16; result[1] = rowmul4(&array[5], r, g, b, a) >> 16; result[2] = rowmul4(&array[10], r, g, b, a) >> 16; result[3] = rowmul4(&array[15], r, g, b, a) >> 16; } static void AffineAdd(SkColorMatrixFilter::State* state, unsigned r, unsigned g, unsigned b, unsigned a) { const int32_t* SK_RESTRICT array = state->fArray; const int shift = state->fShift; int32_t* SK_RESTRICT result = state->fResult; result[0] = rowmul3(&array[0], r, g, b) >> shift; result[1] = rowmul3(&array[5], r, g, b) >> shift; result[2] = rowmul3(&array[10], r, g, b) >> shift; result[3] = a; } static void AffineAdd16(SkColorMatrixFilter::State* state, unsigned r, unsigned g, unsigned b, unsigned a) { const int32_t* SK_RESTRICT array = state->fArray; int32_t* SK_RESTRICT result = state->fResult; result[0] = rowmul3(&array[0], r, g, b) >> 16; result[1] = rowmul3(&array[5], r, g, b) >> 16; result[2] = rowmul3(&array[10], r, g, b) >> 16; result[3] = a; } static void ScaleAdd(SkColorMatrixFilter::State* state, unsigned r, unsigned g, unsigned b, unsigned a) { const int32_t* SK_RESTRICT array = state->fArray; const int shift = state->fShift; int32_t* SK_RESTRICT result = state->fResult; // cast to (int) to keep the expression signed for the shift result[0] = (array[0] * (int)r + array[4]) >> shift; result[1] = (array[6] * (int)g + array[9]) >> shift; result[2] = (array[12] * (int)b + array[14]) >> shift; result[3] = a; } static void ScaleAdd16(SkColorMatrixFilter::State* state, unsigned r, unsigned g, unsigned b, unsigned a) { const int32_t* SK_RESTRICT array = state->fArray; int32_t* SK_RESTRICT result = state->fResult; // cast to (int) to keep the expression signed for the shift result[0] = (array[0] * (int)r + array[4]) >> 16; result[1] = (array[6] * (int)g + array[9]) >> 16; result[2] = (array[12] * (int)b + array[14]) >> 16; result[3] = a; } static void Add(SkColorMatrixFilter::State* state, unsigned r, unsigned g, unsigned b, unsigned a) { const int32_t* SK_RESTRICT array = state->fArray; const int shift = state->fShift; int32_t* SK_RESTRICT result = state->fResult; result[0] = r + (array[4] >> shift); result[1] = g + (array[9] >> shift); result[2] = b + (array[14] >> shift); result[3] = a; } static void Add16(SkColorMatrixFilter::State* state, unsigned r, unsigned g, unsigned b, unsigned a) { const int32_t* SK_RESTRICT array = state->fArray; int32_t* SK_RESTRICT result = state->fResult; result[0] = r + (array[4] >> 16); result[1] = g + (array[9] >> 16); result[2] = b + (array[14] >> 16); result[3] = a; } #define kNO_ALPHA_FLAGS (SkColorFilter::kAlphaUnchanged_Flag | \ SkColorFilter::kHasFilter16_Flag) // src is [20] but some compilers won't accept __restrict__ on anything // but an raw pointer or reference void SkColorMatrixFilter::setup(const SkScalar* SK_RESTRICT src) { if (NULL == src) { fProc = NULL; // signals identity fFlags = kNO_ALPHA_FLAGS; // fState is undefined, but that is OK, since we shouldn't look at it return; } int32_t* SK_RESTRICT array = fState.fArray; int i; SkFixed max = 0; for (int i = 0; i < 20; i++) { SkFixed value = SkScalarToFixed(src[i]); array[i] = value; value = SkAbs32(value); max = SkMax32(max, value); } /* All of fArray[] values must fit in 23 bits, to safely allow me to multiply them by 8bit unsigned values, and get a signed answer without overflow. This means clz needs to be 9 or bigger */ int bits = SkCLZ(max); int32_t one = SK_Fixed1; fState.fShift = 16; // we are starting out as fixed 16.16 if (bits < 9) { bits = 9 - bits; fState.fShift -= bits; for (i = 0; i < 20; i++) { array[i] >>= bits; } one >>= bits; } // check if we have to munge Alpha int32_t changesAlpha = (array[15] | array[16] | array[17] | (array[18] - one) | array[19]); int32_t usesAlpha = (array[3] | array[8] | array[13]); bool shiftIs16 = (16 == fState.fShift); if (changesAlpha | usesAlpha) { fProc = shiftIs16 ? General16 : General; fFlags = changesAlpha ? 0 : SkColorFilter::kAlphaUnchanged_Flag; } else { fFlags = kNO_ALPHA_FLAGS; int32_t needsScale = (array[0] - one) | // red axis (array[6] - one) | // green axis (array[12] - one); // blue axis int32_t needs3x3 = array[1] | array[2] | // red off-axis array[5] | array[7] | // green off-axis array[10] | array[11]; // blue off-axis if (needs3x3) { fProc = shiftIs16 ? AffineAdd16 : AffineAdd; } else if (needsScale) { fProc = shiftIs16 ? ScaleAdd16 : ScaleAdd; } else if (array[4] | array[9] | array[14]) { // needs add fProc = shiftIs16 ? Add16 : Add; } else { fProc = NULL; // identity } } /* preround our add values so we get a rounded shift. We do this after we analyze the array, so we don't miss the case where the caller has zeros which could make us accidentally take the General or Add case. */ if (NULL != fProc) { int32_t add = 1 << (fState.fShift - 1); array[4] += add; array[9] += add; array[14] += add; array[19] += add; } } /////////////////////////////////////////////////////////////////////////////// static int32_t pin(int32_t value, int32_t max) { if (value < 0) { value = 0; } if (value > max) { value = max; } return value; } SkColorMatrixFilter::SkColorMatrixFilter() { this->setup(NULL); } SkColorMatrixFilter::SkColorMatrixFilter(const SkColorMatrix& cm) { this->setup(cm.fMat); } SkColorMatrixFilter::SkColorMatrixFilter(const SkScalar array[20]) { this->setup(array); } uint32_t SkColorMatrixFilter::getFlags() { return this->INHERITED::getFlags() | fFlags; } void SkColorMatrixFilter::filterSpan(const SkPMColor src[], int count, SkPMColor dst[]) { Proc proc = fProc; State* state = &fState; int32_t* SK_RESTRICT result = state->fResult; if (NULL == proc) { if (src != dst) { memcpy(dst, src, count * sizeof(SkPMColor)); } return; } const SkUnPreMultiply::Scale* table = SkUnPreMultiply::GetScaleTable(); for (int i = 0; i < count; i++) { SkPMColor c = src[i]; unsigned r = SkGetPackedR32(c); unsigned g = SkGetPackedG32(c); unsigned b = SkGetPackedB32(c); unsigned a = SkGetPackedA32(c); // need our components to be un-premultiplied if (255 != a) { SkUnPreMultiply::Scale scale = table[a]; r = SkUnPreMultiply::ApplyScale(scale, r); g = SkUnPreMultiply::ApplyScale(scale, g); b = SkUnPreMultiply::ApplyScale(scale, b); SkASSERT(r <= 255); SkASSERT(g <= 255); SkASSERT(b <= 255); } proc(state, r, g, b, a); r = pin(result[0], SK_R32_MASK); g = pin(result[1], SK_G32_MASK); b = pin(result[2], SK_B32_MASK); a = pin(result[3], SK_A32_MASK); // re-prepremultiply if needed dst[i] = SkPremultiplyARGBInline(a, r, g, b); } } void SkColorMatrixFilter::filterSpan16(const uint16_t src[], int count, uint16_t dst[]) { SkASSERT(fFlags & SkColorFilter::kHasFilter16_Flag); Proc proc = fProc; State* state = &fState; int32_t* SK_RESTRICT result = state->fResult; if (NULL == proc) { if (src != dst) { memcpy(dst, src, count * sizeof(uint16_t)); } return; } for (int i = 0; i < count; i++) { uint16_t c = src[i]; // expand to 8bit components (since our matrix translate is 8bit biased unsigned r = SkPacked16ToR32(c); unsigned g = SkPacked16ToG32(c); unsigned b = SkPacked16ToB32(c); proc(state, r, g, b, 0); r = pin(result[0], SK_R32_MASK); g = pin(result[1], SK_G32_MASK); b = pin(result[2], SK_B32_MASK); // now packed it back down to 16bits (hmmm, could dither...) dst[i] = SkPack888ToRGB16(r, g, b); } } /////////////////////////////////////////////////////////////////////////////// void SkColorMatrixFilter::flatten(SkFlattenableWriteBuffer& buffer) { this->INHERITED::flatten(buffer); buffer.writeFunctionPtr((void*)fProc); buffer.writeMul4(&fState, sizeof(fState)); buffer.write32(fFlags); } SkFlattenable::Factory SkColorMatrixFilter::getFactory() { return CreateProc; } SkColorMatrixFilter::SkColorMatrixFilter(SkFlattenableReadBuffer& buffer) : INHERITED(buffer) { fProc = (Proc)buffer.readFunctionPtr(); buffer.read(&fState, sizeof(fState)); fFlags = buffer.readU32(); } bool SkColorMatrixFilter::asColorMatrix(SkScalar matrix[20]) { int32_t* SK_RESTRICT array = fState.fArray; int unshift = 16 - fState.fShift; for (int i = 0; i < 20; i++) { matrix[i] = SkFixedToScalar(array[i] << unshift); } if (NULL != fProc) { // Undo the offset applied to the constant column in setup(). SkFixed offset = 1 << (fState.fShift - 1); matrix[4] = SkFixedToScalar((array[4] - offset) << unshift); matrix[9] = SkFixedToScalar((array[9] - offset) << unshift); matrix[14] = SkFixedToScalar((array[14] - offset) << unshift); matrix[19] = SkFixedToScalar((array[19] - offset) << unshift); } return true; } SkFlattenable* SkColorMatrixFilter::CreateProc(SkFlattenableReadBuffer& buf) { return SkNEW_ARGS(SkColorMatrixFilter, (buf)); } void SkColorMatrixFilter::setMatrix(const SkColorMatrix& matrix) { setup(matrix.fMat); } void SkColorMatrixFilter::setArray(const SkScalar array[20]) { setup(array); } SK_DEFINE_FLATTENABLE_REGISTRAR(SkColorMatrixFilter) <|endoftext|>
<commit_before>/* * ARMEmulator.cpp * * Created on: Oct 10, 2015 * Author: anon */ #include "debug.h" #include "ARMEmulator.h" #include "ARMDisassembler.h" using namespace std; using namespace Register; using namespace Disassembler; namespace Emulator { ARMEmulator::ARMEmulator(ARMContext *context, Memory::AbstractMemory *memory, ARMMode mode, ARMVariants variant) : m_mode{mode}, m_contex{context}, m_memory{memory} { m_dis = new ARMDisassembler(variant); m_interpreter = new ARMInterpreter(*m_contex); } ARMEmulator::~ARMEmulator() { } void ARMEmulator::start(unsigned count) { bool stop = false; unsigned n_executed = 0; uint32_t cur_pc = 0; uint32_t cur_opcode = 0; ARMMode cur_mode = m_mode; m_contex->getRegister(ARM_REG_PC, cur_pc); while (!stop && n_executed < count) { // 1. Fetch an instruction from main memory. m_memory->read_value(cur_pc, cur_opcode); // 2. Decode it. ARMInstruction ins = m_dis->disassemble(cur_opcode, cur_mode); LOG_INFO("Emulating instruction @ cur_pc=0x%.8x cur_opcode=0x%.8x string='%s' size=%d decoder='%s'", cur_pc, cur_opcode, ins.toString().c_str(), ins.ins_size, ins.m_decoded_by.c_str()); // 3. Execute the instruction. m_interpreter->execute(ins); // 4. Print the status of the registers. m_contex->dump(); if (cur_pc == m_contex->PC()) { cur_pc += ins.ins_size / 8; m_contex->PC(cur_pc); } n_executed++; } } } <commit_msg>Removes overly verbose debug print<commit_after>/* * ARMEmulator.cpp * * Created on: Oct 10, 2015 * Author: anon */ #include "debug.h" #include "ARMEmulator.h" #include "ARMDisassembler.h" using namespace std; using namespace Register; using namespace Disassembler; namespace Emulator { ARMEmulator::ARMEmulator(ARMContext *context, Memory::AbstractMemory *memory, ARMMode mode, ARMVariants variant) : m_mode{mode}, m_contex{context}, m_memory{memory} { m_dis = new ARMDisassembler(variant); m_interpreter = new ARMInterpreter(*m_contex); } ARMEmulator::~ARMEmulator() { } void ARMEmulator::start(unsigned count) { bool stop = false; unsigned n_executed = 0; uint32_t cur_pc = 0; uint32_t cur_opcode = 0; ARMMode cur_mode = m_mode; m_contex->getRegister(ARM_REG_PC, cur_pc); while (!stop && n_executed < count) { // 1. Fetch an instruction from main memory. m_memory->read_value(cur_pc, cur_opcode); // 2. Decode it. ARMInstruction ins = m_dis->disassemble(cur_opcode, cur_mode); // 3. Execute the instruction. m_interpreter->execute(ins); // 4. Print the status of the registers. m_contex->dump(); if (cur_pc == m_contex->PC()) { cur_pc += ins.ins_size / 8; m_contex->PC(cur_pc); } n_executed++; } } } <|endoftext|>
<commit_before>/************************************************************************** ** ** This file is part of Qt Creator ** ** Copyright (c) 2011 Nokia Corporation and/or its subsidiary(-ies). ** ** Contact: Nokia Corporation (info@qt.nokia.com) ** ** ** GNU Lesser General Public License Usage ** ** This file may be used under the terms of the GNU Lesser General Public ** License version 2.1 as published by the Free Software Foundation and ** appearing in the file LICENSE.LGPL included in the packaging of this file. ** Please review the following information to ensure the GNU Lesser General ** Public License version 2.1 requirements will be met: ** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Nokia gives you certain additional ** rights. These rights are described in the Nokia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ** Other Usage ** ** Alternatively, this file may be used in accordance with the terms and ** conditions contained in a signed written agreement between you and Nokia. ** ** If you have questions regarding the use of this file, please contact ** Nokia at info@qt.nokia.com. ** **************************************************************************/ #include "qmljsscopeastpath.h" #include "parser/qmljsast_p.h" using namespace QmlJS; using namespace AST; ScopeAstPath::ScopeAstPath(Document::Ptr doc) : _doc(doc) { } QList<Node *> ScopeAstPath::operator()(quint32 offset) { _result.clear(); _offset = offset; if (_doc) Node::accept(_doc->ast(), this); return _result; } void ScopeAstPath::accept(Node *node) { Node::acceptChild(node, this); } bool ScopeAstPath::preVisit(Node *node) { if (Statement *stmt = node->statementCast()) { return containsOffset(stmt->firstSourceLocation(), stmt->lastSourceLocation()); } else if (ExpressionNode *exp = node->expressionCast()) { return containsOffset(exp->firstSourceLocation(), exp->lastSourceLocation()); } else if (UiObjectMember *ui = node->uiObjectMemberCast()) { return containsOffset(ui->firstSourceLocation(), ui->lastSourceLocation()); } return true; } bool ScopeAstPath::visit(UiPublicMember *node) { if (node && node->statement && node->statement->kind == node->Kind_Block && containsOffset(node->statement->firstSourceLocation(), node->statement->lastSourceLocation())) { _result.append(node); Node::accept(node->statement, this); return false; } return true; } bool ScopeAstPath::visit(UiScriptBinding *node) { if (node && node->statement && node->statement->kind == node->Kind_Block && containsOffset(node->statement->firstSourceLocation(), node->statement->lastSourceLocation())) { _result.append(node); Node::accept(node->statement, this); return false; } return true; } bool ScopeAstPath::visit(UiObjectDefinition *node) { _result.append(node); Node::accept(node->initializer, this); return false; } bool ScopeAstPath::visit(UiObjectBinding *node) { _result.append(node); Node::accept(node->initializer, this); return false; } bool ScopeAstPath::visit(FunctionDeclaration *node) { return visit(static_cast<FunctionExpression *>(node)); } bool ScopeAstPath::visit(FunctionExpression *node) { Node::accept(node->formals, this); _result.append(node); Node::accept(node->body, this); return false; } bool ScopeAstPath::containsOffset(SourceLocation start, SourceLocation end) { return _offset >= start.begin() && _offset <= end.end(); } <commit_msg>QmlJS: Clean up ScopeAstPath visitor.<commit_after>/************************************************************************** ** ** This file is part of Qt Creator ** ** Copyright (c) 2011 Nokia Corporation and/or its subsidiary(-ies). ** ** Contact: Nokia Corporation (info@qt.nokia.com) ** ** ** GNU Lesser General Public License Usage ** ** This file may be used under the terms of the GNU Lesser General Public ** License version 2.1 as published by the Free Software Foundation and ** appearing in the file LICENSE.LGPL included in the packaging of this file. ** Please review the following information to ensure the GNU Lesser General ** Public License version 2.1 requirements will be met: ** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Nokia gives you certain additional ** rights. These rights are described in the Nokia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ** Other Usage ** ** Alternatively, this file may be used in accordance with the terms and ** conditions contained in a signed written agreement between you and Nokia. ** ** If you have questions regarding the use of this file, please contact ** Nokia at info@qt.nokia.com. ** **************************************************************************/ #include "qmljsscopeastpath.h" #include "parser/qmljsast_p.h" using namespace QmlJS; using namespace AST; ScopeAstPath::ScopeAstPath(Document::Ptr doc) : _doc(doc) { } QList<Node *> ScopeAstPath::operator()(quint32 offset) { _result.clear(); _offset = offset; if (_doc) accept(_doc->ast()); return _result; } void ScopeAstPath::accept(Node *node) { Node::accept(node, this); } bool ScopeAstPath::preVisit(Node *node) { if (Statement *stmt = node->statementCast()) { return containsOffset(stmt->firstSourceLocation(), stmt->lastSourceLocation()); } else if (ExpressionNode *exp = node->expressionCast()) { return containsOffset(exp->firstSourceLocation(), exp->lastSourceLocation()); } else if (UiObjectMember *ui = node->uiObjectMemberCast()) { return containsOffset(ui->firstSourceLocation(), ui->lastSourceLocation()); } return true; } bool ScopeAstPath::visit(UiPublicMember *node) { if (node && node->statement && node->statement->kind == node->Kind_Block && containsOffset(node->statement->firstSourceLocation(), node->statement->lastSourceLocation())) { _result.append(node); accept(node->statement); return false; } return true; } bool ScopeAstPath::visit(UiScriptBinding *node) { if (node && node->statement && node->statement->kind == node->Kind_Block && containsOffset(node->statement->firstSourceLocation(), node->statement->lastSourceLocation())) { _result.append(node); accept(node->statement); return false; } return true; } bool ScopeAstPath::visit(UiObjectDefinition *node) { _result.append(node); accept(node->initializer); return false; } bool ScopeAstPath::visit(UiObjectBinding *node) { _result.append(node); accept(node->initializer); return false; } bool ScopeAstPath::visit(FunctionDeclaration *node) { return visit(static_cast<FunctionExpression *>(node)); } bool ScopeAstPath::visit(FunctionExpression *node) { accept(node->formals); _result.append(node); accept(node->body); return false; } bool ScopeAstPath::containsOffset(SourceLocation start, SourceLocation end) { return _offset >= start.begin() && _offset <= end.end(); } <|endoftext|>
<commit_before>#include "change_map.h" #include "logconsole.h" #include "entity_system.h" #include "cli_normal_chat.h" #include "srv_normal_chat.h" #include "components/basic_info.h" #include "whisper_char.h" using namespace RoseCommon; using namespace RoseCommon::Packet; void Map::change_map_request(EntitySystem& entitySystem, Entity entity, const CliChangeMapReq&) { auto logger = Core::CLog::GetLogger(Core::log_type::GENERAL).lock(); logger->trace("Map::change_map_request"); logger->trace("entity {}", entity); entitySystem.send_to(entity, SrvChangeMapReply::create()); const auto& basicInfo = entitySystem.get_component<Component::BasicInfo>(entity); Chat::send_whisper(entitySystem, entity, fmt::format("You are client {}", basicInfo.id)); entitySystem.send_nearby_except_me(SrvPlayerChar::create()); const auto& nearby_entities = entitySystem.get_nearby(entity); for (auto e : nearby_entities) { if (e != entity) { entitySystem.send_to(entity, SrvPlayerChar::create()); } } if (const auto client_ptr = registry.try_get<const Component::Client>(entity)) { if (auto client = client_ptr->client.lock()) { client->set_logged_in(); } } } <commit_msg>Update change_map.cpp<commit_after>#include "change_map.h" #include "logconsole.h" #include "entity_system.h" #include "cli_normal_chat.h" #include "srv_normal_chat.h" #include "cli_change_map_req.h" #include "components/basic_info.h" #include "whisper_char.h" using namespace RoseCommon; using namespace RoseCommon::Packet; void Map::change_map_request(EntitySystem& entitySystem, Entity entity, const CliChangeMapReq&) { auto logger = Core::CLog::GetLogger(Core::log_type::GENERAL).lock(); logger->trace("Map::change_map_request"); logger->trace("entity {}", entity); entitySystem.send_to(entity, SrvChangeMapReply::create()); const auto& basicInfo = entitySystem.get_component<Component::BasicInfo>(entity); Chat::send_whisper(entitySystem, entity, fmt::format("You are client {}", basicInfo.id)); entitySystem.send_nearby_except_me(SrvPlayerChar::create()); const auto& nearby_entities = entitySystem.get_nearby(entity); for (auto e : nearby_entities) { if (e != entity) { entitySystem.send_to(entity, SrvPlayerChar::create()); } } if (const auto client_ptr = registry.try_get<const Component::Client>(entity)) { if (auto client = client_ptr->client.lock()) { client->set_logged_in(); } } } <|endoftext|>
<commit_before>#include "Ext.h" #include "preprocessor/llvm_includes_start.h" #include <llvm/IR/IntrinsicInst.h> #include "preprocessor/llvm_includes_end.h" #include "RuntimeManager.h" #include "Memory.h" #include "Type.h" #include "Endianness.h" namespace dev { namespace eth { namespace jit { Ext::Ext(RuntimeManager& _runtimeManager, Memory& _memoryMan): RuntimeHelper(_runtimeManager), m_memoryMan(_memoryMan) { m_funcs = decltype(m_funcs)(); m_argAllocas = decltype(m_argAllocas)(); m_size = m_builder.CreateAlloca(Type::Size, nullptr, "env.size"); } using FuncDesc = std::tuple<char const*, llvm::FunctionType*>; llvm::FunctionType* getFunctionType(llvm::Type* _returnType, std::initializer_list<llvm::Type*> const& _argsTypes) { return llvm::FunctionType::get(_returnType, llvm::ArrayRef<llvm::Type*>{_argsTypes.begin(), _argsTypes.size()}, false); } std::array<FuncDesc, sizeOf<EnvFunc>::value> const& getEnvFuncDescs() { static std::array<FuncDesc, sizeOf<EnvFunc>::value> descs{{ FuncDesc{"env_sload", getFunctionType(Type::Void, {Type::EnvPtr, Type::WordPtr, Type::WordPtr})}, FuncDesc{"env_sstore", getFunctionType(Type::Void, {Type::EnvPtr, Type::WordPtr, Type::WordPtr})}, FuncDesc{"env_sha3", getFunctionType(Type::Void, {Type::BytePtr, Type::Size, Type::WordPtr})}, FuncDesc{"env_balance", getFunctionType(Type::Void, {Type::EnvPtr, Type::WordPtr, Type::WordPtr})}, FuncDesc{"env_create", getFunctionType(Type::Void, {Type::EnvPtr, Type::GasPtr, Type::WordPtr, Type::BytePtr, Type::Size, Type::WordPtr})}, FuncDesc{"env_call", getFunctionType(Type::Bool, {Type::EnvPtr, Type::GasPtr, Type::Gas, Type::WordPtr, Type::WordPtr, Type::BytePtr, Type::Size, Type::BytePtr, Type::Size, Type::WordPtr})}, FuncDesc{"env_log", getFunctionType(Type::Void, {Type::EnvPtr, Type::BytePtr, Type::Size, Type::WordPtr, Type::WordPtr, Type::WordPtr, Type::WordPtr})}, FuncDesc{"env_blockhash", getFunctionType(Type::Void, {Type::EnvPtr, Type::WordPtr, Type::WordPtr})}, FuncDesc{"env_extcode", getFunctionType(Type::BytePtr, {Type::EnvPtr, Type::WordPtr, Type::Size->getPointerTo()})}, }}; return descs; } llvm::Function* createFunc(EnvFunc _id, llvm::Module* _module) { auto&& desc = getEnvFuncDescs()[static_cast<size_t>(_id)]; return llvm::Function::Create(std::get<1>(desc), llvm::Function::ExternalLinkage, std::get<0>(desc), _module); } llvm::Value* Ext::getArgAlloca() { auto& a = m_argAllocas[m_argCounter]; if (!a) { InsertPointGuard g{getBuilder()}; auto allocaIt = getMainFunction()->front().begin(); std::advance(allocaIt, m_argCounter); // Skip already created allocas getBuilder().SetInsertPoint(allocaIt); a = getBuilder().CreateAlloca(Type::Word, nullptr, {"a.", std::to_string(m_argCounter)}); } ++m_argCounter; return a; } llvm::Value* Ext::byPtr(llvm::Value* _value) { auto a = getArgAlloca(); getBuilder().CreateStore(_value, a); return a; } llvm::CallInst* Ext::createCall(EnvFunc _funcId, std::initializer_list<llvm::Value*> const& _args) { auto& func = m_funcs[static_cast<size_t>(_funcId)]; if (!func) func = createFunc(_funcId, getModule()); m_argCounter = 0; return getBuilder().CreateCall(func, {_args.begin(), _args.size()}); } llvm::Value* Ext::sload(llvm::Value* _index) { auto ret = getArgAlloca(); createCall(EnvFunc::sload, {getRuntimeManager().getEnvPtr(), byPtr(_index), ret}); // Uses native endianness return m_builder.CreateLoad(ret); } void Ext::sstore(llvm::Value* _index, llvm::Value* _value) { createCall(EnvFunc::sstore, {getRuntimeManager().getEnvPtr(), byPtr(_index), byPtr(_value)}); // Uses native endianness } llvm::Value* Ext::calldataload(llvm::Value* _idx) { auto ret = getArgAlloca(); auto result = m_builder.CreateBitCast(ret, Type::BytePtr); auto callDataSize = getRuntimeManager().getCallDataSize(); auto callDataSize64 = m_builder.CreateTrunc(callDataSize, Type::Size); auto idxValid = m_builder.CreateICmpULT(_idx, callDataSize); auto idx = m_builder.CreateTrunc(m_builder.CreateSelect(idxValid, _idx, callDataSize), Type::Size, "idx"); auto end = m_builder.CreateNUWAdd(idx, m_builder.getInt64(32)); end = m_builder.CreateSelect(m_builder.CreateICmpULE(end, callDataSize64), end, callDataSize64); auto copySize = m_builder.CreateNUWSub(end, idx); auto padSize = m_builder.CreateNUWSub(m_builder.getInt64(32), copySize); auto dataBegin = m_builder.CreateGEP(Type::Byte, getRuntimeManager().getCallData(), idx); m_builder.CreateMemCpy(result, dataBegin, copySize, 1); auto pad = m_builder.CreateGEP(Type::Byte, result, copySize); m_builder.CreateMemSet(pad, m_builder.getInt8(0), padSize, 1); return Endianness::toNative(m_builder, m_builder.CreateLoad(ret)); } llvm::Value* Ext::balance(llvm::Value* _address) { auto address = Endianness::toBE(m_builder, _address); auto ret = getArgAlloca(); createCall(EnvFunc::balance, {getRuntimeManager().getEnvPtr(), byPtr(address), ret}); return m_builder.CreateLoad(ret); } llvm::Value* Ext::blockhash(llvm::Value* _number) { auto hash = getArgAlloca(); createCall(EnvFunc::blockhash, {getRuntimeManager().getEnvPtr(), byPtr(_number), hash}); hash = m_builder.CreateLoad(hash); return Endianness::toNative(getBuilder(), hash); } llvm::Value* Ext::create(llvm::Value* _endowment, llvm::Value* _initOff, llvm::Value* _initSize) { auto ret = getArgAlloca(); auto begin = m_memoryMan.getBytePtr(_initOff); auto size = m_builder.CreateTrunc(_initSize, Type::Size, "size"); createCall(EnvFunc::create, {getRuntimeManager().getEnvPtr(), getRuntimeManager().getGasPtr(), byPtr(_endowment), begin, size, ret}); llvm::Value* address = m_builder.CreateLoad(ret); address = Endianness::toNative(m_builder, address); return address; } llvm::Value* Ext::call(llvm::Value* _callGas, llvm::Value* _receiveAddress, llvm::Value* _value, llvm::Value* _inOff, llvm::Value* _inSize, llvm::Value* _outOff, llvm::Value* _outSize, llvm::Value* _codeAddress) { auto receiveAddress = Endianness::toBE(m_builder, _receiveAddress); auto inBeg = m_memoryMan.getBytePtr(_inOff); auto inSize = m_builder.CreateTrunc(_inSize, Type::Size, "in.size"); auto outBeg = m_memoryMan.getBytePtr(_outOff); auto outSize = m_builder.CreateTrunc(_outSize, Type::Size, "out.size"); auto codeAddress = Endianness::toBE(m_builder, _codeAddress); auto callGas = m_builder.CreateSelect( m_builder.CreateICmpULE(_callGas, m_builder.CreateZExt(Constant::gasMax, Type::Word)), m_builder.CreateTrunc(_callGas, Type::Gas), Constant::gasMax); auto ret = createCall(EnvFunc::call, {getRuntimeManager().getEnvPtr(), getRuntimeManager().getGasPtr(), callGas, byPtr(receiveAddress), byPtr(_value), inBeg, inSize, outBeg, outSize, byPtr(codeAddress)}); return m_builder.CreateZExt(ret, Type::Word, "ret"); } llvm::Value* Ext::sha3(llvm::Value* _inOff, llvm::Value* _inSize) { auto begin = m_memoryMan.getBytePtr(_inOff); auto size = m_builder.CreateTrunc(_inSize, Type::Size, "size"); auto ret = getArgAlloca(); createCall(EnvFunc::sha3, {begin, size, ret}); llvm::Value* hash = m_builder.CreateLoad(ret); hash = Endianness::toNative(m_builder, hash); return hash; } MemoryRef Ext::extcode(llvm::Value* _addr) { auto addr = Endianness::toBE(m_builder, _addr); auto code = createCall(EnvFunc::extcode, {getRuntimeManager().getEnvPtr(), byPtr(addr), m_size}); auto codeSize = m_builder.CreateLoad(m_size); auto codeSize256 = m_builder.CreateZExt(codeSize, Type::Word); return {code, codeSize256}; } void Ext::log(llvm::Value* _memIdx, llvm::Value* _numBytes, std::array<llvm::Value*,4> const& _topics) { auto begin = m_memoryMan.getBytePtr(_memIdx); auto size = m_builder.CreateTrunc(_numBytes, Type::Size, "size"); llvm::Value* args[] = {getRuntimeManager().getEnvPtr(), begin, size, getArgAlloca(), getArgAlloca(), getArgAlloca(), getArgAlloca()}; auto topicArgPtr = &args[3]; for (auto&& topic : _topics) { if (topic) m_builder.CreateStore(Endianness::toBE(m_builder, topic), *topicArgPtr); else *topicArgPtr = llvm::ConstantPointerNull::get(Type::WordPtr); ++topicArgPtr; } createCall(EnvFunc::log, {args[0], args[1], args[2], args[3], args[4], args[5], args[6]}); // TODO: use std::initializer_list<> } } } } <commit_msg>Release aquired arg allocas in Ext::calldataload.<commit_after>#include "Ext.h" #include "preprocessor/llvm_includes_start.h" #include <llvm/IR/IntrinsicInst.h> #include "preprocessor/llvm_includes_end.h" #include "RuntimeManager.h" #include "Memory.h" #include "Type.h" #include "Endianness.h" namespace dev { namespace eth { namespace jit { Ext::Ext(RuntimeManager& _runtimeManager, Memory& _memoryMan): RuntimeHelper(_runtimeManager), m_memoryMan(_memoryMan) { m_funcs = decltype(m_funcs)(); m_argAllocas = decltype(m_argAllocas)(); m_size = m_builder.CreateAlloca(Type::Size, nullptr, "env.size"); } using FuncDesc = std::tuple<char const*, llvm::FunctionType*>; llvm::FunctionType* getFunctionType(llvm::Type* _returnType, std::initializer_list<llvm::Type*> const& _argsTypes) { return llvm::FunctionType::get(_returnType, llvm::ArrayRef<llvm::Type*>{_argsTypes.begin(), _argsTypes.size()}, false); } std::array<FuncDesc, sizeOf<EnvFunc>::value> const& getEnvFuncDescs() { static std::array<FuncDesc, sizeOf<EnvFunc>::value> descs{{ FuncDesc{"env_sload", getFunctionType(Type::Void, {Type::EnvPtr, Type::WordPtr, Type::WordPtr})}, FuncDesc{"env_sstore", getFunctionType(Type::Void, {Type::EnvPtr, Type::WordPtr, Type::WordPtr})}, FuncDesc{"env_sha3", getFunctionType(Type::Void, {Type::BytePtr, Type::Size, Type::WordPtr})}, FuncDesc{"env_balance", getFunctionType(Type::Void, {Type::EnvPtr, Type::WordPtr, Type::WordPtr})}, FuncDesc{"env_create", getFunctionType(Type::Void, {Type::EnvPtr, Type::GasPtr, Type::WordPtr, Type::BytePtr, Type::Size, Type::WordPtr})}, FuncDesc{"env_call", getFunctionType(Type::Bool, {Type::EnvPtr, Type::GasPtr, Type::Gas, Type::WordPtr, Type::WordPtr, Type::BytePtr, Type::Size, Type::BytePtr, Type::Size, Type::WordPtr})}, FuncDesc{"env_log", getFunctionType(Type::Void, {Type::EnvPtr, Type::BytePtr, Type::Size, Type::WordPtr, Type::WordPtr, Type::WordPtr, Type::WordPtr})}, FuncDesc{"env_blockhash", getFunctionType(Type::Void, {Type::EnvPtr, Type::WordPtr, Type::WordPtr})}, FuncDesc{"env_extcode", getFunctionType(Type::BytePtr, {Type::EnvPtr, Type::WordPtr, Type::Size->getPointerTo()})}, }}; return descs; } llvm::Function* createFunc(EnvFunc _id, llvm::Module* _module) { auto&& desc = getEnvFuncDescs()[static_cast<size_t>(_id)]; return llvm::Function::Create(std::get<1>(desc), llvm::Function::ExternalLinkage, std::get<0>(desc), _module); } llvm::Value* Ext::getArgAlloca() { auto& a = m_argAllocas[m_argCounter]; if (!a) { InsertPointGuard g{getBuilder()}; auto allocaIt = getMainFunction()->front().begin(); std::advance(allocaIt, m_argCounter); // Skip already created allocas getBuilder().SetInsertPoint(allocaIt); a = getBuilder().CreateAlloca(Type::Word, nullptr, {"a.", std::to_string(m_argCounter)}); } ++m_argCounter; return a; } llvm::Value* Ext::byPtr(llvm::Value* _value) { auto a = getArgAlloca(); getBuilder().CreateStore(_value, a); return a; } llvm::CallInst* Ext::createCall(EnvFunc _funcId, std::initializer_list<llvm::Value*> const& _args) { auto& func = m_funcs[static_cast<size_t>(_funcId)]; if (!func) func = createFunc(_funcId, getModule()); m_argCounter = 0; return getBuilder().CreateCall(func, {_args.begin(), _args.size()}); } llvm::Value* Ext::sload(llvm::Value* _index) { auto ret = getArgAlloca(); createCall(EnvFunc::sload, {getRuntimeManager().getEnvPtr(), byPtr(_index), ret}); // Uses native endianness return m_builder.CreateLoad(ret); } void Ext::sstore(llvm::Value* _index, llvm::Value* _value) { createCall(EnvFunc::sstore, {getRuntimeManager().getEnvPtr(), byPtr(_index), byPtr(_value)}); // Uses native endianness } llvm::Value* Ext::calldataload(llvm::Value* _idx) { auto ret = getArgAlloca(); auto result = m_builder.CreateBitCast(ret, Type::BytePtr); auto callDataSize = getRuntimeManager().getCallDataSize(); auto callDataSize64 = m_builder.CreateTrunc(callDataSize, Type::Size); auto idxValid = m_builder.CreateICmpULT(_idx, callDataSize); auto idx = m_builder.CreateTrunc(m_builder.CreateSelect(idxValid, _idx, callDataSize), Type::Size, "idx"); auto end = m_builder.CreateNUWAdd(idx, m_builder.getInt64(32)); end = m_builder.CreateSelect(m_builder.CreateICmpULE(end, callDataSize64), end, callDataSize64); auto copySize = m_builder.CreateNUWSub(end, idx); auto padSize = m_builder.CreateNUWSub(m_builder.getInt64(32), copySize); auto dataBegin = m_builder.CreateGEP(Type::Byte, getRuntimeManager().getCallData(), idx); m_builder.CreateMemCpy(result, dataBegin, copySize, 1); auto pad = m_builder.CreateGEP(Type::Byte, result, copySize); m_builder.CreateMemSet(pad, m_builder.getInt8(0), padSize, 1); m_argCounter = 0; // Release args allocas. TODO: This is a bad design return Endianness::toNative(m_builder, m_builder.CreateLoad(ret)); } llvm::Value* Ext::balance(llvm::Value* _address) { auto address = Endianness::toBE(m_builder, _address); auto ret = getArgAlloca(); createCall(EnvFunc::balance, {getRuntimeManager().getEnvPtr(), byPtr(address), ret}); return m_builder.CreateLoad(ret); } llvm::Value* Ext::blockhash(llvm::Value* _number) { auto hash = getArgAlloca(); createCall(EnvFunc::blockhash, {getRuntimeManager().getEnvPtr(), byPtr(_number), hash}); hash = m_builder.CreateLoad(hash); return Endianness::toNative(getBuilder(), hash); } llvm::Value* Ext::create(llvm::Value* _endowment, llvm::Value* _initOff, llvm::Value* _initSize) { auto ret = getArgAlloca(); auto begin = m_memoryMan.getBytePtr(_initOff); auto size = m_builder.CreateTrunc(_initSize, Type::Size, "size"); createCall(EnvFunc::create, {getRuntimeManager().getEnvPtr(), getRuntimeManager().getGasPtr(), byPtr(_endowment), begin, size, ret}); llvm::Value* address = m_builder.CreateLoad(ret); address = Endianness::toNative(m_builder, address); return address; } llvm::Value* Ext::call(llvm::Value* _callGas, llvm::Value* _receiveAddress, llvm::Value* _value, llvm::Value* _inOff, llvm::Value* _inSize, llvm::Value* _outOff, llvm::Value* _outSize, llvm::Value* _codeAddress) { auto receiveAddress = Endianness::toBE(m_builder, _receiveAddress); auto inBeg = m_memoryMan.getBytePtr(_inOff); auto inSize = m_builder.CreateTrunc(_inSize, Type::Size, "in.size"); auto outBeg = m_memoryMan.getBytePtr(_outOff); auto outSize = m_builder.CreateTrunc(_outSize, Type::Size, "out.size"); auto codeAddress = Endianness::toBE(m_builder, _codeAddress); auto callGas = m_builder.CreateSelect( m_builder.CreateICmpULE(_callGas, m_builder.CreateZExt(Constant::gasMax, Type::Word)), m_builder.CreateTrunc(_callGas, Type::Gas), Constant::gasMax); auto ret = createCall(EnvFunc::call, {getRuntimeManager().getEnvPtr(), getRuntimeManager().getGasPtr(), callGas, byPtr(receiveAddress), byPtr(_value), inBeg, inSize, outBeg, outSize, byPtr(codeAddress)}); return m_builder.CreateZExt(ret, Type::Word, "ret"); } llvm::Value* Ext::sha3(llvm::Value* _inOff, llvm::Value* _inSize) { auto begin = m_memoryMan.getBytePtr(_inOff); auto size = m_builder.CreateTrunc(_inSize, Type::Size, "size"); auto ret = getArgAlloca(); createCall(EnvFunc::sha3, {begin, size, ret}); llvm::Value* hash = m_builder.CreateLoad(ret); hash = Endianness::toNative(m_builder, hash); return hash; } MemoryRef Ext::extcode(llvm::Value* _addr) { auto addr = Endianness::toBE(m_builder, _addr); auto code = createCall(EnvFunc::extcode, {getRuntimeManager().getEnvPtr(), byPtr(addr), m_size}); auto codeSize = m_builder.CreateLoad(m_size); auto codeSize256 = m_builder.CreateZExt(codeSize, Type::Word); return {code, codeSize256}; } void Ext::log(llvm::Value* _memIdx, llvm::Value* _numBytes, std::array<llvm::Value*,4> const& _topics) { auto begin = m_memoryMan.getBytePtr(_memIdx); auto size = m_builder.CreateTrunc(_numBytes, Type::Size, "size"); llvm::Value* args[] = {getRuntimeManager().getEnvPtr(), begin, size, getArgAlloca(), getArgAlloca(), getArgAlloca(), getArgAlloca()}; auto topicArgPtr = &args[3]; for (auto&& topic : _topics) { if (topic) m_builder.CreateStore(Endianness::toBE(m_builder, topic), *topicArgPtr); else *topicArgPtr = llvm::ConstantPointerNull::get(Type::WordPtr); ++topicArgPtr; } createCall(EnvFunc::log, {args[0], args[1], args[2], args[3], args[4], args[5], args[6]}); // TODO: use std::initializer_list<> } } } } <|endoftext|>
<commit_before>#include "Ext.h" #include "preprocessor/llvm_includes_start.h" #include <llvm/IR/IntrinsicInst.h> #include "preprocessor/llvm_includes_end.h" #include "RuntimeManager.h" #include "Memory.h" #include "Type.h" #include "Endianness.h" namespace dev { namespace eth { namespace jit { Ext::Ext(RuntimeManager& _runtimeManager, Memory& _memoryMan): RuntimeHelper(_runtimeManager), m_memoryMan(_memoryMan) { m_funcs = decltype(m_funcs)(); m_argAllocas = decltype(m_argAllocas)(); m_size = m_builder.CreateAlloca(Type::Size, nullptr, "env.size"); } using FuncDesc = std::tuple<char const*, llvm::FunctionType*>; llvm::FunctionType* getFunctionType(llvm::Type* _returnType, std::initializer_list<llvm::Type*> const& _argsTypes) { return llvm::FunctionType::get(_returnType, llvm::ArrayRef<llvm::Type*>{_argsTypes.begin(), _argsTypes.size()}, false); } std::array<FuncDesc, sizeOf<EnvFunc>::value> const& getEnvFuncDescs() { static std::array<FuncDesc, sizeOf<EnvFunc>::value> descs{{ FuncDesc{"env_sload", getFunctionType(Type::Void, {Type::EnvPtr, Type::WordPtr, Type::WordPtr})}, FuncDesc{"env_sstore", getFunctionType(Type::Void, {Type::EnvPtr, Type::WordPtr, Type::WordPtr})}, FuncDesc{"env_sha3", getFunctionType(Type::Void, {Type::BytePtr, Type::Size, Type::WordPtr})}, FuncDesc{"env_balance", getFunctionType(Type::Void, {Type::EnvPtr, Type::WordPtr, Type::WordPtr})}, FuncDesc{"env_create", getFunctionType(Type::Void, {Type::EnvPtr, Type::GasPtr, Type::WordPtr, Type::BytePtr, Type::Size, Type::WordPtr})}, FuncDesc{"env_call", getFunctionType(Type::Bool, {Type::EnvPtr, Type::GasPtr, Type::Gas, Type::WordPtr, Type::WordPtr, Type::BytePtr, Type::Size, Type::BytePtr, Type::Size, Type::WordPtr})}, FuncDesc{"env_log", getFunctionType(Type::Void, {Type::EnvPtr, Type::BytePtr, Type::Size, Type::WordPtr, Type::WordPtr, Type::WordPtr, Type::WordPtr})}, FuncDesc{"env_blockhash", getFunctionType(Type::Void, {Type::EnvPtr, Type::WordPtr, Type::WordPtr})}, FuncDesc{"env_extcode", getFunctionType(Type::BytePtr, {Type::EnvPtr, Type::WordPtr, Type::Size->getPointerTo()})}, }}; return descs; } llvm::Function* createFunc(EnvFunc _id, llvm::Module* _module) { auto&& desc = getEnvFuncDescs()[static_cast<size_t>(_id)]; return llvm::Function::Create(std::get<1>(desc), llvm::Function::ExternalLinkage, std::get<0>(desc), _module); } llvm::Value* Ext::getArgAlloca() { auto& a = m_argAllocas[m_argCounter]; if (!a) { InsertPointGuard g{getBuilder()}; auto allocaIt = getMainFunction()->front().begin(); std::advance(allocaIt, m_argCounter); // Skip already created allocas getBuilder().SetInsertPoint(allocaIt); a = getBuilder().CreateAlloca(Type::Word, nullptr, {"a.", std::to_string(m_argCounter)}); } ++m_argCounter; return a; } llvm::Value* Ext::byPtr(llvm::Value* _value) { auto a = getArgAlloca(); getBuilder().CreateStore(_value, a); return a; } llvm::CallInst* Ext::createCall(EnvFunc _funcId, std::initializer_list<llvm::Value*> const& _args) { auto& func = m_funcs[static_cast<size_t>(_funcId)]; if (!func) func = createFunc(_funcId, getModule()); m_argCounter = 0; return getBuilder().CreateCall(func, {_args.begin(), _args.size()}); } llvm::Value* Ext::sload(llvm::Value* _index) { auto ret = getArgAlloca(); createCall(EnvFunc::sload, {getRuntimeManager().getEnvPtr(), byPtr(_index), ret}); // Uses native endianness return m_builder.CreateLoad(ret); } void Ext::sstore(llvm::Value* _index, llvm::Value* _value) { createCall(EnvFunc::sstore, {getRuntimeManager().getEnvPtr(), byPtr(_index), byPtr(_value)}); // Uses native endianness } llvm::Value* Ext::calldataload(llvm::Value* _idx) { auto ret = getArgAlloca(); auto result = m_builder.CreateBitCast(ret, Type::BytePtr); auto callDataSize = getRuntimeManager().getCallDataSize(); auto callDataSize64 = m_builder.CreateTrunc(callDataSize, Type::Size); auto idxValid = m_builder.CreateICmpULT(_idx, callDataSize); auto idx = m_builder.CreateTrunc(m_builder.CreateSelect(idxValid, _idx, callDataSize), Type::Size, "idx"); auto end = m_builder.CreateNUWAdd(idx, m_builder.getInt64(32)); end = m_builder.CreateSelect(m_builder.CreateICmpULE(end, callDataSize64), end, callDataSize64); auto copySize = m_builder.CreateNUWSub(end, idx); auto padSize = m_builder.CreateNUWSub(m_builder.getInt64(32), copySize); auto dataBegin = m_builder.CreateGEP(Type::Byte, getRuntimeManager().getCallData(), idx); m_builder.CreateMemCpy(result, dataBegin, copySize, 1); auto pad = m_builder.CreateGEP(Type::Byte, result, copySize); m_builder.CreateMemSet(pad, m_builder.getInt8(0), padSize, 1); return Endianness::toNative(m_builder, m_builder.CreateLoad(ret)); } llvm::Value* Ext::balance(llvm::Value* _address) { auto address = Endianness::toBE(m_builder, _address); auto ret = getArgAlloca(); createCall(EnvFunc::balance, {getRuntimeManager().getEnvPtr(), byPtr(address), ret}); return m_builder.CreateLoad(ret); } llvm::Value* Ext::blockhash(llvm::Value* _number) { auto hash = getArgAlloca(); createCall(EnvFunc::blockhash, {getRuntimeManager().getEnvPtr(), byPtr(_number), hash}); hash = m_builder.CreateLoad(hash); return Endianness::toNative(getBuilder(), hash); } llvm::Value* Ext::create(llvm::Value* _endowment, llvm::Value* _initOff, llvm::Value* _initSize) { auto ret = getArgAlloca(); auto begin = m_memoryMan.getBytePtr(_initOff); auto size = m_builder.CreateTrunc(_initSize, Type::Size, "size"); createCall(EnvFunc::create, {getRuntimeManager().getEnvPtr(), getRuntimeManager().getGasPtr(), byPtr(_endowment), begin, size, ret}); llvm::Value* address = m_builder.CreateLoad(ret); address = Endianness::toNative(m_builder, address); return address; } llvm::Value* Ext::call(llvm::Value* _callGas, llvm::Value* _receiveAddress, llvm::Value* _value, llvm::Value* _inOff, llvm::Value* _inSize, llvm::Value* _outOff, llvm::Value* _outSize, llvm::Value* _codeAddress) { auto receiveAddress = Endianness::toBE(m_builder, _receiveAddress); auto inBeg = m_memoryMan.getBytePtr(_inOff); auto inSize = m_builder.CreateTrunc(_inSize, Type::Size, "in.size"); auto outBeg = m_memoryMan.getBytePtr(_outOff); auto outSize = m_builder.CreateTrunc(_outSize, Type::Size, "out.size"); auto codeAddress = Endianness::toBE(m_builder, _codeAddress); auto callGas = m_builder.CreateSelect( m_builder.CreateICmpULE(_callGas, m_builder.CreateZExt(Constant::gasMax, Type::Word)), m_builder.CreateTrunc(_callGas, Type::Gas), Constant::gasMax); auto ret = createCall(EnvFunc::call, {getRuntimeManager().getEnvPtr(), getRuntimeManager().getGasPtr(), callGas, byPtr(receiveAddress), byPtr(_value), inBeg, inSize, outBeg, outSize, byPtr(codeAddress)}); return m_builder.CreateZExt(ret, Type::Word, "ret"); } llvm::Value* Ext::sha3(llvm::Value* _inOff, llvm::Value* _inSize) { auto begin = m_memoryMan.getBytePtr(_inOff); auto size = m_builder.CreateTrunc(_inSize, Type::Size, "size"); auto ret = getArgAlloca(); createCall(EnvFunc::sha3, {begin, size, ret}); llvm::Value* hash = m_builder.CreateLoad(ret); hash = Endianness::toNative(m_builder, hash); return hash; } MemoryRef Ext::extcode(llvm::Value* _addr) { auto addr = Endianness::toBE(m_builder, _addr); auto code = createCall(EnvFunc::extcode, {getRuntimeManager().getEnvPtr(), byPtr(addr), m_size}); auto codeSize = m_builder.CreateLoad(m_size); auto codeSize256 = m_builder.CreateZExt(codeSize, Type::Word); return {code, codeSize256}; } void Ext::log(llvm::Value* _memIdx, llvm::Value* _numBytes, std::array<llvm::Value*,4> const& _topics) { auto begin = m_memoryMan.getBytePtr(_memIdx); auto size = m_builder.CreateTrunc(_numBytes, Type::Size, "size"); llvm::Value* args[] = {getRuntimeManager().getEnvPtr(), begin, size, getArgAlloca(), getArgAlloca(), getArgAlloca(), getArgAlloca()}; auto topicArgPtr = &args[3]; for (auto&& topic : _topics) { if (topic) m_builder.CreateStore(Endianness::toBE(m_builder, topic), *topicArgPtr); else *topicArgPtr = llvm::ConstantPointerNull::get(Type::WordPtr); ++topicArgPtr; } createCall(EnvFunc::log, {args[0], args[1], args[2], args[3], args[4], args[5], args[6]}); // TODO: use std::initializer_list<> } } } } <commit_msg>Release aquired arg allocas in Ext::calldataload.<commit_after>#include "Ext.h" #include "preprocessor/llvm_includes_start.h" #include <llvm/IR/IntrinsicInst.h> #include "preprocessor/llvm_includes_end.h" #include "RuntimeManager.h" #include "Memory.h" #include "Type.h" #include "Endianness.h" namespace dev { namespace eth { namespace jit { Ext::Ext(RuntimeManager& _runtimeManager, Memory& _memoryMan): RuntimeHelper(_runtimeManager), m_memoryMan(_memoryMan) { m_funcs = decltype(m_funcs)(); m_argAllocas = decltype(m_argAllocas)(); m_size = m_builder.CreateAlloca(Type::Size, nullptr, "env.size"); } using FuncDesc = std::tuple<char const*, llvm::FunctionType*>; llvm::FunctionType* getFunctionType(llvm::Type* _returnType, std::initializer_list<llvm::Type*> const& _argsTypes) { return llvm::FunctionType::get(_returnType, llvm::ArrayRef<llvm::Type*>{_argsTypes.begin(), _argsTypes.size()}, false); } std::array<FuncDesc, sizeOf<EnvFunc>::value> const& getEnvFuncDescs() { static std::array<FuncDesc, sizeOf<EnvFunc>::value> descs{{ FuncDesc{"env_sload", getFunctionType(Type::Void, {Type::EnvPtr, Type::WordPtr, Type::WordPtr})}, FuncDesc{"env_sstore", getFunctionType(Type::Void, {Type::EnvPtr, Type::WordPtr, Type::WordPtr})}, FuncDesc{"env_sha3", getFunctionType(Type::Void, {Type::BytePtr, Type::Size, Type::WordPtr})}, FuncDesc{"env_balance", getFunctionType(Type::Void, {Type::EnvPtr, Type::WordPtr, Type::WordPtr})}, FuncDesc{"env_create", getFunctionType(Type::Void, {Type::EnvPtr, Type::GasPtr, Type::WordPtr, Type::BytePtr, Type::Size, Type::WordPtr})}, FuncDesc{"env_call", getFunctionType(Type::Bool, {Type::EnvPtr, Type::GasPtr, Type::Gas, Type::WordPtr, Type::WordPtr, Type::BytePtr, Type::Size, Type::BytePtr, Type::Size, Type::WordPtr})}, FuncDesc{"env_log", getFunctionType(Type::Void, {Type::EnvPtr, Type::BytePtr, Type::Size, Type::WordPtr, Type::WordPtr, Type::WordPtr, Type::WordPtr})}, FuncDesc{"env_blockhash", getFunctionType(Type::Void, {Type::EnvPtr, Type::WordPtr, Type::WordPtr})}, FuncDesc{"env_extcode", getFunctionType(Type::BytePtr, {Type::EnvPtr, Type::WordPtr, Type::Size->getPointerTo()})}, }}; return descs; } llvm::Function* createFunc(EnvFunc _id, llvm::Module* _module) { auto&& desc = getEnvFuncDescs()[static_cast<size_t>(_id)]; return llvm::Function::Create(std::get<1>(desc), llvm::Function::ExternalLinkage, std::get<0>(desc), _module); } llvm::Value* Ext::getArgAlloca() { auto& a = m_argAllocas[m_argCounter]; if (!a) { InsertPointGuard g{getBuilder()}; auto allocaIt = getMainFunction()->front().begin(); std::advance(allocaIt, m_argCounter); // Skip already created allocas getBuilder().SetInsertPoint(allocaIt); a = getBuilder().CreateAlloca(Type::Word, nullptr, {"a.", std::to_string(m_argCounter)}); } ++m_argCounter; return a; } llvm::Value* Ext::byPtr(llvm::Value* _value) { auto a = getArgAlloca(); getBuilder().CreateStore(_value, a); return a; } llvm::CallInst* Ext::createCall(EnvFunc _funcId, std::initializer_list<llvm::Value*> const& _args) { auto& func = m_funcs[static_cast<size_t>(_funcId)]; if (!func) func = createFunc(_funcId, getModule()); m_argCounter = 0; return getBuilder().CreateCall(func, {_args.begin(), _args.size()}); } llvm::Value* Ext::sload(llvm::Value* _index) { auto ret = getArgAlloca(); createCall(EnvFunc::sload, {getRuntimeManager().getEnvPtr(), byPtr(_index), ret}); // Uses native endianness return m_builder.CreateLoad(ret); } void Ext::sstore(llvm::Value* _index, llvm::Value* _value) { createCall(EnvFunc::sstore, {getRuntimeManager().getEnvPtr(), byPtr(_index), byPtr(_value)}); // Uses native endianness } llvm::Value* Ext::calldataload(llvm::Value* _idx) { auto ret = getArgAlloca(); auto result = m_builder.CreateBitCast(ret, Type::BytePtr); auto callDataSize = getRuntimeManager().getCallDataSize(); auto callDataSize64 = m_builder.CreateTrunc(callDataSize, Type::Size); auto idxValid = m_builder.CreateICmpULT(_idx, callDataSize); auto idx = m_builder.CreateTrunc(m_builder.CreateSelect(idxValid, _idx, callDataSize), Type::Size, "idx"); auto end = m_builder.CreateNUWAdd(idx, m_builder.getInt64(32)); end = m_builder.CreateSelect(m_builder.CreateICmpULE(end, callDataSize64), end, callDataSize64); auto copySize = m_builder.CreateNUWSub(end, idx); auto padSize = m_builder.CreateNUWSub(m_builder.getInt64(32), copySize); auto dataBegin = m_builder.CreateGEP(Type::Byte, getRuntimeManager().getCallData(), idx); m_builder.CreateMemCpy(result, dataBegin, copySize, 1); auto pad = m_builder.CreateGEP(Type::Byte, result, copySize); m_builder.CreateMemSet(pad, m_builder.getInt8(0), padSize, 1); m_argCounter = 0; // Release args allocas. TODO: This is a bad design return Endianness::toNative(m_builder, m_builder.CreateLoad(ret)); } llvm::Value* Ext::balance(llvm::Value* _address) { auto address = Endianness::toBE(m_builder, _address); auto ret = getArgAlloca(); createCall(EnvFunc::balance, {getRuntimeManager().getEnvPtr(), byPtr(address), ret}); return m_builder.CreateLoad(ret); } llvm::Value* Ext::blockhash(llvm::Value* _number) { auto hash = getArgAlloca(); createCall(EnvFunc::blockhash, {getRuntimeManager().getEnvPtr(), byPtr(_number), hash}); hash = m_builder.CreateLoad(hash); return Endianness::toNative(getBuilder(), hash); } llvm::Value* Ext::create(llvm::Value* _endowment, llvm::Value* _initOff, llvm::Value* _initSize) { auto ret = getArgAlloca(); auto begin = m_memoryMan.getBytePtr(_initOff); auto size = m_builder.CreateTrunc(_initSize, Type::Size, "size"); createCall(EnvFunc::create, {getRuntimeManager().getEnvPtr(), getRuntimeManager().getGasPtr(), byPtr(_endowment), begin, size, ret}); llvm::Value* address = m_builder.CreateLoad(ret); address = Endianness::toNative(m_builder, address); return address; } llvm::Value* Ext::call(llvm::Value* _callGas, llvm::Value* _receiveAddress, llvm::Value* _value, llvm::Value* _inOff, llvm::Value* _inSize, llvm::Value* _outOff, llvm::Value* _outSize, llvm::Value* _codeAddress) { auto receiveAddress = Endianness::toBE(m_builder, _receiveAddress); auto inBeg = m_memoryMan.getBytePtr(_inOff); auto inSize = m_builder.CreateTrunc(_inSize, Type::Size, "in.size"); auto outBeg = m_memoryMan.getBytePtr(_outOff); auto outSize = m_builder.CreateTrunc(_outSize, Type::Size, "out.size"); auto codeAddress = Endianness::toBE(m_builder, _codeAddress); auto callGas = m_builder.CreateSelect( m_builder.CreateICmpULE(_callGas, m_builder.CreateZExt(Constant::gasMax, Type::Word)), m_builder.CreateTrunc(_callGas, Type::Gas), Constant::gasMax); auto ret = createCall(EnvFunc::call, {getRuntimeManager().getEnvPtr(), getRuntimeManager().getGasPtr(), callGas, byPtr(receiveAddress), byPtr(_value), inBeg, inSize, outBeg, outSize, byPtr(codeAddress)}); return m_builder.CreateZExt(ret, Type::Word, "ret"); } llvm::Value* Ext::sha3(llvm::Value* _inOff, llvm::Value* _inSize) { auto begin = m_memoryMan.getBytePtr(_inOff); auto size = m_builder.CreateTrunc(_inSize, Type::Size, "size"); auto ret = getArgAlloca(); createCall(EnvFunc::sha3, {begin, size, ret}); llvm::Value* hash = m_builder.CreateLoad(ret); hash = Endianness::toNative(m_builder, hash); return hash; } MemoryRef Ext::extcode(llvm::Value* _addr) { auto addr = Endianness::toBE(m_builder, _addr); auto code = createCall(EnvFunc::extcode, {getRuntimeManager().getEnvPtr(), byPtr(addr), m_size}); auto codeSize = m_builder.CreateLoad(m_size); auto codeSize256 = m_builder.CreateZExt(codeSize, Type::Word); return {code, codeSize256}; } void Ext::log(llvm::Value* _memIdx, llvm::Value* _numBytes, std::array<llvm::Value*,4> const& _topics) { auto begin = m_memoryMan.getBytePtr(_memIdx); auto size = m_builder.CreateTrunc(_numBytes, Type::Size, "size"); llvm::Value* args[] = {getRuntimeManager().getEnvPtr(), begin, size, getArgAlloca(), getArgAlloca(), getArgAlloca(), getArgAlloca()}; auto topicArgPtr = &args[3]; for (auto&& topic : _topics) { if (topic) m_builder.CreateStore(Endianness::toBE(m_builder, topic), *topicArgPtr); else *topicArgPtr = llvm::ConstantPointerNull::get(Type::WordPtr); ++topicArgPtr; } createCall(EnvFunc::log, {args[0], args[1], args[2], args[3], args[4], args[5], args[6]}); // TODO: use std::initializer_list<> } } } } <|endoftext|>
<commit_before>#include "Node.h" #include "NodePart.h" #include "Animation.h" #include "NodeAnimation.h" #include "Keyframe.h" #include "Material.h" #include "Attributes.h" #include "MeshPart.h" #include "Mesh.h" #include "Model.h" #include "Reference.h" #include "FileIO.h" #include "Reference.h" namespace fbxconv { namespace modeldata { static const char* getTextureUseString(const Material::Texture::Usage &textureUse) { switch(textureUse){ case Material::Texture::Ambient: return "AMBIENT"; case Material::Texture::Bump: return "BUMP"; case Material::Texture::Diffuse: return "DIFFUSE"; case Material::Texture::Emissive: return "EMISSIVE"; case Material::Texture::None: return "NONE"; case Material::Texture::Normal: return "NORMAL"; case Material::Texture::Reflection: return "REFLECTION"; case Material::Texture::Shininess: return "SHININESS"; case Material::Texture::Specular: return "SPECULAR"; case Material::Texture::Transparency: return "TRANSPARENCY"; default: return "UNKNOWN"; } } static const char* getWrapModeUseString(const FbxFileTexture::EWrapMode &textureUse) { switch(textureUse){ case FbxFileTexture::eRepeat: return "REPEAT"; case FbxFileTexture::eClamp: return "CLAMP"; default: return "UNKNOWN"; } } void Model::writeBinary(FILE* file) { std::list<std::string> _bonenames; for (std::vector<Node *>::const_iterator itr = nodes.begin(); itr != nodes.end(); ++itr) { (*itr)->loadBoneNames(_bonenames); } for (std::vector<Node *>::const_iterator itr = nodes.begin(); itr != nodes.end(); ++itr) { bool skeleton=false; (*itr)->checkIsSkeleton(skeleton,_bonenames); (*itr)->setSkeleton(skeleton); } unsigned int size = meshes.size(); if(size>0) { meshes[0]->object.fPosition = ftell(file); } write(size, file); // write mesh for(auto itr = meshes.begin(); itr != meshes.end(); itr++) { (*itr)->writeBinary(file); } // write material size = materials.size(); if(size>0) { materials[0]->object.fPosition = ftell(file); } write(size, file); for(auto itr = materials.begin(); itr != materials.end(); itr++) { (*itr)->writeBinary(file); } // node num size = nodes.size(); if(size>0) { nodes[0]->object.fPosition = ftell(file); } write(size, file); for(auto itr = nodes.begin(); itr != nodes.end(); itr++) { (*itr)->writeBinary(file); } // animations write(size, file); for(auto itr : animations) { itr->object.fPosition = ftell(file); itr->writeBinary(file); } } void Mesh::writeBinary(FILE* file) { // attribute attributes.writeBinary(file); // write vertices if(vertices.size() > 0) { unsigned int size = vertices.size(); write(size, file); write(&vertices[0],size,file); } else { write((unsigned int)0, file); } // write parts. unsigned int size = parts.size(); write(size, file); for(auto itr = parts.begin(); itr != parts.end(); itr++) { (*itr)->writeBinary(file); } } void MeshPart::writeBinary(FILE* file) { write(id, file); //aabb write((unsigned int)6, file); write(aabb, 6, file); // indices size unsigned int size = indices.size(); write(size, file); // indices. for(auto itr1 = indices.begin(); itr1 != indices.end(); itr1++) write(*itr1,file); } void Attributes::writeBinary(FILE* file) { std::vector<MeshVertexAttrib> attribs; MeshVertexAttrib attrib; for (unsigned int i = 0; i < length(); i++) { std::string key = name(i); attrib = attributemap.find(key)->second; attribs.push_back(attrib); if(key == "VERTEX_ATTRIB_BLEND_INDEX") { break; } } unsigned int size = attribs.size(); write(size, file); for( int i = 0 ; i < size ; i++ ) { write(attribs[i].size, file); write(attribs[i].type, file); write(attribs[i].name, file); } } void Material::writeBinary(FILE* file) { write(id, file); write(diffuse.value, 3, file); write(ambient.value, 3, file); write(emissive.value, 3, file); write(opacity.value,file); write(specular.value, 3, file); write(shininess.value,file); unsigned int size = textures.size(); write(size, file); for(auto itr = textures.begin(); itr != textures.end(); itr++) { write((*itr)->id, file); write((*itr)->path, file); write((*itr)->uvTranslation, 2, file); write((*itr)->uvScale, 2, file); std::string wrapModeU=getWrapModeUseString((*itr)->wrapModeU); std::string wrapModeV=getWrapModeUseString((*itr)->wrapModeV); std::string type= getTextureUseString((*itr)->usage); write(type,file); write(wrapModeU,file); write(wrapModeV,file); } } void Node::writeBinary(FILE* file) { write(id, file); write(_skeleton, file); // rotation scale translation write(transforms, 16, file); //write(transform.scale, 3, file); //write(transform.translation, 3, file); // node part unsigned int partsSize = parts.size(); write(partsSize,file); if(parts.size()>0) { for(int i = 0 ; i < parts.size() ; i++ ) { NodePart* nodepart = parts[i]; if(nodepart) { if(nodepart->meshPart) { //meshpartid write(nodepart->meshPart->id, file); } else { write("null", file); } //materialid if(nodepart->material) { write(nodepart->material->id, file); } else { write("null", file); } // bone num unsigned int size = nodepart->bones.size(); write(size, file); for(auto itr = nodepart->bones.begin(); itr != nodepart->bones.end(); itr++) { // write name write(itr->first->id, file); // write transform float tmp[16]; for(int i = 0; i < 4; i++) { for(int j = 0; j < 4; j++) { tmp[i*4 + j] = itr->second.Double44()[i][j]; } } write(tmp, 16, file); } // uvMapping size = nodepart->uvMapping.size(); write(size, file); for(auto itr = nodepart->uvMapping.begin(); itr != nodepart->uvMapping.end(); itr++) { unsigned int size = itr->size(); write(size, file); //TextureIndex for (auto tt = (*itr).begin(); tt != (*itr).end(); ++tt) { unsigned int index = nodepart->material->getTextureIndex(*tt); write(index, file); } } } } } // children unsigned int childrenSize = children.size(); write(childrenSize,file); for(auto itr = children.begin(); itr != children.end(); itr++) { Node* node = *itr; if(node) { node->writeBinary(file); } } } void Animation::writeBinary(FILE* file) { write(id, file); write(length, file); write(static_cast<unsigned int>(nodeAnimations.size()), file); for(auto itr = nodeAnimations.begin(); itr != nodeAnimations.end(); itr++) { NodeAnimation* nodeanim = *itr; write(nodeanim->node->id, file); write(static_cast<unsigned int>(nodeanim->keyframes.size()), file); for(auto itr1 = nodeanim->keyframes.begin(); itr1 != nodeanim->keyframes.end(); itr1++) { Keyframe* keyframe = *itr1; // write time write(keyframe->time, file); // write transform flag unsigned char transformflag(0); if (keyframe->hasRotation) transformflag |= 0x01; if (keyframe->hasScale) transformflag |= (0x01 << 1); if (keyframe->hasTranslation) transformflag |= (0x01 << 2); write(transformflag, file); // write rotation val if (keyframe->hasRotation) write(keyframe->rotation, 4, file); // write scale val if (keyframe->hasScale) write(keyframe->scale, 3, file); // write translation val if (keyframe->hasTranslation) write(keyframe->translation, 3, file); } } } } }<commit_msg>change AABB write order<commit_after>#include "Node.h" #include "NodePart.h" #include "Animation.h" #include "NodeAnimation.h" #include "Keyframe.h" #include "Material.h" #include "Attributes.h" #include "MeshPart.h" #include "Mesh.h" #include "Model.h" #include "Reference.h" #include "FileIO.h" #include "Reference.h" namespace fbxconv { namespace modeldata { static const char* getTextureUseString(const Material::Texture::Usage &textureUse) { switch(textureUse){ case Material::Texture::Ambient: return "AMBIENT"; case Material::Texture::Bump: return "BUMP"; case Material::Texture::Diffuse: return "DIFFUSE"; case Material::Texture::Emissive: return "EMISSIVE"; case Material::Texture::None: return "NONE"; case Material::Texture::Normal: return "NORMAL"; case Material::Texture::Reflection: return "REFLECTION"; case Material::Texture::Shininess: return "SHININESS"; case Material::Texture::Specular: return "SPECULAR"; case Material::Texture::Transparency: return "TRANSPARENCY"; default: return "UNKNOWN"; } } static const char* getWrapModeUseString(const FbxFileTexture::EWrapMode &textureUse) { switch(textureUse){ case FbxFileTexture::eRepeat: return "REPEAT"; case FbxFileTexture::eClamp: return "CLAMP"; default: return "UNKNOWN"; } } void Model::writeBinary(FILE* file) { std::list<std::string> _bonenames; for (std::vector<Node *>::const_iterator itr = nodes.begin(); itr != nodes.end(); ++itr) { (*itr)->loadBoneNames(_bonenames); } for (std::vector<Node *>::const_iterator itr = nodes.begin(); itr != nodes.end(); ++itr) { bool skeleton=false; (*itr)->checkIsSkeleton(skeleton,_bonenames); (*itr)->setSkeleton(skeleton); } unsigned int size = meshes.size(); if(size>0) { meshes[0]->object.fPosition = ftell(file); } write(size, file); // write mesh for(auto itr = meshes.begin(); itr != meshes.end(); itr++) { (*itr)->writeBinary(file); } // write material size = materials.size(); if(size>0) { materials[0]->object.fPosition = ftell(file); } write(size, file); for(auto itr = materials.begin(); itr != materials.end(); itr++) { (*itr)->writeBinary(file); } // node num size = nodes.size(); if(size>0) { nodes[0]->object.fPosition = ftell(file); } write(size, file); for(auto itr = nodes.begin(); itr != nodes.end(); itr++) { (*itr)->writeBinary(file); } // animations write(size, file); for(auto itr : animations) { itr->object.fPosition = ftell(file); itr->writeBinary(file); } } void Mesh::writeBinary(FILE* file) { // attribute attributes.writeBinary(file); // write vertices if(vertices.size() > 0) { unsigned int size = vertices.size(); write(size, file); write(&vertices[0],size,file); } else { write((unsigned int)0, file); } // write parts. unsigned int size = parts.size(); write(size, file); for(auto itr = parts.begin(); itr != parts.end(); itr++) { (*itr)->writeBinary(file); } } void MeshPart::writeBinary(FILE* file) { write(id, file); // indices size unsigned int size = indices.size(); write(size, file); // indices. for(auto itr1 = indices.begin(); itr1 != indices.end(); itr1++) write(*itr1,file); //aabb write(aabb, 6, file); } void Attributes::writeBinary(FILE* file) { std::vector<MeshVertexAttrib> attribs; MeshVertexAttrib attrib; for (unsigned int i = 0; i < length(); i++) { std::string key = name(i); attrib = attributemap.find(key)->second; attribs.push_back(attrib); if(key == "VERTEX_ATTRIB_BLEND_INDEX") { break; } } unsigned int size = attribs.size(); write(size, file); for( int i = 0 ; i < size ; i++ ) { write(attribs[i].size, file); write(attribs[i].type, file); write(attribs[i].name, file); } } void Material::writeBinary(FILE* file) { write(id, file); write(diffuse.value, 3, file); write(ambient.value, 3, file); write(emissive.value, 3, file); write(opacity.value,file); write(specular.value, 3, file); write(shininess.value,file); unsigned int size = textures.size(); write(size, file); for(auto itr = textures.begin(); itr != textures.end(); itr++) { write((*itr)->id, file); write((*itr)->path, file); write((*itr)->uvTranslation, 2, file); write((*itr)->uvScale, 2, file); std::string wrapModeU=getWrapModeUseString((*itr)->wrapModeU); std::string wrapModeV=getWrapModeUseString((*itr)->wrapModeV); std::string type= getTextureUseString((*itr)->usage); write(type,file); write(wrapModeU,file); write(wrapModeV,file); } } void Node::writeBinary(FILE* file) { write(id, file); write(_skeleton, file); // rotation scale translation write(transforms, 16, file); //write(transform.scale, 3, file); //write(transform.translation, 3, file); // node part unsigned int partsSize = parts.size(); write(partsSize,file); if(parts.size()>0) { for(int i = 0 ; i < parts.size() ; i++ ) { NodePart* nodepart = parts[i]; if(nodepart) { if(nodepart->meshPart) { //meshpartid write(nodepart->meshPart->id, file); } else { write("null", file); } //materialid if(nodepart->material) { write(nodepart->material->id, file); } else { write("null", file); } // bone num unsigned int size = nodepart->bones.size(); write(size, file); for(auto itr = nodepart->bones.begin(); itr != nodepart->bones.end(); itr++) { // write name write(itr->first->id, file); // write transform float tmp[16]; for(int i = 0; i < 4; i++) { for(int j = 0; j < 4; j++) { tmp[i*4 + j] = itr->second.Double44()[i][j]; } } write(tmp, 16, file); } // uvMapping size = nodepart->uvMapping.size(); write(size, file); for(auto itr = nodepart->uvMapping.begin(); itr != nodepart->uvMapping.end(); itr++) { unsigned int size = itr->size(); write(size, file); //TextureIndex for (auto tt = (*itr).begin(); tt != (*itr).end(); ++tt) { unsigned int index = nodepart->material->getTextureIndex(*tt); write(index, file); } } } } } // children unsigned int childrenSize = children.size(); write(childrenSize,file); for(auto itr = children.begin(); itr != children.end(); itr++) { Node* node = *itr; if(node) { node->writeBinary(file); } } } void Animation::writeBinary(FILE* file) { write(id, file); write(length, file); write(static_cast<unsigned int>(nodeAnimations.size()), file); for(auto itr = nodeAnimations.begin(); itr != nodeAnimations.end(); itr++) { NodeAnimation* nodeanim = *itr; write(nodeanim->node->id, file); write(static_cast<unsigned int>(nodeanim->keyframes.size()), file); for(auto itr1 = nodeanim->keyframes.begin(); itr1 != nodeanim->keyframes.end(); itr1++) { Keyframe* keyframe = *itr1; // write time write(keyframe->time, file); // write transform flag unsigned char transformflag(0); if (keyframe->hasRotation) transformflag |= 0x01; if (keyframe->hasScale) transformflag |= (0x01 << 1); if (keyframe->hasTranslation) transformflag |= (0x01 << 2); write(transformflag, file); // write rotation val if (keyframe->hasRotation) write(keyframe->rotation, 4, file); // write scale val if (keyframe->hasScale) write(keyframe->scale, 3, file); // write translation val if (keyframe->hasTranslation) write(keyframe->translation, 3, file); } } } } }<|endoftext|>
<commit_before>// Copyright (c) 2014 Ratcoin dev-team // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "processNetwork.h" #include "common/nodesManager.h" #include "common/communicationProtocol.h" #include "common/actionHandler.h" #include "common/nodeMedium.h" #include "configureMonitorActionHandler.h" #include "monitor/connectNodeAction.h" #include "monitor/reputationTracer.h" #include "monitor/monitorNodeMedium.h" namespace monitor { CProcessNetwork * CProcessNetwork::ms_instance = NULL; CProcessNetwork* CProcessNetwork::getInstance() { if ( !ms_instance ) { ms_instance = new CProcessNetwork(); }; return ms_instance; } bool CProcessNetwork::processMessage(common::CSelfNode* pfrom, CDataStream& vRecv) { std::vector< common::CMessage > messages; vRecv >> messages; // it is stupid to call this over and over again if ( !CReputationTracker::getInstance()->getMediumForNode( pfrom ) ) { CReputationTracker::getInstance()->addNode( new CMonitorNodeMedium( pfrom ) ); } BOOST_FOREACH( common::CMessage const & message, messages ) { if ( message.m_header.m_payloadKind == common::CPayloadKind::RoleInfo || message.m_header.m_payloadKind == common::CPayloadKind::Result || message.m_header.m_payloadKind == common::CPayloadKind::NetworkInfo || message.m_header.m_payloadKind == common::CPayloadKind::NetworkInfo ) { common::CNodeMedium< MonitorResponses > * nodeMedium = CReputationTracker::getInstance()->getMediumForNode( pfrom ); if ( common::CNetworkActionRegister::getInstance()->isServicedByAction( message.m_header.m_actionKey ) ) { nodeMedium->setResponse( message.m_header.m_actionKey, common::CMessageResult( message, convertToInt( nodeMedium->getNode() ) ) ); } else { } } /* { CPubKey pubKey; if( !CTrackerNodesManager::getInstance()->getPublicKey( pfrom->addr, pubKey ) ) { assert( !"for now assert this" ); return true; } }*/ else if ( message.m_header.m_payloadKind == common::CPayloadKind::InfoReq ) { // } else if ( message.m_header.m_payloadKind == common::CPayloadKind::IntroductionReq ) { common::CIdentifyMessage identifyMessage; convertPayload( message, identifyMessage ); common::CNodeMedium< MonitorResponses > * nodeMedium = CReputationTracker::getInstance()->getMediumForNode( pfrom ); if ( common::CNetworkActionRegister::getInstance()->isServicedByAction( message.m_header.m_actionKey ) ) { nodeMedium->setResponse( message.m_header.m_actionKey, common::CIdentificationResult( identifyMessage.m_payload, identifyMessage.m_signed, identifyMessage.m_key, pfrom->addr ) ); } else { CConnectNodeAction * connectNodeAction= new CConnectNodeAction( nodeMedium->getNode()->addr , message.m_header.m_actionKey , identifyMessage.m_payload , convertToInt( nodeMedium->getNode() ) ); common::CActionHandler< MonitorResponses >::getInstance()->executeAction( connectNodeAction ); } } else if ( message.m_header.m_payloadKind == common::CPayloadKind::Ack ) { common::CAck ack; common::convertPayload( message, ack ); common::CNodeMedium< MonitorResponses > * nodeMedium = CReputationTracker::getInstance()->getMediumForNode( pfrom ); if ( common::CNetworkActionRegister::getInstance()->isServicedByAction( message.m_header.m_actionKey ) ) { nodeMedium->setResponse( message.m_header.m_actionKey, common::CAckResult( convertToInt( nodeMedium->getNode() ) ) ); } } else if ( message.m_header.m_payloadKind == common::CPayloadKind::Uninitiated ) { // } } /* */ return true; } bool CProcessNetwork::sendMessages(common::CSelfNode* pto, bool fSendTrickle) { pto->sendMessages(); return true; } } <commit_msg>info exchange<commit_after>// Copyright (c) 2014 Ratcoin dev-team // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "processNetwork.h" #include "common/nodesManager.h" #include "common/communicationProtocol.h" #include "common/actionHandler.h" #include "common/nodeMedium.h" #include "configureMonitorActionHandler.h" #include "monitor/connectNodeAction.h" #include "monitor/reputationTracer.h" #include "monitor/monitorNodeMedium.h" namespace monitor { CProcessNetwork * CProcessNetwork::ms_instance = NULL; CProcessNetwork* CProcessNetwork::getInstance() { if ( !ms_instance ) { ms_instance = new CProcessNetwork(); }; return ms_instance; } bool CProcessNetwork::processMessage(common::CSelfNode* pfrom, CDataStream& vRecv) { std::vector< common::CMessage > messages; vRecv >> messages; // it is stupid to call this over and over again if ( !CReputationTracker::getInstance()->getMediumForNode( pfrom ) ) { CReputationTracker::getInstance()->addNode( new CMonitorNodeMedium( pfrom ) ); } BOOST_FOREACH( common::CMessage const & message, messages ) { if ( message.m_header.m_payloadKind == common::CPayloadKind::RoleInfo || message.m_header.m_payloadKind == common::CPayloadKind::Result || message.m_header.m_payloadKind == common::CPayloadKind::NetworkInfo || message.m_header.m_payloadKind == common::CPayloadKind::InfoRes ) { common::CNodeMedium< MonitorResponses > * nodeMedium = CReputationTracker::getInstance()->getMediumForNode( pfrom ); if ( common::CNetworkActionRegister::getInstance()->isServicedByAction( message.m_header.m_actionKey ) ) { nodeMedium->setResponse( message.m_header.m_actionKey, common::CMessageResult( message, convertToInt( nodeMedium->getNode() ) ) ); } else { } } /* { CPubKey pubKey; if( !CTrackerNodesManager::getInstance()->getPublicKey( pfrom->addr, pubKey ) ) { assert( !"for now assert this" ); return true; } }*/ else if ( message.m_header.m_payloadKind == common::CPayloadKind::InfoReq ) { // } else if ( message.m_header.m_payloadKind == common::CPayloadKind::IntroductionReq ) { common::CIdentifyMessage identifyMessage; convertPayload( message, identifyMessage ); common::CNodeMedium< MonitorResponses > * nodeMedium = CReputationTracker::getInstance()->getMediumForNode( pfrom ); if ( common::CNetworkActionRegister::getInstance()->isServicedByAction( message.m_header.m_actionKey ) ) { nodeMedium->setResponse( message.m_header.m_actionKey, common::CIdentificationResult( identifyMessage.m_payload, identifyMessage.m_signed, identifyMessage.m_key, pfrom->addr ) ); } else { CConnectNodeAction * connectNodeAction= new CConnectNodeAction( nodeMedium->getNode()->addr , message.m_header.m_actionKey , identifyMessage.m_payload , convertToInt( nodeMedium->getNode() ) ); common::CActionHandler< MonitorResponses >::getInstance()->executeAction( connectNodeAction ); } } else if ( message.m_header.m_payloadKind == common::CPayloadKind::Ack ) { common::CAck ack; common::convertPayload( message, ack ); common::CNodeMedium< MonitorResponses > * nodeMedium = CReputationTracker::getInstance()->getMediumForNode( pfrom ); if ( common::CNetworkActionRegister::getInstance()->isServicedByAction( message.m_header.m_actionKey ) ) { nodeMedium->setResponse( message.m_header.m_actionKey, common::CAckResult( convertToInt( nodeMedium->getNode() ) ) ); } } else if ( message.m_header.m_payloadKind == common::CPayloadKind::Uninitiated ) { // } } /* */ return true; } bool CProcessNetwork::sendMessages(common::CSelfNode* pto, bool fSendTrickle) { pto->sendMessages(); return true; } } <|endoftext|>
<commit_before>/* $Id: middlewareTimerTests.cpp,v 1.1.2.5 2012/11/30 17:32:33 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 "mama/mama.h" #include "MainUnitTestC.h" #include <iostream> #include "bridge.h" #include "mama/types.h" using std::cout; using std::endl; class MiddlewareTimerTests : public ::testing::Test { protected: MiddlewareTimerTests(void); virtual ~MiddlewareTimerTests(void); virtual void SetUp(void); virtual void TearDown(void); mamaBridge mBridge; }; MiddlewareTimerTests::MiddlewareTimerTests(void) { } MiddlewareTimerTests::~MiddlewareTimerTests(void) { } void MiddlewareTimerTests::SetUp(void) { mama_loadBridge (&mBridge,getMiddleware()); } void MiddlewareTimerTests::TearDown(void) { } static void MAMACALLTYPE onTick(mamaTimer timer, void* closure) { } static void MAMACALLTYPE onTimerDestroy(mamaTimer timer, void* closure) { } /*=================================================================== = mamaTimer bridge functions = ====================================================================*/ TEST_F (MiddlewareTimerTests, create) { timerBridge timer = NULL; double interval = 1; mamaTimer fakeParent = (mamaTimer) NOT_NULL; void* closure = NULL; void* handle = NULL; mamaQueue mDefaultQueue = NULL; ASSERT_EQ(MAMA_STATUS_OK, mama_getDefaultEventQueue(mBridge,&mDefaultQueue)); ASSERT_EQ(MAMA_STATUS_OK, mamaQueue_getNativeHandle(mDefaultQueue, &handle)); ASSERT_EQ(MAMA_STATUS_OK, mBridge->bridgeMamaTimerCreate(&timer, handle, onTick, onTimerDestroy, interval, fakeParent, closure)); } TEST_F (MiddlewareTimerTests, createInvalidResult) { void* nativeQueueHandle = NOT_NULL; mamaTimerCb action = (mamaTimerCb) NOT_NULL; mamaTimerCb onTimerDestroyed = (mamaTimerCb) NOT_NULL; double interval = 0.0; mamaTimer parent = (mamaTimer) NOT_NULL; void* closure = NOT_NULL; ASSERT_EQ (MAMA_STATUS_NULL_ARG, mBridge->bridgeMamaTimerCreate(NULL, nativeQueueHandle, action, onTimerDestroyed, interval, parent, closure)); } TEST_F (MiddlewareTimerTests, createInvalidNativeQueueHandle) { timerBridge result = (timerBridge) NOT_NULL; mamaTimerCb action = (mamaTimerCb) NOT_NULL; mamaTimerCb onTimerDestroyed = (mamaTimerCb) NOT_NULL; double interval = 0.0; mamaTimer parent = (mamaTimer) NOT_NULL; void* closure = NOT_NULL; ASSERT_EQ (MAMA_STATUS_NULL_ARG, mBridge->bridgeMamaTimerCreate(&result, NULL, action, onTimerDestroyed, interval, parent, closure)); } TEST_F (MiddlewareTimerTests, createInvalidActionCB) { timerBridge result = (timerBridge) NOT_NULL; void* nativeQueueHandle = NOT_NULL; mamaTimerCb onTimerDestroyed = (mamaTimerCb) NOT_NULL; double interval = 0.0; mamaTimer parent = (mamaTimer) NOT_NULL; void* closure = NOT_NULL; ASSERT_EQ (MAMA_STATUS_NULL_ARG, mBridge->bridgeMamaTimerCreate(&result, nativeQueueHandle, NULL, onTimerDestroyed, interval, parent, closure)); } TEST_F (MiddlewareTimerTests, createInvalidDestroyCB) { timerBridge result = (timerBridge) NOT_NULL; void* nativeQueueHandle = NOT_NULL; mamaTimerCb action = (mamaTimerCb) NOT_NULL; double interval = 0.0; mamaTimer parent = (mamaTimer) NOT_NULL; void* closure = NOT_NULL; ASSERT_EQ (MAMA_STATUS_NULL_ARG, mBridge->bridgeMamaTimerCreate(&result, nativeQueueHandle, action, NULL, interval, parent, closure)); } /* TODO: Determine if interval maybe a NULL value */ TEST_F (MiddlewareTimerTests, DISABLED_createInvalidInterval) { timerBridge result = (timerBridge) NOT_NULL; void* nativeQueueHandle = NOT_NULL; mamaTimerCb action = (mamaTimerCb) NOT_NULL; mamaTimerCb onTimerDestroyed = (mamaTimerCb) NOT_NULL; mamaTimer parent = (mamaTimer) NOT_NULL; void* closure = NOT_NULL; ASSERT_EQ (MAMA_STATUS_NULL_ARG, mBridge->bridgeMamaTimerCreate(&result, nativeQueueHandle, action, onTimerDestroyed, NULL, parent, closure)); } TEST_F (MiddlewareTimerTests, createInvalidParent) { timerBridge result = (timerBridge) NOT_NULL; void* nativeQueueHandle = NOT_NULL; mamaTimerCb action = (mamaTimerCb) NOT_NULL; mamaTimerCb onTimerDestroyed = (mamaTimerCb) NOT_NULL; double interval = 0.0; void* closure = NOT_NULL; ASSERT_EQ (MAMA_STATUS_NULL_ARG, mBridge->bridgeMamaTimerCreate(&result, nativeQueueHandle, action, onTimerDestroyed, interval, NULL, closure)); } TEST_F (MiddlewareTimerTests, destroy) { timerBridge timer = NULL; double interval = 1; mamaTimer fakeParent = (mamaTimer) NOT_NULL; void* closure = NULL; void* handle = NULL; mamaQueue mDefaultQueue = NULL; ASSERT_EQ(MAMA_STATUS_OK, mama_getDefaultEventQueue(mBridge, &mDefaultQueue)); ASSERT_EQ(MAMA_STATUS_OK, mamaQueue_getNativeHandle(mDefaultQueue, &handle)); ASSERT_EQ(MAMA_STATUS_OK, mBridge->bridgeMamaTimerCreate(&timer, handle, onTick, onTimerDestroy, interval, fakeParent, closure)); ASSERT_EQ(MAMA_STATUS_OK, mBridge->bridgeMamaTimerDestroy(timer)); } TEST_F (MiddlewareTimerTests, destroyInvalid) { ASSERT_EQ (MAMA_STATUS_NULL_ARG, mBridge->bridgeMamaTimerDestroy(NULL)); } TEST_F (MiddlewareTimerTests, reset) { timerBridge timer = NULL; double interval = 1; mamaTimer fakeParent = (mamaTimer) NOT_NULL; void* closure = NULL; void* handle = NULL; mamaQueue mDefaultQueue = NULL; ASSERT_EQ(MAMA_STATUS_OK, mama_getDefaultEventQueue(mBridge,&mDefaultQueue)); ASSERT_EQ(MAMA_STATUS_OK, mamaQueue_getNativeHandle(mDefaultQueue, &handle)); ASSERT_EQ(MAMA_STATUS_OK, mBridge->bridgeMamaTimerCreate(&timer, handle, onTick, onTimerDestroy, interval, fakeParent, closure)); ASSERT_EQ(MAMA_STATUS_OK, mBridge->bridgeMamaTimerReset(timer)); } TEST_F (MiddlewareTimerTests, resetInvalid) { ASSERT_EQ (MAMA_STATUS_NULL_ARG, mBridge->bridgeMamaTimerReset(NULL)); } TEST_F (MiddlewareTimerTests, setInterval) { timerBridge timer = NULL; double interval = 1; mamaTimer fakeParent = (mamaTimer) NOT_NULL; void* closure = NULL; void* handle = NULL; mamaQueue mDefaultQueue = NULL; mama_f64_t newInterval = 10; ASSERT_EQ(MAMA_STATUS_OK, mama_getDefaultEventQueue(mBridge,&mDefaultQueue)); ASSERT_EQ(MAMA_STATUS_OK, mamaQueue_getNativeHandle(mDefaultQueue, &handle)); ASSERT_EQ(MAMA_STATUS_OK, mBridge->bridgeMamaTimerCreate(&timer, handle, onTick, onTimerDestroy, interval, fakeParent, closure)); ASSERT_EQ(MAMA_STATUS_OK, mBridge->bridgeMamaTimerSetInterval(timer,newInterval)); } TEST_F (MiddlewareTimerTests, setIntervalInvalidTimerBridge) { mama_f64_t interval = 500; ASSERT_EQ (MAMA_STATUS_NULL_ARG, mBridge->bridgeMamaTimerSetInterval(NULL,interval)); } /* TODO: Determine if interval can be set to a NULL value (0.0 in this case) */ TEST_F (MiddlewareTimerTests, DISABLED_setIntervalInvalidInterval) { timerBridge timer = (timerBridge) NOT_NULL; ASSERT_EQ (MAMA_STATUS_NULL_ARG, mBridge->bridgeMamaTimerSetInterval(timer,NULL)); } TEST_F (MiddlewareTimerTests, getInterval) { timerBridge timer = NULL; double interval = 1; mamaTimer fakeParent = (mamaTimer) NOT_NULL; void* closure = NULL; void* handle = NULL; mamaQueue mDefaultQueue = NULL; mama_f64_t newInterval = 10; mama_f64_t testInterval = 5; ASSERT_EQ(MAMA_STATUS_OK, mama_getDefaultEventQueue(mBridge,&mDefaultQueue)); ASSERT_EQ(MAMA_STATUS_OK, mamaQueue_getNativeHandle(mDefaultQueue, &handle)); ASSERT_EQ(MAMA_STATUS_OK, mBridge->bridgeMamaTimerCreate(&timer, handle, onTick, onTimerDestroy, interval, fakeParent, closure)); ASSERT_EQ(MAMA_STATUS_OK, mBridge->bridgeMamaTimerSetInterval(timer,newInterval)); ASSERT_EQ(MAMA_STATUS_OK, mBridge->bridgeMamaTimerGetInterval(timer,&testInterval)); ASSERT_EQ(testInterval, newInterval); } TEST_F (MiddlewareTimerTests, getIntervalInvalidTimerBridge) { mama_f64_t interval = 500; ASSERT_EQ (MAMA_STATUS_NULL_ARG, mBridge->bridgeMamaTimerGetInterval(NULL,&interval)); } TEST_F (MiddlewareTimerTests, getIntervalInvalidInterval) { timerBridge timer = (timerBridge) NOT_NULL; ASSERT_EQ (MAMA_STATUS_NULL_ARG, mBridge->bridgeMamaTimerGetInterval(timer,NULL)); } <commit_msg>UNIT TESTS: Disabling the invalid timer destroy callback test.<commit_after>/* $Id: middlewareTimerTests.cpp,v 1.1.2.5 2012/11/30 17:32:33 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 "mama/mama.h" #include "MainUnitTestC.h" #include <iostream> #include "bridge.h" #include "mama/types.h" using std::cout; using std::endl; class MiddlewareTimerTests : public ::testing::Test { protected: MiddlewareTimerTests(void); virtual ~MiddlewareTimerTests(void); virtual void SetUp(void); virtual void TearDown(void); mamaBridge mBridge; }; MiddlewareTimerTests::MiddlewareTimerTests(void) { } MiddlewareTimerTests::~MiddlewareTimerTests(void) { } void MiddlewareTimerTests::SetUp(void) { mama_loadBridge (&mBridge,getMiddleware()); } void MiddlewareTimerTests::TearDown(void) { } static void MAMACALLTYPE onTick(mamaTimer timer, void* closure) { } static void MAMACALLTYPE onTimerDestroy(mamaTimer timer, void* closure) { } /*=================================================================== = mamaTimer bridge functions = ====================================================================*/ TEST_F (MiddlewareTimerTests, create) { timerBridge timer = NULL; double interval = 1; mamaTimer fakeParent = (mamaTimer) NOT_NULL; void* closure = NULL; void* handle = NULL; mamaQueue mDefaultQueue = NULL; ASSERT_EQ(MAMA_STATUS_OK, mama_getDefaultEventQueue(mBridge,&mDefaultQueue)); ASSERT_EQ(MAMA_STATUS_OK, mamaQueue_getNativeHandle(mDefaultQueue, &handle)); ASSERT_EQ(MAMA_STATUS_OK, mBridge->bridgeMamaTimerCreate(&timer, handle, onTick, onTimerDestroy, interval, fakeParent, closure)); } TEST_F (MiddlewareTimerTests, createInvalidResult) { void* nativeQueueHandle = NOT_NULL; mamaTimerCb action = (mamaTimerCb) NOT_NULL; mamaTimerCb onTimerDestroyed = (mamaTimerCb) NOT_NULL; double interval = 0.0; mamaTimer parent = (mamaTimer) NOT_NULL; void* closure = NOT_NULL; ASSERT_EQ (MAMA_STATUS_NULL_ARG, mBridge->bridgeMamaTimerCreate(NULL, nativeQueueHandle, action, onTimerDestroyed, interval, parent, closure)); } TEST_F (MiddlewareTimerTests, createInvalidNativeQueueHandle) { timerBridge result = (timerBridge) NOT_NULL; mamaTimerCb action = (mamaTimerCb) NOT_NULL; mamaTimerCb onTimerDestroyed = (mamaTimerCb) NOT_NULL; double interval = 0.0; mamaTimer parent = (mamaTimer) NOT_NULL; void* closure = NOT_NULL; ASSERT_EQ (MAMA_STATUS_NULL_ARG, mBridge->bridgeMamaTimerCreate(&result, NULL, action, onTimerDestroyed, interval, parent, closure)); } TEST_F (MiddlewareTimerTests, createInvalidActionCB) { timerBridge result = (timerBridge) NOT_NULL; void* nativeQueueHandle = NOT_NULL; mamaTimerCb onTimerDestroyed = (mamaTimerCb) NOT_NULL; double interval = 0.0; mamaTimer parent = (mamaTimer) NOT_NULL; void* closure = NOT_NULL; ASSERT_EQ (MAMA_STATUS_NULL_ARG, mBridge->bridgeMamaTimerCreate(&result, nativeQueueHandle, NULL, onTimerDestroyed, interval, parent, closure)); } TEST_F (MiddlewareTimerTests, DISABLED_createInvalidDestroyCB) { timerBridge result = (timerBridge) NOT_NULL; void* nativeQueueHandle = NOT_NULL; mamaTimerCb action = (mamaTimerCb) NOT_NULL; double interval = 0.0; mamaTimer parent = (mamaTimer) NOT_NULL; void* closure = NOT_NULL; ASSERT_EQ (MAMA_STATUS_NULL_ARG, mBridge->bridgeMamaTimerCreate(&result, nativeQueueHandle, action, NULL, interval, parent, closure)); } /* TODO: Determine if interval maybe a NULL value */ TEST_F (MiddlewareTimerTests, DISABLED_createInvalidInterval) { timerBridge result = (timerBridge) NOT_NULL; void* nativeQueueHandle = NOT_NULL; mamaTimerCb action = (mamaTimerCb) NOT_NULL; mamaTimerCb onTimerDestroyed = (mamaTimerCb) NOT_NULL; mamaTimer parent = (mamaTimer) NOT_NULL; void* closure = NOT_NULL; ASSERT_EQ (MAMA_STATUS_NULL_ARG, mBridge->bridgeMamaTimerCreate(&result, nativeQueueHandle, action, onTimerDestroyed, NULL, parent, closure)); } TEST_F (MiddlewareTimerTests, createInvalidParent) { timerBridge result = (timerBridge) NOT_NULL; void* nativeQueueHandle = NOT_NULL; mamaTimerCb action = (mamaTimerCb) NOT_NULL; mamaTimerCb onTimerDestroyed = (mamaTimerCb) NOT_NULL; double interval = 0.0; void* closure = NOT_NULL; ASSERT_EQ (MAMA_STATUS_NULL_ARG, mBridge->bridgeMamaTimerCreate(&result, nativeQueueHandle, action, onTimerDestroyed, interval, NULL, closure)); } TEST_F (MiddlewareTimerTests, destroy) { timerBridge timer = NULL; double interval = 1; mamaTimer fakeParent = (mamaTimer) NOT_NULL; void* closure = NULL; void* handle = NULL; mamaQueue mDefaultQueue = NULL; ASSERT_EQ(MAMA_STATUS_OK, mama_getDefaultEventQueue(mBridge, &mDefaultQueue)); ASSERT_EQ(MAMA_STATUS_OK, mamaQueue_getNativeHandle(mDefaultQueue, &handle)); ASSERT_EQ(MAMA_STATUS_OK, mBridge->bridgeMamaTimerCreate(&timer, handle, onTick, onTimerDestroy, interval, fakeParent, closure)); ASSERT_EQ(MAMA_STATUS_OK, mBridge->bridgeMamaTimerDestroy(timer)); } TEST_F (MiddlewareTimerTests, destroyInvalid) { ASSERT_EQ (MAMA_STATUS_NULL_ARG, mBridge->bridgeMamaTimerDestroy(NULL)); } TEST_F (MiddlewareTimerTests, reset) { timerBridge timer = NULL; double interval = 1; mamaTimer fakeParent = (mamaTimer) NOT_NULL; void* closure = NULL; void* handle = NULL; mamaQueue mDefaultQueue = NULL; ASSERT_EQ(MAMA_STATUS_OK, mama_getDefaultEventQueue(mBridge,&mDefaultQueue)); ASSERT_EQ(MAMA_STATUS_OK, mamaQueue_getNativeHandle(mDefaultQueue, &handle)); ASSERT_EQ(MAMA_STATUS_OK, mBridge->bridgeMamaTimerCreate(&timer, handle, onTick, onTimerDestroy, interval, fakeParent, closure)); ASSERT_EQ(MAMA_STATUS_OK, mBridge->bridgeMamaTimerReset(timer)); } TEST_F (MiddlewareTimerTests, resetInvalid) { ASSERT_EQ (MAMA_STATUS_NULL_ARG, mBridge->bridgeMamaTimerReset(NULL)); } TEST_F (MiddlewareTimerTests, setInterval) { timerBridge timer = NULL; double interval = 1; mamaTimer fakeParent = (mamaTimer) NOT_NULL; void* closure = NULL; void* handle = NULL; mamaQueue mDefaultQueue = NULL; mama_f64_t newInterval = 10; ASSERT_EQ(MAMA_STATUS_OK, mama_getDefaultEventQueue(mBridge,&mDefaultQueue)); ASSERT_EQ(MAMA_STATUS_OK, mamaQueue_getNativeHandle(mDefaultQueue, &handle)); ASSERT_EQ(MAMA_STATUS_OK, mBridge->bridgeMamaTimerCreate(&timer, handle, onTick, onTimerDestroy, interval, fakeParent, closure)); ASSERT_EQ(MAMA_STATUS_OK, mBridge->bridgeMamaTimerSetInterval(timer,newInterval)); } TEST_F (MiddlewareTimerTests, setIntervalInvalidTimerBridge) { mama_f64_t interval = 500; ASSERT_EQ (MAMA_STATUS_NULL_ARG, mBridge->bridgeMamaTimerSetInterval(NULL,interval)); } /* TODO: Determine if interval can be set to a NULL value (0.0 in this case) */ TEST_F (MiddlewareTimerTests, DISABLED_setIntervalInvalidInterval) { timerBridge timer = (timerBridge) NOT_NULL; ASSERT_EQ (MAMA_STATUS_NULL_ARG, mBridge->bridgeMamaTimerSetInterval(timer,NULL)); } TEST_F (MiddlewareTimerTests, getInterval) { timerBridge timer = NULL; double interval = 1; mamaTimer fakeParent = (mamaTimer) NOT_NULL; void* closure = NULL; void* handle = NULL; mamaQueue mDefaultQueue = NULL; mama_f64_t newInterval = 10; mama_f64_t testInterval = 5; ASSERT_EQ(MAMA_STATUS_OK, mama_getDefaultEventQueue(mBridge,&mDefaultQueue)); ASSERT_EQ(MAMA_STATUS_OK, mamaQueue_getNativeHandle(mDefaultQueue, &handle)); ASSERT_EQ(MAMA_STATUS_OK, mBridge->bridgeMamaTimerCreate(&timer, handle, onTick, onTimerDestroy, interval, fakeParent, closure)); ASSERT_EQ(MAMA_STATUS_OK, mBridge->bridgeMamaTimerSetInterval(timer,newInterval)); ASSERT_EQ(MAMA_STATUS_OK, mBridge->bridgeMamaTimerGetInterval(timer,&testInterval)); ASSERT_EQ(testInterval, newInterval); } TEST_F (MiddlewareTimerTests, getIntervalInvalidTimerBridge) { mama_f64_t interval = 500; ASSERT_EQ (MAMA_STATUS_NULL_ARG, mBridge->bridgeMamaTimerGetInterval(NULL,&interval)); } TEST_F (MiddlewareTimerTests, getIntervalInvalidInterval) { timerBridge timer = (timerBridge) NOT_NULL; ASSERT_EQ (MAMA_STATUS_NULL_ARG, mBridge->bridgeMamaTimerGetInterval(timer,NULL)); } <|endoftext|>
<commit_before>/****************************************************************/ /* MOOSE - Multiphysics Object Oriented Simulation Environment */ /* */ /* All contents are licensed under LGPL V2.1 */ /* See LICENSE for full restrictions */ /****************************************************************/ #include "EulerAngleProvider2RGBAux.h" #include "GrainTracker.h" #include "EulerAngleProvider.h" #include "Euler2RGB.h" template<> InputParameters validParams<EulerAngleProvider2RGBAux>() { InputParameters params = validParams<AuxKernel>(); params.addClassDescription("Output RGB representation of crystal orientation from user object to an AuxVariable. The entire domain must have the same crystal structure."); MooseEnum sd_enum = MooseEnum("100=1 010=2 001=3", "001"); params.addParam<MooseEnum>("sd", sd_enum, "Reference sample direction"); MooseEnum structure_enum = MooseEnum("cubic=43 hexagonal=62 tetragonal=42 trigonal=32 orthorhombic=22 monoclinic=2 triclinic=1"); params.addRequiredParam<MooseEnum>("crystal_structure",structure_enum,"Crystal structure of the material"); MooseEnum output_types = MooseEnum("red green blue scalar", "scalar"); params.addParam<MooseEnum>("output_type", output_types, "Type of value that will be outputted"); params.addRequiredParam<UserObjectName>("euler_angle_provider", "Name of Euler angle provider user object"); params.addRequiredParam<UserObjectName>("grain_tracker", "The GrainTracker UserObject to get values from."); params.addParam<Point>("no_grain_color", Point(0, 0, 0), "RGB value of color used to represent area with no grains, defaults to black"); return params; } EulerAngleProvider2RGBAux::EulerAngleProvider2RGBAux(const InputParameters & parameters) : AuxKernel(parameters), _sd(getParam<MooseEnum>("sd")), _xtal_class(getParam<MooseEnum>("crystal_structure")), _output_type(getParam<MooseEnum>("output_type")), _euler(getUserObject<EulerAngleProvider>("euler_angle_provider")), _grain_tracker(getUserObject<GrainTracker>("grain_tracker")), _no_grain_color(getParam<Point>("no_grain_color")) { } void EulerAngleProvider2RGBAux::precalculateValue() { // ID of unique grain at current point const int grain_id = _grain_tracker.getEntityValue((isNodal() ? _current_node->id() : _current_elem->id()), FeatureFloodCount::FieldType::UNIQUE_REGION, 0); // Recover euler angles for current grain RealVectorValue angles; if (grain_id >= 0) angles = _euler.getEulerAngles(grain_id); // Assign correct RGB value either from euler2RGB or from _no_grain_color Point RGB; if (grain_id < 0) //If not in a grain, return _no_grain_color RGB = _no_grain_color; else RGB = euler2RGB(_sd, angles(0) / 180.0 * libMesh::pi, angles(1) / 180.0 * libMesh::pi, angles(2) / 180.0 * libMesh::pi, 1.0, _xtal_class); // Create correct scalar output if (_output_type < 3) _value = RGB(_output_type); else if (_output_type == 3) { Real RGBint = 0.0; for (unsigned int i = 0; i < 3; ++i) RGBint = 256 * RGBint + (RGB(i) >= 1 ? 255 : std::floor(RGB(i) * 256.0)); _value = RGBint; } else mooseError("Incorrect value for output_type in EulerAngleProvider2RGBAux"); } Real EulerAngleProvider2RGBAux::computeValue() { return _value; } <commit_msg>Check grain id validity (#8402)<commit_after>/****************************************************************/ /* MOOSE - Multiphysics Object Oriented Simulation Environment */ /* */ /* All contents are licensed under LGPL V2.1 */ /* See LICENSE for full restrictions */ /****************************************************************/ #include "EulerAngleProvider2RGBAux.h" #include "GrainTracker.h" #include "EulerAngleProvider.h" #include "Euler2RGB.h" template<> InputParameters validParams<EulerAngleProvider2RGBAux>() { InputParameters params = validParams<AuxKernel>(); params.addClassDescription("Output RGB representation of crystal orientation from user object to an AuxVariable. The entire domain must have the same crystal structure."); MooseEnum sd_enum = MooseEnum("100=1 010=2 001=3", "001"); params.addParam<MooseEnum>("sd", sd_enum, "Reference sample direction"); MooseEnum structure_enum = MooseEnum("cubic=43 hexagonal=62 tetragonal=42 trigonal=32 orthorhombic=22 monoclinic=2 triclinic=1"); params.addRequiredParam<MooseEnum>("crystal_structure",structure_enum,"Crystal structure of the material"); MooseEnum output_types = MooseEnum("red green blue scalar", "scalar"); params.addParam<MooseEnum>("output_type", output_types, "Type of value that will be outputted"); params.addRequiredParam<UserObjectName>("euler_angle_provider", "Name of Euler angle provider user object"); params.addRequiredParam<UserObjectName>("grain_tracker", "The GrainTracker UserObject to get values from."); params.addParam<Point>("no_grain_color", Point(0, 0, 0), "RGB value of color used to represent area with no grains, defaults to black"); return params; } EulerAngleProvider2RGBAux::EulerAngleProvider2RGBAux(const InputParameters & parameters) : AuxKernel(parameters), _sd(getParam<MooseEnum>("sd")), _xtal_class(getParam<MooseEnum>("crystal_structure")), _output_type(getParam<MooseEnum>("output_type")), _euler(getUserObject<EulerAngleProvider>("euler_angle_provider")), _grain_tracker(getUserObject<GrainTracker>("grain_tracker")), _no_grain_color(getParam<Point>("no_grain_color")) { } void EulerAngleProvider2RGBAux::precalculateValue() { // ID of unique grain at current point const int grain_id = _grain_tracker.getEntityValue((isNodal() ? _current_node->id() : _current_elem->id()), FeatureFloodCount::FieldType::UNIQUE_REGION, 0); // Recover Euler angles for current grain and assign correct // RGB value either from euler2RGB or from _no_grain_color Point RGB; if (grain_id >= 0 && grain_id < _euler.getGrainNum()) { const RealVectorValue & angles = _euler.getEulerAngles(grain_id); RGB = euler2RGB(_sd, angles(0) / 180.0 * libMesh::pi, angles(1) / 180.0 * libMesh::pi, angles(2) / 180.0 * libMesh::pi, 1.0, _xtal_class); } else RGB = _no_grain_color; // Create correct scalar output if (_output_type < 3) _value = RGB(_output_type); else if (_output_type == 3) { Real RGBint = 0.0; for (unsigned int i = 0; i < 3; ++i) RGBint = 256 * RGBint + (RGB(i) >= 1 ? 255 : std::floor(RGB(i) * 256.0)); _value = RGBint; } else mooseError("Incorrect value for output_type in EulerAngleProvider2RGBAux"); } Real EulerAngleProvider2RGBAux::computeValue() { return _value; } <|endoftext|>
<commit_before>//---------------------------------------------------------------------------// /* Copyright (c) 2014, Stuart R. Slattery 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 Oak Ridge National Laboratory nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ //---------------------------------------------------------------------------// /*! * \file consistent_interpolation.cpp * \author Stuart Slattery * \brief STK file-based consistent interpolation example. */ //---------------------------------------------------------------------------// #include <iostream> #include <vector> #include <cmath> #include <sstream> #include <algorithm> #include <cassert> #include <ctime> #include <cstdlib> #include "DTK_STKMeshDOFVector.hpp" #include "DTK_STKMeshHelpers.hpp" #include "DTK_STKMeshManager.hpp" #include "DTK_ConsistentInterpolationOperator.hpp" #include <Teuchos_GlobalMPISession.hpp> #include "Teuchos_CommandLineProcessor.hpp" #include "Teuchos_XMLParameterListCoreHelpers.hpp" #include "Teuchos_ParameterList.hpp" #include <Teuchos_DefaultComm.hpp> #include <Teuchos_DefaultMpiComm.hpp> #include <Teuchos_CommHelpers.hpp> #include <Teuchos_RCP.hpp> #include <Teuchos_ArrayRCP.hpp> #include <Teuchos_Array.hpp> #include <Teuchos_OpaqueWrapper.hpp> #include <Teuchos_TypeTraits.hpp> #include <Teuchos_VerboseObject.hpp> #include <Teuchos_StandardCatchMacros.hpp> #include <Teuchos_TimeMonitor.hpp> #include <Tpetra_MultiVector.hpp> #include <Intrepid_FieldContainer.hpp> #include <stk_util/parallel/Parallel.hpp> #include <stk_mesh/base/MetaData.hpp> #include <stk_mesh/base/BulkData.hpp> #include <stk_mesh/base/Types.hpp> #include <stk_mesh/base/FieldBase.hpp> #include <stk_mesh/base/Field.hpp> #include <stk_mesh/base/GetEntities.hpp> #include <stk_mesh/base/Selector.hpp> #include <stk_topology/topology.hpp> #include <stk_io/IossBridge.hpp> #include <stk_io/StkMeshIoBroker.hpp> #include <init/Ionit_Initializer.h> #include <Ioss_SubSystem.h> //---------------------------------------------------------------------------// // Example driver. //---------------------------------------------------------------------------// int main(int argc, char* argv[]) { // INITIALIZATION // -------------- // Setup communication. Teuchos::GlobalMPISession mpiSession(&argc,&argv); Teuchos::RCP<const Teuchos::Comm<int> > comm = Teuchos::DefaultComm<int>::getComm(); // Read in command line options. std::string xml_input_filename; Teuchos::CommandLineProcessor clp(false); clp.setOption( "xml-in-file", &xml_input_filename, "The XML file to read into a parameter list" ); clp.parse(argc,argv); // Build the parameter list from the xml input. Teuchos::RCP<Teuchos::ParameterList> plist = Teuchos::rcp( new Teuchos::ParameterList() ); Teuchos::updateParametersFromXmlFile( xml_input_filename, Teuchos::inoutArg(*plist) ); // Read command-line options std::string source_mesh_input_file = plist->get<std::string>("Source Mesh Input File"); std::string source_mesh_output_file = plist->get<std::string>("Source Mesh Output File"); std::string source_mesh_part_name = plist->get<std::string>("Source Mesh Part"); std::string target_mesh_input_file = plist->get<std::string>("Target Mesh Input File"); std::string target_mesh_output_file = plist->get<std::string>("Target Mesh Output File"); std::string target_mesh_part_name = plist->get<std::string>("Target Mesh Part"); // Get the raw mpi communicator (basic typedef in STK). Teuchos::RCP<const Teuchos::MpiComm<int> > mpi_comm = Teuchos::rcp_dynamic_cast<const Teuchos::MpiComm<int> >( comm ); Teuchos::RCP<const Teuchos::OpaqueWrapper<MPI_Comm> > opaque_comm = mpi_comm->getRawMpiComm(); stk::ParallelMachine parallel_machine = (*opaque_comm)(); // SOURCE MESH READ // ---------------- // Load the source mesh. stk::io::StkMeshIoBroker src_broker( parallel_machine ); std::size_t src_input_index = src_broker.add_mesh_database( source_mesh_input_file, "exodus", stk::io::READ_MESH ); src_broker.set_active_mesh( src_input_index ); src_broker.create_input_mesh(); // Add a nodal field to the source part. stk::mesh::Field<double>& source_field = src_broker.meta_data().declare_field<stk::mesh::Field<double> >( stk::topology::NODE_RANK, "u_src" ); stk::mesh::Part* src_part = src_broker.meta_data().get_part( source_mesh_part_name ); stk::mesh::put_field( source_field, *src_part ); // Create the source bulk data. src_broker.populate_bulk_data(); Teuchos::RCP<stk::mesh::BulkData> src_bulk_data = Teuchos::rcpFromRef( src_broker.bulk_data() ); // Put some data in the source field. We will use the distance of the node // from the origin as the data. stk::mesh::Selector src_stk_selector( *src_part ); stk::mesh::BucketVector src_part_buckets = src_stk_selector.get_buckets( stk::topology::NODE_RANK ); std::vector<stk::mesh::Entity> src_part_nodes; stk::mesh::get_selected_entities( src_stk_selector, src_part_buckets, src_part_nodes ); Intrepid::FieldContainer<double> src_node_coords = DataTransferKit::STKMeshHelpers::getEntityNodeCoordinates( Teuchos::Array<stk::mesh::Entity>(src_part_nodes), *src_bulk_data ); double* src_field_data; int num_src_part_nodes = src_part_nodes.size(); for ( int n = 0; n < num_src_part_nodes; ++n ) { src_field_data = stk::mesh::field_data( source_field, src_part_nodes[n] ); src_field_data[0] = src_node_coords(n,0,0)*src_node_coords(n,0,0) + src_node_coords(n,0,1)*src_node_coords(n,0,1) + src_node_coords(n,0,2)*src_node_coords(n,0,2); } // TARGET MESH READ // ---------------- // Load the target mesh. stk::io::StkMeshIoBroker tgt_broker( parallel_machine ); std::size_t tgt_input_index = tgt_broker.add_mesh_database( target_mesh_input_file, "exodus", stk::io::READ_MESH ); tgt_broker.set_active_mesh( tgt_input_index ); tgt_broker.create_input_mesh(); // Add a nodal field to the target part. stk::mesh::Field<double>& target_field = tgt_broker.meta_data().declare_field<stk::mesh::Field<double> >( stk::topology::NODE_RANK, "u_tgt" ); stk::mesh::Part* tgt_part = tgt_broker.meta_data().get_part( target_mesh_part_name ); stk::mesh::put_field( target_field, *tgt_part ); // Create the target bulk data. tgt_broker.populate_bulk_data(); Teuchos::RCP<stk::mesh::BulkData> tgt_bulk_data = Teuchos::rcpFromRef( tgt_broker.bulk_data() ); // SOLUTION TRANSFER SETUP // ----------------------- // Solution transfer parameters. Teuchos::RCP<Teuchos::ParameterList> parameters = Teuchos::parameterList(); // Create a manager for the source part elements. DataTransferKit::STKMeshManager src_manager( src_bulk_data, src_stk_selector, DataTransferKit::ENTITY_TYPE_VOLUME ); // Create a manager for the target part nodes. stk::mesh::Selector tgt_stk_selector( *tgt_part ); DataTransferKit::STKMeshManager tgt_manager( tgt_bulk_data, tgt_stk_selector, DataTransferKit::ENTITY_TYPE_NODE ); // Create a solution vector for the source. Teuchos::RCP<Tpetra::MultiVector<double,int,std::size_t> > src_vector = DataTransferKit::STKMeshDOFVector::pullTpetraMultiVectorFromSTKField<double>( *src_bulk_data, source_field, 1 ); // Create a solution vector for the target. Teuchos::RCP<Tpetra::MultiVector<double,int,std::size_t> > tgt_vector = DataTransferKit::STKMeshDOFVector::pullTpetraMultiVectorFromSTKField<double>( *tgt_bulk_data, target_field, 1 ); // SOLUTION TRANSFER // ----------------- // Create a consistent interpolation operator. DataTransferKit::ConsistentInterpolationOperator<double> interpolation_operator; // Setup the consistent interpolation operator. interpolation_operator.setup( src_vector->getMap(), src_manager.functionSpace(), tgt_vector->getMap(), tgt_manager.functionSpace(), parameters ); // Apply the consistent interpolation operator. interpolation_operator.apply( *src_vector, *tgt_vector ); // Push the target vector onto the target mesh. DataTransferKit::STKMeshDOFVector::pushTpetraMultiVectorToSTKField( *tgt_vector, *tgt_bulk_data, target_field ); // SOURCE MESH WRITE // ----------------- std::size_t src_output_index = src_broker.create_output_mesh( source_mesh_output_file, stk::io::WRITE_RESULTS ); src_broker.add_field( src_output_index, source_field ); src_broker.begin_output_step( src_output_index, 0.0 ); src_broker.write_defined_output_fields( src_output_index ); src_broker.end_output_step( src_output_index ); // TARGET MESH WRITE // ----------------- std::size_t tgt_output_index = tgt_broker.create_output_mesh( target_mesh_output_file, stk::io::WRITE_RESULTS ); tgt_broker.add_field( tgt_output_index, target_field ); tgt_broker.begin_output_step( tgt_output_index, 0.0 ); tgt_broker.write_defined_output_fields( tgt_output_index ); tgt_broker.end_output_step( tgt_output_index ); } //---------------------------------------------------------------------------// // end tstSTK_Mesh.cpp //---------------------------------------------------------------------------// <commit_msg>adding error calculation to interpolation<commit_after>//---------------------------------------------------------------------------// /* Copyright (c) 2014, Stuart R. Slattery 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 Oak Ridge National Laboratory nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ //---------------------------------------------------------------------------// /*! * \file consistent_interpolation.cpp * \author Stuart Slattery * \brief STK file-based consistent interpolation example. */ //---------------------------------------------------------------------------// #include <iostream> #include <vector> #include <cmath> #include <sstream> #include <algorithm> #include <cassert> #include <ctime> #include <cstdlib> #include "DTK_STKMeshDOFVector.hpp" #include "DTK_STKMeshHelpers.hpp" #include "DTK_STKMeshManager.hpp" #include "DTK_ConsistentInterpolationOperator.hpp" #include <Teuchos_GlobalMPISession.hpp> #include "Teuchos_CommandLineProcessor.hpp" #include "Teuchos_XMLParameterListCoreHelpers.hpp" #include "Teuchos_ParameterList.hpp" #include <Teuchos_DefaultComm.hpp> #include <Teuchos_DefaultMpiComm.hpp> #include <Teuchos_CommHelpers.hpp> #include <Teuchos_RCP.hpp> #include <Teuchos_ArrayRCP.hpp> #include <Teuchos_Array.hpp> #include <Teuchos_OpaqueWrapper.hpp> #include <Teuchos_TypeTraits.hpp> #include <Teuchos_VerboseObject.hpp> #include <Teuchos_StandardCatchMacros.hpp> #include <Teuchos_TimeMonitor.hpp> #include <Tpetra_MultiVector.hpp> #include <Intrepid_FieldContainer.hpp> #include <stk_util/parallel/Parallel.hpp> #include <stk_mesh/base/MetaData.hpp> #include <stk_mesh/base/BulkData.hpp> #include <stk_mesh/base/Types.hpp> #include <stk_mesh/base/FieldBase.hpp> #include <stk_mesh/base/Field.hpp> #include <stk_mesh/base/GetEntities.hpp> #include <stk_mesh/base/Selector.hpp> #include <stk_topology/topology.hpp> #include <stk_io/IossBridge.hpp> #include <stk_io/StkMeshIoBroker.hpp> #include <init/Ionit_Initializer.h> #include <Ioss_SubSystem.h> //---------------------------------------------------------------------------// // Data field function. //---------------------------------------------------------------------------// double dataFunction( double x, double y, double z ) { return std::abs(x) + std::abs(y) + std::abs(z) + 1.0; } //---------------------------------------------------------------------------// // Example driver. //---------------------------------------------------------------------------// int main(int argc, char* argv[]) { // INITIALIZATION // -------------- // Setup communication. Teuchos::GlobalMPISession mpiSession(&argc,&argv); Teuchos::RCP<const Teuchos::Comm<int> > comm = Teuchos::DefaultComm<int>::getComm(); // Read in command line options. std::string xml_input_filename; Teuchos::CommandLineProcessor clp(false); clp.setOption( "xml-in-file", &xml_input_filename, "The XML file to read into a parameter list" ); clp.parse(argc,argv); // Build the parameter list from the xml input. Teuchos::RCP<Teuchos::ParameterList> plist = Teuchos::rcp( new Teuchos::ParameterList() ); Teuchos::updateParametersFromXmlFile( xml_input_filename, Teuchos::inoutArg(*plist) ); // Read command-line options std::string source_mesh_input_file = plist->get<std::string>("Source Mesh Input File"); std::string source_mesh_output_file = plist->get<std::string>("Source Mesh Output File"); std::string source_mesh_part_name = plist->get<std::string>("Source Mesh Part"); std::string target_mesh_input_file = plist->get<std::string>("Target Mesh Input File"); std::string target_mesh_output_file = plist->get<std::string>("Target Mesh Output File"); std::string target_mesh_part_name = plist->get<std::string>("Target Mesh Part"); // Get the raw mpi communicator (basic typedef in STK). Teuchos::RCP<const Teuchos::MpiComm<int> > mpi_comm = Teuchos::rcp_dynamic_cast<const Teuchos::MpiComm<int> >( comm ); Teuchos::RCP<const Teuchos::OpaqueWrapper<MPI_Comm> > opaque_comm = mpi_comm->getRawMpiComm(); stk::ParallelMachine parallel_machine = (*opaque_comm)(); // SOURCE MESH READ // ---------------- // Load the source mesh. stk::io::StkMeshIoBroker src_broker( parallel_machine ); std::size_t src_input_index = src_broker.add_mesh_database( source_mesh_input_file, "exodus", stk::io::READ_MESH ); src_broker.set_active_mesh( src_input_index ); src_broker.create_input_mesh(); // Add a nodal field to the source part. stk::mesh::Field<double>& source_field = src_broker.meta_data().declare_field<stk::mesh::Field<double> >( stk::topology::NODE_RANK, "u_src" ); stk::mesh::Part* src_part = src_broker.meta_data().get_part( source_mesh_part_name ); stk::mesh::put_field( source_field, *src_part ); // Create the source bulk data. src_broker.populate_bulk_data(); Teuchos::RCP<stk::mesh::BulkData> src_bulk_data = Teuchos::rcpFromRef( src_broker.bulk_data() ); // Put some data in the source field. We will use the distance of the node // from the origin as the data. stk::mesh::Selector src_stk_selector( *src_part ); stk::mesh::BucketVector src_part_buckets = src_stk_selector.get_buckets( stk::topology::NODE_RANK ); std::vector<stk::mesh::Entity> src_part_nodes; stk::mesh::get_selected_entities( src_stk_selector, src_part_buckets, src_part_nodes ); Intrepid::FieldContainer<double> src_node_coords = DataTransferKit::STKMeshHelpers::getEntityNodeCoordinates( Teuchos::Array<stk::mesh::Entity>(src_part_nodes), *src_bulk_data ); double* src_field_data; int num_src_part_nodes = src_part_nodes.size(); for ( int n = 0; n < num_src_part_nodes; ++n ) { src_field_data = stk::mesh::field_data( source_field, src_part_nodes[n] ); src_field_data[0] = dataFunction( src_node_coords(n,0,0), src_node_coords(n,0,1), src_node_coords(n,0,2) ); } // TARGET MESH READ // ---------------- // Load the target mesh. stk::io::StkMeshIoBroker tgt_broker( parallel_machine ); std::size_t tgt_input_index = tgt_broker.add_mesh_database( target_mesh_input_file, "exodus", stk::io::READ_MESH ); tgt_broker.set_active_mesh( tgt_input_index ); tgt_broker.create_input_mesh(); // Add a nodal field to the target part. stk::mesh::Field<double>& target_field = tgt_broker.meta_data().declare_field<stk::mesh::Field<double> >( stk::topology::NODE_RANK, "u_tgt" ); stk::mesh::Part* tgt_part = tgt_broker.meta_data().get_part( target_mesh_part_name ); stk::mesh::put_field( target_field, *tgt_part ); // Add an error nodal field to the target part. stk::mesh::Field<double>& target_error_field = tgt_broker.meta_data().declare_field<stk::mesh::Field<double> >( stk::topology::NODE_RANK, "u_err" ); stk::mesh::put_field( target_error_field, *tgt_part ); // Create the target bulk data. tgt_broker.populate_bulk_data(); Teuchos::RCP<stk::mesh::BulkData> tgt_bulk_data = Teuchos::rcpFromRef( tgt_broker.bulk_data() ); // SOLUTION TRANSFER SETUP // ----------------------- // Solution transfer parameters. Teuchos::RCP<Teuchos::ParameterList> parameters = Teuchos::parameterList(); // Create a manager for the source part elements. DataTransferKit::STKMeshManager src_manager( src_bulk_data, src_stk_selector, DataTransferKit::ENTITY_TYPE_VOLUME ); // Create a manager for the target part nodes. stk::mesh::Selector tgt_stk_selector( *tgt_part ); DataTransferKit::STKMeshManager tgt_manager( tgt_bulk_data, tgt_stk_selector, DataTransferKit::ENTITY_TYPE_NODE ); // Create a solution vector for the source. Teuchos::RCP<Tpetra::MultiVector<double,int,std::size_t> > src_vector = DataTransferKit::STKMeshDOFVector::pullTpetraMultiVectorFromSTKField<double>( *src_bulk_data, source_field, 1 ); // Create a solution vector for the target. Teuchos::RCP<Tpetra::MultiVector<double,int,std::size_t> > tgt_vector = DataTransferKit::STKMeshDOFVector::pullTpetraMultiVectorFromSTKField<double>( *tgt_bulk_data, target_field, 1 ); // SOLUTION TRANSFER // ----------------- // Create a consistent interpolation operator. DataTransferKit::ConsistentInterpolationOperator<double> interpolation_operator; // Setup the consistent interpolation operator. interpolation_operator.setup( src_vector->getMap(), src_manager.functionSpace(), tgt_vector->getMap(), tgt_manager.functionSpace(), parameters ); // Apply the consistent interpolation operator. interpolation_operator.apply( *src_vector, *tgt_vector ); // Push the target vector onto the target mesh. DataTransferKit::STKMeshDOFVector::pushTpetraMultiVectorToSTKField( *tgt_vector, *tgt_bulk_data, target_field ); // COMPUTE THE SOLUTION ERROR // -------------------------- stk::mesh::BucketVector tgt_part_buckets = tgt_stk_selector.get_buckets( stk::topology::NODE_RANK ); std::vector<stk::mesh::Entity> tgt_part_nodes; stk::mesh::get_selected_entities( tgt_stk_selector, tgt_part_buckets, tgt_part_nodes ); Intrepid::FieldContainer<double> tgt_node_coords = DataTransferKit::STKMeshHelpers::getEntityNodeCoordinates( Teuchos::Array<stk::mesh::Entity>(tgt_part_nodes), *tgt_bulk_data ); double* tgt_field_data; double* err_field_data; int num_tgt_part_nodes = tgt_part_nodes.size(); double error_l2_norm = 0.0; double field_l2_norm = 0.0; for ( int n = 0; n < num_tgt_part_nodes; ++n ) { double gold_value = dataFunction( tgt_node_coords(n,0,0), tgt_node_coords(n,0,1), tgt_node_coords(n,0,2) ); tgt_field_data = stk::mesh::field_data( target_field, tgt_part_nodes[n] ); err_field_data = stk::mesh::field_data( target_error_field, tgt_part_nodes[n] ); err_field_data[0] = tgt_field_data[0] - gold_value; error_l2_norm += err_field_data[0] * err_field_data[0]; field_l2_norm += tgt_field_data[0] * tgt_field_data[0]; err_field_data[0] /= gold_value; } error_l2_norm = std::sqrt( error_l2_norm ); field_l2_norm = std::sqrt( field_l2_norm ); std::cout << "|e|_2 / |f|_2: " << error_l2_norm / field_l2_norm << std::endl; // SOURCE MESH WRITE // ----------------- std::size_t src_output_index = src_broker.create_output_mesh( source_mesh_output_file, stk::io::WRITE_RESULTS ); src_broker.add_field( src_output_index, source_field ); src_broker.begin_output_step( src_output_index, 0.0 ); src_broker.write_defined_output_fields( src_output_index ); src_broker.end_output_step( src_output_index ); // TARGET MESH WRITE // ----------------- std::size_t tgt_output_index = tgt_broker.create_output_mesh( target_mesh_output_file, stk::io::WRITE_RESULTS ); tgt_broker.add_field( tgt_output_index, target_field ); tgt_broker.add_field( tgt_output_index, target_error_field ); tgt_broker.begin_output_step( tgt_output_index, 0.0 ); tgt_broker.write_defined_output_fields( tgt_output_index ); tgt_broker.end_output_step( tgt_output_index ); } //---------------------------------------------------------------------------// // end tstSTK_Mesh.cpp //---------------------------------------------------------------------------// <|endoftext|>
<commit_before>#include "thruster_tortuga.h" ThrusterTortugaNode::ThrusterTortugaNode(int argc, char **argv, int rate): TortugaNode(){ ros::Rate loop_rate(rate); subscriber = n.subscribe("/qubo/thruster_input", 1000, &ThrusterTortugaNode::thrusterCallBack, this); ROS_DEBUG("Opening sensorboard"); sensor_file = "/dev/sensor"; fd = openSensorBoard(sensor_file.c_str()); ROS_DEBUG("Opened sensorboard with fd %d.", fd); checkError(syncBoard(fd)); ROS_DEBUG("Synced with the Board"); //GH: This is not the correct use of checkError. //It should be called on the return value of a function call, not on the file descriptor. //checkError(fd); // Unsafe all the thrusters ROS_DEBUG("Unsafing all thrusters"); for (int i = 6; i <= 11; i++) { checkError(setThrusterSafety(fd, i)); } ROS_DEBUG("Unsafed all thrusters"); for(int i = 0; i < NUM_THRUSTERS; i++){ thruster_powers.data[i] = 0; } } ThrusterTortugaNode::~ThrusterTortugaNode(){ //Stop all the thrusters ROS_DEBUG("Stopping thrusters"); readSpeedResponses(fd); setSpeeds(fd, 0, 0, 0, 0, 0, 0); ROS_DEBUG("Safing thrusters"); // Safe all the thrusters for (int i = 0; i <= 5; i++) { checkError(setThrusterSafety(fd, i)); } ROS_DEBUG("Safed thrusters"); //Close the sensorboard close(fd); } void ThrusterTortugaNode::update(){ //I think we need to initialize thrusters and stuff before this will work ros::spinOnce(); // setSpeeds(fd, msg.data[0], msg.data[1], msg.data[2], msg.data[3], msg.data[4], msg.data[5]); // ROS_DEBUG("fd = %x",fd); ROS_DEBUG("Setting thruster speeds"); int retR = readSpeedResponses(fd); ROS_DEBUG("Read speed before: %x", retR); int retS = setSpeeds(fd, 128, 128, 128, 128, 128, 128); ROS_DEBUG("Set speed status: %x", retS); usleep(20*1000); int retA = readSpeedResponses(fd); ROS_DEBUG("Read speed after: %x", retA); ROS_DEBUG("thruster state = %x", readThrusterState(fd)); ROS_DEBUG("set speed returns %x", retS); ROS_DEBUG("read speed returns %x", retR); } void ThrusterTortugaNode::publish(){ // setSpeeds(fd, msg.data[0], msg.data[1], msg.data[2], msg.data[3], msg.data[4], msg.data[5]); } void ThrusterTortugaNode::thrusterCallBack(const std_msgs::Int64MultiArray new_powers){ //SG: TODO change this shit for(int i = 0 ;i < NUM_THRUSTERS; i++){ thruster_powers.data[i] = new_powers.data[i]; } } //ssh robot@192.168.10.12 <commit_msg>we now actually use the values we subscribe to.. also added some more debug output<commit_after>#include "thruster_tortuga.h" ThrusterTortugaNode::ThrusterTortugaNode(int argc, char **argv, int rate): TortugaNode(){ ros::Rate loop_rate(rate); subscriber = n.subscribe("/qubo/thruster_input", 1000, &ThrusterTortugaNode::thrusterCallBack, this); ROS_DEBUG("Opening sensorboard"); sensor_file = "/dev/sensor"; fd = openSensorBoard(sensor_file.c_str()); ROS_DEBUG("Opened sensorboard with fd %d.", fd); checkError(syncBoard(fd)); ROS_DEBUG("Synced with the Board"); //GH: This is not the correct use of checkError. //It should be called on the return value of a function call, not on the file descriptor. //checkError(fd); // Unsafe all the thrusters ROS_DEBUG("Unsafing all thrusters"); for (int i = 6; i <= 11; i++) { checkError(setThrusterSafety(fd, i)); } ROS_DEBUG("Unsafed all thrusters"); for(int i = 0; i < NUM_THRUSTERS; i++){ thruster_powers.data[i] = 0; } } ThrusterTortugaNode::~ThrusterTortugaNode(){ //Stop all the thrusters ROS_DEBUG("Stopping thrusters"); readSpeedResponses(fd); setSpeeds(fd, 0, 0, 0, 0, 0, 0); ROS_DEBUG("Safing thrusters"); // Safe all the thrusters for (int i = 0; i <= 5; i++) { checkError(setThrusterSafety(fd, i)); } ROS_DEBUG("Safed thrusters"); //Close the sensorboard close(fd); } void ThrusterTortugaNode::update(){ //I think we need to initialize thrusters and stuff before this will work ros::spinOnce(); // setSpeeds(fd, msg.data[0], msg.data[1], msg.data[2], msg.data[3], msg.data[4], msg.data[5]); // ROS_DEBUG("fd = %x",fd); ROS_DEBUG("Setting thruster speeds"); int retR = readSpeedResponses(fd); ROS_DEBUG("Read speed before: %x", retR); for(int i = 0 ;i < NUM_THRUSTERS; i++){ ROS_DEBUG("thruster value %i = %i\n" i, thruster_powers.data[i]) } int retS = setSpeeds(fd, thruster_powers.data[0], , thruster_powers.data[1], thruster_powers.data[2], thruster_powers[3], thruster_powers[4]); ROS_DEBUG("Set speed status: %x", retS); usleep(20*1000); int retA = readSpeedResponses(fd); ROS_DEBUG("Read speed after: %x", retA); ROS_DEBUG("thruster state = %x", readThrusterState(fd)); ROS_DEBUG("set speed returns %x", retS); ROS_DEBUG("read speed returns %x", retR); } void ThrusterTortugaNode::publish(){ // setSpeeds(fd, msg.data[0], msg.data[1], msg.data[2], msg.data[3], msg.data[4], msg.data[5]); } void ThrusterTortugaNode::thrusterCallBack(const std_msgs::Int64MultiArray new_powers){ for(int i = 0 ;i < NUM_THRUSTERS; i++){ thruster_powers.data[i] = new_powers.data[i]; } } //ssh robot@192.168.10.12 <|endoftext|>
<commit_before>#include "ClientSocket.hh" #include "Server.hh" #include <signal.h> #include <fstream> #include <random> #include <string> #include <vector> Server server; void handleExitSignal( int /* signal */ ) { server.close(); } void unescapeQuote( std::string& quote ) { std::size_t position = 0; std::string target = "\\n"; std::string replacement = "\n"; while( ( position = quote.find( target, position ) ) != std::string::npos ) { quote.replace( position, target.length(), replacement ); position += replacement.length(); } } std::vector<std::string> readQuotes( const std::string& filename ) { std::ifstream in( filename ); if( !in ) return {}; std::vector<std::string> quotes; std::string line; while( std::getline( in, line ) ) { unescapeQuote( line ); quotes.push_back( line ); } return quotes; } int main( int argc, char** argv ) { std::vector<std::string> quotes; if( argc > 1 ) quotes = readQuotes( argv[1] ); else quotes = { "Sorry, no quote today, mate.\n" }; std::random_device rd; std::mt19937 rng( rd() ); std::uniform_int_distribution<std::size_t> distribution( 0, quotes.size() - 1 ); signal( SIGINT, handleExitSignal ); server.setPort( 2048 ); server.onAccept( [&] ( std::unique_ptr<ClientSocket> socket ) { socket->write( quotes.at( distribution( rng ) ) ); socket->close(); } ); server.listen(); return 0; } <commit_msg>Changed QOTD port<commit_after>#include "ClientSocket.hh" #include "Server.hh" #include <signal.h> #include <fstream> #include <random> #include <string> #include <vector> Server server; void handleExitSignal( int /* signal */ ) { server.close(); } void unescapeQuote( std::string& quote ) { std::size_t position = 0; std::string target = "\\n"; std::string replacement = "\n"; while( ( position = quote.find( target, position ) ) != std::string::npos ) { quote.replace( position, target.length(), replacement ); position += replacement.length(); } } std::vector<std::string> readQuotes( const std::string& filename ) { std::ifstream in( filename ); if( !in ) return {}; std::vector<std::string> quotes; std::string line; while( std::getline( in, line ) ) { unescapeQuote( line ); quotes.push_back( line ); } return quotes; } int main( int argc, char** argv ) { std::vector<std::string> quotes; if( argc > 1 ) quotes = readQuotes( argv[1] ); else quotes = { "Sorry, no quote today, mate.\n" }; std::random_device rd; std::mt19937 rng( rd() ); std::uniform_int_distribution<std::size_t> distribution( 0, quotes.size() - 1 ); signal( SIGINT, handleExitSignal ); server.setPort( 1041 ); server.onAccept( [&] ( std::unique_ptr<ClientSocket> socket ) { socket->write( quotes.at( distribution( rng ) ) ); socket->close(); } ); server.listen(); return 0; } <|endoftext|>
<commit_before>/* * Copyright (c) 2010 ARM Limited * All rights reserved * * The license below extends only to copyright in the software and shall * not be construed as granting a license to any other intellectual * property including but not limited to intellectual property relating * to a hardware implementation of the functionality of the software * licensed hereunder. You may use the software subject to the license * terms below provided that you ensure that this notice is replicated * unmodified and in its entirety in all distributions of the software, * modified or unmodified, in source code or in binary form. * * Copyright (c) 2005 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. * * Authors: Ali Saidi */ /** @file * Implementiation of a PL390 GIC */ #ifndef __DEV_ARM_GIC_PL390_H__ #define __DEV_ARM_GIC_PL390_H__ #include "base/bitunion.hh" #include "cpu/intr_control.hh" #include "dev/arm/base_gic.hh" #include "dev/io_device.hh" #include "dev/platform.hh" #include "params/Pl390.hh" /** @todo this code only assumes one processor for now. Low word * of intEnabled and pendingInt need to be replicated per CPU. * bottom 31 interrupts (7 words) need to be replicated for * for interrupt priority register, processor target registers * interrupt config registers */ class Pl390 : public BaseGic { protected: // distributor memory addresses static const int ICDDCR = 0x000; // control register static const int ICDICTR = 0x004; // controller type static const int ICDIIDR = 0x008; // implementer id static const int ICDISER_ST = 0x100; // interrupt set enable static const int ICDISER_ED = 0x17c; static const int ICDICER_ST = 0x180; // interrupt clear enable static const int ICDICER_ED = 0x1fc; static const int ICDISPR_ST = 0x200; // set pending interrupt static const int ICDISPR_ED = 0x27c; static const int ICDICPR_ST = 0x280; // clear pending interrupt static const int ICDICPR_ED = 0x2fc; static const int ICDABR_ST = 0x300; // active bit registers static const int ICDABR_ED = 0x37c; static const int ICDIPR_ST = 0x400; // interrupt priority registers static const int ICDIPR_ED = 0x7f8; static const int ICDIPTR_ST = 0x800; // processor target registers static const int ICDIPTR_ED = 0xbf8; static const int ICDICFR_ST = 0xc00; // interrupt config registers static const int ICDICFR_ED = 0xcfc; static const int ICDSGIR = 0xf00; // software generated interrupt static const int DIST_SIZE = 0xfff; // cpu memory addressesa static const int ICCICR = 0x00; // CPU control register static const int ICCPMR = 0x04; // Interrupt priority mask static const int ICCBPR = 0x08; // binary point register static const int ICCIAR = 0x0C; // interrupt ack register static const int ICCEOIR = 0x10; // end of interrupt static const int ICCRPR = 0x14; // runing priority static const int ICCHPIR = 0x18; // highest pending interrupt static const int ICCABPR = 0x1c; // aliased binary point static const int ICCIIDR = 0xfc; // cpu interface id register static const int CPU_SIZE = 0xff; static const int SGI_MAX = 16; // Number of Software Gen Interrupts static const int PPI_MAX = 16; // Number of Private Peripheral Interrupts /** Mask off SGI's when setting/clearing pending bits */ static const int SGI_MASK = 0xFFFF0000; /** Mask for bits that config N:N mode in ICDICFR's */ static const int NN_CONFIG_MASK = 0x55555555; static const int CPU_MAX = 8; // Max number of supported CPU interfaces static const int SPURIOUS_INT = 1023; static const int INT_BITS_MAX = 32; static const int INT_LINES_MAX = 1020; BitUnion32(SWI) Bitfield<3,0> sgi_id; Bitfield<23,16> cpu_list; Bitfield<25,24> list_type; EndBitUnion(SWI) BitUnion32(IAR) Bitfield<9,0> ack_id; Bitfield<12,10> cpu_id; EndBitUnion(IAR) /** Distributor address GIC listens at */ Addr distAddr; /** CPU address GIC listens at */ /** @todo is this one per cpu? */ Addr cpuAddr; /** Latency for a distributor operation */ Tick distPioDelay; /** Latency for a cpu operation */ Tick cpuPioDelay; /** Latency for a interrupt to get to CPU */ Tick intLatency; /** Gic enabled */ bool enabled; /** Number of itLines enabled */ uint32_t itLines; uint32_t itLinesLog2; /** interrupt enable bits for all possible 1020 interupts. * one bit per interrupt, 32 bit per word = 32 words */ uint32_t intEnabled[INT_BITS_MAX]; /** interrupt pending bits for all possible 1020 interupts. * one bit per interrupt, 32 bit per word = 32 words */ uint32_t pendingInt[INT_BITS_MAX]; /** interrupt active bits for all possible 1020 interupts. * one bit per interrupt, 32 bit per word = 32 words */ uint32_t activeInt[INT_BITS_MAX]; /** read only running priroity register, 1 per cpu*/ uint32_t iccrpr[CPU_MAX]; /** an 8 bit priority (lower is higher priority) for each * of the 1020 possible supported interrupts. */ uint8_t intPriority[INT_LINES_MAX]; /** an 8 bit cpu target id for each shared peripheral interrupt * of the 1020 possible supported interrupts. */ uint8_t cpuTarget[INT_LINES_MAX]; /** 2 bit per interrupt signaling if it's level or edge sensitive * and if it is 1:N or N:N */ uint32_t intConfig[INT_BITS_MAX*2]; /** CPU enabled */ bool cpuEnabled[CPU_MAX]; /** CPU priority */ uint8_t cpuPriority[CPU_MAX]; /** Binary point registers */ uint8_t cpuBpr[CPU_MAX]; /** highest interrupt that is interrupting CPU */ uint32_t cpuHighestInt[CPU_MAX]; /** One bit per cpu per software interrupt that is pending for each possible * sgi source. Indexed by SGI number. Each byte in generating cpu id and * bits in position is destination id. e.g. 0x4 = CPU 0 generated interrupt * for CPU 2. */ uint64_t cpuSgiPending[SGI_MAX]; uint64_t cpuSgiActive[SGI_MAX]; /** One bit per private peripheral interrupt. Only upper 16 bits * will be used since PPI interrupts are numberred from 16 to 32 */ uint32_t cpuPpiPending[CPU_MAX]; uint32_t cpuPpiActive[CPU_MAX]; /** Banked interrupt prioirty registers for SGIs and PPIs */ uint8_t bankedIntPriority[CPU_MAX][SGI_MAX + PPI_MAX]; /** IRQ Enable Used for debug */ bool irqEnable; /** software generated interrupt * @param data data to decode that indicates which cpus to interrupt */ void softInt(int ctx_id, SWI swi); /** See if some processor interrupt flags need to be enabled/disabled * @param hint which set of interrupts needs to be checked */ void updateIntState(int hint); /** Update the register that records priority of the highest priority * active interrupt*/ void updateRunPri(); /** generate a bit mask to check cpuSgi for an interrupt. */ uint64_t genSwiMask(int cpu); int intNumToWord(int num) const { return num >> 5; } int intNumToBit(int num) const { return num % 32; } /** Post an interrupt to a CPU */ void postInt(uint32_t cpu, Tick when); /** Event definition to post interrupt to CPU after a delay */ class PostIntEvent : public Event { private: uint32_t cpu; Platform *platform; public: PostIntEvent( uint32_t c, Platform* p) : cpu(c), platform(p) { } void process() { platform->intrctrl->post(cpu, ArmISA::INT_IRQ, 0);} const char *description() const { return "Post Interrupt to CPU"; } }; PostIntEvent *postIntEvent[CPU_MAX]; public: typedef Pl390Params Params; const Params * params() const { return dynamic_cast<const Params *>(_params); } Pl390(const Params *p); /** Return the address ranges used by the Gic * This is the distributor address + all cpu addresses */ virtual AddrRangeList getAddrRanges() const; /** A PIO read to the device, immediately split up into * readDistributor() or readCpu() */ virtual Tick read(PacketPtr pkt); /** A PIO read to the device, immediately split up into * writeDistributor() or writeCpu() */ virtual Tick write(PacketPtr pkt); /** Handle a read to the distributor poriton of the GIC * @param pkt packet to respond to */ Tick readDistributor(PacketPtr pkt); /** Handle a read to the cpu poriton of the GIC * @param pkt packet to respond to */ Tick readCpu(PacketPtr pkt); /** Handle a write to the distributor poriton of the GIC * @param pkt packet to respond to */ Tick writeDistributor(PacketPtr pkt); /** Handle a write to the cpu poriton of the GIC * @param pkt packet to respond to */ Tick writeCpu(PacketPtr pkt); /** Post an interrupt from a device that is connected to the Gic. * Depending on the configuration, the gic will pass this interrupt * on through to a CPU. * @param number number of interrupt to send */ void sendInt(uint32_t number); /** Interface call for private peripheral interrupts */ void sendPPInt(uint32_t num, uint32_t cpu); /** Clear an interrupt from a device that is connected to the Gic * Depending on the configuration, the gic may de-assert it's cpu line * @param number number of interrupt to send */ void clearInt(uint32_t number); /* Various functions fer testing and debugging */ void driveSPI(uint32_t spi); void driveLegIRQ(bool state); void driveLegFIQ(bool state); void driveIrqEn(bool state); virtual void serialize(std::ostream &os); virtual void unserialize(Checkpoint *cp, const std::string &section); }; #endif //__DEV_ARM_GIC_H__ <commit_msg>arm: Don't export private GIC methods<commit_after>/* * Copyright (c) 2010 ARM Limited * All rights reserved * * The license below extends only to copyright in the software and shall * not be construed as granting a license to any other intellectual * property including but not limited to intellectual property relating * to a hardware implementation of the functionality of the software * licensed hereunder. You may use the software subject to the license * terms below provided that you ensure that this notice is replicated * unmodified and in its entirety in all distributions of the software, * modified or unmodified, in source code or in binary form. * * Copyright (c) 2005 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. * * Authors: Ali Saidi */ /** @file * Implementiation of a PL390 GIC */ #ifndef __DEV_ARM_GIC_PL390_H__ #define __DEV_ARM_GIC_PL390_H__ #include "base/bitunion.hh" #include "cpu/intr_control.hh" #include "dev/arm/base_gic.hh" #include "dev/io_device.hh" #include "dev/platform.hh" #include "params/Pl390.hh" /** @todo this code only assumes one processor for now. Low word * of intEnabled and pendingInt need to be replicated per CPU. * bottom 31 interrupts (7 words) need to be replicated for * for interrupt priority register, processor target registers * interrupt config registers */ class Pl390 : public BaseGic { protected: // distributor memory addresses static const int ICDDCR = 0x000; // control register static const int ICDICTR = 0x004; // controller type static const int ICDIIDR = 0x008; // implementer id static const int ICDISER_ST = 0x100; // interrupt set enable static const int ICDISER_ED = 0x17c; static const int ICDICER_ST = 0x180; // interrupt clear enable static const int ICDICER_ED = 0x1fc; static const int ICDISPR_ST = 0x200; // set pending interrupt static const int ICDISPR_ED = 0x27c; static const int ICDICPR_ST = 0x280; // clear pending interrupt static const int ICDICPR_ED = 0x2fc; static const int ICDABR_ST = 0x300; // active bit registers static const int ICDABR_ED = 0x37c; static const int ICDIPR_ST = 0x400; // interrupt priority registers static const int ICDIPR_ED = 0x7f8; static const int ICDIPTR_ST = 0x800; // processor target registers static const int ICDIPTR_ED = 0xbf8; static const int ICDICFR_ST = 0xc00; // interrupt config registers static const int ICDICFR_ED = 0xcfc; static const int ICDSGIR = 0xf00; // software generated interrupt static const int DIST_SIZE = 0xfff; // cpu memory addressesa static const int ICCICR = 0x00; // CPU control register static const int ICCPMR = 0x04; // Interrupt priority mask static const int ICCBPR = 0x08; // binary point register static const int ICCIAR = 0x0C; // interrupt ack register static const int ICCEOIR = 0x10; // end of interrupt static const int ICCRPR = 0x14; // runing priority static const int ICCHPIR = 0x18; // highest pending interrupt static const int ICCABPR = 0x1c; // aliased binary point static const int ICCIIDR = 0xfc; // cpu interface id register static const int CPU_SIZE = 0xff; static const int SGI_MAX = 16; // Number of Software Gen Interrupts static const int PPI_MAX = 16; // Number of Private Peripheral Interrupts /** Mask off SGI's when setting/clearing pending bits */ static const int SGI_MASK = 0xFFFF0000; /** Mask for bits that config N:N mode in ICDICFR's */ static const int NN_CONFIG_MASK = 0x55555555; static const int CPU_MAX = 8; // Max number of supported CPU interfaces static const int SPURIOUS_INT = 1023; static const int INT_BITS_MAX = 32; static const int INT_LINES_MAX = 1020; BitUnion32(SWI) Bitfield<3,0> sgi_id; Bitfield<23,16> cpu_list; Bitfield<25,24> list_type; EndBitUnion(SWI) BitUnion32(IAR) Bitfield<9,0> ack_id; Bitfield<12,10> cpu_id; EndBitUnion(IAR) /** Distributor address GIC listens at */ Addr distAddr; /** CPU address GIC listens at */ /** @todo is this one per cpu? */ Addr cpuAddr; /** Latency for a distributor operation */ Tick distPioDelay; /** Latency for a cpu operation */ Tick cpuPioDelay; /** Latency for a interrupt to get to CPU */ Tick intLatency; /** Gic enabled */ bool enabled; /** Number of itLines enabled */ uint32_t itLines; uint32_t itLinesLog2; /** interrupt enable bits for all possible 1020 interupts. * one bit per interrupt, 32 bit per word = 32 words */ uint32_t intEnabled[INT_BITS_MAX]; /** interrupt pending bits for all possible 1020 interupts. * one bit per interrupt, 32 bit per word = 32 words */ uint32_t pendingInt[INT_BITS_MAX]; /** interrupt active bits for all possible 1020 interupts. * one bit per interrupt, 32 bit per word = 32 words */ uint32_t activeInt[INT_BITS_MAX]; /** read only running priroity register, 1 per cpu*/ uint32_t iccrpr[CPU_MAX]; /** an 8 bit priority (lower is higher priority) for each * of the 1020 possible supported interrupts. */ uint8_t intPriority[INT_LINES_MAX]; /** an 8 bit cpu target id for each shared peripheral interrupt * of the 1020 possible supported interrupts. */ uint8_t cpuTarget[INT_LINES_MAX]; /** 2 bit per interrupt signaling if it's level or edge sensitive * and if it is 1:N or N:N */ uint32_t intConfig[INT_BITS_MAX*2]; /** CPU enabled */ bool cpuEnabled[CPU_MAX]; /** CPU priority */ uint8_t cpuPriority[CPU_MAX]; /** Binary point registers */ uint8_t cpuBpr[CPU_MAX]; /** highest interrupt that is interrupting CPU */ uint32_t cpuHighestInt[CPU_MAX]; /** One bit per cpu per software interrupt that is pending for each possible * sgi source. Indexed by SGI number. Each byte in generating cpu id and * bits in position is destination id. e.g. 0x4 = CPU 0 generated interrupt * for CPU 2. */ uint64_t cpuSgiPending[SGI_MAX]; uint64_t cpuSgiActive[SGI_MAX]; /** One bit per private peripheral interrupt. Only upper 16 bits * will be used since PPI interrupts are numberred from 16 to 32 */ uint32_t cpuPpiPending[CPU_MAX]; uint32_t cpuPpiActive[CPU_MAX]; /** Banked interrupt prioirty registers for SGIs and PPIs */ uint8_t bankedIntPriority[CPU_MAX][SGI_MAX + PPI_MAX]; /** IRQ Enable Used for debug */ bool irqEnable; /** software generated interrupt * @param data data to decode that indicates which cpus to interrupt */ void softInt(int ctx_id, SWI swi); /** See if some processor interrupt flags need to be enabled/disabled * @param hint which set of interrupts needs to be checked */ void updateIntState(int hint); /** Update the register that records priority of the highest priority * active interrupt*/ void updateRunPri(); /** generate a bit mask to check cpuSgi for an interrupt. */ uint64_t genSwiMask(int cpu); int intNumToWord(int num) const { return num >> 5; } int intNumToBit(int num) const { return num % 32; } /** Post an interrupt to a CPU */ void postInt(uint32_t cpu, Tick when); /** Event definition to post interrupt to CPU after a delay */ class PostIntEvent : public Event { private: uint32_t cpu; Platform *platform; public: PostIntEvent( uint32_t c, Platform* p) : cpu(c), platform(p) { } void process() { platform->intrctrl->post(cpu, ArmISA::INT_IRQ, 0);} const char *description() const { return "Post Interrupt to CPU"; } }; PostIntEvent *postIntEvent[CPU_MAX]; public: typedef Pl390Params Params; const Params * params() const { return dynamic_cast<const Params *>(_params); } Pl390(const Params *p); /** @{ */ /** Return the address ranges used by the Gic * This is the distributor address + all cpu addresses */ virtual AddrRangeList getAddrRanges() const; /** A PIO read to the device, immediately split up into * readDistributor() or readCpu() */ virtual Tick read(PacketPtr pkt); /** A PIO read to the device, immediately split up into * writeDistributor() or writeCpu() */ virtual Tick write(PacketPtr pkt); /** @} */ /** @{ */ /** Post an interrupt from a device that is connected to the Gic. * Depending on the configuration, the gic will pass this interrupt * on through to a CPU. * @param number number of interrupt to send */ void sendInt(uint32_t number); /** Interface call for private peripheral interrupts */ void sendPPInt(uint32_t num, uint32_t cpu); /** Clear an interrupt from a device that is connected to the Gic * Depending on the configuration, the gic may de-assert it's cpu line * @param number number of interrupt to send */ void clearInt(uint32_t number); /** @} */ /** @{ */ /* Various functions fer testing and debugging */ void driveSPI(uint32_t spi); void driveLegIRQ(bool state); void driveLegFIQ(bool state); void driveIrqEn(bool state); /** @} */ virtual void serialize(std::ostream &os); virtual void unserialize(Checkpoint *cp, const std::string &section); protected: /** Handle a read to the distributor poriton of the GIC * @param pkt packet to respond to */ Tick readDistributor(PacketPtr pkt); /** Handle a read to the cpu poriton of the GIC * @param pkt packet to respond to */ Tick readCpu(PacketPtr pkt); /** Handle a write to the distributor poriton of the GIC * @param pkt packet to respond to */ Tick writeDistributor(PacketPtr pkt); /** Handle a write to the cpu poriton of the GIC * @param pkt packet to respond to */ Tick writeCpu(PacketPtr pkt); }; #endif //__DEV_ARM_GIC_H__ <|endoftext|>
<commit_before>// LaminaFS is Copyright (c) 2016 Brett Lajzer // See LICENSE for license information. #include "Directory.h" #include <cstdio> #include <cstring> #include <errno.h> #include <sys/types.h> #include <sys/stat.h> #ifdef _WIN32 #define UNICODE 1 #define _UNICODE 1 #define _CRT_SECURE_NO_WARNINGS 1 #include <windows.h> #include <shellapi.h> #else #include <fts.h> #include <unistd.h> #endif using namespace laminaFS; namespace { #ifdef _WIN32 constexpr uint32_t MAX_PATH_LEN = 1024; int widen(const char *inStr, WCHAR *outStr, size_t outStrLen) { return MultiByteToWideChar(CP_UTF8, 0, inStr, -1, outStr, (int)outStrLen); } ErrorCode convertError(DWORD error) { ErrorCode result = LFS_GENERIC_ERROR; switch (error) { case ERROR_FILE_NOT_FOUND: case ERROR_PATH_NOT_FOUND: result = LFS_NOT_FOUND; break; case ERROR_ACCESS_DENIED: result = LFS_PERMISSIONS_ERROR; break; }; return result; } #else ErrorCode convertError(int error) { ErrorCode result = LFS_GENERIC_ERROR; switch (error) { case EEXIST: result = LFS_ALREADY_EXISTS; break; case EPERM: case EACCES: result = LFS_PERMISSIONS_ERROR; break; case EROFS: result = LFS_UNSUPPORTED; break; case ENOENT: result = LFS_NOT_FOUND; break; } return result; } #endif } DirectoryDevice::DirectoryDevice(Allocator *allocator, const char *path) { _alloc = allocator; // TODO: realpath() _pathLen = static_cast<uint32_t>(strlen(path)); _devicePath = reinterpret_cast<char*>(_alloc->alloc(_alloc->allocator, sizeof(char) * (_pathLen + 1), alignof(char))); strcpy(_devicePath, path); } DirectoryDevice::~DirectoryDevice() { _alloc->free(_alloc->allocator, _devicePath); } ErrorCode DirectoryDevice::create(Allocator *alloc, const char *path, void **device) { ErrorCode returnCode = LFS_OK; #ifdef _WIN32 WCHAR windowsPath[MAX_PATH_LEN]; widen(path, &windowsPath[0], MAX_PATH_LEN); DWORD result = GetFileAttributesW(&windowsPath[0]); if (result != INVALID_FILE_ATTRIBUTES && (result & FILE_ATTRIBUTE_DIRECTORY)) { *device = new(alloc->alloc(alloc->allocator, sizeof(DirectoryDevice), alignof(DirectoryDevice))) DirectoryDevice(alloc, path); } else { returnCode = LFS_NOT_FOUND; } #else struct stat statInfo; int result = stat(path, &statInfo); if (result == 0 && S_ISDIR(statInfo.st_mode)) { *device = new(alloc->alloc(alloc->allocator, sizeof(DirectoryDevice), alignof(DirectoryDevice))) DirectoryDevice(alloc, path); } else { *device = nullptr; returnCode = LFS_NOT_FOUND; } #endif return returnCode; } void DirectoryDevice::destroy(void *device) { DirectoryDevice *dir = static_cast<DirectoryDevice *>(device); dir->~DirectoryDevice(); dir->_alloc->free(dir->_alloc->allocator, device); } #ifdef _WIN32 void *DirectoryDevice::openFile(const char *filePath, uint32_t accessMode, uint32_t createMode) { char *diskPath = getDevicePath(filePath); WCHAR windowsPath[MAX_PATH_LEN]; widen(diskPath, &windowsPath[0], MAX_PATH_LEN); freeDevicePath(diskPath); HANDLE file = CreateFileW( &windowsPath[0], accessMode, FILE_SHARE_READ | FILE_SHARE_WRITE, nullptr, createMode, FILE_ATTRIBUTE_NORMAL, nullptr); return file; } #else FILE *DirectoryDevice::openFile(const char *filePath, const char *modeString) { char *diskPath = getDevicePath(filePath); FILE *file = fopen(diskPath, modeString); freeDevicePath(diskPath); return file; } #endif char *DirectoryDevice::getDevicePath(const char *filePath) { uint32_t diskPathLen = static_cast<uint32_t>(_pathLen + strlen(filePath) + 1); char *diskPath = reinterpret_cast<char*>(_alloc->alloc(_alloc->allocator, sizeof(char) * diskPathLen, alignof(char))); strcpy(diskPath, _devicePath); strcpy(diskPath + _pathLen, filePath); // replace forward slashes with backslashes on windows #ifdef _WIN32 for (uint32_t i = 0; i < diskPathLen; ++i) { if (diskPath[i] == '/') diskPath[i] = '\\'; } #endif return diskPath; } void DirectoryDevice::freeDevicePath(char *path) { _alloc->free(_alloc->allocator, path); } bool DirectoryDevice::fileExists(void *device, const char *filePath) { DirectoryDevice *dev = static_cast<DirectoryDevice*>(device); char *diskPath = dev->getDevicePath(filePath); #ifdef _WIN32 WCHAR windowsPath[MAX_PATH_LEN]; widen(diskPath, &windowsPath[0], MAX_PATH_LEN); dev->freeDevicePath(diskPath); DWORD result = GetFileAttributesW(&windowsPath[0]); return result != INVALID_FILE_ATTRIBUTES && !(result & FILE_ATTRIBUTE_DIRECTORY); #else struct stat statInfo; int result = stat(diskPath, &statInfo); dev->freeDevicePath(diskPath); return result == 0 && S_ISREG(statInfo.st_mode); #endif } size_t DirectoryDevice::fileSize(void *device, const char *filePath, ErrorCode *outError) { DirectoryDevice *dev = static_cast<DirectoryDevice*>(device); size_t size = 0; #ifdef _WIN32 HANDLE file = dev->openFile(filePath, GENERIC_READ, OPEN_EXISTING); if (file) { LARGE_INTEGER result; if(!GetFileSizeEx(file, &result)) { printf("error code %lu\n", GetLastError()); } else { size = result.QuadPart; } CloseHandle(file); } else { *outError = convertError(GetLastError()); } #else char *diskPath = dev->getDevicePath(filePath); struct stat statInfo; int result = stat(diskPath, &statInfo); dev->freeDevicePath(diskPath); if (result == 0 && S_ISREG(statInfo.st_mode)) { *outError = LFS_OK; size = statInfo.st_size; } else if (result != 0) { *outError = convertError(errno); } else { *outError = LFS_UNSUPPORTED; } #endif return size; } size_t DirectoryDevice::readFile(void *device, const char *filePath, Allocator *alloc, void **buffer, bool nullTerminate, ErrorCode *outError) { size_t bytesRead = 0; DirectoryDevice *dir = static_cast<DirectoryDevice*>(device); #ifdef _WIN32 HANDLE file = dir->openFile(filePath, GENERIC_READ, OPEN_EXISTING); if (file) { LARGE_INTEGER result; GetFileSizeEx(file, &result); size_t fileSize = result.QuadPart; if (fileSize) { *buffer = dir->_alloc->alloc(dir->_alloc->allocator, fileSize + (nullTerminate ? 1 : 0), 1); DWORD bytesReadTemp = 0; if (!ReadFile(file, *buffer, (DWORD)fileSize, &bytesReadTemp, nullptr)) { *outError = convertError(GetLastError()); } else if (nullTerminate) { (*(char**)buffer)[bytesRead] = 0; } bytesRead = bytesReadTemp; } CloseHandle(file); } else { *outError = LFS_NOT_FOUND; } #else FILE *file = dir->openFile(filePath, "rb"); if (file) { size_t fileSize = 0; if (fseek(file, 0L, SEEK_END) == 0) { fileSize = ftell(file); } if (fileSize && fseek(file, 0L, SEEK_SET) == 0) { *buffer = dir->_alloc->alloc(dir->_alloc->allocator, fileSize + (nullTerminate ? 1 : 0), 1); if (*buffer) { bytesRead = fread(*buffer, 1, fileSize, file); if (nullTerminate) { (*(char**)buffer)[bytesRead] = 0; } } } *outError = ferror(file) ? LFS_GENERIC_ERROR : LFS_OK; fclose(file); } else { *outError = LFS_NOT_FOUND; } #endif return bytesRead; } size_t DirectoryDevice::writeFile(void *device, const char *filePath, void *buffer, size_t bytesToWrite, bool append, ErrorCode *outError) { size_t bytesWritten = 0; DirectoryDevice *dev = static_cast<DirectoryDevice*>(device); #ifdef _WIN32 HANDLE file = dev->openFile(filePath, GENERIC_WRITE, append ? OPEN_ALWAYS : CREATE_ALWAYS); if (file) { if (append) { if (SetFilePointer(file, 0, nullptr, FILE_END) == INVALID_SET_FILE_POINTER) { *outError = LFS_GENERIC_ERROR; CloseHandle(file); return bytesWritten; } } DWORD temp = 0; if (!WriteFile(file, buffer, (DWORD)bytesToWrite, &temp, nullptr)) { *outError = LFS_GENERIC_ERROR; } else { bytesWritten = temp; } } else { *outError = convertError(GetLastError()); } CloseHandle(file); #else FILE *file = dev->openFile(filePath, append ? "ab" : "wb"); if (file) { bytesWritten = fwrite(buffer, 1, bytesToWrite, file); *outError = ferror(file) ? LFS_GENERIC_ERROR : LFS_OK; fclose(file); } else { *outError = LFS_PERMISSIONS_ERROR; } #endif return bytesWritten; } ErrorCode DirectoryDevice::deleteFile(void *device, const char *filePath) { DirectoryDevice *dev = static_cast<DirectoryDevice*>(device); char *diskPath = dev->getDevicePath(filePath); ErrorCode resultCode = LFS_OK; #ifdef _WIN32 WCHAR windowsPath[MAX_PATH_LEN]; widen(diskPath, &windowsPath[0], MAX_PATH_LEN); if (!DeleteFileW(&windowsPath[0])) { resultCode = convertError(GetLastError()); } #else if (unlink(diskPath) != 0) { resultCode = convertError(errno); } #endif dev->freeDevicePath(diskPath); return resultCode; } ErrorCode DirectoryDevice::createDir(void *device, const char *path) { DirectoryDevice *dev = static_cast<DirectoryDevice*>(device); char *diskPath = dev->getDevicePath(path); ErrorCode resultCode = LFS_OK; #ifdef _WIN32 WCHAR windowsPath[MAX_PATH_LEN]; widen(diskPath, &windowsPath[0], MAX_PATH_LEN); if (!CreateDirectoryW(&windowsPath[0], nullptr)) { resultCode = convertError(GetLastError()); } #else int result = mkdir(diskPath, DEFFILEMODE | S_IXUSR | S_IXGRP | S_IRWXO); if (result != 0) { resultCode = convertError(errno); } #endif dev->freeDevicePath(diskPath); return resultCode; } ErrorCode DirectoryDevice::deleteDir(void *device, const char *path) { DirectoryDevice *dev = static_cast<DirectoryDevice*>(device); char *diskPath = dev->getDevicePath(path); ErrorCode resultCode = LFS_OK; #ifdef _WIN32 WCHAR windowsPath[MAX_PATH_LEN]; int len = widen(diskPath, &windowsPath[0], MAX_PATH_LEN - 1); // XXX: ensure one space for double-null windowsPath[len] = 0; // just use the shell API to delete the directory. // requires path to be double null-terminated. // https://msdn.microsoft.com/en-us/library/windows/desktop/bb762164(v=vs.85).aspx SHFILEOPSTRUCTW shOp; shOp.hwnd = nullptr; shOp.wFunc = FO_DELETE; shOp.pFrom = &windowsPath[0]; shOp.pTo = nullptr; shOp.fFlags = FOF_NO_UI; shOp.fAnyOperationsAborted = FALSE; shOp.hNameMappings = nullptr; shOp.lpszProgressTitle = nullptr; int result = SHFileOperationW(&shOp); switch (result) { case 0: break; case 0x7C: // DE_INVALIDFILES resultCode = LFS_NOT_FOUND; break; case 0x78: // DE_ACCESSDENIEDSRC case 0x86: // DE_SRC_IS_CDROM case 0x87: // DE_SRC_IS_DVD resultCode = LFS_PERMISSIONS_ERROR; break; default: resultCode = LFS_GENERIC_ERROR; break; }; #else FTS *fts = nullptr; char *fileList[] = {diskPath, nullptr}; bool error = false; if ((fts = fts_open(fileList, FTS_PHYSICAL | FTS_NOCHDIR | FTS_XDEV, nullptr))) { FTSENT *ent = fts_read(fts); while (!error && ent) { switch (ent->fts_info) { // ignore directories until post-traversal (FTS_DP) case FTS_D: break; // normal stuff we want to delete case FTS_DEFAULT: case FTS_DP: case FTS_F: case FTS_SL: case FTS_SLNONE: if (remove(ent->fts_accpath) == -1) { error = true; } break; // shouldn't ever hit these case FTS_DC: case FTS_DOT: case FTS_NSOK: break; // errors case FTS_NS: case FTS_DNR: case FTS_ERR: error = true; errno = ent->fts_errno; break; }; if (!error) ent = fts_read(fts); } error = error || errno != 0; fts_close(fts); } if (error) { resultCode = convertError(errno); } #endif dev->freeDevicePath(diskPath); return resultCode; } <commit_msg>Use the correct allocator when reading files.<commit_after>// LaminaFS is Copyright (c) 2016 Brett Lajzer // See LICENSE for license information. #include "Directory.h" #include <cstdio> #include <cstring> #include <errno.h> #include <sys/types.h> #include <sys/stat.h> #ifdef _WIN32 #define UNICODE 1 #define _UNICODE 1 #define _CRT_SECURE_NO_WARNINGS 1 #include <windows.h> #include <shellapi.h> #else #include <fts.h> #include <unistd.h> #endif using namespace laminaFS; namespace { #ifdef _WIN32 constexpr uint32_t MAX_PATH_LEN = 1024; int widen(const char *inStr, WCHAR *outStr, size_t outStrLen) { return MultiByteToWideChar(CP_UTF8, 0, inStr, -1, outStr, (int)outStrLen); } ErrorCode convertError(DWORD error) { ErrorCode result = LFS_GENERIC_ERROR; switch (error) { case ERROR_FILE_NOT_FOUND: case ERROR_PATH_NOT_FOUND: result = LFS_NOT_FOUND; break; case ERROR_ACCESS_DENIED: result = LFS_PERMISSIONS_ERROR; break; }; return result; } #else ErrorCode convertError(int error) { ErrorCode result = LFS_GENERIC_ERROR; switch (error) { case EEXIST: result = LFS_ALREADY_EXISTS; break; case EPERM: case EACCES: result = LFS_PERMISSIONS_ERROR; break; case EROFS: result = LFS_UNSUPPORTED; break; case ENOENT: result = LFS_NOT_FOUND; break; } return result; } #endif } DirectoryDevice::DirectoryDevice(Allocator *allocator, const char *path) { _alloc = allocator; // TODO: realpath() _pathLen = static_cast<uint32_t>(strlen(path)); _devicePath = reinterpret_cast<char*>(_alloc->alloc(_alloc->allocator, sizeof(char) * (_pathLen + 1), alignof(char))); strcpy(_devicePath, path); } DirectoryDevice::~DirectoryDevice() { _alloc->free(_alloc->allocator, _devicePath); } ErrorCode DirectoryDevice::create(Allocator *alloc, const char *path, void **device) { ErrorCode returnCode = LFS_OK; #ifdef _WIN32 WCHAR windowsPath[MAX_PATH_LEN]; widen(path, &windowsPath[0], MAX_PATH_LEN); DWORD result = GetFileAttributesW(&windowsPath[0]); if (result != INVALID_FILE_ATTRIBUTES && (result & FILE_ATTRIBUTE_DIRECTORY)) { *device = new(alloc->alloc(alloc->allocator, sizeof(DirectoryDevice), alignof(DirectoryDevice))) DirectoryDevice(alloc, path); } else { returnCode = LFS_NOT_FOUND; } #else struct stat statInfo; int result = stat(path, &statInfo); if (result == 0 && S_ISDIR(statInfo.st_mode)) { *device = new(alloc->alloc(alloc->allocator, sizeof(DirectoryDevice), alignof(DirectoryDevice))) DirectoryDevice(alloc, path); } else { *device = nullptr; returnCode = LFS_NOT_FOUND; } #endif return returnCode; } void DirectoryDevice::destroy(void *device) { DirectoryDevice *dir = static_cast<DirectoryDevice *>(device); dir->~DirectoryDevice(); dir->_alloc->free(dir->_alloc->allocator, device); } #ifdef _WIN32 void *DirectoryDevice::openFile(const char *filePath, uint32_t accessMode, uint32_t createMode) { char *diskPath = getDevicePath(filePath); WCHAR windowsPath[MAX_PATH_LEN]; widen(diskPath, &windowsPath[0], MAX_PATH_LEN); freeDevicePath(diskPath); HANDLE file = CreateFileW( &windowsPath[0], accessMode, FILE_SHARE_READ | FILE_SHARE_WRITE, nullptr, createMode, FILE_ATTRIBUTE_NORMAL, nullptr); return file; } #else FILE *DirectoryDevice::openFile(const char *filePath, const char *modeString) { char *diskPath = getDevicePath(filePath); FILE *file = fopen(diskPath, modeString); freeDevicePath(diskPath); return file; } #endif char *DirectoryDevice::getDevicePath(const char *filePath) { uint32_t diskPathLen = static_cast<uint32_t>(_pathLen + strlen(filePath) + 1); char *diskPath = reinterpret_cast<char*>(_alloc->alloc(_alloc->allocator, sizeof(char) * diskPathLen, alignof(char))); strcpy(diskPath, _devicePath); strcpy(diskPath + _pathLen, filePath); // replace forward slashes with backslashes on windows #ifdef _WIN32 for (uint32_t i = 0; i < diskPathLen; ++i) { if (diskPath[i] == '/') diskPath[i] = '\\'; } #endif return diskPath; } void DirectoryDevice::freeDevicePath(char *path) { _alloc->free(_alloc->allocator, path); } bool DirectoryDevice::fileExists(void *device, const char *filePath) { DirectoryDevice *dev = static_cast<DirectoryDevice*>(device); char *diskPath = dev->getDevicePath(filePath); #ifdef _WIN32 WCHAR windowsPath[MAX_PATH_LEN]; widen(diskPath, &windowsPath[0], MAX_PATH_LEN); dev->freeDevicePath(diskPath); DWORD result = GetFileAttributesW(&windowsPath[0]); return result != INVALID_FILE_ATTRIBUTES && !(result & FILE_ATTRIBUTE_DIRECTORY); #else struct stat statInfo; int result = stat(diskPath, &statInfo); dev->freeDevicePath(diskPath); return result == 0 && S_ISREG(statInfo.st_mode); #endif } size_t DirectoryDevice::fileSize(void *device, const char *filePath, ErrorCode *outError) { DirectoryDevice *dev = static_cast<DirectoryDevice*>(device); size_t size = 0; #ifdef _WIN32 HANDLE file = dev->openFile(filePath, GENERIC_READ, OPEN_EXISTING); if (file) { LARGE_INTEGER result; if(!GetFileSizeEx(file, &result)) { printf("error code %lu\n", GetLastError()); } else { size = result.QuadPart; } CloseHandle(file); } else { *outError = convertError(GetLastError()); } #else char *diskPath = dev->getDevicePath(filePath); struct stat statInfo; int result = stat(diskPath, &statInfo); dev->freeDevicePath(diskPath); if (result == 0 && S_ISREG(statInfo.st_mode)) { *outError = LFS_OK; size = statInfo.st_size; } else if (result != 0) { *outError = convertError(errno); } else { *outError = LFS_UNSUPPORTED; } #endif return size; } size_t DirectoryDevice::readFile(void *device, const char *filePath, Allocator *alloc, void **buffer, bool nullTerminate, ErrorCode *outError) { size_t bytesRead = 0; DirectoryDevice *dir = static_cast<DirectoryDevice*>(device); #ifdef _WIN32 HANDLE file = dir->openFile(filePath, GENERIC_READ, OPEN_EXISTING); if (file) { LARGE_INTEGER result; GetFileSizeEx(file, &result); size_t fileSize = result.QuadPart; if (fileSize) { *buffer = alloc->alloc(alloc->allocator, fileSize + (nullTerminate ? 1 : 0), 1); DWORD bytesReadTemp = 0; if (!ReadFile(file, *buffer, (DWORD)fileSize, &bytesReadTemp, nullptr)) { *outError = convertError(GetLastError()); } else if (nullTerminate) { (*(char**)buffer)[bytesRead] = 0; } bytesRead = bytesReadTemp; } CloseHandle(file); } else { *outError = LFS_NOT_FOUND; } #else FILE *file = dir->openFile(filePath, "rb"); if (file) { size_t fileSize = 0; if (fseek(file, 0L, SEEK_END) == 0) { fileSize = ftell(file); } if (fileSize && fseek(file, 0L, SEEK_SET) == 0) { *buffer = alloc->alloc(alloc->allocator, fileSize + (nullTerminate ? 1 : 0), 1); if (*buffer) { bytesRead = fread(*buffer, 1, fileSize, file); if (nullTerminate) { (*(char**)buffer)[bytesRead] = 0; } } } *outError = ferror(file) ? LFS_GENERIC_ERROR : LFS_OK; fclose(file); } else { *outError = LFS_NOT_FOUND; } #endif return bytesRead; } size_t DirectoryDevice::writeFile(void *device, const char *filePath, void *buffer, size_t bytesToWrite, bool append, ErrorCode *outError) { size_t bytesWritten = 0; DirectoryDevice *dev = static_cast<DirectoryDevice*>(device); #ifdef _WIN32 HANDLE file = dev->openFile(filePath, GENERIC_WRITE, append ? OPEN_ALWAYS : CREATE_ALWAYS); if (file) { if (append) { if (SetFilePointer(file, 0, nullptr, FILE_END) == INVALID_SET_FILE_POINTER) { *outError = LFS_GENERIC_ERROR; CloseHandle(file); return bytesWritten; } } DWORD temp = 0; if (!WriteFile(file, buffer, (DWORD)bytesToWrite, &temp, nullptr)) { *outError = LFS_GENERIC_ERROR; } else { bytesWritten = temp; } } else { *outError = convertError(GetLastError()); } CloseHandle(file); #else FILE *file = dev->openFile(filePath, append ? "ab" : "wb"); if (file) { bytesWritten = fwrite(buffer, 1, bytesToWrite, file); *outError = ferror(file) ? LFS_GENERIC_ERROR : LFS_OK; fclose(file); } else { *outError = LFS_PERMISSIONS_ERROR; } #endif return bytesWritten; } ErrorCode DirectoryDevice::deleteFile(void *device, const char *filePath) { DirectoryDevice *dev = static_cast<DirectoryDevice*>(device); char *diskPath = dev->getDevicePath(filePath); ErrorCode resultCode = LFS_OK; #ifdef _WIN32 WCHAR windowsPath[MAX_PATH_LEN]; widen(diskPath, &windowsPath[0], MAX_PATH_LEN); if (!DeleteFileW(&windowsPath[0])) { resultCode = convertError(GetLastError()); } #else if (unlink(diskPath) != 0) { resultCode = convertError(errno); } #endif dev->freeDevicePath(diskPath); return resultCode; } ErrorCode DirectoryDevice::createDir(void *device, const char *path) { DirectoryDevice *dev = static_cast<DirectoryDevice*>(device); char *diskPath = dev->getDevicePath(path); ErrorCode resultCode = LFS_OK; #ifdef _WIN32 WCHAR windowsPath[MAX_PATH_LEN]; widen(diskPath, &windowsPath[0], MAX_PATH_LEN); if (!CreateDirectoryW(&windowsPath[0], nullptr)) { resultCode = convertError(GetLastError()); } #else int result = mkdir(diskPath, DEFFILEMODE | S_IXUSR | S_IXGRP | S_IRWXO); if (result != 0) { resultCode = convertError(errno); } #endif dev->freeDevicePath(diskPath); return resultCode; } ErrorCode DirectoryDevice::deleteDir(void *device, const char *path) { DirectoryDevice *dev = static_cast<DirectoryDevice*>(device); char *diskPath = dev->getDevicePath(path); ErrorCode resultCode = LFS_OK; #ifdef _WIN32 WCHAR windowsPath[MAX_PATH_LEN]; int len = widen(diskPath, &windowsPath[0], MAX_PATH_LEN - 1); // XXX: ensure one space for double-null windowsPath[len] = 0; // just use the shell API to delete the directory. // requires path to be double null-terminated. // https://msdn.microsoft.com/en-us/library/windows/desktop/bb762164(v=vs.85).aspx SHFILEOPSTRUCTW shOp; shOp.hwnd = nullptr; shOp.wFunc = FO_DELETE; shOp.pFrom = &windowsPath[0]; shOp.pTo = nullptr; shOp.fFlags = FOF_NO_UI; shOp.fAnyOperationsAborted = FALSE; shOp.hNameMappings = nullptr; shOp.lpszProgressTitle = nullptr; int result = SHFileOperationW(&shOp); switch (result) { case 0: break; case 0x7C: // DE_INVALIDFILES resultCode = LFS_NOT_FOUND; break; case 0x78: // DE_ACCESSDENIEDSRC case 0x86: // DE_SRC_IS_CDROM case 0x87: // DE_SRC_IS_DVD resultCode = LFS_PERMISSIONS_ERROR; break; default: resultCode = LFS_GENERIC_ERROR; break; }; #else FTS *fts = nullptr; char *fileList[] = {diskPath, nullptr}; bool error = false; if ((fts = fts_open(fileList, FTS_PHYSICAL | FTS_NOCHDIR | FTS_XDEV, nullptr))) { FTSENT *ent = fts_read(fts); while (!error && ent) { switch (ent->fts_info) { // ignore directories until post-traversal (FTS_DP) case FTS_D: break; // normal stuff we want to delete case FTS_DEFAULT: case FTS_DP: case FTS_F: case FTS_SL: case FTS_SLNONE: if (remove(ent->fts_accpath) == -1) { error = true; } break; // shouldn't ever hit these case FTS_DC: case FTS_DOT: case FTS_NSOK: break; // errors case FTS_NS: case FTS_DNR: case FTS_ERR: error = true; errno = ent->fts_errno; break; }; if (!error) ent = fts_read(fts); } error = error || errno != 0; fts_close(fts); } if (error) { resultCode = convertError(errno); } #endif dev->freeDevicePath(diskPath); return resultCode; } <|endoftext|>
<commit_before>#include <iostream> void SetAliEnSettings() { // Routine to load settings from an AliEn environment file. ifstream fileIn; fileIn.open(Form("%s/gclient_env_%d", gSystem->TempDirectory(), gSystem->GetUid())); if (gDebug>0) {printf("P010_TAlien.C: parsing %s/gclient_env_$UID\n", gSystem->TempDirectory());} TString lineS,tmp; char line[4096]; while (fileIn.good()){ fileIn.getline(line,4096,'\n'); lineS = line; if (lineS.IsNull()) continue; if (lineS.Contains("export ")) { lineS.ReplaceAll("export ",""); TObjArray* array = lineS.Tokenize("="); if (array->GetEntries() == 2) { TObjString *strVar = (TObjString *) array->At(0); TObjString *strVal = (TObjString *) array->At(1); if ((strVar)&&(strVal)) { tmp = strVal->GetString(); tmp.ReplaceAll("\"",""); tmp.ReplaceAll("$LD_LIBRARY_PATH",gSystem->Getenv("LD_LIBRARY_PATH")); tmp.ReplaceAll("$DYLD_LIBRARY_PATH",gSystem->Getenv("DYLD_LIBRARY_PATH")); tmp.ReplaceAll(" ",""); gSystem->Unsetenv(strVar->GetString()); gSystem->Setenv(strVar->GetString(), tmp); if (gDebug>0) { Info("P010_TAlien", "setting environment %s=\"%s\"", strVar->GetString().Data(), tmp.Data()); } if (!strVar->GetString().CompareTo("GCLIENT_SERVER_LIST")) { gSystem->Unsetenv("alien_API_SERVER_LIST"); gSystem->Setenv("alien_API_SERVER_LIST", tmp); } } if (array) { delete array; array = 0 ; } } else { // parse the MONA_ stuff TObjArray* array = lineS.Tokenize("\" "); TString key=""; TString val=""; for (int i=0; i< array->GetEntries(); i++) { if ( ((TObjString*) array->At(i))->GetString().Contains("=")) { if (key.Length() && val.Length()) { val.Resize(val.Length()-1); if (gDebug>0) { Info("P010_TAlien", "setting environment %s=\"%s\"", key.Data(), val.Data()); } gSystem->Unsetenv(key); gSystem->Setenv(key, val); key=""; val=""; } key = ((TObjString*) array->At(i))->GetString(); key.ReplaceAll("=",""); } else { val+=((TObjString*) array->At(i))->GetString(); val+=" "; } } if (key.Length() && val.Length()) { if (gDebug>0) { Info("P010_TAlien", "setting environment %s=\"%s\"", key.Data(), val.Data()); } gSystem->Unsetenv(key); gSystem->Setenv(key, val); } } } } } void P010_TAlien() { TString configfeatures = gROOT->GetConfigFeatures(); TString ralienpath = gSystem->Getenv("ROOTSYS"); ralienpath += "/lib/"; ralienpath += "libRAliEn.so"; // only if ROOT was compiled with enable-alien we do library setup and configure a handler if ((!gSystem->AccessPathName(ralienpath)) || (configfeatures.contains("alien"))) { // you can enforce if ((!gSystem->Getenv("GBBOX_ENVFILE")) || ( gSystem->Getenv("ALIEN_SOURCE_GCLIENT_ENV")) || (!gSystem->Getenv("ALIEN_SKIP_GCLIENT_ENV")) ) { SetAliEnSettings(); } if ( ((gSystem->Load("libgapiUI.so")>=0) && (gSystem->Load("libRAliEn.so")>=0))) { gPluginMgr->AddHandler("TGrid", "^alien", "TAlien", "RAliEn", "TAlien(const char*,const char*,const char*,const char*)"); } else { Error("P010_TAlien","Please fix your loader path environment variable to be able to load libRAliEn.so"); } } } <commit_msg>Fix typo.<commit_after>#include <iostream> void SetAliEnSettings() { // Routine to load settings from an AliEn environment file. ifstream fileIn; fileIn.open(Form("%s/gclient_env_%d", gSystem->TempDirectory(), gSystem->GetUid())); if (gDebug>0) {printf("P010_TAlien.C: parsing %s/gclient_env_$UID\n", gSystem->TempDirectory());} TString lineS,tmp; char line[4096]; while (fileIn.good()){ fileIn.getline(line,4096,'\n'); lineS = line; if (lineS.IsNull()) continue; if (lineS.Contains("export ")) { lineS.ReplaceAll("export ",""); TObjArray* array = lineS.Tokenize("="); if (array->GetEntries() == 2) { TObjString *strVar = (TObjString *) array->At(0); TObjString *strVal = (TObjString *) array->At(1); if ((strVar)&&(strVal)) { tmp = strVal->GetString(); tmp.ReplaceAll("\"",""); tmp.ReplaceAll("$LD_LIBRARY_PATH",gSystem->Getenv("LD_LIBRARY_PATH")); tmp.ReplaceAll("$DYLD_LIBRARY_PATH",gSystem->Getenv("DYLD_LIBRARY_PATH")); tmp.ReplaceAll(" ",""); gSystem->Unsetenv(strVar->GetString()); gSystem->Setenv(strVar->GetString(), tmp); if (gDebug>0) { Info("P010_TAlien", "setting environment %s=\"%s\"", strVar->GetString().Data(), tmp.Data()); } if (!strVar->GetString().CompareTo("GCLIENT_SERVER_LIST")) { gSystem->Unsetenv("alien_API_SERVER_LIST"); gSystem->Setenv("alien_API_SERVER_LIST", tmp); } } if (array) { delete array; array = 0 ; } } else { // parse the MONA_ stuff TObjArray* array = lineS.Tokenize("\" "); TString key=""; TString val=""; for (int i=0; i< array->GetEntries(); i++) { if ( ((TObjString*) array->At(i))->GetString().Contains("=")) { if (key.Length() && val.Length()) { val.Resize(val.Length()-1); if (gDebug>0) { Info("P010_TAlien", "setting environment %s=\"%s\"", key.Data(), val.Data()); } gSystem->Unsetenv(key); gSystem->Setenv(key, val); key=""; val=""; } key = ((TObjString*) array->At(i))->GetString(); key.ReplaceAll("=",""); } else { val+=((TObjString*) array->At(i))->GetString(); val+=" "; } } if (key.Length() && val.Length()) { if (gDebug>0) { Info("P010_TAlien", "setting environment %s=\"%s\"", key.Data(), val.Data()); } gSystem->Unsetenv(key); gSystem->Setenv(key, val); } } } } } void P010_TAlien() { TString configfeatures = gROOT->GetConfigFeatures(); TString ralienpath = gSystem->Getenv("ROOTSYS"); ralienpath += "/lib/"; ralienpath += "libRAliEn.so"; // only if ROOT was compiled with enable-alien we do library setup and configure a handler if ((!gSystem->AccessPathName(ralienpath)) || (configfeatures.Contains("alien"))) { // you can enforce if ((!gSystem->Getenv("GBBOX_ENVFILE")) || ( gSystem->Getenv("ALIEN_SOURCE_GCLIENT_ENV")) || (!gSystem->Getenv("ALIEN_SKIP_GCLIENT_ENV")) ) { SetAliEnSettings(); } if ( ((gSystem->Load("libgapiUI.so")>=0) && (gSystem->Load("libRAliEn.so")>=0))) { gPluginMgr->AddHandler("TGrid", "^alien", "TAlien", "RAliEn", "TAlien(const char*,const char*,const char*,const char*)"); } else { Error("P010_TAlien","Please fix your loader path environment variable to be able to load libRAliEn.so"); } } } <|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 "content/public/browser/browser_main_runner.h" #include "base/allocator/allocator_shim.h" #include "base/base_switches.h" #include "base/command_line.h" #include "base/debug/trace_event.h" #include "base/logging.h" #include "base/metrics/histogram.h" #include "base/metrics/statistics_recorder.h" #include "content/browser/browser_main_loop.h" #include "content/browser/notification_service_impl.h" #include "content/public/common/content_switches.h" #include "content/public/common/main_function_params.h" #include "ui/base/ime/input_method_initializer.h" #if defined(OS_WIN) #include "base/win/metro.h" #include "base/win/windows_version.h" #include "ui/base/win/scoped_ole_initializer.h" #endif bool g_exited_main_message_loop = false; namespace content { class BrowserMainRunnerImpl : public BrowserMainRunner { public: BrowserMainRunnerImpl() : is_initialized_(false), is_shutdown_(false), created_threads_(false) { } virtual ~BrowserMainRunnerImpl() { if (is_initialized_ && !is_shutdown_) Shutdown(); } virtual int Initialize(const MainFunctionParams& parameters) OVERRIDE { TRACE_EVENT0("startup", "BrowserMainRunnerImpl::Initialize") is_initialized_ = true; #if defined(OS_WIN) if (parameters.command_line.HasSwitch( switches::kEnableTextServicesFramework)) { base::win::SetForceToUseTSF(); } else if (base::win::GetVersion() < base::win::VERSION_VISTA) { // When "Extend support of advanced text services to all programs" // (a.k.a. Cicero Unaware Application Support; CUAS) is enabled on // Windows XP and handwriting modules shipped with Office 2003 are // installed, "penjpn.dll" and "skchui.dll" will be loaded and then crash // unless a user installs Office 2003 SP3. To prevent these modules from // being loaded, disable TSF entirely. crbug/160914. // TODO(yukawa): Add a high-level wrapper for this instead of calling // Win32 API here directly. ImmDisableTextFrameService(static_cast<DWORD>(-1)); } #endif // OS_WIN base::StatisticsRecorder::Initialize(); notification_service_.reset(new NotificationServiceImpl); #if defined(OS_WIN) // Ole must be initialized before starting message pump, so that TSF // (Text Services Framework) module can interact with the message pump // on Windows 8 Metro mode. ole_initializer_.reset(new ui::ScopedOleInitializer); #endif // OS_WIN main_loop_.reset(new BrowserMainLoop(parameters)); main_loop_->Init(); main_loop_->EarlyInitialization(); // Must happen before we try to use a message loop or display any UI. main_loop_->InitializeToolkit(); main_loop_->MainMessageLoopStart(); // WARNING: If we get a WM_ENDSESSION, objects created on the stack here // are NOT deleted. If you need something to run during WM_ENDSESSION add it // to browser_shutdown::Shutdown or BrowserProcess::EndSession. #if defined(OS_WIN) && !defined(NO_TCMALLOC) // When linking shared libraries, NO_TCMALLOC is defined, and dynamic // allocator selection is not supported. // Make this call before going multithreaded, or spawning any subprocesses. base::allocator::SetupSubprocessAllocator(); #endif ui::InitializeInputMethod(); main_loop_->CreateThreads(); int result_code = main_loop_->GetResultCode(); if (result_code > 0) return result_code; created_threads_ = true; // Return -1 to indicate no early termination. return -1; } virtual int Run() OVERRIDE { DCHECK(is_initialized_); DCHECK(!is_shutdown_); main_loop_->RunMainMessageLoopParts(); return main_loop_->GetResultCode(); } virtual void Shutdown() OVERRIDE { DCHECK(is_initialized_); DCHECK(!is_shutdown_); g_exited_main_message_loop = true; if (created_threads_) main_loop_->ShutdownThreadsAndCleanUp(); ui::ShutdownInputMethod(); #if defined(OS_WIN) ole_initializer_.reset(NULL); #endif main_loop_.reset(NULL); notification_service_.reset(NULL); is_shutdown_ = true; } protected: // True if the runner has been initialized. bool is_initialized_; // True if the runner has been shut down. bool is_shutdown_; // True if the non-UI threads were created. bool created_threads_; scoped_ptr<NotificationServiceImpl> notification_service_; scoped_ptr<BrowserMainLoop> main_loop_; #if defined(OS_WIN) scoped_ptr<ui::ScopedOleInitializer> ole_initializer_; #endif DISALLOW_COPY_AND_ASSIGN(BrowserMainRunnerImpl); }; // static BrowserMainRunner* BrowserMainRunner::Create() { return new BrowserMainRunnerImpl(); } } // namespace content <commit_msg>Fix --wait-for-debugger.<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 "content/public/browser/browser_main_runner.h" #include "base/allocator/allocator_shim.h" #include "base/base_switches.h" #include "base/command_line.h" #include "base/debug/trace_event.h" #include "base/logging.h" #include "base/metrics/histogram.h" #include "base/metrics/statistics_recorder.h" #include "content/browser/browser_main_loop.h" #include "content/browser/notification_service_impl.h" #include "content/public/common/content_switches.h" #include "content/public/common/main_function_params.h" #include "ui/base/ime/input_method_initializer.h" #if defined(OS_WIN) #include "base/win/metro.h" #include "base/win/windows_version.h" #include "ui/base/win/scoped_ole_initializer.h" #endif bool g_exited_main_message_loop = false; namespace content { class BrowserMainRunnerImpl : public BrowserMainRunner { public: BrowserMainRunnerImpl() : is_initialized_(false), is_shutdown_(false), created_threads_(false) { } virtual ~BrowserMainRunnerImpl() { if (is_initialized_ && !is_shutdown_) Shutdown(); } virtual int Initialize(const MainFunctionParams& parameters) OVERRIDE { TRACE_EVENT0("startup", "BrowserMainRunnerImpl::Initialize") is_initialized_ = true; #if !defined(OS_IOS) if (parameters.command_line.HasSwitch(switches::kWaitForDebugger)) base::debug::WaitForDebugger(60, true); #endif #if defined(OS_WIN) if (parameters.command_line.HasSwitch( switches::kEnableTextServicesFramework)) { base::win::SetForceToUseTSF(); } else if (base::win::GetVersion() < base::win::VERSION_VISTA) { // When "Extend support of advanced text services to all programs" // (a.k.a. Cicero Unaware Application Support; CUAS) is enabled on // Windows XP and handwriting modules shipped with Office 2003 are // installed, "penjpn.dll" and "skchui.dll" will be loaded and then crash // unless a user installs Office 2003 SP3. To prevent these modules from // being loaded, disable TSF entirely. crbug/160914. // TODO(yukawa): Add a high-level wrapper for this instead of calling // Win32 API here directly. ImmDisableTextFrameService(static_cast<DWORD>(-1)); } #endif // OS_WIN base::StatisticsRecorder::Initialize(); notification_service_.reset(new NotificationServiceImpl); #if defined(OS_WIN) // Ole must be initialized before starting message pump, so that TSF // (Text Services Framework) module can interact with the message pump // on Windows 8 Metro mode. ole_initializer_.reset(new ui::ScopedOleInitializer); #endif // OS_WIN main_loop_.reset(new BrowserMainLoop(parameters)); main_loop_->Init(); main_loop_->EarlyInitialization(); // Must happen before we try to use a message loop or display any UI. main_loop_->InitializeToolkit(); main_loop_->MainMessageLoopStart(); // WARNING: If we get a WM_ENDSESSION, objects created on the stack here // are NOT deleted. If you need something to run during WM_ENDSESSION add it // to browser_shutdown::Shutdown or BrowserProcess::EndSession. #if defined(OS_WIN) && !defined(NO_TCMALLOC) // When linking shared libraries, NO_TCMALLOC is defined, and dynamic // allocator selection is not supported. // Make this call before going multithreaded, or spawning any subprocesses. base::allocator::SetupSubprocessAllocator(); #endif ui::InitializeInputMethod(); main_loop_->CreateThreads(); int result_code = main_loop_->GetResultCode(); if (result_code > 0) return result_code; created_threads_ = true; // Return -1 to indicate no early termination. return -1; } virtual int Run() OVERRIDE { DCHECK(is_initialized_); DCHECK(!is_shutdown_); main_loop_->RunMainMessageLoopParts(); return main_loop_->GetResultCode(); } virtual void Shutdown() OVERRIDE { DCHECK(is_initialized_); DCHECK(!is_shutdown_); g_exited_main_message_loop = true; if (created_threads_) main_loop_->ShutdownThreadsAndCleanUp(); ui::ShutdownInputMethod(); #if defined(OS_WIN) ole_initializer_.reset(NULL); #endif main_loop_.reset(NULL); notification_service_.reset(NULL); is_shutdown_ = true; } protected: // True if the runner has been initialized. bool is_initialized_; // True if the runner has been shut down. bool is_shutdown_; // True if the non-UI threads were created. bool created_threads_; scoped_ptr<NotificationServiceImpl> notification_service_; scoped_ptr<BrowserMainLoop> main_loop_; #if defined(OS_WIN) scoped_ptr<ui::ScopedOleInitializer> ole_initializer_; #endif DISALLOW_COPY_AND_ASSIGN(BrowserMainRunnerImpl); }; // static BrowserMainRunner* BrowserMainRunner::Create() { return new BrowserMainRunnerImpl(); } } // namespace content <|endoftext|>
<commit_before>#define BOOST_TEST_MODULE RDOTriangularTest #include <boost/test/included/unit_test.hpp> // ----------------------------------------------------------------------- SYNOPSIS #include "simulator/runtime/rdo_random_distribution.h" BOOST_AUTO_TEST_CASE(RDOTriangularTest) { }<commit_msg>* reverted changes from rev.4925<commit_after>/*! \copyright (c) RDO-Team, 2011 \file main.cpp \author (rdo@rk9.bmstu.ru) \authors (impus@hotbox.ru) \date 12.09.2011 \brief \indent 4T */ // ---------------------------------------------------------------------------- PCH // ----------------------------------------------------------------------- INCLUDES #include "stdafx.h" #define BOOST_TEST_MODULE RDOTriangularTest #include <boost/test/included/unit_test.hpp> // ----------------------------------------------------------------------- SYNOPSIS #include "simulator/runtime/rdo_random_distribution.h" // -------------------------------------------------------------------------------- BOOST_AUTO_TEST_CASE(RDOTriangularTest) { } <|endoftext|>
<commit_before>/****************************************************************************** * Copyright (c) 2016 Charles R. Allen * * 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. ****************************************************************************** * lepton.cpp * * Created on: Mar 7, 2016 * Author: Charles Allen */ #include <fcntl.h> #include <error.h> #include <errno.h> #include <inttypes.h> #include <signal.h> #include <unistd.h> #include <stdio.h> #include <mraa.h> #include <string> #include <arpa/inet.h> #include <sys/types.h> #include <sys/socket.h> #include <netinet/in.h> #include <netinet/ip.h> #include <opencv2/opencv.hpp> #include <opencv2/imgproc/imgproc.hpp> using namespace cv; using namespace std; static const char *dev_name = "/dev/lepton"; void sig_handler(int signum); static sig_atomic_t volatile isrunning = 1; uint32_t frame_counter = 0; #define exitIfMRAAError(x) exitIfMRAAError_internal(x, __FILE__, __LINE__) static void exitIfMRAAError_internal(mraa_result_t result, const char *filename, unsigned int linenum) { if (__builtin_expect(result != MRAA_SUCCESS, 0)) { const char *errMsg = NULL; switch (result) { case MRAA_ERROR_FEATURE_NOT_IMPLEMENTED: errMsg = "MRAA_ERROR_FEATURE_NOT_IMPLEMENTED"; break; case MRAA_ERROR_FEATURE_NOT_SUPPORTED: errMsg = "MRAA_ERROR_FEATURE_NOT_SUPPORTED"; break; case MRAA_ERROR_INVALID_VERBOSITY_LEVEL: errMsg = "MRAA_ERROR_INVALID_VERBOSITY_LEVEL"; break; case MRAA_ERROR_INVALID_PARAMETER: errMsg = "MRAA_ERROR_INVALID_PARAMETER"; break; case MRAA_ERROR_INVALID_HANDLE: errMsg = "MRAA_ERROR_INVALID_HANDLE"; break; case MRAA_ERROR_NO_RESOURCES: errMsg = "MRAA_ERROR_NO_RESOURCES"; break; case MRAA_ERROR_INVALID_RESOURCE: errMsg = "MRAA_ERROR_INVALID_RESOURCE"; break; case MRAA_ERROR_INVALID_QUEUE_TYPE: errMsg = "MRAA_ERROR_INVALID_QUEUE_TYPE"; break; case MRAA_ERROR_NO_DATA_AVAILABLE: errMsg = "MRAA_ERROR_NO_DATA_AVAILABLE"; break; case MRAA_ERROR_INVALID_PLATFORM: errMsg = "MRAA_ERROR_INVALID_PLATFORM"; break; case MRAA_ERROR_PLATFORM_NOT_INITIALISED: errMsg = "MRAA_ERROR_PLATFORM_NOT_INITIALISED"; break; case MRAA_ERROR_PLATFORM_ALREADY_INITIALISED: errMsg = "MRAA_ERROR_PLATFORM_ALREADY_INITIALISED"; break; case MRAA_ERROR_UNSPECIFIED: errMsg = "MRAA_ERROR_UNSPECIFIED"; break; default: errMsg = "Completely unknown error in MRAA"; } error_at_line(result, errno, filename, linenum, "Error %d in MRAA: %s", (int) result, errMsg); } } static int captureImage(uint16_t *image, mraa_gpio_context cs, int fd) { const int line_len = 164; int result, i = 0, retval = 0; uint8_t buff[line_len * 60]; while (i < 60 && isrunning) { uint8_t *line = &buff[i * line_len]; uint16_t *line16 = (uint16_t *) line; memset(line, 0, line_len); result = read(fd, line, line_len); if (__builtin_expect(result == -1, 0)) { error(0, errno, "Error reading from [%s]", dev_name); break; } else if (__builtin_expect(result != line_len, 0)) { error(0, errno, "Size did not match, read %d, expected %d", (int) result, line_len); break; } line[0] &= 0x0F; if (__builtin_expect(line[0] != 0x0F, 0)) { uint16_t lineNum = ntohs(line16[0]); if (__builtin_expect(i != lineNum, 0)) { printf("Unexpected line. Expected %d found %d\n", (int) i, (int) lineNum); break; } ++i; } } retval = i - 60; if (__builtin_expect(retval, 0)) { return retval; } for (i = 0; i < 60; ++i) { uint8_t *line = &buff[i * line_len]; memcpy(&image[i * 80], &line[4], 160); } return retval; } #define BOUNDARY "hfihuuhf782hf4278fh2h4f7842hfh87942h" static const char boundary_end_str[] = "\r\n--" BOUNDARY "\r\n"; static int safe_write(int fd, uint8_t *ptr, ssize_t len) { for (ssize_t write_remaining = len, my_write = 0; write_remaining > 0; write_remaining -= my_write) { my_write = write(fd, ptr, write_remaining); if (__builtin_expect(-1 == my_write, 0)) { // Skip things like EAGAIN for now error(0, errno, "Error writing image data"); return -1; } ptr = &ptr[my_write]; } return len; } // image is still BigEndian when it gets here static int printImg(uint16_t *image, int out_fd) { uint16_t min_v = (uint16_t) -1; uint16_t max_v = 0; for (int i = 0; i < 60; ++i) { uint16_t *line = &image[i * 80]; for (int j = 0; j < 78/*80*/; ++j) { uint16_t v = line[j] = ntohs(line[j]); if (__builtin_expect(v > max_v, 0)) { max_v = v; } if (__builtin_expect(v < min_v, 0)) { min_v = v; } } } uint16_t scale = max_v - min_v; Mat grayScaleImage(60, 80, CV_8UC1); uint8_t *img_out = (uint8_t *) &grayScaleImage.data[0]; for (int i = 0; i < 60; ++i) { const int idex = i * 80; uint16_t *line = &image[idex]; uint8_t *line_out = &img_out[idex]; for (int j = 0; j < 78/*80*/; ++j) { line_out[j] = (((line[j] - min_v) << 8) / scale) & 0xFF; } line_out[78] = line_out[79] = 0; } uint8_t strbuff[1024]; std::vector<uchar> buff; try { if (!imencode(".jpeg", grayScaleImage, buff)) { error(0, 0, "Error writing jpeg image to buffer"); return -1; } } catch (cv::Exception &ex) { std::cout << "Error writing image: " <<ex.what() << std::endl; return -1; } ssize_t out_str_len = snprintf((char *) strbuff, sizeof(strbuff), "Content-Type: image/jpeg\r\nContent-Length: %d\r\n\r\n", buff.size()); if (out_str_len < 0) { error(0, errno, "Error writing output header"); return -1; } if (safe_write(out_fd, strbuff, out_str_len) < 0) { return -1; } if (safe_write(out_fd, buff.data(), buff.size()) < 0) { return -1; } if (safe_write(out_fd, (uint8_t *) boundary_end_str, sizeof(boundary_end_str) - 1) < 0) { return -1; } return 0; } int main(int argc, char **argv) { int fd; uint32_t frameNum = 0; uint16_t image[80 * 60]; mraa_gpio_context cs; Size size(80, 60); socklen_t sin_size = sizeof(struct sockaddr_in); int socket_fd = socket(PF_INET, SOCK_STREAM, 0); struct sockaddr_in sin, their_sin; sin.sin_family = AF_INET; inet_aton("192.168.1.139", &sin.sin_addr); //sin.sin_addr.s_addr = INADDR_ANY; sin.sin_port = htons(8888); memset(&(sin.sin_zero), '\0', 8); if (-1 == bind(socket_fd, (const struct sockaddr *) &sin, sizeof(sockaddr_in))) { error(-1, errno, "Error binding to 8888"); } if (-1 == listen(socket_fd, 1)) { error(-1, errno, "Error listening"); } signal(SIGINT, &sig_handler); cs = mraa_gpio_init(45); if (cs == NULL) { error(1, errno, "Error initializing cs on gpio10"); } exitIfMRAAError(mraa_gpio_dir(cs, MRAA_GPIO_OUT)); exitIfMRAAError(mraa_gpio_write(cs, 1)); // write CS` printf("Syncing with Lepton...\n"); usleep(200000); fd = open(dev_name, O_RDONLY); if (fd == -1) { error(-1, errno, "Error opening %s", dev_name); } printf("Activating Lepton...\n"); int out_fd = -1; while (isrunning) { if (-1 == out_fd || captureImage(image, cs, fd) < 0) { exitIfMRAAError(mraa_gpio_write(cs, 1)); // High to de-select while (-1 == out_fd && isrunning) { out_fd = accept(socket_fd, (struct sockaddr *) &their_sin, &sin_size); if (-1 == out_fd) { error(0, errno, "Error accepting socket, retrying"); } else { char out_buffer[4096] = { 0 }; snprintf(out_buffer, sizeof(out_buffer), "HTTP/1.0 20 OK\r\n" "Content-Type: multipart/x-mixed-replace;boundary=" BOUNDARY "\r\n" "\r\n--" BOUNDARY "\r\n"); int len = strlen(out_buffer); if (len != write(out_fd, out_buffer, len)) { error(0, 0, "Error writing bytes"); close(out_fd); out_fd = -1; } } }; frameNum = 0; // Actually only needs to be ~185ms usleep(200000); exitIfMRAAError(mraa_gpio_write(cs, 0)); // Select device } else { if (frameNum++ % 3 == 0) { if (-1 == printImg(image, out_fd)) { error(0, 0, "Problem with socket, closing. %s", isrunning ? "" : "Also is done"); close(out_fd); out_fd = -1; } } } } exitIfMRAAError(mraa_gpio_write(cs, 1)); // High to de-select exitIfMRAAError(mraa_gpio_close(cs)); if (out_fd != -1) { close(out_fd); } close(fd); return 0; } void sig_handler(int signum) { if (signum == SIGINT) isrunning = 0; } <commit_msg>Remove specific IP address.<commit_after>/****************************************************************************** * Copyright (c) 2016 Charles R. Allen * * 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. ****************************************************************************** * lepton.cpp * * Created on: Mar 7, 2016 * Author: Charles Allen */ #include <fcntl.h> #include <error.h> #include <errno.h> #include <inttypes.h> #include <signal.h> #include <unistd.h> #include <stdio.h> #include <mraa.h> #include <string> #include <arpa/inet.h> #include <sys/types.h> #include <sys/socket.h> #include <netinet/in.h> #include <netinet/ip.h> #include <opencv2/opencv.hpp> #include <opencv2/imgproc/imgproc.hpp> using namespace cv; using namespace std; static const char *dev_name = "/dev/lepton"; void sig_handler(int signum); static sig_atomic_t volatile isrunning = 1; uint32_t frame_counter = 0; #define exitIfMRAAError(x) exitIfMRAAError_internal(x, __FILE__, __LINE__) static void exitIfMRAAError_internal(mraa_result_t result, const char *filename, unsigned int linenum) { if (__builtin_expect(result != MRAA_SUCCESS, 0)) { const char *errMsg = NULL; switch (result) { case MRAA_ERROR_FEATURE_NOT_IMPLEMENTED: errMsg = "MRAA_ERROR_FEATURE_NOT_IMPLEMENTED"; break; case MRAA_ERROR_FEATURE_NOT_SUPPORTED: errMsg = "MRAA_ERROR_FEATURE_NOT_SUPPORTED"; break; case MRAA_ERROR_INVALID_VERBOSITY_LEVEL: errMsg = "MRAA_ERROR_INVALID_VERBOSITY_LEVEL"; break; case MRAA_ERROR_INVALID_PARAMETER: errMsg = "MRAA_ERROR_INVALID_PARAMETER"; break; case MRAA_ERROR_INVALID_HANDLE: errMsg = "MRAA_ERROR_INVALID_HANDLE"; break; case MRAA_ERROR_NO_RESOURCES: errMsg = "MRAA_ERROR_NO_RESOURCES"; break; case MRAA_ERROR_INVALID_RESOURCE: errMsg = "MRAA_ERROR_INVALID_RESOURCE"; break; case MRAA_ERROR_INVALID_QUEUE_TYPE: errMsg = "MRAA_ERROR_INVALID_QUEUE_TYPE"; break; case MRAA_ERROR_NO_DATA_AVAILABLE: errMsg = "MRAA_ERROR_NO_DATA_AVAILABLE"; break; case MRAA_ERROR_INVALID_PLATFORM: errMsg = "MRAA_ERROR_INVALID_PLATFORM"; break; case MRAA_ERROR_PLATFORM_NOT_INITIALISED: errMsg = "MRAA_ERROR_PLATFORM_NOT_INITIALISED"; break; case MRAA_ERROR_PLATFORM_ALREADY_INITIALISED: errMsg = "MRAA_ERROR_PLATFORM_ALREADY_INITIALISED"; break; case MRAA_ERROR_UNSPECIFIED: errMsg = "MRAA_ERROR_UNSPECIFIED"; break; default: errMsg = "Completely unknown error in MRAA"; } error_at_line(result, errno, filename, linenum, "Error %d in MRAA: %s", (int) result, errMsg); } } static int captureImage(uint16_t *image, mraa_gpio_context cs, int fd) { const int line_len = 164; int result, i = 0, retval = 0; uint8_t buff[line_len * 60]; while (i < 60 && isrunning) { uint8_t *line = &buff[i * line_len]; uint16_t *line16 = (uint16_t *) line; memset(line, 0, line_len); result = read(fd, line, line_len); if (__builtin_expect(result == -1, 0)) { error(0, errno, "Error reading from [%s]", dev_name); break; } else if (__builtin_expect(result != line_len, 0)) { error(0, errno, "Size did not match, read %d, expected %d", (int) result, line_len); break; } line[0] &= 0x0F; if (__builtin_expect(line[0] != 0x0F, 0)) { uint16_t lineNum = ntohs(line16[0]); if (__builtin_expect(i != lineNum, 0)) { printf("Unexpected line. Expected %d found %d\n", (int) i, (int) lineNum); break; } ++i; } } retval = i - 60; if (__builtin_expect(retval, 0)) { return retval; } for (i = 0; i < 60; ++i) { uint8_t *line = &buff[i * line_len]; memcpy(&image[i * 80], &line[4], 160); } return retval; } #define BOUNDARY "hfihuuhf782hf4278fh2h4f7842hfh87942h" static const char boundary_end_str[] = "\r\n--" BOUNDARY "\r\n"; static int safe_write(int fd, uint8_t *ptr, ssize_t len) { for (ssize_t write_remaining = len, my_write = 0; write_remaining > 0; write_remaining -= my_write) { my_write = write(fd, ptr, write_remaining); if (__builtin_expect(-1 == my_write, 0)) { // Skip things like EAGAIN for now error(0, errno, "Error writing image data"); return -1; } ptr = &ptr[my_write]; } return len; } // image is still BigEndian when it gets here static int printImg(uint16_t *image, int out_fd) { uint16_t min_v = (uint16_t) -1; uint16_t max_v = 0; for (int i = 0; i < 60; ++i) { uint16_t *line = &image[i * 80]; for (int j = 0; j < 78/*80*/; ++j) { uint16_t v = line[j] = ntohs(line[j]); if (__builtin_expect(v > max_v, 0)) { max_v = v; } if (__builtin_expect(v < min_v, 0)) { min_v = v; } } } uint16_t scale = max_v - min_v; Mat grayScaleImage(60, 80, CV_8UC1); uint8_t *img_out = (uint8_t *) &grayScaleImage.data[0]; for (int i = 0; i < 60; ++i) { const int idex = i * 80; uint16_t *line = &image[idex]; uint8_t *line_out = &img_out[idex]; for (int j = 0; j < 78/*80*/; ++j) { line_out[j] = (((line[j] - min_v) << 8) / scale) & 0xFF; } line_out[78] = line_out[79] = 0; } uint8_t strbuff[1024]; std::vector<uchar> buff; try { if (!imencode(".jpeg", grayScaleImage, buff)) { error(0, 0, "Error writing jpeg image to buffer"); return -1; } } catch (cv::Exception &ex) { std::cout << "Error writing image: " <<ex.what() << std::endl; return -1; } ssize_t out_str_len = snprintf((char *) strbuff, sizeof(strbuff), "Content-Type: image/jpeg\r\nContent-Length: %d\r\n\r\n", buff.size()); if (out_str_len < 0) { error(0, errno, "Error writing output header"); return -1; } if (safe_write(out_fd, strbuff, out_str_len) < 0) { return -1; } if (safe_write(out_fd, buff.data(), buff.size()) < 0) { return -1; } if (safe_write(out_fd, (uint8_t *) boundary_end_str, sizeof(boundary_end_str) - 1) < 0) { return -1; } return 0; } int main(int argc, char **argv) { int fd; uint32_t frameNum = 0; uint16_t image[80 * 60]; mraa_gpio_context cs; Size size(80, 60); socklen_t sin_size = sizeof(struct sockaddr_in); int socket_fd = socket(PF_INET, SOCK_STREAM, 0); struct sockaddr_in sin, their_sin; sin.sin_family = AF_INET; sin.sin_addr.s_addr = INADDR_ANY; sin.sin_port = htons(8888); memset(&(sin.sin_zero), '\0', 8); if (-1 == bind(socket_fd, (const struct sockaddr *) &sin, sizeof(sockaddr_in))) { error(-1, errno, "Error binding to 8888"); } if (-1 == listen(socket_fd, 1)) { error(-1, errno, "Error listening"); } signal(SIGINT, &sig_handler); cs = mraa_gpio_init(45); if (cs == NULL) { error(1, errno, "Error initializing cs on gpio10"); } exitIfMRAAError(mraa_gpio_dir(cs, MRAA_GPIO_OUT)); exitIfMRAAError(mraa_gpio_write(cs, 1)); // write CS` printf("Syncing with Lepton...\n"); usleep(200000); fd = open(dev_name, O_RDONLY); if (fd == -1) { error(-1, errno, "Error opening %s", dev_name); } printf("Activating Lepton...\n"); int out_fd = -1; while (isrunning) { if (-1 == out_fd || captureImage(image, cs, fd) < 0) { exitIfMRAAError(mraa_gpio_write(cs, 1)); // High to de-select while (-1 == out_fd && isrunning) { out_fd = accept(socket_fd, (struct sockaddr *) &their_sin, &sin_size); if (-1 == out_fd) { error(0, errno, "Error accepting socket, retrying"); } else { char out_buffer[4096] = { 0 }; snprintf(out_buffer, sizeof(out_buffer), "HTTP/1.0 20 OK\r\n" "Content-Type: multipart/x-mixed-replace;boundary=" BOUNDARY "\r\n" "\r\n--" BOUNDARY "\r\n"); int len = strlen(out_buffer); if (len != write(out_fd, out_buffer, len)) { error(0, 0, "Error writing bytes"); close(out_fd); out_fd = -1; } } }; frameNum = 0; // Actually only needs to be ~185ms usleep(200000); exitIfMRAAError(mraa_gpio_write(cs, 0)); // Select device } else { if (frameNum++ % 3 == 0) { if (-1 == printImg(image, out_fd)) { error(0, 0, "Problem with socket, closing. %s", isrunning ? "" : "Also is done"); close(out_fd); out_fd = -1; } } } } exitIfMRAAError(mraa_gpio_write(cs, 1)); // High to de-select exitIfMRAAError(mraa_gpio_close(cs)); if (out_fd != -1) { close(out_fd); } close(fd); return 0; } void sig_handler(int signum) { if (signum == SIGINT) isrunning = 0; } <|endoftext|>
<commit_before>// Copyright 2012 Google Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include "syzygy/agent/profiler/return_thunk_factory.h" #include "syzygy/agent/profiler/scoped_last_error_keeper.h" namespace { // Static assembly function called by all thunks. It ends up calling to // ReturnThunkFactory::ThunkMain. extern "C" void __declspec(naked) thunk_main_asm() { __asm { // Stash volatile registers. push eax push ecx push edx pushfd // Get the current cycle time. rdtsc push edx push eax // Calculate a pointer to the start of the thunk object as // the return address pushed by the caller, subtracting 5 (the // size of the E8 call instruction) to get a pointer to the // start of the thunk object. mov eax, DWORD PTR[esp + 0x18] sub eax, 5 push eax call agent::client::ReturnThunkFactory::ThunkMain // Restore volatile registers, except eax. popfd pop edx pop ecx // We start with: // EAX: real ret-address // stack: // pushed EAX // ret-address to thunk // // We end with: // EAX: pushed EAX // stack: // ret-address to thunk // real ret-address xchg eax, DWORD PTR[esp + 0x4] xchg eax, DWORD PTR[esp] // Return to the thunk, which will in turn return to the real // return address. ret } } } // namespace namespace agent { namespace client { ReturnThunkFactory::ReturnThunkFactory(Delegate* delegate) : delegate_(delegate), first_free_thunk_(NULL) { DCHECK(delegate_ != NULL); AddPage(); } ReturnThunkFactory::~ReturnThunkFactory() { // Walk to the head of the page list, then release to the tail. Page* current_page = PageFromThunk(first_free_thunk_); while (current_page->previous_page) current_page = current_page->previous_page; while (current_page->next_page) { Page* page_to_free = current_page; current_page = current_page->next_page; // Notify the delegate of the release. We do this before freeing the memory // to make sure we don't open a race where a new thread could sneak a stack // into the page allocation. delegate_->OnPageRemoved(page_to_free); ::VirtualFree(page_to_free, 0, MEM_RELEASE); } } ReturnThunkFactory::Thunk* ReturnThunkFactory::MakeThunk(RetAddr real_ret) { Thunk* thunk = first_free_thunk_; thunk->caller = real_ret; Page* current_page = PageFromThunk(first_free_thunk_); if (first_free_thunk_ != LastThunk(current_page)) { first_free_thunk_++; } else if (current_page->next_page) { first_free_thunk_ = &current_page->next_page->thunks[0]; } else { AddPage(); } return thunk; } void ReturnThunkFactory::AddPage() { Page* previous_page = PageFromThunk(first_free_thunk_); DCHECK(previous_page == NULL || previous_page->next_page == NULL); // TODO(joi): This may be consuming 64K of memory, in which case it would // be more efficient to reserve a larger block at a time if we think we // normally need more than 4K of thunks. Page* new_page = reinterpret_cast<Page*>(::VirtualAlloc( NULL, kPageSize, MEM_COMMIT | MEM_RESERVE, PAGE_EXECUTE_READWRITE)); CHECK(new_page); new_page->previous_page = previous_page; new_page->next_page = NULL; new_page->factory = this; if (previous_page) previous_page->next_page = new_page; // Since thunks get reused a lot, we optimize a bit by filling in the // static part of all thunks when each page is allocated. for (size_t i= 0; i < kNumThunksPerPage; ++i) { Thunk* thunk = &new_page->thunks[i]; thunk->call = 0xE8; // call thunk->func_addr = reinterpret_cast<DWORD>(thunk_main_asm) - reinterpret_cast<DWORD>(&thunk->ret); thunk->ret = 0xC3; } first_free_thunk_ = &new_page->thunks[0]; // Notify the delegate that the page has been allocated. delegate_->OnPageAdded(new_page); } // static ReturnThunkFactory::Page* ReturnThunkFactory::PageFromThunk(Thunk* thunk) { return reinterpret_cast<Page*>(reinterpret_cast<DWORD>(thunk) & kPageMask); } // static ReturnThunkFactory::Thunk* ReturnThunkFactory::LastThunk(Page* page) { return &page->thunks[kNumThunksPerPage - 1]; } // static RetAddr WINAPI ReturnThunkFactory::ThunkMain(Thunk* thunk, uint64 cycles) { DCHECK(*reinterpret_cast<BYTE*>(thunk) == 0xE8); ScopedLastErrorKeeper keep_last_error; ReturnThunkFactory* factory = PageFromThunk(thunk)->factory; factory->first_free_thunk_ = thunk; factory->delegate_->OnFunctionExit(thunk, cycles); return thunk->caller; } } // namespace client } // namespace agent <commit_msg>Tweak return thunk assembly.<commit_after>// Copyright 2012 Google Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include "syzygy/agent/profiler/return_thunk_factory.h" #include "syzygy/agent/profiler/scoped_last_error_keeper.h" namespace { // Static assembly function called by all thunks. It ends up calling to // ReturnThunkFactory::ThunkMain. extern "C" void __declspec(naked) thunk_main_asm() { __asm { // Stash volatile registers. push eax push edx // Get the current cycle time ASAP. rdtsc push ecx pushfd // Push the cycle time arg for the ThunkMain function. push edx push eax // Calculate a pointer to the start of the thunk object as // the return address pushed by the caller, subtracting 5 (the // size of the E8 call instruction) to get a pointer to the // start of the thunk object. mov eax, DWORD PTR[esp + 0x18] sub eax, 5 push eax call agent::client::ReturnThunkFactory::ThunkMain // Restore volatile registers, except eax. popfd pop ecx pop edx // At this point we have: // EAX: real ret-address // stack: // pushed EAX // ret-address to thunk push eax mov eax, DWORD PTR[esp+4] // Return and discard the stored eax and discarded return address. ret 8 } } } // namespace namespace agent { namespace client { ReturnThunkFactory::ReturnThunkFactory(Delegate* delegate) : delegate_(delegate), first_free_thunk_(NULL) { DCHECK(delegate_ != NULL); AddPage(); } ReturnThunkFactory::~ReturnThunkFactory() { // Walk to the head of the page list, then release to the tail. Page* current_page = PageFromThunk(first_free_thunk_); while (current_page->previous_page) current_page = current_page->previous_page; while (current_page->next_page) { Page* page_to_free = current_page; current_page = current_page->next_page; // Notify the delegate of the release. We do this before freeing the memory // to make sure we don't open a race where a new thread could sneak a stack // into the page allocation. delegate_->OnPageRemoved(page_to_free); ::VirtualFree(page_to_free, 0, MEM_RELEASE); } } ReturnThunkFactory::Thunk* ReturnThunkFactory::MakeThunk(RetAddr real_ret) { Thunk* thunk = first_free_thunk_; thunk->caller = real_ret; Page* current_page = PageFromThunk(first_free_thunk_); if (first_free_thunk_ != LastThunk(current_page)) { first_free_thunk_++; } else if (current_page->next_page) { first_free_thunk_ = &current_page->next_page->thunks[0]; } else { AddPage(); } return thunk; } void ReturnThunkFactory::AddPage() { Page* previous_page = PageFromThunk(first_free_thunk_); DCHECK(previous_page == NULL || previous_page->next_page == NULL); // TODO(joi): This may be consuming 64K of memory, in which case it would // be more efficient to reserve a larger block at a time if we think we // normally need more than 4K of thunks. Page* new_page = reinterpret_cast<Page*>(::VirtualAlloc( NULL, kPageSize, MEM_COMMIT | MEM_RESERVE, PAGE_EXECUTE_READWRITE)); CHECK(new_page); new_page->previous_page = previous_page; new_page->next_page = NULL; new_page->factory = this; if (previous_page) previous_page->next_page = new_page; // Since thunks get reused a lot, we optimize a bit by filling in the // static part of all thunks when each page is allocated. for (size_t i= 0; i < kNumThunksPerPage; ++i) { Thunk* thunk = &new_page->thunks[i]; thunk->call = 0xE8; // call thunk->func_addr = reinterpret_cast<DWORD>(thunk_main_asm) - reinterpret_cast<DWORD>(&thunk->caller); } first_free_thunk_ = &new_page->thunks[0]; // Notify the delegate that the page has been allocated. delegate_->OnPageAdded(new_page); } // static ReturnThunkFactory::Page* ReturnThunkFactory::PageFromThunk(Thunk* thunk) { return reinterpret_cast<Page*>(reinterpret_cast<DWORD>(thunk) & kPageMask); } // static ReturnThunkFactory::Thunk* ReturnThunkFactory::LastThunk(Page* page) { return &page->thunks[kNumThunksPerPage - 1]; } // static RetAddr WINAPI ReturnThunkFactory::ThunkMain(Thunk* thunk, uint64 cycles) { DCHECK(*reinterpret_cast<BYTE*>(thunk) == 0xE8); ScopedLastErrorKeeper keep_last_error; ReturnThunkFactory* factory = PageFromThunk(thunk)->factory; factory->first_free_thunk_ = thunk; factory->delegate_->OnFunctionExit(thunk, cycles); return thunk->caller; } } // namespace client } // namespace agent <|endoftext|>
<commit_before>#include "engine/polyline_compressor.hpp" #include <boost/assert.hpp> #include <cstddef> #include <cstdlib> #include <cmath> #include <algorithm> namespace osrm { namespace engine { namespace /*detail*/ // anonymous to keep TU local { std::string encode(int number_to_encode) { std::string output; while (number_to_encode >= 0x20) { const int next_value = (0x20 | (number_to_encode & 0x1f)) + 63; output += static_cast<char>(next_value); number_to_encode >>= 5; } number_to_encode += 63; output += static_cast<char>(number_to_encode); return output; } std::string encode(std::vector<int> &numbers) { std::string output; for (auto &number : numbers) { bool isNegative = number < 0; if (isNegative) { const unsigned binary = std::llabs(number); const unsigned twos = (~binary) + 1u; number = twos; } number <<= 1u; if (isNegative) { number = ~number; } } for (const int number : numbers) { output += encode(number); } return output; } } // anonymous ns std::string encodePolyline(CoordVectorForwardIter begin, CoordVectorForwardIter end) { auto size = std::distance(begin, end); if (size == 0) { return {}; } std::vector<int> delta_numbers; BOOST_ASSERT(size > 0); delta_numbers.reserve((size - 1) * 2); util::Coordinate previous_coordinate{util::FixedLongitude(0), util::FixedLatitude(0)}; std::for_each(begin, end, [&delta_numbers, &previous_coordinate](const util::Coordinate loc) { const int lat_diff = static_cast<int>(loc.lat - previous_coordinate.lat) * detail::COORDINATE_TO_POLYLINE; const int lon_diff = static_cast<int>(loc.lon - previous_coordinate.lon) * detail::COORDINATE_TO_POLYLINE; delta_numbers.emplace_back(lat_diff); delta_numbers.emplace_back(lon_diff); previous_coordinate = loc; }); return encode(delta_numbers); } std::vector<util::Coordinate> decodePolyline(const std::string &geometry_string) { std::vector<util::Coordinate> new_coordinates; int index = 0, len = geometry_string.size(); int lat = 0, lng = 0; while (index < len) { int b, shift = 0, result = 0; do { b = geometry_string.at(index++) - 63; result |= (b & 0x1f) << shift; shift += 5; } while (b >= 0x20); int dlat = ((result & 1) != 0 ? ~(result >> 1) : (result >> 1)); lat += dlat; shift = 0; result = 0; do { b = geometry_string.at(index++) - 63; result |= (b & 0x1f) << shift; shift += 5; } while (b >= 0x20); int dlng = ((result & 1) != 0 ? ~(result >> 1) : (result >> 1)); lng += dlng; util::Coordinate p; p.lat = util::FixedLatitude(lat * detail::POLYLINE_TO_COORDINATE); p.lon = util::FixedLongitude(lng * detail::POLYLINE_TO_COORDINATE); new_coordinates.push_back(p); } return new_coordinates; } } } <commit_msg>Fix numerical problems with polyline<commit_after>#include "engine/polyline_compressor.hpp" #include <boost/assert.hpp> #include <cstddef> #include <cstdlib> #include <cmath> #include <algorithm> namespace osrm { namespace engine { namespace /*detail*/ // anonymous to keep TU local { std::string encode(int number_to_encode) { std::string output; while (number_to_encode >= 0x20) { const int next_value = (0x20 | (number_to_encode & 0x1f)) + 63; output += static_cast<char>(next_value); number_to_encode >>= 5; } number_to_encode += 63; output += static_cast<char>(number_to_encode); return output; } std::string encode(std::vector<int> &numbers) { std::string output; for (auto &number : numbers) { bool isNegative = number < 0; if (isNegative) { const unsigned binary = std::llabs(number); const unsigned twos = (~binary) + 1u; number = twos; } number <<= 1u; if (isNegative) { number = ~number; } } for (const int number : numbers) { output += encode(number); } return output; } } // anonymous ns std::string encodePolyline(CoordVectorForwardIter begin, CoordVectorForwardIter end) { auto size = std::distance(begin, end); if (size == 0) { return {}; } std::vector<int> delta_numbers; BOOST_ASSERT(size > 0); delta_numbers.reserve((size - 1) * 2); int current_lat = 0; int current_lon = 0; std::for_each(begin, end, [&delta_numbers, &current_lat, &current_lon](const util::Coordinate loc) { const int lat_diff = std::round(static_cast<int>(loc.lat) * detail::COORDINATE_TO_POLYLINE) - current_lat; const int lon_diff = std::round(static_cast<int>(loc.lon) * detail::COORDINATE_TO_POLYLINE) - current_lon; delta_numbers.emplace_back(lat_diff); delta_numbers.emplace_back(lon_diff); current_lat += lat_diff; current_lon += lon_diff; }); return encode(delta_numbers); } std::vector<util::Coordinate> decodePolyline(const std::string &geometry_string) { std::vector<util::Coordinate> new_coordinates; int index = 0, len = geometry_string.size(); int lat = 0, lng = 0; while (index < len) { int b, shift = 0, result = 0; do { b = geometry_string.at(index++) - 63; result |= (b & 0x1f) << shift; shift += 5; } while (b >= 0x20); int dlat = ((result & 1) != 0 ? ~(result >> 1) : (result >> 1)); lat += dlat; shift = 0; result = 0; do { b = geometry_string.at(index++) - 63; result |= (b & 0x1f) << shift; shift += 5; } while (b >= 0x20); int dlng = ((result & 1) != 0 ? ~(result >> 1) : (result >> 1)); lng += dlng; util::Coordinate p; p.lat = util::FixedLatitude(lat * detail::POLYLINE_TO_COORDINATE); p.lon = util::FixedLongitude(lng * detail::POLYLINE_TO_COORDINATE); new_coordinates.push_back(p); } return new_coordinates; } } } <|endoftext|>
<commit_before>/* =========================================================================== Daemon GPL Source Code Copyright (C) 2012 Unvanquished Developers This file is part of the Daemon GPL Source Code (Daemon Source Code). Daemon Source Code 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. Daemon Source 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 for more details. You should have received a copy of the GNU General Public License along with Daemon Source Code. If not, see <http://www.gnu.org/licenses/>. In addition, the Daemon Source Code is also subject to certain additional terms. You should have received a copy of these additional terms immediately following the terms and conditions of the GNU General Public License which accompanied the Daemon Source Code. If not, please request a copy in writing from id Software at the address below. If you have questions concerning this license or the applicable additional terms, you may contact in writing id Software LLC, c/o ZeniMax Media Inc., Suite 120, Rockville, Maryland 20850 USA. =========================================================================== */ extern "C" { #include "q_shared.h" #include "qcommon.h" #include "../../libs/findlocale/findlocale.h" } #include "../../libs/tinygettext/tinygettext.hpp" #include <sstream> #include <iostream> using namespace tinygettext; // Ugly char buffer static char gettextbuffer[ MAX_STRING_CHARS ]; DictionaryManager trans_manager; DictionaryManager trans_managergame; Dictionary trans_dict; Dictionary trans_dictgame; cvar_t *language; cvar_t *language_debug; cvar_t *trans_encodings; cvar_t *trans_languages; bool enabled = false; int modificationCount=0; #define _(x) Trans_Gettext(x) #define C_(x, y) Trans_Pgettext(x, y) /* ==================== Trans_ReturnLanguage Return a loaded language. If desired language is not found, return closest match. If no languages are close, force English. ==================== */ Language Trans_ReturnLanguage( const char *lang ) { int bestScore = 0; Language bestLang, language = Language::from_env( std::string( lang ) ); std::set<Language> langs = trans_manager.get_languages(); for( std::set<Language>::iterator i = langs.begin(); i != langs.end(); i++ ) { int score = Language::match( language, *i ); if( score > bestScore ) { bestScore = score; bestLang = *i; } } // Return "en" if language not found if( !bestLang ) { Com_Printf( _("^3WARNING:^7 Language \"%s\" (%s) not found. Default to \"English\" (en)\n"), language.get_name().empty() ? _("Unknown Language") : language.get_name().c_str(), lang ); bestLang = Language::from_env( "en" ); } return bestLang; } extern "C" void Trans_UpdateLanguage_f( void ) { if( !enabled ) { return; } Language lang = Trans_ReturnLanguage( language->string ); trans_dict = trans_manager.get_dictionary( lang ); trans_dictgame = trans_managergame.get_dictionary( lang ); Com_Printf(_( "Switched language to %s\n"), lang.get_name().c_str() ); #ifndef DEDICATED // update the default console keys string extern cvar_t *cl_consoleKeys; // should really #include client.h Z_Free( cl_consoleKeys->resetString ); cl_consoleKeys->resetString = CopyString( _("~ ` 0x7e 0x60") ); #endif } /* ============ Trans_Init ============ */ extern "C" void Trans_Init( void ) { char **poFiles, langList[ MAX_TOKEN_CHARS ] = "", encList[ MAX_TOKEN_CHARS ] = ""; int numPoFiles, i; FL_Locale *locale; std::set<Language> langs; Language lang; language = Cvar_Get( "language", "", CVAR_ARCHIVE ); language_debug = Cvar_Get( "language_debug", "0", CVAR_ARCHIVE ); trans_languages = Cvar_Get( "trans_languages", "", CVAR_ROM ); trans_encodings = Cvar_Get( "trans_languages", "", CVAR_ROM ); // Only detect locale if no previous language set. if( !language->string[0] ) { FL_FindLocale( &locale, FL_MESSAGES ); // Invalid or not found. Just use builtin language. if( !locale->lang || !locale->lang[0] || !locale->country || !locale->country[0] ) { Cvar_Set( "language", "en" ); } else { Cvar_Set( "language", va( "%s%s%s", locale->lang, locale->country[0] ? "_" : "", locale->country ) ); } } poFiles = FS_ListFiles( "translation/client", ".po", &numPoFiles ); // This assumes that the filenames in both folders are the same for( i = 0; i < numPoFiles; i++ ) { int ret; char *buffer, language[ 6 ]; if( FS_ReadFile( va( "translation/client/%s", poFiles[ i ] ), ( void ** ) &buffer ) > 0 ) { COM_StripExtension2( poFiles[ i ], language, sizeof( language ) ); std::stringstream ss( buffer ); trans_manager.add_po( poFiles[ i ], ss, Language::from_env( std::string( language ) ) ); FS_FreeFile( buffer ); } else { Com_Printf(_( "^1ERROR: Could not open client translation: %s\n"), poFiles[ i ] ); } if( FS_ReadFile( va( "translation/game/%s", poFiles[ i ] ), ( void ** ) &buffer ) > 0 ) { COM_StripExtension2( poFiles[ i ], language, sizeof( language ) ); std::stringstream ss( buffer ); trans_managergame.add_po( poFiles[ i ], ss, Language::from_env( std::string( language ) ) ); FS_FreeFile( buffer ); } else { Com_Printf(_( "^1ERROR: Could not open game translation: %s\n"), poFiles[ i ] ); } } FS_FreeFileList( poFiles ); langs = trans_manager.get_languages(); for( std::set<Language>::iterator p = langs.begin(); p != langs.end(); p++ ) { Q_strcat( langList, sizeof( langList ), va( "\"%s\" ", p->get_name().c_str() ) ); Q_strcat( encList, sizeof( encList ), va( "\"%s%s%s\" ", p->get_language().c_str(), p->get_country().c_str()[0] ? "_" : "", p->get_country().c_str() ) ); } Cvar_Set( "trans_languages", langList ); Cvar_Set( "trans_encodings", encList ); Com_Printf(_( "Loaded %lu language(s)\n"), langs.size() ); Cmd_AddCommand( "updatelanguage", Trans_UpdateLanguage_f ); if( langs.size() ) { lang = Trans_ReturnLanguage( language->string ); trans_dict = trans_manager.get_dictionary( lang ); trans_dictgame = trans_managergame.get_dictionary( lang ); enabled = true; } } extern "C" const char* Trans_Gettext( const char *msgid ) { if( !enabled ) { return msgid; } Q_strncpyz( gettextbuffer, trans_dict.translate( msgid ).c_str(), sizeof( gettextbuffer ) ); return gettextbuffer; } extern "C" const char* Trans_Pgettext( const char *ctxt, const char *msgid ) { if ( !enabled ) { return msgid; } Q_strncpyz( gettextbuffer, trans_dict.translate_ctxt( ctxt, msgid ).c_str(), sizeof( gettextbuffer ) ); return gettextbuffer; } extern "C" const char* Trans_GettextGame( const char *msgid ) { if( !enabled ) { return msgid; } Q_strncpyz( gettextbuffer, trans_dictgame.translate( msgid ).c_str(), sizeof( gettextbuffer ) ); return gettextbuffer; } extern "C" const char* Trans_PgettextGame( const char *ctxt, const char *msgid ) { if( !enabled ) { return msgid; } return trans_dictgame.translate_ctxt( std::string( ctxt ), std::string( msgid ) ).c_str(); } extern "C" const char* Trans_GettextPlural( const char *msgid, const char *msgid_plural, int num ) { if( !enabled ) { return num == 1 ? msgid : msgid_plural; } Q_strncpyz( gettextbuffer, trans_dict.translate_plural( msgid, msgid_plural, num ).c_str(), sizeof( gettextbuffer ) ); return gettextbuffer; } extern "C" const char* Trans_GettextGamePlural( const char *msgid, const char *msgid_plural, int num ) { if( !enabled ) { return num == 1 ? msgid : msgid_plural; } Q_strncpyz( gettextbuffer, trans_dictgame.translate_plural( msgid, msgid_plural, num ).c_str(), sizeof( gettextbuffer ) ); return gettextbuffer; } <commit_msg>Fix some unused variable warnings<commit_after>/* =========================================================================== Daemon GPL Source Code Copyright (C) 2012 Unvanquished Developers This file is part of the Daemon GPL Source Code (Daemon Source Code). Daemon Source Code 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. Daemon Source 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 for more details. You should have received a copy of the GNU General Public License along with Daemon Source Code. If not, see <http://www.gnu.org/licenses/>. In addition, the Daemon Source Code is also subject to certain additional terms. You should have received a copy of these additional terms immediately following the terms and conditions of the GNU General Public License which accompanied the Daemon Source Code. If not, please request a copy in writing from id Software at the address below. If you have questions concerning this license or the applicable additional terms, you may contact in writing id Software LLC, c/o ZeniMax Media Inc., Suite 120, Rockville, Maryland 20850 USA. =========================================================================== */ extern "C" { #include "q_shared.h" #include "qcommon.h" #include "../../libs/findlocale/findlocale.h" } #include "../../libs/tinygettext/tinygettext.hpp" #include <sstream> #include <iostream> using namespace tinygettext; // Ugly char buffer static char gettextbuffer[ MAX_STRING_CHARS ]; DictionaryManager trans_manager; DictionaryManager trans_managergame; Dictionary trans_dict; Dictionary trans_dictgame; cvar_t *language; cvar_t *language_debug; cvar_t *trans_encodings; cvar_t *trans_languages; bool enabled = false; int modificationCount=0; #define _(x) Trans_Gettext(x) #define C_(x, y) Trans_Pgettext(x, y) /* ==================== Trans_ReturnLanguage Return a loaded language. If desired language is not found, return closest match. If no languages are close, force English. ==================== */ Language Trans_ReturnLanguage( const char *lang ) { int bestScore = 0; Language bestLang, language = Language::from_env( std::string( lang ) ); std::set<Language> langs = trans_manager.get_languages(); for( std::set<Language>::iterator i = langs.begin(); i != langs.end(); i++ ) { int score = Language::match( language, *i ); if( score > bestScore ) { bestScore = score; bestLang = *i; } } // Return "en" if language not found if( !bestLang ) { Com_Printf( _("^3WARNING:^7 Language \"%s\" (%s) not found. Default to \"English\" (en)\n"), language.get_name().empty() ? _("Unknown Language") : language.get_name().c_str(), lang ); bestLang = Language::from_env( "en" ); } return bestLang; } extern "C" void Trans_UpdateLanguage_f( void ) { if( !enabled ) { return; } Language lang = Trans_ReturnLanguage( language->string ); trans_dict = trans_manager.get_dictionary( lang ); trans_dictgame = trans_managergame.get_dictionary( lang ); Com_Printf(_( "Switched language to %s\n"), lang.get_name().c_str() ); #ifndef DEDICATED // update the default console keys string extern cvar_t *cl_consoleKeys; // should really #include client.h Z_Free( cl_consoleKeys->resetString ); cl_consoleKeys->resetString = CopyString( _("~ ` 0x7e 0x60") ); #endif } /* ============ Trans_Init ============ */ extern "C" void Trans_Init( void ) { char **poFiles, langList[ MAX_TOKEN_CHARS ] = "", encList[ MAX_TOKEN_CHARS ] = ""; int numPoFiles, i; FL_Locale *locale; std::set<Language> langs; Language lang; language = Cvar_Get( "language", "", CVAR_ARCHIVE ); language_debug = Cvar_Get( "language_debug", "0", CVAR_ARCHIVE ); trans_languages = Cvar_Get( "trans_languages", "", CVAR_ROM ); trans_encodings = Cvar_Get( "trans_languages", "", CVAR_ROM ); // Only detect locale if no previous language set. if( !language->string[0] ) { FL_FindLocale( &locale, FL_MESSAGES ); // Invalid or not found. Just use builtin language. if( !locale->lang || !locale->lang[0] || !locale->country || !locale->country[0] ) { Cvar_Set( "language", "en" ); } else { Cvar_Set( "language", va( "%s%s%s", locale->lang, locale->country[0] ? "_" : "", locale->country ) ); } } poFiles = FS_ListFiles( "translation/client", ".po", &numPoFiles ); // This assumes that the filenames in both folders are the same for( i = 0; i < numPoFiles; i++ ) { char *buffer, language[ 6 ]; if( FS_ReadFile( va( "translation/client/%s", poFiles[ i ] ), ( void ** ) &buffer ) > 0 ) { COM_StripExtension2( poFiles[ i ], language, sizeof( language ) ); std::stringstream ss( buffer ); trans_manager.add_po( poFiles[ i ], ss, Language::from_env( std::string( language ) ) ); FS_FreeFile( buffer ); } else { Com_Printf(_( "^1ERROR: Could not open client translation: %s\n"), poFiles[ i ] ); } if( FS_ReadFile( va( "translation/game/%s", poFiles[ i ] ), ( void ** ) &buffer ) > 0 ) { COM_StripExtension2( poFiles[ i ], language, sizeof( language ) ); std::stringstream ss( buffer ); trans_managergame.add_po( poFiles[ i ], ss, Language::from_env( std::string( language ) ) ); FS_FreeFile( buffer ); } else { Com_Printf(_( "^1ERROR: Could not open game translation: %s\n"), poFiles[ i ] ); } } FS_FreeFileList( poFiles ); langs = trans_manager.get_languages(); for( std::set<Language>::iterator p = langs.begin(); p != langs.end(); p++ ) { Q_strcat( langList, sizeof( langList ), va( "\"%s\" ", p->get_name().c_str() ) ); Q_strcat( encList, sizeof( encList ), va( "\"%s%s%s\" ", p->get_language().c_str(), p->get_country().c_str()[0] ? "_" : "", p->get_country().c_str() ) ); } Cvar_Set( "trans_languages", langList ); Cvar_Set( "trans_encodings", encList ); Com_Printf(_( "Loaded %lu language(s)\n"), langs.size() ); Cmd_AddCommand( "updatelanguage", Trans_UpdateLanguage_f ); if( langs.size() ) { lang = Trans_ReturnLanguage( language->string ); trans_dict = trans_manager.get_dictionary( lang ); trans_dictgame = trans_managergame.get_dictionary( lang ); enabled = true; } } extern "C" const char* Trans_Gettext( const char *msgid ) { if( !enabled ) { return msgid; } Q_strncpyz( gettextbuffer, trans_dict.translate( msgid ).c_str(), sizeof( gettextbuffer ) ); return gettextbuffer; } extern "C" const char* Trans_Pgettext( const char *ctxt, const char *msgid ) { if ( !enabled ) { return msgid; } Q_strncpyz( gettextbuffer, trans_dict.translate_ctxt( ctxt, msgid ).c_str(), sizeof( gettextbuffer ) ); return gettextbuffer; } extern "C" const char* Trans_GettextGame( const char *msgid ) { if( !enabled ) { return msgid; } Q_strncpyz( gettextbuffer, trans_dictgame.translate( msgid ).c_str(), sizeof( gettextbuffer ) ); return gettextbuffer; } extern "C" const char* Trans_PgettextGame( const char *ctxt, const char *msgid ) { if( !enabled ) { return msgid; } return trans_dictgame.translate_ctxt( std::string( ctxt ), std::string( msgid ) ).c_str(); } extern "C" const char* Trans_GettextPlural( const char *msgid, const char *msgid_plural, int num ) { if( !enabled ) { return num == 1 ? msgid : msgid_plural; } Q_strncpyz( gettextbuffer, trans_dict.translate_plural( msgid, msgid_plural, num ).c_str(), sizeof( gettextbuffer ) ); return gettextbuffer; } extern "C" const char* Trans_GettextGamePlural( const char *msgid, const char *msgid_plural, int num ) { if( !enabled ) { return num == 1 ? msgid : msgid_plural; } Q_strncpyz( gettextbuffer, trans_dictgame.translate_plural( msgid, msgid_plural, num ).c_str(), sizeof( gettextbuffer ) ); return gettextbuffer; } <|endoftext|>
<commit_before>/*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #ifndef __MITK_NRRD_DIFFUSION_VOULMES_IO_FACTORY_CPP__ #define __MITK_NRRD_DIFFUSION_VOULMES_IO_FACTORY_CPP__ #include "mitkDiffusionImageSource.h" #include "mitkDiffusionImage.h" template<typename TPixelType> mitk::DiffusionImageSource<TPixelType>::DiffusionImageSource() { // Create the output. We use static_cast<> here because we know the default // output must be of type DiffusionImage typename mitk::DiffusionImage<TPixelType>::Pointer output = static_cast<typename mitk::DiffusionImage<TPixelType>*>(this->MakeOutput(0).GetPointer()); Superclass::SetNumberOfRequiredOutputs(1); Superclass::SetNthOutput(0, output.GetPointer()); } template<typename TPixelType> mitk::DiffusionImageSource<TPixelType>::~DiffusionImageSource() { } template<typename TPixelType> itk::DataObject::Pointer mitk::DiffusionImageSource<TPixelType>::MakeOutput ( DataObjectPointerArraySizeType /*idx*/ ) { return OutputType::New().GetPointer(); } template<typename TPixelType> itk::DataObject::Pointer mitk::DiffusionImageSource<TPixelType>::MakeOutput( const DataObjectIdentifierType & name ) { itkDebugMacro("MakeOutput(" << name << ")"); if( this->IsIndexedOutputName(name) ) { return this->MakeOutput( this->MakeIndexFromOutputName(name) ); } return static_cast<itk::DataObject *>(OutputType::New().GetPointer()); } template<typename TPixelType> typename mitk::DiffusionImageSource<TPixelType>::OutputType* mitk::DiffusionImageSource<TPixelType>::GetOutput(void) { return itkDynamicCastInDebugMode<OutputType*>( this->GetPrimaryOutput() ); } template<typename TPixelType> const typename mitk::DiffusionImageSource<TPixelType>::OutputType* mitk::DiffusionImageSource<TPixelType>::GetOutput(void) const { return itkDynamicCastInDebugMode<const OutputType*>( this->GetPrimaryOutput() ); } template<typename TPixelType> typename mitk::DiffusionImageSource<TPixelType>::OutputType* mitk::DiffusionImageSource<TPixelType>::GetOutput(DataObjectPointerArraySizeType idx) { OutputType* out = dynamic_cast<OutputType*>( this->ProcessObject::GetOutput(idx) ); if ( out == NULL && this->ProcessObject::GetOutput(idx) != NULL ) { itkWarningMacro (<< "Unable to convert output number " << idx << " to type " << typeid( OutputType ).name () ); } return out; } template<typename TPixelType> const typename mitk::DiffusionImageSource<TPixelType>::OutputType* mitk::DiffusionImageSource<TPixelType>::GetOutput(DataObjectPointerArraySizeType idx) const { const OutputType* out = dynamic_cast<const OutputType*>( this->ProcessObject::GetOutput(idx) ); if ( out == NULL && this->ProcessObject::GetOutput(idx) != NULL ) { itkWarningMacro (<< "Unable to convert output number " << idx << " to type " << typeid( OutputType ).name () ); } return out; } #endif //__MITK_NRRD_DIFFUSION_VOULMES_IO_FACTORY_CPP__ <commit_msg>Fixed pre-processor macro name<commit_after>/*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #ifndef __MITK_DIFFUSIONIMAGE_SOURCE_CPP__ #define __MITK_DIFFUSIONIMAGE_SOURCE_CPP__ #include "mitkDiffusionImageSource.h" #include "mitkDiffusionImage.h" template<typename TPixelType> mitk::DiffusionImageSource<TPixelType>::DiffusionImageSource() { // Create the output. We use static_cast<> here because we know the default // output must be of type DiffusionImage typename mitk::DiffusionImage<TPixelType>::Pointer output = static_cast<typename mitk::DiffusionImage<TPixelType>*>(this->MakeOutput(0).GetPointer()); Superclass::SetNumberOfRequiredOutputs(1); Superclass::SetNthOutput(0, output.GetPointer()); } template<typename TPixelType> mitk::DiffusionImageSource<TPixelType>::~DiffusionImageSource() { } template<typename TPixelType> itk::DataObject::Pointer mitk::DiffusionImageSource<TPixelType>::MakeOutput ( DataObjectPointerArraySizeType /*idx*/ ) { return OutputType::New().GetPointer(); } template<typename TPixelType> itk::DataObject::Pointer mitk::DiffusionImageSource<TPixelType>::MakeOutput( const DataObjectIdentifierType & name ) { itkDebugMacro("MakeOutput(" << name << ")"); if( this->IsIndexedOutputName(name) ) { return this->MakeOutput( this->MakeIndexFromOutputName(name) ); } return static_cast<itk::DataObject *>(OutputType::New().GetPointer()); } template<typename TPixelType> typename mitk::DiffusionImageSource<TPixelType>::OutputType* mitk::DiffusionImageSource<TPixelType>::GetOutput(void) { return itkDynamicCastInDebugMode<OutputType*>( this->GetPrimaryOutput() ); } template<typename TPixelType> const typename mitk::DiffusionImageSource<TPixelType>::OutputType* mitk::DiffusionImageSource<TPixelType>::GetOutput(void) const { return itkDynamicCastInDebugMode<const OutputType*>( this->GetPrimaryOutput() ); } template<typename TPixelType> typename mitk::DiffusionImageSource<TPixelType>::OutputType* mitk::DiffusionImageSource<TPixelType>::GetOutput(DataObjectPointerArraySizeType idx) { OutputType* out = dynamic_cast<OutputType*>( this->ProcessObject::GetOutput(idx) ); if ( out == NULL && this->ProcessObject::GetOutput(idx) != NULL ) { itkWarningMacro (<< "Unable to convert output number " << idx << " to type " << typeid( OutputType ).name () ); } return out; } template<typename TPixelType> const typename mitk::DiffusionImageSource<TPixelType>::OutputType* mitk::DiffusionImageSource<TPixelType>::GetOutput(DataObjectPointerArraySizeType idx) const { const OutputType* out = dynamic_cast<const OutputType*>( this->ProcessObject::GetOutput(idx) ); if ( out == NULL && this->ProcessObject::GetOutput(idx) != NULL ) { itkWarningMacro (<< "Unable to convert output number " << idx << " to type " << typeid( OutputType ).name () ); } return out; } #endif //__MITK_DIFFUSIONIMAGE_SOURCE_CPP__ <|endoftext|>
<commit_before>/* This file is part of Magnum. Copyright © 2010, 2011, 2012, 2013, 2014, 2015 Vladimír Vondruš <mosra@centrum.cz> Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #include "Magnum/Context.h" #include "Magnum/Extensions.h" #include "Magnum/Test/AbstractOpenGLTester.h" namespace Magnum { namespace Test { struct ContextGLTest: AbstractOpenGLTester { explicit ContextGLTest(); void constructCopyMove(); void isVersionSupported(); void supportedVersion(); void isExtensionSupported(); void isExtensionDisabled(); }; ContextGLTest::ContextGLTest() { addTests({&ContextGLTest::constructCopyMove, &ContextGLTest::isVersionSupported, &ContextGLTest::supportedVersion, &ContextGLTest::isExtensionSupported, &ContextGLTest::isExtensionDisabled}); } void ContextGLTest::constructCopyMove() { /* Only move-construction allowed */ CORRADE_VERIFY(!(std::is_constructible<Context, const Context&>{})); CORRADE_VERIFY((std::is_constructible<Context, Context&&>{})); CORRADE_VERIFY(!(std::is_assignable<Context, const Context&>{})); CORRADE_VERIFY(!(std::is_assignable<Context, Context&&>{})); } void ContextGLTest::isVersionSupported() { const Version v = Context::current()->version(); CORRADE_VERIFY(Context::current()->isVersionSupported(v)); CORRADE_VERIFY(Context::current()->isVersionSupported(Version(Int(v)-1))); CORRADE_VERIFY(!Context::current()->isVersionSupported(Version(Int(v)+1))); /* No assertions should be fired */ MAGNUM_ASSERT_VERSION_SUPPORTED(v); MAGNUM_ASSERT_VERSION_SUPPORTED(Version(Int(v)-1)); } void ContextGLTest::supportedVersion() { const Version v = Context::current()->version(); /* Selects first supported version (thus not necessarily the highest) */ CORRADE_VERIFY(Context::current()->supportedVersion({Version(Int(v)+1), v, Version(Int(v)-1)}) == v); CORRADE_VERIFY(Context::current()->supportedVersion({Version(Int(v)+1), Version(Int(v)-1), v}) == Version(Int(v)-1)); } void ContextGLTest::isExtensionSupported() { #ifndef MAGNUM_TARGET_GLES if(Context::current()->isExtensionSupported<Extensions::GL::GREMEDY::string_marker>()) CORRADE_SKIP(Extensions::GL::GREMEDY::string_marker::string() + std::string(" extension should not be supported, can't test")); if(!Context::current()->isExtensionSupported<Extensions::GL::EXT::texture_filter_anisotropic>()) CORRADE_SKIP(Extensions::GL::EXT::texture_filter_anisotropic::string() + std::string(" extension should be supported, can't test")); if(!Context::current()->isExtensionSupported<Extensions::GL::ARB::explicit_attrib_location>()) CORRADE_SKIP(Extensions::GL::ARB::explicit_attrib_location::string() + std::string(" extension should be supported, can't test")); /* Test that we have proper extension list parser */ std::string extensions(reinterpret_cast<const char*>(glGetString(GL_EXTENSIONS))); CORRADE_VERIFY(extensions.find(Extensions::GL::EXT::texture_filter_anisotropic::string()) != std::string::npos); CORRADE_VERIFY(extensions.find(Extensions::GL::GREMEDY::string_marker::string()) == std::string::npos); /* This is disabled in GL < 3.2 to work around GLSL compiler bugs */ CORRADE_VERIFY(!Context::current()->isExtensionSupported<Extensions::GL::ARB::explicit_attrib_location>(Version::GL310)); CORRADE_VERIFY(Context::current()->isExtensionSupported<Extensions::GL::ARB::explicit_attrib_location>(Version::GL320)); #else CORRADE_SKIP("No useful extensions to test on OpenGL ES"); #endif } void ContextGLTest::isExtensionDisabled() { #ifndef MAGNUM_TARGET_GLES if(!Context::current()->isExtensionSupported<Extensions::GL::ARB::vertex_array_object>()) CORRADE_SKIP(Extensions::GL::ARB::vertex_array_object::string() + std::string(" extension should be supported, can't test")); if(!Context::current()->isExtensionSupported<Extensions::GL::ARB::explicit_attrib_location>()) CORRADE_SKIP(Extensions::GL::ARB::explicit_attrib_location::string() + std::string(" extension should be supported, can't test")); /* This is not disabled anywhere */ CORRADE_VERIFY(!Context::current()->isExtensionDisabled<Extensions::GL::ARB::vertex_array_object>()); /* This is disabled in GL < 3.2 to work around GLSL compiler bugs */ CORRADE_VERIFY(Context::current()->isExtensionDisabled<Extensions::GL::ARB::explicit_attrib_location>(Version::GL310)); CORRADE_VERIFY(!Context::current()->isExtensionDisabled<Extensions::GL::ARB::explicit_attrib_location>(Version::GL320)); #else CORRADE_SKIP("No useful extensions to test on OpenGL ES"); #endif } }} MAGNUM_GL_TEST_MAIN(Magnum::Test::ContextGLTest) <commit_msg>Don't use raw GL calls (that are even deprecated) in tests.<commit_after>/* This file is part of Magnum. Copyright © 2010, 2011, 2012, 2013, 2014, 2015 Vladimír Vondruš <mosra@centrum.cz> Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #include <algorithm> #include "Magnum/Context.h" #include "Magnum/Extensions.h" #include "Magnum/Test/AbstractOpenGLTester.h" namespace Magnum { namespace Test { struct ContextGLTest: AbstractOpenGLTester { explicit ContextGLTest(); void constructCopyMove(); void isVersionSupported(); void supportedVersion(); void isExtensionSupported(); void isExtensionDisabled(); }; ContextGLTest::ContextGLTest() { addTests({&ContextGLTest::constructCopyMove, &ContextGLTest::isVersionSupported, &ContextGLTest::supportedVersion, &ContextGLTest::isExtensionSupported, &ContextGLTest::isExtensionDisabled}); } void ContextGLTest::constructCopyMove() { /* Only move-construction allowed */ CORRADE_VERIFY(!(std::is_constructible<Context, const Context&>{})); CORRADE_VERIFY((std::is_constructible<Context, Context&&>{})); CORRADE_VERIFY(!(std::is_assignable<Context, const Context&>{})); CORRADE_VERIFY(!(std::is_assignable<Context, Context&&>{})); } void ContextGLTest::isVersionSupported() { const Version v = Context::current()->version(); CORRADE_VERIFY(Context::current()->isVersionSupported(v)); CORRADE_VERIFY(Context::current()->isVersionSupported(Version(Int(v)-1))); CORRADE_VERIFY(!Context::current()->isVersionSupported(Version(Int(v)+1))); /* No assertions should be fired */ MAGNUM_ASSERT_VERSION_SUPPORTED(v); MAGNUM_ASSERT_VERSION_SUPPORTED(Version(Int(v)-1)); } void ContextGLTest::supportedVersion() { const Version v = Context::current()->version(); /* Selects first supported version (thus not necessarily the highest) */ CORRADE_VERIFY(Context::current()->supportedVersion({Version(Int(v)+1), v, Version(Int(v)-1)}) == v); CORRADE_VERIFY(Context::current()->supportedVersion({Version(Int(v)+1), Version(Int(v)-1), v}) == Version(Int(v)-1)); } void ContextGLTest::isExtensionSupported() { #ifndef MAGNUM_TARGET_GLES if(Context::current()->isExtensionSupported<Extensions::GL::GREMEDY::string_marker>()) CORRADE_SKIP(Extensions::GL::GREMEDY::string_marker::string() + std::string(" extension should not be supported, can't test")); if(!Context::current()->isExtensionSupported<Extensions::GL::EXT::texture_filter_anisotropic>()) CORRADE_SKIP(Extensions::GL::EXT::texture_filter_anisotropic::string() + std::string(" extension should be supported, can't test")); if(!Context::current()->isExtensionSupported<Extensions::GL::ARB::explicit_attrib_location>()) CORRADE_SKIP(Extensions::GL::ARB::explicit_attrib_location::string() + std::string(" extension should be supported, can't test")); /* Test that we have proper extension list parser */ std::vector<std::string> extensions = Context::current()->extensionStrings(); CORRADE_VERIFY(std::find(extensions.begin(), extensions.end(), Extensions::GL::EXT::texture_filter_anisotropic::string()) != extensions.end()); CORRADE_VERIFY(std::find(extensions.begin(), extensions.end(), Extensions::GL::GREMEDY::string_marker::string()) == extensions.end()); /* This is disabled in GL < 3.2 to work around GLSL compiler bugs */ CORRADE_VERIFY(!Context::current()->isExtensionSupported<Extensions::GL::ARB::explicit_attrib_location>(Version::GL310)); CORRADE_VERIFY(Context::current()->isExtensionSupported<Extensions::GL::ARB::explicit_attrib_location>(Version::GL320)); #else CORRADE_SKIP("No useful extensions to test on OpenGL ES"); #endif } void ContextGLTest::isExtensionDisabled() { #ifndef MAGNUM_TARGET_GLES if(!Context::current()->isExtensionSupported<Extensions::GL::ARB::vertex_array_object>()) CORRADE_SKIP(Extensions::GL::ARB::vertex_array_object::string() + std::string(" extension should be supported, can't test")); if(!Context::current()->isExtensionSupported<Extensions::GL::ARB::explicit_attrib_location>()) CORRADE_SKIP(Extensions::GL::ARB::explicit_attrib_location::string() + std::string(" extension should be supported, can't test")); /* This is not disabled anywhere */ CORRADE_VERIFY(!Context::current()->isExtensionDisabled<Extensions::GL::ARB::vertex_array_object>()); /* This is disabled in GL < 3.2 to work around GLSL compiler bugs */ CORRADE_VERIFY(Context::current()->isExtensionDisabled<Extensions::GL::ARB::explicit_attrib_location>(Version::GL310)); CORRADE_VERIFY(!Context::current()->isExtensionDisabled<Extensions::GL::ARB::explicit_attrib_location>(Version::GL320)); #else CORRADE_SKIP("No useful extensions to test on OpenGL ES"); #endif } }} MAGNUM_GL_TEST_MAIN(Magnum::Test::ContextGLTest) <|endoftext|>
<commit_before><commit_msg>Planning: some minor bug fixes.<commit_after><|endoftext|>
<commit_before>/* * Copyright 2015 - 2018 gtalent2@gmail.com * * 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/. */ #pragma once #include <ox/std/std.hpp> namespace ox::ptrarith { template<typename T, typename size_t, size_t minOffset = 1> class Ptr { private: uint8_t *m_dataStart = nullptr; size_t m_itemOffset = 0; size_t m_itemSize = 0; // this should be removed later on, but the excessive validation is // desirable during during heavy development mutable uint8_t m_validated = false; public: inline Ptr() = default; inline Ptr(std::nullptr_t); inline Ptr(void *dataStart, size_t dataSize, size_t itemStart, size_t itemSize = sizeof(T)); inline bool valid() const; inline size_t size() const; inline size_t offset() const; inline size_t end(); inline const T *get() const; inline T *get(); inline const T *operator->() const; inline T *operator->(); inline operator const T*() const; inline operator T*(); inline const T &operator*() const; inline T &operator*(); inline operator size_t() const; inline bool operator==(const Ptr<T, size_t, minOffset> &other) const; inline bool operator!=(const Ptr<T, size_t, minOffset> &other) const; template<typename SubT> inline const Ptr<SubT, size_t, sizeof(T)> subPtr(size_t offset, size_t size) const; template<typename SubT> inline const Ptr<SubT, size_t, sizeof(T)> subPtr(size_t offset) const; template<typename SubT> inline Ptr<SubT, size_t, sizeof(T)> subPtr(size_t offset, size_t size); template<typename SubT> inline Ptr<SubT, size_t, sizeof(T)> subPtr(size_t offset); }; template<typename T, typename size_t, size_t minOffset> inline Ptr<T, size_t, minOffset>::Ptr(std::nullptr_t) { } template<typename T, typename size_t, size_t minOffset> inline Ptr<T, size_t, minOffset>::Ptr(void *dataStart, size_t dataSize, size_t itemStart, size_t itemSize) { // do some sanity checks before assuming this is valid if (itemSize >= sizeof(T) and dataStart and itemStart >= minOffset and itemStart + itemSize <= dataSize) { m_dataStart = reinterpret_cast<uint8_t*>(dataStart); m_itemOffset = itemStart; m_itemSize = itemSize; } } template<typename T, typename size_t, size_t minOffset> inline bool Ptr<T, size_t, minOffset>::valid() const { m_validated = m_dataStart != nullptr; return m_validated; } template<typename T, typename size_t, size_t minOffset> inline size_t Ptr<T, size_t, minOffset>::size() const { return m_itemSize; } template<typename T, typename size_t, size_t minOffset> inline size_t Ptr<T, size_t, minOffset>::offset() const { return m_itemOffset; } template<typename T, typename size_t, size_t minOffset> inline size_t Ptr<T, size_t, minOffset>::end() { return m_itemOffset + m_itemSize; } template<typename T, typename size_t, size_t minOffset> inline const T *Ptr<T, size_t, minOffset>::get() const { oxAssert(m_validated, "Unvalidated pointer access. (ox::fs::Ptr::get())"); oxAssert(valid(), "Invalid pointer access. (ox::fs::Ptr::get())"); return reinterpret_cast<T*>(m_dataStart + m_itemOffset); } template<typename T, typename size_t, size_t minOffset> inline T *Ptr<T, size_t, minOffset>::get() { oxAssert(m_validated, "Unvalidated pointer access. (ox::fs::Ptr::get())"); oxAssert(valid(), "Invalid pointer access. (ox::fs::Ptr::get())"); return reinterpret_cast<T*>(m_dataStart + m_itemOffset); } template<typename T, typename size_t, size_t minOffset> inline const T *Ptr<T, size_t, minOffset>::operator->() const { oxAssert(m_validated, "Unvalidated pointer access. (ox::fs::Ptr::operator->())"); oxAssert(valid(), "Invalid pointer access. (ox::fs::Ptr::operator->())"); return reinterpret_cast<T*>(m_dataStart + m_itemOffset); } template<typename T, typename size_t, size_t minOffset> inline T *Ptr<T, size_t, minOffset>::operator->() { oxAssert(m_validated, "Unvalidated pointer access. (ox::fs::Ptr::operator->())"); oxAssert(valid(), "Invalid pointer access. (ox::fs::Ptr::operator->())"); return reinterpret_cast<T*>(m_dataStart + m_itemOffset); } template<typename T, typename size_t, size_t minOffset> inline Ptr<T, size_t, minOffset>::operator const T*() const { return reinterpret_cast<T*>(m_dataStart + m_itemOffset); } template<typename T, typename size_t, size_t minOffset> inline Ptr<T, size_t, minOffset>::operator T*() { return reinterpret_cast<T*>(m_dataStart + m_itemOffset); } template<typename T, typename size_t, size_t minOffset> inline const T &Ptr<T, size_t, minOffset>::operator*() const { oxAssert(m_validated, "Unvalidated pointer dereference. (ox::fs::Ptr::operator*())"); oxAssert(valid(), "Invalid pointer dereference. (ox::fs::Ptr::operator*())"); return *reinterpret_cast<T*>(this); } template<typename T, typename size_t, size_t minOffset> inline T &Ptr<T, size_t, minOffset>::operator*() { oxAssert(m_validated, "Unvalidated pointer dereference. (ox::fs::Ptr::operator*())"); oxAssert(valid(), "Invalid pointer dereference. (ox::fs::Ptr::operator*())"); return *reinterpret_cast<T*>(this); } template<typename T, typename size_t, size_t minOffset> inline Ptr<T, size_t, minOffset>::operator size_t() const { if (m_dataStart and m_itemOffset) { return m_itemOffset; } return 0; } template<typename T, typename size_t, size_t minOffset> inline bool Ptr<T, size_t, minOffset>::operator==(const Ptr<T, size_t, minOffset> &other) const { return m_dataStart == other.m_dataStart && m_itemOffset == other.m_itemOffset && m_itemSize == other.m_itemSize; } template<typename T, typename size_t, size_t minOffset> inline bool Ptr<T, size_t, minOffset>::operator!=(const Ptr<T, size_t, minOffset> &other) const { return m_dataStart != other.m_dataStart || m_itemOffset != other.m_itemOffset || m_itemSize != other.m_itemSize; } template<typename T, typename size_t, size_t minOffset> template<typename SubT> inline const Ptr<SubT, size_t, sizeof(T)> Ptr<T, size_t, minOffset>::subPtr(size_t offset, size_t size) const { auto out = Ptr<SubT, size_t, sizeof(T)>(get(), this->size(), offset, size); return out; } template<typename T, typename size_t, size_t minOffset> template<typename SubT> inline const Ptr<SubT, size_t, sizeof(T)> Ptr<T, size_t, minOffset>::subPtr(size_t offset) const { oxTrace("ox::fs::Ptr::subPtr") << m_itemOffset << this->size() << offset << m_itemSize << (m_itemSize - offset); return subPtr<SubT>(offset, m_itemSize - offset); } template<typename T, typename size_t, size_t minOffset> template<typename SubT> inline Ptr<SubT, size_t, sizeof(T)> Ptr<T, size_t, minOffset>::subPtr(size_t offset, size_t size) { auto out = Ptr<SubT, size_t, sizeof(T)>(get(), this->size(), offset, size); return out; } template<typename T, typename size_t, size_t minOffset> template<typename SubT> inline Ptr<SubT, size_t, sizeof(T)> Ptr<T, size_t, minOffset>::subPtr(size_t offset) { oxTrace("ox::fs::Ptr::subPtr") << m_itemOffset << this->size() << offset << m_itemSize << (m_itemSize - offset); return subPtr<SubT>(offset, m_itemSize - offset); } } <commit_msg>[ox/buffer] Add to to Ptr<commit_after>/* * Copyright 2015 - 2018 gtalent2@gmail.com * * 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/. */ #pragma once #include <ox/std/std.hpp> namespace ox::ptrarith { template<typename T, typename size_t, size_t minOffset = 1> class Ptr { private: uint8_t *m_dataStart = nullptr; size_t m_dataSize = 0; size_t m_itemOffset = 0; size_t m_itemSize = 0; // this should be removed later on, but the excessive validation is // desirable during during heavy development mutable uint8_t m_validated = false; public: inline Ptr() = default; inline Ptr(std::nullptr_t); inline Ptr(void *dataStart, size_t dataSize, size_t itemStart, size_t itemSize = sizeof(T)); inline bool valid() const; inline size_t size() const; inline size_t offset() const; inline size_t end(); inline const T *get() const; inline T *get(); inline const T *operator->() const; inline T *operator->(); inline operator const T*() const; inline operator T*(); inline const T &operator*() const; inline T &operator*(); inline operator size_t() const; inline bool operator==(const Ptr<T, size_t, minOffset> &other) const; inline bool operator!=(const Ptr<T, size_t, minOffset> &other) const; template<typename SubT> inline const Ptr<SubT, size_t, sizeof(T)> subPtr(size_t offset, size_t size) const; template<typename SubT> inline const Ptr<SubT, size_t, sizeof(T)> subPtr(size_t offset) const; template<typename SubT> inline Ptr<SubT, size_t, sizeof(T)> subPtr(size_t offset, size_t size); template<typename SubT> inline Ptr<SubT, size_t, sizeof(T)> subPtr(size_t offset); template<typename SubT> inline const Ptr<SubT, size_t, minOffset> to() const; }; template<typename T, typename size_t, size_t minOffset> inline Ptr<T, size_t, minOffset>::Ptr(std::nullptr_t) { } template<typename T, typename size_t, size_t minOffset> inline Ptr<T, size_t, minOffset>::Ptr(void *dataStart, size_t dataSize, size_t itemStart, size_t itemSize) { // do some sanity checks before assuming this is valid if (itemSize >= sizeof(T) and dataStart and itemStart >= minOffset and itemStart + itemSize <= dataSize) { m_dataStart = reinterpret_cast<uint8_t*>(dataStart); m_dataSize = dataSize; m_itemOffset = itemStart; m_itemSize = itemSize; } } template<typename T, typename size_t, size_t minOffset> inline bool Ptr<T, size_t, minOffset>::valid() const { m_validated = m_dataStart != nullptr; return m_validated; } template<typename T, typename size_t, size_t minOffset> inline size_t Ptr<T, size_t, minOffset>::size() const { return m_itemSize; } template<typename T, typename size_t, size_t minOffset> inline size_t Ptr<T, size_t, minOffset>::offset() const { return m_itemOffset; } template<typename T, typename size_t, size_t minOffset> inline size_t Ptr<T, size_t, minOffset>::end() { return m_itemOffset + m_itemSize; } template<typename T, typename size_t, size_t minOffset> inline const T *Ptr<T, size_t, minOffset>::get() const { oxAssert(m_validated, "Unvalidated pointer access. (ox::fs::Ptr::get())"); oxAssert(valid(), "Invalid pointer access. (ox::fs::Ptr::get())"); return reinterpret_cast<T*>(m_dataStart + m_itemOffset); } template<typename T, typename size_t, size_t minOffset> inline T *Ptr<T, size_t, minOffset>::get() { oxAssert(m_validated, "Unvalidated pointer access. (ox::fs::Ptr::get())"); oxAssert(valid(), "Invalid pointer access. (ox::fs::Ptr::get())"); return reinterpret_cast<T*>(m_dataStart + m_itemOffset); } template<typename T, typename size_t, size_t minOffset> inline const T *Ptr<T, size_t, minOffset>::operator->() const { oxAssert(m_validated, "Unvalidated pointer access. (ox::fs::Ptr::operator->())"); oxAssert(valid(), "Invalid pointer access. (ox::fs::Ptr::operator->())"); return reinterpret_cast<T*>(m_dataStart + m_itemOffset); } template<typename T, typename size_t, size_t minOffset> inline T *Ptr<T, size_t, minOffset>::operator->() { oxAssert(m_validated, "Unvalidated pointer access. (ox::fs::Ptr::operator->())"); oxAssert(valid(), "Invalid pointer access. (ox::fs::Ptr::operator->())"); return reinterpret_cast<T*>(m_dataStart + m_itemOffset); } template<typename T, typename size_t, size_t minOffset> inline Ptr<T, size_t, minOffset>::operator const T*() const { return reinterpret_cast<T*>(m_dataStart + m_itemOffset); } template<typename T, typename size_t, size_t minOffset> inline Ptr<T, size_t, minOffset>::operator T*() { return reinterpret_cast<T*>(m_dataStart + m_itemOffset); } template<typename T, typename size_t, size_t minOffset> inline const T &Ptr<T, size_t, minOffset>::operator*() const { oxAssert(m_validated, "Unvalidated pointer dereference. (ox::fs::Ptr::operator*())"); oxAssert(valid(), "Invalid pointer dereference. (ox::fs::Ptr::operator*())"); return *reinterpret_cast<T*>(this); } template<typename T, typename size_t, size_t minOffset> inline T &Ptr<T, size_t, minOffset>::operator*() { oxAssert(m_validated, "Unvalidated pointer dereference. (ox::fs::Ptr::operator*())"); oxAssert(valid(), "Invalid pointer dereference. (ox::fs::Ptr::operator*())"); return *reinterpret_cast<T*>(this); } template<typename T, typename size_t, size_t minOffset> inline Ptr<T, size_t, minOffset>::operator size_t() const { if (m_dataStart and m_itemOffset) { return m_itemOffset; } return 0; } template<typename T, typename size_t, size_t minOffset> inline bool Ptr<T, size_t, minOffset>::operator==(const Ptr<T, size_t, minOffset> &other) const { return m_dataStart == other.m_dataStart && m_itemOffset == other.m_itemOffset && m_itemSize == other.m_itemSize; } template<typename T, typename size_t, size_t minOffset> inline bool Ptr<T, size_t, minOffset>::operator!=(const Ptr<T, size_t, minOffset> &other) const { return m_dataStart != other.m_dataStart || m_itemOffset != other.m_itemOffset || m_itemSize != other.m_itemSize; } template<typename T, typename size_t, size_t minOffset> template<typename SubT> inline const Ptr<SubT, size_t, sizeof(T)> Ptr<T, size_t, minOffset>::subPtr(size_t offset, size_t size) const { return Ptr<SubT, size_t, sizeof(T)>(get(), this->size(), offset, size); } template<typename T, typename size_t, size_t minOffset> template<typename SubT> inline const Ptr<SubT, size_t, sizeof(T)> Ptr<T, size_t, minOffset>::subPtr(size_t offset) const { oxTrace("ox::fs::Ptr::subPtr") << m_itemOffset << this->size() << offset << m_itemSize << (m_itemSize - offset); return subPtr<SubT>(offset, m_itemSize - offset); } template<typename T, typename size_t, size_t minOffset> template<typename SubT> inline Ptr<SubT, size_t, sizeof(T)> Ptr<T, size_t, minOffset>::subPtr(size_t offset, size_t size) { return Ptr<SubT, size_t, sizeof(T)>(get(), this->size(), offset, size); } template<typename T, typename size_t, size_t minOffset> template<typename SubT> inline Ptr<SubT, size_t, sizeof(T)> Ptr<T, size_t, minOffset>::subPtr(size_t offset) { oxTrace("ox::fs::Ptr::subPtr") << m_itemOffset << this->size() << offset << m_itemSize << (m_itemSize - offset); return subPtr<SubT>(offset, m_itemSize - offset); } template<typename T, typename size_t, size_t minOffset> template<typename SubT> inline const Ptr<SubT, size_t, minOffset> Ptr<T, size_t, minOffset>::to() const { return Ptr<SubT, size_t, minOffset>(m_dataStart, m_dataSize, m_itemOffset, m_itemSize); } } <|endoftext|>
<commit_before>// Copyright 2018 The Flutter 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 "flutter/fml/file.h" #include <Shlwapi.h> #include <sstream> #include "flutter/fml/platform/win/wstring_conversion.h" namespace fml { fml::UniqueFD OpenFile(const std::wstring& path, OpenPermission permission, bool is_directory) { if (path.size() == 0) { return fml::UniqueFD{}; } DWORD desired_access = 0; switch (permission) { case OpenPermission::kRead: desired_access = GENERIC_READ; break; case OpenPermission::kWrite: desired_access = GENERIC_WRITE; break; case OpenPermission::kReadWrite: desired_access = GENERIC_WRITE | GENERIC_READ; break; case OpenPermission::kExecute: desired_access = GENERIC_READ | GENERIC_EXECUTE; break; } return fml::UniqueFD{::CreateFile( path.c_str(), // lpFileName desired_access, // dwDesiredAccess FILE_SHARE_READ, // dwShareMode 0, // lpSecurityAttributes OPEN_EXISTING, // dwCreationDisposition FILE_ATTRIBUTE_NORMAL, // dwFlagsAndAttributes 0 // hTemplateFile )}; } fml::UniqueFD OpenFile(const char* path, OpenPermission permission, bool is_directory) { return OpenFile(ConvertToWString(path), permission, is_directory); } static std::wstring GetFullHandlePath(const fml::UniqueFD& handle) { wchar_t buffer[MAX_PATH]; DWORD returned = ::GetFinalPathNameByHandle(handle.get(), buffer, MAX_PATH, FILE_NAME_NORMALIZED); if (returned == 0 || returned > MAX_PATH) { return {}; } return {buffer}; } fml::UniqueFD OpenFile(const fml::UniqueFD& base_directory, const char* path, OpenPermission permission, bool is_directory) { // If the base directory is invalid or the path is absolute, use the generic // open file variant. if (!base_directory.is_valid()) { return OpenFile(path, permission, is_directory); } const auto wpath = ConvertToWString(path); if (!::PathIsRelative(wpath.c_str())) { return OpenFile(path, permission, is_directory); } std::wstringstream stream; stream << GetFullHandlePath(base_directory) << "\\" << path; return OpenFile(stream.str(), permission, is_directory); } fml::UniqueFD Duplicate(fml::UniqueFD::element_type descriptor) { if (descriptor == INVALID_HANDLE_VALUE) { return fml::UniqueFD{}; } HANDLE duplicated = INVALID_HANDLE_VALUE; if (!::DuplicateHandle( GetCurrentProcess(), // source process descriptor, // source handle GetCurrentProcess(), // target process &duplicated, // target handle 0, // desired access (ignored because DUPLICATE_SAME_ACCESS) FALSE, // inheritable DUPLICATE_SAME_ACCESS) // options ) { return fml::UniqueFD{}; } return fml::UniqueFD{duplicated}; } bool IsDirectory(const fml::UniqueFD& directory) { BY_HANDLE_FILE_INFORMATION info; if (!::GetFileInformationByHandle(directory.get(), &info)) { return false; } return info.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY; } } // namespace fml <commit_msg>Fix file flags for directories and backslashes on Windows. (#5387)<commit_after>// Copyright 2018 The Flutter 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 "flutter/fml/file.h" #include <Shlwapi.h> #include <algorithm> #include <sstream> #include "flutter/fml/platform/win/wstring_conversion.h" namespace fml { static fml::UniqueFD OpenFile(std::wstring path, OpenPermission permission, bool is_directory) { if (path.size() == 0) { return fml::UniqueFD{}; } DWORD desired_access = 0; switch (permission) { case OpenPermission::kRead: desired_access = GENERIC_READ; break; case OpenPermission::kWrite: desired_access = GENERIC_WRITE; break; case OpenPermission::kReadWrite: desired_access = GENERIC_WRITE | GENERIC_READ; break; case OpenPermission::kExecute: desired_access = GENERIC_READ | GENERIC_EXECUTE; break; } DWORD flags = FILE_ATTRIBUTE_NORMAL; if (is_directory) { flags |= FILE_FLAG_BACKUP_SEMANTICS; } std::replace(path.begin(), path.end(), '/', '\\'); return fml::UniqueFD{::CreateFile(path.c_str(), // lpFileName desired_access, // dwDesiredAccess FILE_SHARE_READ, // dwShareMode 0, // lpSecurityAttributes OPEN_EXISTING, // dwCreationDisposition flags, // dwFlagsAndAttributes 0 // hTemplateFile )}; } fml::UniqueFD OpenFile(const char* path, OpenPermission permission, bool is_directory) { return OpenFile(ConvertToWString(path), permission, is_directory); } static std::wstring GetFullHandlePath(const fml::UniqueFD& handle) { wchar_t buffer[MAX_PATH]; DWORD returned = ::GetFinalPathNameByHandle(handle.get(), buffer, MAX_PATH, FILE_NAME_NORMALIZED); if (returned == 0 || returned > MAX_PATH) { return {}; } return {buffer}; } fml::UniqueFD OpenFile(const fml::UniqueFD& base_directory, const char* path, OpenPermission permission, bool is_directory) { // If the base directory is invalid or the path is absolute, use the generic // open file variant. if (!base_directory.is_valid()) { return OpenFile(path, permission, is_directory); } const auto wpath = ConvertToWString(path); if (!::PathIsRelative(wpath.c_str())) { return OpenFile(path, permission, is_directory); } std::wstringstream stream; stream << GetFullHandlePath(base_directory) << "\\" << path; return OpenFile(stream.str(), permission, is_directory); } fml::UniqueFD Duplicate(fml::UniqueFD::element_type descriptor) { if (descriptor == INVALID_HANDLE_VALUE) { return fml::UniqueFD{}; } HANDLE duplicated = INVALID_HANDLE_VALUE; if (!::DuplicateHandle( GetCurrentProcess(), // source process descriptor, // source handle GetCurrentProcess(), // target process &duplicated, // target handle 0, // desired access (ignored because DUPLICATE_SAME_ACCESS) FALSE, // inheritable DUPLICATE_SAME_ACCESS) // options ) { return fml::UniqueFD{}; } return fml::UniqueFD{duplicated}; } bool IsDirectory(const fml::UniqueFD& directory) { BY_HANDLE_FILE_INFORMATION info; if (!::GetFileInformationByHandle(directory.get(), &info)) { return false; } return info.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY; } } // namespace fml <|endoftext|>
<commit_before>// // // Description: This file is part of FET // // // Author: Lalescu Liviu <Please see http://lalescu.ro/liviu/ for details about contacting Liviu Lalescu (in particular, you can find here the e-mail address)> // Copyright (C) 2005 Liviu Lalescu <http://lalescu.ro/liviu/> // /*************************************************************************** * * * This program is free software: you can redistribute it and/or modify * * it under the terms of the GNU Affero General Public License as * * published by the Free Software Foundation, either version 3 of the * * License, or (at your option) any later version. * * * ***************************************************************************/ #include "timetable_defs.h" #include "timetable.h" #include "fet.h" #include "activitytagsform.h" #include "studentsset.h" #include "teacher.h" #include "subject.h" #include "activitytag.h" #include <QInputDialog> #include <QMessageBox> #include <QListWidget> #include <QAbstractItemView> #include <QSplitter> #include <QSettings> #include <QObject> #include <QMetaObject> extern const QString COMPANY; extern const QString PROGRAM; ActivityTagsForm::ActivityTagsForm(QWidget* parent): QDialog(parent) { setupUi(this); currentActivityTagTextEdit->setReadOnly(true); renameActivityTagPushButton->setDefault(true); activityTagsListWidget->setSelectionMode(QAbstractItemView::SingleSelection); connect(closePushButton, SIGNAL(clicked()), this, SLOT(close())); connect(addActivityTagPushButton, SIGNAL(clicked()), this, SLOT(addActivityTag())); connect(removeActivityTagPushButton, SIGNAL(clicked()), this, SLOT(removeActivityTag())); connect(renameActivityTagPushButton, SIGNAL(clicked()), this, SLOT(renameActivityTag())); connect(moveActivityTagUpPushButton, SIGNAL(clicked()), this, SLOT(moveActivityTagUp())); connect(moveActivityTagDownPushButton, SIGNAL(clicked()), this, SLOT(moveActivityTagDown())); connect(sortActivityTagsPushButton, SIGNAL(clicked()), this, SLOT(sortActivityTags())); connect(activityTagsListWidget, SIGNAL(currentRowChanged(int)), this, SLOT(activityTagChanged(int))); connect(activateActivityTagPushButton, SIGNAL(clicked()), this, SLOT(activateActivityTag())); connect(deactivateActivityTagPushButton, SIGNAL(clicked()), this, SLOT(deactivateActivityTag())); connect(activityTagsListWidget, SIGNAL(itemDoubleClicked(QListWidgetItem*)), this, SLOT(renameActivityTag())); connect(helpPushButton, SIGNAL(clicked()), this, SLOT(help())); connect(printablePushButton, SIGNAL(clicked()), this, SLOT(printableActivityTag())); connect(notPrintablePushButton, SIGNAL(clicked()), this, SLOT(notPrintableActivityTag())); connect(commentsPushButton, SIGNAL(clicked()), this, SLOT(comments())); centerWidgetOnScreen(this); restoreFETDialogGeometry(this); //restore splitter state QSettings settings(COMPANY, PROGRAM); if(settings.contains(this->metaObject()->className()+QString("/splitter-state"))) splitter->restoreState(settings.value(this->metaObject()->className()+QString("/splitter-state")).toByteArray()); activityTagsListWidget->clear(); for(int i=0; i<gt.rules.activityTagsList.size(); i++){ ActivityTag* sbt=gt.rules.activityTagsList[i]; activityTagsListWidget->addItem(sbt->name); } if(activityTagsListWidget->count()>0) activityTagsListWidget->setCurrentRow(0); } ActivityTagsForm::~ActivityTagsForm() { saveFETDialogGeometry(this); //save splitter state QSettings settings(COMPANY, PROGRAM); settings.setValue(this->metaObject()->className()+QString("/splitter-state"), splitter->saveState()); } void ActivityTagsForm::addActivityTag() { bool ok = false; ActivityTag* sbt=new ActivityTag(); sbt->name = QInputDialog::getText( this, tr("Add activity tag"), tr("Please enter activity tag's name") , QLineEdit::Normal, QString(), &ok ); if ( ok && !((sbt->name).isEmpty()) ){ // user entered something and pressed OK if(!gt.rules.addActivityTag(sbt)){ QMessageBox::information( this, tr("Activity tag insertion dialog"), tr("Could not insert item. Must be a duplicate")); delete sbt; } else{ activityTagsListWidget->addItem(sbt->name); activityTagsListWidget->setCurrentRow(activityTagsListWidget->count()-1); } } else{ if(ok){ //the user entered nothing QMessageBox::information(this, tr("FET information"), tr("Incorrect name")); } delete sbt;// user entered nothing or pressed Cancel } } void ActivityTagsForm::removeActivityTag() { int i=activityTagsListWidget->currentRow(); if(activityTagsListWidget->currentRow()<0){ QMessageBox::information(this, tr("FET information"), tr("Invalid selected activity tag")); return; } QString text=activityTagsListWidget->currentItem()->text(); int activity_tag_ID=gt.rules.searchActivityTag(text); if(activity_tag_ID<0){ QMessageBox::information(this, tr("FET information"), tr("Invalid selected activity tag")); return; } if(QMessageBox::warning( this, tr("FET"), tr("Are you sure you want to delete this activity tag?"), tr("Yes"), tr("No"), 0, 0, 1 ) == 1) return; int tmp=gt.rules.removeActivityTag(text); if(tmp){ activityTagsListWidget->setCurrentRow(-1); QListWidgetItem* item; item=activityTagsListWidget->takeItem(i); delete item; if(i>=activityTagsListWidget->count()) i=activityTagsListWidget->count()-1; if(i>=0) activityTagsListWidget->setCurrentRow(i); else currentActivityTagTextEdit->setPlainText(QString("")); } } void ActivityTagsForm::renameActivityTag() { int i=activityTagsListWidget->currentRow(); if(activityTagsListWidget->currentRow()<0){ QMessageBox::information(this, tr("FET information"), tr("Invalid selected activity tag")); return; } QString initialActivityTagName=activityTagsListWidget->currentItem()->text(); int activity_tag_ID=gt.rules.searchActivityTag(initialActivityTagName); if(activity_tag_ID<0){ QMessageBox::information(this, tr("FET information"), tr("Invalid selected activity tag")); return; } bool ok = false; QString finalActivityTagName; finalActivityTagName = QInputDialog::getText( this, tr("Rename activity tag"), tr("Please enter new activity tag's name") , QLineEdit::Normal, initialActivityTagName, &ok ); if ( ok && !(finalActivityTagName.isEmpty()) ){ // user entered something and pressed OK if(gt.rules.searchActivityTag(finalActivityTagName)>=0){ QMessageBox::information( this, tr("Activity tag insertion dialog"), tr("Could not modify item. New name must be a duplicate")); } else{ gt.rules.modifyActivityTag(initialActivityTagName, finalActivityTagName); activityTagsListWidget->item(i)->setText(finalActivityTagName); activityTagChanged(activityTagsListWidget->currentRow()); } } } void ActivityTagsForm::moveActivityTagUp() { if(activityTagsListWidget->count()<=1) return; int i=activityTagsListWidget->currentRow(); if(i<0 || i>=activityTagsListWidget->count()) return; if(i==0) return; QString s1=activityTagsListWidget->item(i)->text(); QString s2=activityTagsListWidget->item(i-1)->text(); ActivityTag* at1=gt.rules.activityTagsList.at(i); ActivityTag* at2=gt.rules.activityTagsList.at(i-1); gt.rules.internalStructureComputed=false; setRulesModifiedAndOtherThings(&gt.rules); activityTagsListWidget->item(i)->setText(s2); activityTagsListWidget->item(i-1)->setText(s1); gt.rules.activityTagsList[i]=at2; gt.rules.activityTagsList[i-1]=at1; activityTagsListWidget->setCurrentRow(i-1); activityTagChanged(i-1); } void ActivityTagsForm::moveActivityTagDown() { if(activityTagsListWidget->count()<=1) return; int i=activityTagsListWidget->currentRow(); if(i<0 || i>=activityTagsListWidget->count()) return; if(i==activityTagsListWidget->count()-1) return; QString s1=activityTagsListWidget->item(i)->text(); QString s2=activityTagsListWidget->item(i+1)->text(); ActivityTag* at1=gt.rules.activityTagsList.at(i); ActivityTag* at2=gt.rules.activityTagsList.at(i+1); gt.rules.internalStructureComputed=false; setRulesModifiedAndOtherThings(&gt.rules); activityTagsListWidget->item(i)->setText(s2); activityTagsListWidget->item(i+1)->setText(s1); gt.rules.activityTagsList[i]=at2; gt.rules.activityTagsList[i+1]=at1; activityTagsListWidget->setCurrentRow(i+1); activityTagChanged(i+1); } void ActivityTagsForm::sortActivityTags() { gt.rules.sortActivityTagsAlphabetically(); activityTagsListWidget->clear(); for(int i=0; i<gt.rules.activityTagsList.size(); i++){ ActivityTag* sbt=gt.rules.activityTagsList[i]; activityTagsListWidget->addItem(sbt->name); } if(activityTagsListWidget->count()>0) activityTagsListWidget->setCurrentRow(0); } void ActivityTagsForm::activityTagChanged(int index) { if(index<0){ currentActivityTagTextEdit->setPlainText(QString("")); return; } ActivityTag* st=gt.rules.activityTagsList.at(index); assert(st); QString s=st->getDetailedDescriptionWithConstraints(gt.rules); currentActivityTagTextEdit->setPlainText(s); } void ActivityTagsForm::activateActivityTag() { if(activityTagsListWidget->currentRow()<0){ QMessageBox::information(this, tr("FET information"), tr("Invalid selected activity tag")); return; } QString text=activityTagsListWidget->currentItem()->text(); int count=gt.rules.activateActivityTag(text); QMessageBox::information(this, tr("FET information"), tr("Activated a number of %1 activities").arg(count)); } void ActivityTagsForm::deactivateActivityTag() { if(activityTagsListWidget->currentRow()<0){ QMessageBox::information(this, tr("FET information"), tr("Invalid selected activity tag")); return; } QString text=activityTagsListWidget->currentItem()->text(); int count=gt.rules.deactivateActivityTag(text); QMessageBox::information(this, tr("FET information"), tr("De-activated a number of %1 activities").arg(count)); } void ActivityTagsForm::printableActivityTag() { if(activityTagsListWidget->currentRow()<0){ QMessageBox::information(this, tr("FET information"), tr("Invalid selected activity tag")); return; } QString text=activityTagsListWidget->currentItem()->text(); gt.rules.makeActivityTagPrintable(text); activityTagChanged(activityTagsListWidget->currentRow()); } void ActivityTagsForm::notPrintableActivityTag() { if(activityTagsListWidget->currentRow()<0){ QMessageBox::information(this, tr("FET information"), tr("Invalid selected activity tag")); return; } QString text=activityTagsListWidget->currentItem()->text(); gt.rules.makeActivityTagNotPrintable(text); activityTagChanged(activityTagsListWidget->currentRow()); } void ActivityTagsForm::help() { QMessageBox::information(this, tr("FET help on activity tags"), tr("Activity tag is a field which can be used or not, depending on your wish (optional field)." " It is designed to help you with some constraints. Each activity has a possible empty list of activity tags" " (if you don't use activity tags, the list will be empty)")); } void ActivityTagsForm::comments() { int ind=activityTagsListWidget->currentRow(); if(ind<0){ QMessageBox::information(this, tr("FET information"), tr("Invalid selected activity tag")); return; } ActivityTag* at=gt.rules.activityTagsList[ind]; assert(at!=NULL); QDialog getCommentsDialog(this); getCommentsDialog.setWindowTitle(tr("Activity tag comments")); QPushButton* okPB=new QPushButton(tr("OK")); okPB->setDefault(true); QPushButton* cancelPB=new QPushButton(tr("Cancel")); connect(okPB, SIGNAL(clicked()), &getCommentsDialog, SLOT(accept())); connect(cancelPB, SIGNAL(clicked()), &getCommentsDialog, SLOT(reject())); QHBoxLayout* hl=new QHBoxLayout(); hl->addStretch(); hl->addWidget(okPB); hl->addWidget(cancelPB); QVBoxLayout* vl=new QVBoxLayout(); QPlainTextEdit* commentsPT=new QPlainTextEdit(); commentsPT->setPlainText(at->comments); commentsPT->selectAll(); commentsPT->setFocus(); vl->addWidget(commentsPT); vl->addLayout(hl); getCommentsDialog.setLayout(vl); const QString settingsName=QString("ActivityTagCommentsDialog"); getCommentsDialog.resize(500, 320); centerWidgetOnScreen(&getCommentsDialog); restoreFETDialogGeometry(&getCommentsDialog, settingsName); int t=getCommentsDialog.exec(); saveFETDialogGeometry(&getCommentsDialog, settingsName); if(t==QDialog::Accepted){ at->comments=commentsPT->toPlainText(); gt.rules.internalStructureComputed=false; setRulesModifiedAndOtherThings(&gt.rules); activityTagChanged(ind); } } <commit_msg>remove empty line<commit_after>// // // Description: This file is part of FET // // // Author: Lalescu Liviu <Please see http://lalescu.ro/liviu/ for details about contacting Liviu Lalescu (in particular, you can find here the e-mail address)> // Copyright (C) 2005 Liviu Lalescu <http://lalescu.ro/liviu/> // /*************************************************************************** * * * This program is free software: you can redistribute it and/or modify * * it under the terms of the GNU Affero General Public License as * * published by the Free Software Foundation, either version 3 of the * * License, or (at your option) any later version. * * * ***************************************************************************/ #include "timetable_defs.h" #include "timetable.h" #include "fet.h" #include "activitytagsform.h" #include "studentsset.h" #include "teacher.h" #include "subject.h" #include "activitytag.h" #include <QInputDialog> #include <QMessageBox> #include <QListWidget> #include <QAbstractItemView> #include <QSplitter> #include <QSettings> #include <QObject> #include <QMetaObject> extern const QString COMPANY; extern const QString PROGRAM; ActivityTagsForm::ActivityTagsForm(QWidget* parent): QDialog(parent) { setupUi(this); currentActivityTagTextEdit->setReadOnly(true); renameActivityTagPushButton->setDefault(true); activityTagsListWidget->setSelectionMode(QAbstractItemView::SingleSelection); connect(closePushButton, SIGNAL(clicked()), this, SLOT(close())); connect(addActivityTagPushButton, SIGNAL(clicked()), this, SLOT(addActivityTag())); connect(removeActivityTagPushButton, SIGNAL(clicked()), this, SLOT(removeActivityTag())); connect(renameActivityTagPushButton, SIGNAL(clicked()), this, SLOT(renameActivityTag())); connect(moveActivityTagUpPushButton, SIGNAL(clicked()), this, SLOT(moveActivityTagUp())); connect(moveActivityTagDownPushButton, SIGNAL(clicked()), this, SLOT(moveActivityTagDown())); connect(sortActivityTagsPushButton, SIGNAL(clicked()), this, SLOT(sortActivityTags())); connect(activityTagsListWidget, SIGNAL(currentRowChanged(int)), this, SLOT(activityTagChanged(int))); connect(activateActivityTagPushButton, SIGNAL(clicked()), this, SLOT(activateActivityTag())); connect(deactivateActivityTagPushButton, SIGNAL(clicked()), this, SLOT(deactivateActivityTag())); connect(activityTagsListWidget, SIGNAL(itemDoubleClicked(QListWidgetItem*)), this, SLOT(renameActivityTag())); connect(helpPushButton, SIGNAL(clicked()), this, SLOT(help())); connect(printablePushButton, SIGNAL(clicked()), this, SLOT(printableActivityTag())); connect(notPrintablePushButton, SIGNAL(clicked()), this, SLOT(notPrintableActivityTag())); connect(commentsPushButton, SIGNAL(clicked()), this, SLOT(comments())); centerWidgetOnScreen(this); restoreFETDialogGeometry(this); //restore splitter state QSettings settings(COMPANY, PROGRAM); if(settings.contains(this->metaObject()->className()+QString("/splitter-state"))) splitter->restoreState(settings.value(this->metaObject()->className()+QString("/splitter-state")).toByteArray()); activityTagsListWidget->clear(); for(int i=0; i<gt.rules.activityTagsList.size(); i++){ ActivityTag* sbt=gt.rules.activityTagsList[i]; activityTagsListWidget->addItem(sbt->name); } if(activityTagsListWidget->count()>0) activityTagsListWidget->setCurrentRow(0); } ActivityTagsForm::~ActivityTagsForm() { saveFETDialogGeometry(this); //save splitter state QSettings settings(COMPANY, PROGRAM); settings.setValue(this->metaObject()->className()+QString("/splitter-state"), splitter->saveState()); } void ActivityTagsForm::addActivityTag() { bool ok = false; ActivityTag* sbt=new ActivityTag(); sbt->name = QInputDialog::getText( this, tr("Add activity tag"), tr("Please enter activity tag's name") , QLineEdit::Normal, QString(), &ok ); if ( ok && !((sbt->name).isEmpty()) ){ // user entered something and pressed OK if(!gt.rules.addActivityTag(sbt)){ QMessageBox::information( this, tr("Activity tag insertion dialog"), tr("Could not insert item. Must be a duplicate")); delete sbt; } else{ activityTagsListWidget->addItem(sbt->name); activityTagsListWidget->setCurrentRow(activityTagsListWidget->count()-1); } } else{ if(ok){ //the user entered nothing QMessageBox::information(this, tr("FET information"), tr("Incorrect name")); } delete sbt;// user entered nothing or pressed Cancel } } void ActivityTagsForm::removeActivityTag() { int i=activityTagsListWidget->currentRow(); if(activityTagsListWidget->currentRow()<0){ QMessageBox::information(this, tr("FET information"), tr("Invalid selected activity tag")); return; } QString text=activityTagsListWidget->currentItem()->text(); int activity_tag_ID=gt.rules.searchActivityTag(text); if(activity_tag_ID<0){ QMessageBox::information(this, tr("FET information"), tr("Invalid selected activity tag")); return; } if(QMessageBox::warning( this, tr("FET"), tr("Are you sure you want to delete this activity tag?"), tr("Yes"), tr("No"), 0, 0, 1 ) == 1) return; int tmp=gt.rules.removeActivityTag(text); if(tmp){ activityTagsListWidget->setCurrentRow(-1); QListWidgetItem* item; item=activityTagsListWidget->takeItem(i); delete item; if(i>=activityTagsListWidget->count()) i=activityTagsListWidget->count()-1; if(i>=0) activityTagsListWidget->setCurrentRow(i); else currentActivityTagTextEdit->setPlainText(QString("")); } } void ActivityTagsForm::renameActivityTag() { int i=activityTagsListWidget->currentRow(); if(activityTagsListWidget->currentRow()<0){ QMessageBox::information(this, tr("FET information"), tr("Invalid selected activity tag")); return; } QString initialActivityTagName=activityTagsListWidget->currentItem()->text(); int activity_tag_ID=gt.rules.searchActivityTag(initialActivityTagName); if(activity_tag_ID<0){ QMessageBox::information(this, tr("FET information"), tr("Invalid selected activity tag")); return; } bool ok = false; QString finalActivityTagName; finalActivityTagName = QInputDialog::getText( this, tr("Rename activity tag"), tr("Please enter new activity tag's name") , QLineEdit::Normal, initialActivityTagName, &ok ); if ( ok && !(finalActivityTagName.isEmpty()) ){ // user entered something and pressed OK if(gt.rules.searchActivityTag(finalActivityTagName)>=0){ QMessageBox::information( this, tr("Activity tag insertion dialog"), tr("Could not modify item. New name must be a duplicate")); } else{ gt.rules.modifyActivityTag(initialActivityTagName, finalActivityTagName); activityTagsListWidget->item(i)->setText(finalActivityTagName); activityTagChanged(activityTagsListWidget->currentRow()); } } } void ActivityTagsForm::moveActivityTagUp() { if(activityTagsListWidget->count()<=1) return; int i=activityTagsListWidget->currentRow(); if(i<0 || i>=activityTagsListWidget->count()) return; if(i==0) return; QString s1=activityTagsListWidget->item(i)->text(); QString s2=activityTagsListWidget->item(i-1)->text(); ActivityTag* at1=gt.rules.activityTagsList.at(i); ActivityTag* at2=gt.rules.activityTagsList.at(i-1); gt.rules.internalStructureComputed=false; setRulesModifiedAndOtherThings(&gt.rules); activityTagsListWidget->item(i)->setText(s2); activityTagsListWidget->item(i-1)->setText(s1); gt.rules.activityTagsList[i]=at2; gt.rules.activityTagsList[i-1]=at1; activityTagsListWidget->setCurrentRow(i-1); activityTagChanged(i-1); } void ActivityTagsForm::moveActivityTagDown() { if(activityTagsListWidget->count()<=1) return; int i=activityTagsListWidget->currentRow(); if(i<0 || i>=activityTagsListWidget->count()) return; if(i==activityTagsListWidget->count()-1) return; QString s1=activityTagsListWidget->item(i)->text(); QString s2=activityTagsListWidget->item(i+1)->text(); ActivityTag* at1=gt.rules.activityTagsList.at(i); ActivityTag* at2=gt.rules.activityTagsList.at(i+1); gt.rules.internalStructureComputed=false; setRulesModifiedAndOtherThings(&gt.rules); activityTagsListWidget->item(i)->setText(s2); activityTagsListWidget->item(i+1)->setText(s1); gt.rules.activityTagsList[i]=at2; gt.rules.activityTagsList[i+1]=at1; activityTagsListWidget->setCurrentRow(i+1); activityTagChanged(i+1); } void ActivityTagsForm::sortActivityTags() { gt.rules.sortActivityTagsAlphabetically(); activityTagsListWidget->clear(); for(int i=0; i<gt.rules.activityTagsList.size(); i++){ ActivityTag* sbt=gt.rules.activityTagsList[i]; activityTagsListWidget->addItem(sbt->name); } if(activityTagsListWidget->count()>0) activityTagsListWidget->setCurrentRow(0); } void ActivityTagsForm::activityTagChanged(int index) { if(index<0){ currentActivityTagTextEdit->setPlainText(QString("")); return; } ActivityTag* st=gt.rules.activityTagsList.at(index); assert(st); QString s=st->getDetailedDescriptionWithConstraints(gt.rules); currentActivityTagTextEdit->setPlainText(s); } void ActivityTagsForm::activateActivityTag() { if(activityTagsListWidget->currentRow()<0){ QMessageBox::information(this, tr("FET information"), tr("Invalid selected activity tag")); return; } QString text=activityTagsListWidget->currentItem()->text(); int count=gt.rules.activateActivityTag(text); QMessageBox::information(this, tr("FET information"), tr("Activated a number of %1 activities").arg(count)); } void ActivityTagsForm::deactivateActivityTag() { if(activityTagsListWidget->currentRow()<0){ QMessageBox::information(this, tr("FET information"), tr("Invalid selected activity tag")); return; } QString text=activityTagsListWidget->currentItem()->text(); int count=gt.rules.deactivateActivityTag(text); QMessageBox::information(this, tr("FET information"), tr("De-activated a number of %1 activities").arg(count)); } void ActivityTagsForm::printableActivityTag() { if(activityTagsListWidget->currentRow()<0){ QMessageBox::information(this, tr("FET information"), tr("Invalid selected activity tag")); return; } QString text=activityTagsListWidget->currentItem()->text(); gt.rules.makeActivityTagPrintable(text); activityTagChanged(activityTagsListWidget->currentRow()); } void ActivityTagsForm::notPrintableActivityTag() { if(activityTagsListWidget->currentRow()<0){ QMessageBox::information(this, tr("FET information"), tr("Invalid selected activity tag")); return; } QString text=activityTagsListWidget->currentItem()->text(); gt.rules.makeActivityTagNotPrintable(text); activityTagChanged(activityTagsListWidget->currentRow()); } void ActivityTagsForm::help() { QMessageBox::information(this, tr("FET help on activity tags"), tr("Activity tag is a field which can be used or not, depending on your wish (optional field)." " It is designed to help you with some constraints. Each activity has a possible empty list of activity tags" " (if you don't use activity tags, the list will be empty)")); } void ActivityTagsForm::comments() { int ind=activityTagsListWidget->currentRow(); if(ind<0){ QMessageBox::information(this, tr("FET information"), tr("Invalid selected activity tag")); return; } ActivityTag* at=gt.rules.activityTagsList[ind]; assert(at!=NULL); QDialog getCommentsDialog(this); getCommentsDialog.setWindowTitle(tr("Activity tag comments")); QPushButton* okPB=new QPushButton(tr("OK")); okPB->setDefault(true); QPushButton* cancelPB=new QPushButton(tr("Cancel")); connect(okPB, SIGNAL(clicked()), &getCommentsDialog, SLOT(accept())); connect(cancelPB, SIGNAL(clicked()), &getCommentsDialog, SLOT(reject())); QHBoxLayout* hl=new QHBoxLayout(); hl->addStretch(); hl->addWidget(okPB); hl->addWidget(cancelPB); QVBoxLayout* vl=new QVBoxLayout(); QPlainTextEdit* commentsPT=new QPlainTextEdit(); commentsPT->setPlainText(at->comments); commentsPT->selectAll(); commentsPT->setFocus(); vl->addWidget(commentsPT); vl->addLayout(hl); getCommentsDialog.setLayout(vl); const QString settingsName=QString("ActivityTagCommentsDialog"); getCommentsDialog.resize(500, 320); centerWidgetOnScreen(&getCommentsDialog); restoreFETDialogGeometry(&getCommentsDialog, settingsName); int t=getCommentsDialog.exec(); saveFETDialogGeometry(&getCommentsDialog, settingsName); if(t==QDialog::Accepted){ at->comments=commentsPT->toPlainText(); gt.rules.internalStructureComputed=false; setRulesModifiedAndOtherThings(&gt.rules); activityTagChanged(ind); } } <|endoftext|>
<commit_before>//IBM_PROLOG_BEGIN_TAG //IBM_PROLOG_END_TAG //-------------------------------------------------------------------- // Includes //-------------------------------------------------------------------- #include <Instruction.H> #include <arpa/inet.h> #include <stdio.h> #include <string.h> #include <sstream> #include <iomanip> #ifdef OTHER_USE #include <OutputLite.H> extern OutputLite out; #else #include <CronusData.H> #endif std::string InstructionTypeToString(Instruction::InstructionType i_type) { switch (i_type) { case Instruction::NOINSTRUCTION: return "NOINSTRUCTION"; case Instruction::FSI: return "FSI"; case Instruction::JTAG: return "JTAG"; case Instruction::MULTIPLEJTAG: return "MULTIPLEJTAG"; case Instruction::PSI: return "PSI"; case Instruction::GPIO: return "GPIO"; case Instruction::I2C: return "I2C"; case Instruction::VPD: return "VPD"; case Instruction::DMA: return "DMA"; case Instruction::CONTROL: return "CONTROL"; case Instruction::DMAEXER: return "DMAEXER"; case Instruction::POWR: return "POWR"; case Instruction::FSISTREAM: return "FSISTREAM"; case Instruction::SBEFIFO: return "SBEFIFO"; case Instruction::GSD2PIB: return "GSD2PIB"; case Instruction::FSIMEMPROC: return "FSIMEMPROC"; case Instruction::PNOR: return "PNOR"; } return ""; } std::string InstructionCommandToString(Instruction::InstructionCommand i_command) { switch (i_command) { case Instruction::NOCOMMAND: return "NOCOMMAND"; case Instruction::SENDCMD: return "SENDCMD"; case Instruction::READ: return "READ"; case Instruction::WRITE: return "WRITE"; case Instruction::LONGIN: return "LONGIN"; case Instruction::LONGOUT: return "LONGOUT"; case Instruction::READ_WRITE: return "READ_WRITE"; case Instruction::SHIFTOUT: return "SHIFTOUT"; case Instruction::DMAIN: return "DMAIN"; case Instruction::DMAOUT: return "DMAOUT"; case Instruction::MISC: return "MISC"; case Instruction::TOTAP: return "TOTAP"; case Instruction::READVPD: return "READVPD"; case Instruction::READSPMEM: return "READSPMEM"; case Instruction::WRITESPMEM: return "WRITESPMEM"; case Instruction::SCOMIN: return "SCOMIN"; case Instruction::SCOMOUT: return "SCOMOUT"; case Instruction::WRITEVPD: return "WRITEVPD"; case Instruction::PSI_RESET: return "PSI_RESET"; case Instruction::PSI_LINK_CALIB: return "PSI_LINK_CALIB"; case Instruction::PSI_EI_REG_READ: return "PSI_EI_REG_READ"; case Instruction::PSI_EI_REG_WRITE: return "PSI_EI_REG_WRITE"; case Instruction::PSI_VERIFY: return "PSI_VERIFY"; case Instruction::PSI_SCOM_READ: return "PSI_SCOM_READ"; case Instruction::PSI_SCOM_WRITE: return "PSI_SCOM_WRITE"; case Instruction::PSI_READ: return "PSI_READ"; case Instruction::PSI_WRITE: return "PSI_WRITE"; case Instruction::PSI_INIT: return "PSI_INIT"; case Instruction::PSI_LINK_ENABLE: return "PSI_LINK_ENABLE"; case Instruction::PSI_SET_SPEED: return "PSI_SET_SPEED"; case Instruction::PSI_LINK_VERIFY: return "PSI_LINK_VERIFY"; case Instruction::I2CWRITE: return "I2CWRITE"; case Instruction::I2CREAD: return "I2CREAD"; case Instruction::GPIO_CONFIGPIN: return "GPIO_CONFIGPIN"; case Instruction::GPIO_READPIN: return "GPIO_READPIN"; case Instruction::GPIO_READPINS: return "GPIO_READPINS"; case Instruction::GPIO_READLATCH: return "GPIO_READLATCH"; case Instruction::GPIO_WRITELATCH: return "GPIO_WRITELATCH"; case Instruction::GPIO_WRITELATCHES: return "GPIO_WRITELATCHES"; case Instruction::GPIO_READCONFIG: return "GPIO_READCONFIG"; case Instruction::GPIO_WRITECONFIG: return "GPIO_WRITECONFIG"; case Instruction::GPIO_WRITECNFGSET: return "GPIO_WRITECNFGSET"; case Instruction::GPIO_WRITECNFGCLR: return "GPIO_WRITECNFGCLR"; case Instruction::DMAEXER_START: return "DMAEXER_START"; case Instruction::DMAEXER_REPORT: return "DMAEXER_REPORT"; case Instruction::DMAEXER_STOP: return "DMAEXER_STOP"; case Instruction::INFO: return "INFO"; case Instruction::RUN_CMD: return "RUN_CMD"; case Instruction::MULTI_ENABLE: return "MULTI_ENABLE"; case Instruction::AUTH: return "AUTH"; case Instruction::ADDAUTH: return "ADDAUTH"; case Instruction::CLEARAUTH: return "CLEARAUTH"; case Instruction::VERSION: return "VERSION"; case Instruction::FLIGHTRECORDER: return "FLIGHTRECORDER"; case Instruction::EXIT: return "EXIT"; case Instruction::SCOMIN_MASK: return "SCOMIN_MASK"; case Instruction::MASK_PERSISTENT: return "MASK_PERSISTENT"; case Instruction::SET_PERSISTENT: return "SET_PERSISTENT"; case Instruction::GET_PERSISTENT: return "GET_PERSISTENT"; case Instruction::READKEYWORD: return "READKEYWORD"; case Instruction::WRITEKEYWORD: return "WRITEKEYWORD"; case Instruction::FRUSTATUS: return "FRUSTATUS"; case Instruction::CHICDOIPL: return "CHICDOIPL"; case Instruction::ENABLE_MEM_VOLTAGES: return "ENABLE_MEM_VOLTAGES"; case Instruction::DISABLE_MEM_VOLTAGES: return "DISABLE_MEM_VOLTAGES"; case Instruction::SNDISTEPMSG: return "SNDISTEPMSG"; case Instruction::MBXTRACEENABLE: return "MBXTRACEENABLE"; case Instruction::MBXTRACEDISABLE: return "MBXTRACEDISABLE"; case Instruction::MBXTRACEREAD: return "MBXTRACEREAD"; case Instruction::PUTMEMPBA: return "PUTMEMPBA"; case Instruction::GETMEMPBA: return "GETMEMPBA"; case Instruction::BULK_SCOMIN: return "BULK_SCOMIN"; case Instruction::BULK_SCOMOUT: return "BULK_SCOMOUT"; case Instruction::STREAM_SETUP: return "STREAM_SETUP"; case Instruction::STREAM_FINISH: return "STREAM_FINISH"; case Instruction::FSPDMAIN: return "FSPDMAIN"; case Instruction::FSPDMAOUT: return "FSPDMAOUT"; case Instruction::SUBMIT: return "SUBMIT"; case Instruction::REQUEST_RESET: return "REQUEST_RESET"; case Instruction::SEND_TAPI_CMD: return "SEND_TAPI_CMD"; case Instruction::PUTMEMPROC: return "PUTMEMPROC"; case Instruction::GETMEMPROC: return "GETMEMPROC"; case Instruction::PNORGETLIST: return "PNORGETLIST"; case Instruction::PNORGET: return "PNORGET"; case Instruction::PNORPUT: return "PNORPUT"; case Instruction::QUERYSP: return "QUERYSP"; } return ""; } /*****************************************************************************/ /* Instruction Implementation ************************************************/ /*****************************************************************************/ Instruction::Instruction(void) : version(0x1), command(NOCOMMAND), type(NOINSTRUCTION), error(0){ } /* for all of these methods check if we are of a different type */ uint32_t Instruction::execute(ecmdDataBuffer & o_data, InstructionStatus & o_status, Handle ** io_handle) { uint32_t rc = 0; /* set the version of this instruction in the status */ o_status.instructionVersion = version; o_status.errorMessage.append("Instruction::execute Unknown Instruction specified. New FSP server may be required."); o_status.rc = SERVER_UNKNOWN_INSTRUCTION; return rc; } uint32_t Instruction::decrementVersion(void) { if (version > 0x1) { version--; return 0; } // return an error if we can not decrement return 1; } uint32_t Instruction::flatten(uint8_t * o_data, uint32_t i_len) const { uint32_t rc = 0; uint32_t * o_ptr = (uint32_t *) o_data; if (i_len < flattenSize()) { out.error("Instruction::flatten", "i_len %d bytes is too small to flatten\n", i_len); rc = 1; } else { // clear memory memset(o_data, 0, flattenSize()); o_ptr[0] = htonl(version); o_ptr[1] = htonl(command); o_ptr[2] = htonl(flags); } return rc; } uint32_t Instruction::unflatten(const uint8_t * i_data, uint32_t i_len) { uint32_t rc = 0; uint32_t * i_ptr = (uint32_t *) i_data; version = ntohl(i_ptr[0]); if(version == 0x1) { command = (InstructionCommand) ntohl(i_ptr[1]); flags = ntohl(i_ptr[2]); } else { error = rc = SERVER_UNKNOWN_INSTRUCTION_VERSION; } return rc; } uint32_t Instruction::flattenSize(void) const { return (3 * sizeof(uint32_t)); } std::string Instruction::dumpInstruction(void) const { std::ostringstream oss; oss << "Instruction" << std::endl; return oss.str(); } uint64_t Instruction::getHash(void) const { return ((0x0000000F & type) << 28); } uint32_t Instruction::closeHandle(Handle ** i_handle) { uint32_t rc = 0; *i_handle = NULL; return rc; } std::string Instruction::getInstructionVars(const InstructionStatus & i_status) const { std::ostringstream oss; oss << std::hex << std::setfill('0'); oss << "rc: " << std::setw(8) << i_status.rc; return oss.str(); } Instruction::InstructionType Instruction::getType(void) const { return type; } Instruction::InstructionCommand Instruction::getCommand(void) const { return command; } uint32_t Instruction::getFlags(void) const { return flags; } uint32_t Instruction::getVersion(void) const { return version; } int Instruction::genWords(const ecmdDataBuffer &data, std::string &words) const { // copied from Debug.C int rc = 0; if (data.getBitLength() == 0) { words = ""; // This will kill the genHexLeftStr error if we have no data } else if (data.getBitLength() <= 128) { words = data.genHexLeftStr(0, data.getBitLength()); } else { words = data.genHexLeftStr(0, 128); } return rc; } std::ostream& operator<<(std::ostream& io_stream, const Instruction& i_instruction ) { io_stream << i_instruction.dumpInstruction() << std::endl; return io_stream; } uint32_t devicestring_genhash(const std::string & i_string, uint32_t & o_hash) { int length = i_string.length(); const char * data = i_string.c_str(); int found = 0; int type = 0; // 3 bits int fsi = 0; // 6 bits int cfam = 0; // 2 bits int engine = 0; // 5 bits int subfsi = 0; // 3 bits int subcfam = 0; // 2 bits int subengine = 0; // 5 bits int subsubfsi = 0; // 3 bits int subsubcfam = 0; // 2 bits o_hash = 0x0; if (length == 5) { type = 1; found = sscanf(data, "L%02dC%d", &fsi, &cfam); if (found != 2) { //std::cout << "ERROR reading data from " << i_string << std::endl; return 1; } } else if (length == 13) { type = 2; found = sscanf(data, "L%02dC%dE%02d:L%dC%d", &fsi, &cfam, &engine, &subfsi, &subcfam); if (found != 5) { //std::cout << "ERROR reading data from " << i_string << std::endl; return 2; } } else if (length == 21) { type = 3; found = sscanf(data, "L%02dC%dE%02d:L%dC%dE%02d:L%dC%d", &fsi, &cfam, &engine, &subfsi, &subcfam, &subengine, &subsubfsi, &subsubcfam); if (found != 8) { //std::cout << "ERROR reading data from " << i_string << std::endl; return 3; } } else { // error //std::cout << "ERROR unknown format for device " << i_string << std::endl; return 4; } o_hash |= ((0x07 & type) << 0); //0x00000007 o_hash |= ((0x3F & fsi) << 3); //0x000001F8 o_hash |= ((0x03 & cfam) << 9); //0x00000600 o_hash |= ((0x1F & engine) << 11); //0x0000F800 o_hash |= ((0x07 & subfsi) << 16); //0x00070000 o_hash |= ((0x03 & subcfam) << 19); //0x00180000 o_hash |= ((0x1F & subengine) << 21); //0x03E00000 o_hash |= ((0x07 & subsubfsi) << 26); //0x1C000000 o_hash |= ((0x03 & subsubcfam) << 29); //0x60000000 return 0; } <commit_msg>fix hash generation for bmc device strings<commit_after>//IBM_PROLOG_BEGIN_TAG //IBM_PROLOG_END_TAG //-------------------------------------------------------------------- // Includes //-------------------------------------------------------------------- #include <Instruction.H> #include <arpa/inet.h> #include <stdio.h> #include <string.h> #include <sstream> #include <iomanip> #include <errno.h> #include <limits.h> #include <iostream> #ifdef OTHER_USE #include <OutputLite.H> extern OutputLite out; #else #include <CronusData.H> #endif std::string InstructionTypeToString(Instruction::InstructionType i_type) { switch (i_type) { case Instruction::NOINSTRUCTION: return "NOINSTRUCTION"; case Instruction::FSI: return "FSI"; case Instruction::JTAG: return "JTAG"; case Instruction::MULTIPLEJTAG: return "MULTIPLEJTAG"; case Instruction::PSI: return "PSI"; case Instruction::GPIO: return "GPIO"; case Instruction::I2C: return "I2C"; case Instruction::VPD: return "VPD"; case Instruction::DMA: return "DMA"; case Instruction::CONTROL: return "CONTROL"; case Instruction::DMAEXER: return "DMAEXER"; case Instruction::POWR: return "POWR"; case Instruction::FSISTREAM: return "FSISTREAM"; case Instruction::SBEFIFO: return "SBEFIFO"; case Instruction::GSD2PIB: return "GSD2PIB"; case Instruction::FSIMEMPROC: return "FSIMEMPROC"; case Instruction::PNOR: return "PNOR"; } return ""; } std::string InstructionCommandToString(Instruction::InstructionCommand i_command) { switch (i_command) { case Instruction::NOCOMMAND: return "NOCOMMAND"; case Instruction::SENDCMD: return "SENDCMD"; case Instruction::READ: return "READ"; case Instruction::WRITE: return "WRITE"; case Instruction::LONGIN: return "LONGIN"; case Instruction::LONGOUT: return "LONGOUT"; case Instruction::READ_WRITE: return "READ_WRITE"; case Instruction::SHIFTOUT: return "SHIFTOUT"; case Instruction::DMAIN: return "DMAIN"; case Instruction::DMAOUT: return "DMAOUT"; case Instruction::MISC: return "MISC"; case Instruction::TOTAP: return "TOTAP"; case Instruction::READVPD: return "READVPD"; case Instruction::READSPMEM: return "READSPMEM"; case Instruction::WRITESPMEM: return "WRITESPMEM"; case Instruction::SCOMIN: return "SCOMIN"; case Instruction::SCOMOUT: return "SCOMOUT"; case Instruction::WRITEVPD: return "WRITEVPD"; case Instruction::PSI_RESET: return "PSI_RESET"; case Instruction::PSI_LINK_CALIB: return "PSI_LINK_CALIB"; case Instruction::PSI_EI_REG_READ: return "PSI_EI_REG_READ"; case Instruction::PSI_EI_REG_WRITE: return "PSI_EI_REG_WRITE"; case Instruction::PSI_VERIFY: return "PSI_VERIFY"; case Instruction::PSI_SCOM_READ: return "PSI_SCOM_READ"; case Instruction::PSI_SCOM_WRITE: return "PSI_SCOM_WRITE"; case Instruction::PSI_READ: return "PSI_READ"; case Instruction::PSI_WRITE: return "PSI_WRITE"; case Instruction::PSI_INIT: return "PSI_INIT"; case Instruction::PSI_LINK_ENABLE: return "PSI_LINK_ENABLE"; case Instruction::PSI_SET_SPEED: return "PSI_SET_SPEED"; case Instruction::PSI_LINK_VERIFY: return "PSI_LINK_VERIFY"; case Instruction::I2CWRITE: return "I2CWRITE"; case Instruction::I2CREAD: return "I2CREAD"; case Instruction::GPIO_CONFIGPIN: return "GPIO_CONFIGPIN"; case Instruction::GPIO_READPIN: return "GPIO_READPIN"; case Instruction::GPIO_READPINS: return "GPIO_READPINS"; case Instruction::GPIO_READLATCH: return "GPIO_READLATCH"; case Instruction::GPIO_WRITELATCH: return "GPIO_WRITELATCH"; case Instruction::GPIO_WRITELATCHES: return "GPIO_WRITELATCHES"; case Instruction::GPIO_READCONFIG: return "GPIO_READCONFIG"; case Instruction::GPIO_WRITECONFIG: return "GPIO_WRITECONFIG"; case Instruction::GPIO_WRITECNFGSET: return "GPIO_WRITECNFGSET"; case Instruction::GPIO_WRITECNFGCLR: return "GPIO_WRITECNFGCLR"; case Instruction::DMAEXER_START: return "DMAEXER_START"; case Instruction::DMAEXER_REPORT: return "DMAEXER_REPORT"; case Instruction::DMAEXER_STOP: return "DMAEXER_STOP"; case Instruction::INFO: return "INFO"; case Instruction::RUN_CMD: return "RUN_CMD"; case Instruction::MULTI_ENABLE: return "MULTI_ENABLE"; case Instruction::AUTH: return "AUTH"; case Instruction::ADDAUTH: return "ADDAUTH"; case Instruction::CLEARAUTH: return "CLEARAUTH"; case Instruction::VERSION: return "VERSION"; case Instruction::FLIGHTRECORDER: return "FLIGHTRECORDER"; case Instruction::EXIT: return "EXIT"; case Instruction::SCOMIN_MASK: return "SCOMIN_MASK"; case Instruction::MASK_PERSISTENT: return "MASK_PERSISTENT"; case Instruction::SET_PERSISTENT: return "SET_PERSISTENT"; case Instruction::GET_PERSISTENT: return "GET_PERSISTENT"; case Instruction::READKEYWORD: return "READKEYWORD"; case Instruction::WRITEKEYWORD: return "WRITEKEYWORD"; case Instruction::FRUSTATUS: return "FRUSTATUS"; case Instruction::CHICDOIPL: return "CHICDOIPL"; case Instruction::ENABLE_MEM_VOLTAGES: return "ENABLE_MEM_VOLTAGES"; case Instruction::DISABLE_MEM_VOLTAGES: return "DISABLE_MEM_VOLTAGES"; case Instruction::SNDISTEPMSG: return "SNDISTEPMSG"; case Instruction::MBXTRACEENABLE: return "MBXTRACEENABLE"; case Instruction::MBXTRACEDISABLE: return "MBXTRACEDISABLE"; case Instruction::MBXTRACEREAD: return "MBXTRACEREAD"; case Instruction::PUTMEMPBA: return "PUTMEMPBA"; case Instruction::GETMEMPBA: return "GETMEMPBA"; case Instruction::BULK_SCOMIN: return "BULK_SCOMIN"; case Instruction::BULK_SCOMOUT: return "BULK_SCOMOUT"; case Instruction::STREAM_SETUP: return "STREAM_SETUP"; case Instruction::STREAM_FINISH: return "STREAM_FINISH"; case Instruction::FSPDMAIN: return "FSPDMAIN"; case Instruction::FSPDMAOUT: return "FSPDMAOUT"; case Instruction::SUBMIT: return "SUBMIT"; case Instruction::REQUEST_RESET: return "REQUEST_RESET"; case Instruction::SEND_TAPI_CMD: return "SEND_TAPI_CMD"; case Instruction::PUTMEMPROC: return "PUTMEMPROC"; case Instruction::GETMEMPROC: return "GETMEMPROC"; case Instruction::PNORGETLIST: return "PNORGETLIST"; case Instruction::PNORGET: return "PNORGET"; case Instruction::PNORPUT: return "PNORPUT"; case Instruction::QUERYSP: return "QUERYSP"; } return ""; } /*****************************************************************************/ /* Instruction Implementation ************************************************/ /*****************************************************************************/ Instruction::Instruction(void) : version(0x1), command(NOCOMMAND), type(NOINSTRUCTION), error(0){ } /* for all of these methods check if we are of a different type */ uint32_t Instruction::execute(ecmdDataBuffer & o_data, InstructionStatus & o_status, Handle ** io_handle) { uint32_t rc = 0; /* set the version of this instruction in the status */ o_status.instructionVersion = version; o_status.errorMessage.append("Instruction::execute Unknown Instruction specified. New FSP server may be required."); o_status.rc = SERVER_UNKNOWN_INSTRUCTION; return rc; } uint32_t Instruction::decrementVersion(void) { if (version > 0x1) { version--; return 0; } // return an error if we can not decrement return 1; } uint32_t Instruction::flatten(uint8_t * o_data, uint32_t i_len) const { uint32_t rc = 0; uint32_t * o_ptr = (uint32_t *) o_data; if (i_len < flattenSize()) { out.error("Instruction::flatten", "i_len %d bytes is too small to flatten\n", i_len); rc = 1; } else { // clear memory memset(o_data, 0, flattenSize()); o_ptr[0] = htonl(version); o_ptr[1] = htonl(command); o_ptr[2] = htonl(flags); } return rc; } uint32_t Instruction::unflatten(const uint8_t * i_data, uint32_t i_len) { uint32_t rc = 0; uint32_t * i_ptr = (uint32_t *) i_data; version = ntohl(i_ptr[0]); if(version == 0x1) { command = (InstructionCommand) ntohl(i_ptr[1]); flags = ntohl(i_ptr[2]); } else { error = rc = SERVER_UNKNOWN_INSTRUCTION_VERSION; } return rc; } uint32_t Instruction::flattenSize(void) const { return (3 * sizeof(uint32_t)); } std::string Instruction::dumpInstruction(void) const { std::ostringstream oss; oss << "Instruction" << std::endl; return oss.str(); } uint64_t Instruction::getHash(void) const { return ((0x0000000F & type) << 28); } uint32_t Instruction::closeHandle(Handle ** i_handle) { uint32_t rc = 0; *i_handle = NULL; return rc; } std::string Instruction::getInstructionVars(const InstructionStatus & i_status) const { std::ostringstream oss; oss << std::hex << std::setfill('0'); oss << "rc: " << std::setw(8) << i_status.rc; return oss.str(); } Instruction::InstructionType Instruction::getType(void) const { return type; } Instruction::InstructionCommand Instruction::getCommand(void) const { return command; } uint32_t Instruction::getFlags(void) const { return flags; } uint32_t Instruction::getVersion(void) const { return version; } int Instruction::genWords(const ecmdDataBuffer &data, std::string &words) const { // copied from Debug.C int rc = 0; if (data.getBitLength() == 0) { words = ""; // This will kill the genHexLeftStr error if we have no data } else if (data.getBitLength() <= 128) { words = data.genHexLeftStr(0, data.getBitLength()); } else { words = data.genHexLeftStr(0, 128); } return rc; } std::ostream& operator<<(std::ostream& io_stream, const Instruction& i_instruction ) { io_stream << i_instruction.dumpInstruction() << std::endl; return io_stream; } uint32_t devicestring_genhash(const std::string & i_string, uint32_t & o_hash) { uint32_t rc = 0; int length = i_string.length(); const char * data = i_string.c_str(); int found = 0; int type = 0; // 3 bits int fsi = 0; // 6 bits int cfam = 0; // 2 bits int engine = 0; // 5 bits int subfsi = 0; // 3 bits int subcfam = 0; // 2 bits int subengine = 0; // 5 bits int subsubfsi = 0; // 3 bits int subsubcfam = 0; // 2 bits o_hash = 0x0; if (length == 5) { type = 1; found = sscanf(data, "L%02dC%d", &fsi, &cfam); if (found != 2) { rc = 1; } } else if (length == 13) { type = 2; found = sscanf(data, "L%02dC%dE%02d:L%dC%d", &fsi, &cfam, &engine, &subfsi, &subcfam); if (found != 5) { rc = 2; } } else if (length == 21) { type = 3; found = sscanf(data, "L%02dC%dE%02d:L%dC%dE%02d:L%dC%d", &fsi, &cfam, &engine, &subfsi, &subcfam, &subengine, &subsubfsi, &subsubcfam); if (found != 8) { rc = 3; } } else { // BMC device case char * endptr = NULL; errno = 0; fsi = strtol(data, &endptr, 10); if (((errno == ERANGE) && ((fsi == LONG_MAX) || (fsi == LONG_MIN))) || ((errno != 0) && (fsi == 0))) { rc = 5; } else if (endptr == data) { rc = 6; } else if (*endptr != '\0') { rc = 4; } } if (rc) { // error std::cout << "ERROR unknown format for device " << i_string << " rc = " << rc << std::endl; } else { o_hash |= ((0x07 & type) << 0); //0x00000007 o_hash |= ((0x3F & fsi) << 3); //0x000001F8 o_hash |= ((0x03 & cfam) << 9); //0x00000600 o_hash |= ((0x1F & engine) << 11); //0x0000F800 o_hash |= ((0x07 & subfsi) << 16); //0x00070000 o_hash |= ((0x03 & subcfam) << 19); //0x00180000 o_hash |= ((0x1F & subengine) << 21); //0x03E00000 o_hash |= ((0x07 & subsubfsi) << 26); //0x1C000000 o_hash |= ((0x03 & subsubcfam) << 29); //0x60000000 } return rc; } <|endoftext|>
<commit_before>#include "geodrawer_plugin.h" #include "geodrawer.h" #include <qqml.h> #include "geometries.h" #include "iooptions.h" #include "drawerfactory.h" #include "selectiondrawer.h" void GeodrawerPlugin::registerTypes(const char *uri) { // @uri n52.org.ilwisobjects qmlRegisterType<GeoDrawer>(uri, 1, 0, "GeoDrawer"); Ilwis::Geodrawer::DrawerFactory::registerDrawer("SelectionDrawer", Ilwis::Geodrawer::SelectionDrawer::create); } <commit_msg>renamed GeoDrawer to LayerView<commit_after>#include "geodrawer_plugin.h" #include "visualizationmanager.h" //#include "geodrawer.h" #include <qqml.h> #include "geometries.h" #include "iooptions.h" #include "drawerfactory.h" #include "selectiondrawer.h" #include "layersview.h" void GeodrawerPlugin::registerTypes(const char *uri) { // @uri n52.org.ilwisobjects qmlRegisterType<LayersView>(uri, 1, 0, "LayersView"); Ilwis::Geodrawer::DrawerFactory::registerDrawer("SelectionDrawer", Ilwis::Geodrawer::SelectionDrawer::create); } <|endoftext|>
<commit_before>/** @date 2015 @author Sensics, Inc. <http://sensics.com/osvr> */ // Copyright 2015 Vuzix Corporation. // // 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. // Internal Includes #include "DriverWrapper.h" #include "InterfaceTraits.h" #include "OSVRViveTracker.h" #include "PropertyHelper.h" #include <osvr/PluginKit/PluginKit.h> #include <osvr/Util/PlatformConfig.h> // Library/third-party includes #include <math.h> #include <openvr_driver.h> // Standard includes #include <chrono> #include <deque> #include <iostream> #include <memory> #include <mutex> #include <thread> #include <vector> // Anonymous namespace to avoid symbol collision namespace { static const auto PREFIX = "[OSVR-Vive] "; class HardwareDetection { public: HardwareDetection() {} OSVR_ReturnCode operator()(OSVR_PluginRegContext ctx) { if (m_driverHost) { // Already found a Vive. /// @todo what are the semantics of the return value from a hardware /// detect? return OSVR_RETURN_SUCCESS; } { osvr::vive::DriverHostPtr host(new osvr::vive::ViveDriverHost); auto vive = osvr::vive::DriverWrapper(host.get()); if (vive.foundDriver()) { std::cout << PREFIX << "Found the Vive driver at " << vive.getDriverFileLocation() << std::endl; } if (!vive.haveDriverLoaded()) { std::cout << PREFIX << "Could not open driver." << std::endl; return OSVR_RETURN_FAILURE; } if (vive.foundConfigDirs()) { std::cout << PREFIX << "Driver config dir is: " << vive.getDriverConfigDir() << std::endl; } if (!vive) { std::cerr << PREFIX << "Error in first-stage Vive driver startup. Exiting" << std::endl; return OSVR_RETURN_FAILURE; } if (!vive.isHMDPresent()) { std::cerr << PREFIX << "Driver loaded, but no Vive is connected. Exiting" << std::endl; return OSVR_RETURN_FAILURE; } std::cout << PREFIX << "Vive is connected." << std::endl; /// Hand the Vive object off to the OSVR driver. auto startResult = host->start(ctx, std::move(vive)); if (startResult) { /// and it started up the rest of the way just fine! /// We'll keep the driver around! m_driverHost = std::move(host); std::cout << PREFIX << "Vive driver finished startup successfully!" << std::endl; return OSVR_RETURN_SUCCESS; } } std::cout << PREFIX << "Vive driver startup failed somewhere, " "unloading to perhaps try again later." << std::endl; return OSVR_RETURN_FAILURE; } private: std::vector<std::string> m_deviceTypes; /// This is the OSVR driver object, which also serves as the "SteamVR" /// driver host. We can only run one Vive at a time. osvr::vive::DriverHostPtr m_driverHost; }; } // namespace OSVR_PLUGIN(com_osvr_Vive) { osvr::pluginkit::PluginContext context(ctx); /// Register a detection callback function object. context.registerHardwareDetectCallback(new HardwareDetection()); return OSVR_RETURN_SUCCESS; } <commit_msg>Adjust hardware detection so we don't unload the DLL so much, for faster detection callbacks.<commit_after>/** @date 2015 @author Sensics, Inc. <http://sensics.com/osvr> */ // Copyright 2015 Vuzix Corporation. // // 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. // Internal Includes #include "DriverWrapper.h" #include "InterfaceTraits.h" #include "OSVRViveTracker.h" #include "PropertyHelper.h" #include <osvr/PluginKit/PluginKit.h> #include <osvr/Util/PlatformConfig.h> // Library/third-party includes #include <math.h> #include <openvr_driver.h> // Standard includes #include <chrono> #include <deque> #include <iostream> #include <memory> #include <mutex> #include <thread> #include <vector> // Anonymous namespace to avoid symbol collision namespace { static const auto PREFIX = "[OSVR-Vive] "; class HardwareDetection { public: HardwareDetection() : m_inactiveDriverHost(new osvr::vive::ViveDriverHost) {} OSVR_ReturnCode operator()(OSVR_PluginRegContext ctx) { if (m_driverHost) { // Already found a Vive. /// @todo what are the semantics of the return value from a hardware /// detect? return OSVR_RETURN_SUCCESS; } if (!m_shouldAttemptDetection) { /// We said we shouldn't and wouldn't try again. return OSVR_RETURN_FAILURE; } auto vivePtr = startupAndGetVive(); if (!vivePtr) { /// There was trouble in early startup return OSVR_RETURN_FAILURE; } if (!vivePtr->isHMDPresent()) { /// Didn't detect anything - leave the driver DLL loaded, /// though, to make things faster next time around. /// Silent failure, to avoid annoying users. return OSVR_RETURN_FAILURE; } std::cout << PREFIX << "Vive is connected." << std::endl; /// Hand the Vive object off to the OSVR driver. auto startResult = finishViveStartup(ctx); if (startResult) { /// and it started up the rest of the way just fine! /// We'll keep the driver around! std::cout << PREFIX << "Vive driver finished startup successfully!" << std::endl; return OSVR_RETURN_SUCCESS; } std::cout << PREFIX << "Vive driver startup failed somewhere, " "unloading to perhaps try again later." << std::endl; unloadTemporaries(); return OSVR_RETURN_FAILURE; } bool finishViveStartup(OSVR_PluginRegContext ctx) { auto startResult = m_inactiveDriverHost->start(ctx, std::move(*m_viveWrapper)); m_viveWrapper.reset(); if (startResult) { m_driverHost = std::move(m_inactiveDriverHost); } return startResult; } /// Attempts the first part of startup, if required. osvr::vive::DriverWrapper *startupAndGetVive() { if (!m_viveWrapper) { m_viveWrapper.reset( new osvr::vive::DriverWrapper(&getInactiveHost())); if (m_viveWrapper->foundDriver()) { std::cout << PREFIX << "Found the Vive driver at " << m_viveWrapper->getDriverFileLocation() << std::endl; } if (!m_viveWrapper->haveDriverLoaded()) { std::cout << PREFIX << "Could not open driver." << std::endl; stopAttemptingDetection(); return nullptr; } if (m_viveWrapper->foundConfigDirs()) { std::cout << PREFIX << "Driver config dir is: " << m_viveWrapper->getDriverConfigDir() << std::endl; } if (!(*m_viveWrapper)) { std::cerr << PREFIX << "Error in first-stage Vive driver startup." << std::endl; m_viveWrapper.reset(); return nullptr; } } return m_viveWrapper.get(); } /// returns a reference because it will never be null. /// Creates one if needed. osvr::vive::ViveDriverHost &getInactiveHost() { if (m_driverHost) { throw std::logic_error("Can't get an inactive host - we already " "have a live device driver!"); } if (!m_inactiveDriverHost) { m_inactiveDriverHost.reset(new osvr::vive::ViveDriverHost); } return *m_inactiveDriverHost.get(); } void stopAttemptingDetection() { std::cerr << PREFIX << "Will not re-attempt detecting Vive." << std::endl; m_shouldAttemptDetection = false; unloadTemporaries(); m_driverHost.reset(); } void unloadTemporaries() { m_viveWrapper.reset(); m_inactiveDriverHost.reset(); } private: /// This is the OSVR driver object, which also serves as the "SteamVR" /// driver host. We can only run one Vive at a time. osvr::vive::DriverHostPtr m_driverHost; /// A Vive object that we hang on to if we don't have a fully-started-up /// device, to save time in hardware detection. std::unique_ptr<osvr::vive::DriverWrapper> m_viveWrapper; /// Populated only when we don't have an active driver - we keep it around /// so we don't have to re-load the full driver every time we get hit with a /// hardware detect request. osvr::vive::DriverHostPtr m_inactiveDriverHost; bool m_shouldAttemptDetection = true; }; } // namespace OSVR_PLUGIN(com_osvr_Vive) { osvr::pluginkit::PluginContext context(ctx); /// Register a detection callback function object. context.registerHardwareDetectCallback(new HardwareDetection()); return OSVR_RETURN_SUCCESS; } <|endoftext|>
<commit_before>/**************************************************************************** ** ** Copyright (C) 2008-2009 Nokia Corporation and/or its subsidiary(-ies). ** All rights reserved. ** Contact: Nokia Corporation (qt-info@nokia.com) ** ** This file is part of the Qt Script Generator project on Qt Labs. ** ** $QT_BEGIN_LICENSE:LGPL$ ** No Commercial Usage ** This file contains pre-release code and may not be distributed. ** You may use this file in accordance with the terms and conditions ** contained in the Technology Preview License Agreement accompanying ** this package. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Nokia gives you certain additional ** rights. These rights are described in the Nokia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ** If you have questions regarding the use of this file, please contact ** Nokia at qt-info@nokia.com. ** ** ** ** ** ** ** ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #include "shellgenerator.h" #include "reporthandler.h" #include "metaqtscript.h" bool ShellGenerator::shouldGenerate(const AbstractMetaClass *meta_class) const { uint cg = meta_class->typeEntry()->codeGeneration(); if (meta_class->name().startsWith("QtScript")) return false; if (meta_class->name().startsWith("QFuture")) return false; if (meta_class->name().startsWith("Global")) return false; if (meta_class->name().startsWith("QStyleOptionComplex")) return false; if (meta_class->name().startsWith("QTextLayout")) return false; //if (meta_class->name().startsWith("QTextStream")) return false; // because of >> operators //if (meta_class->name().startsWith("QDataStream")) return false; // " return ((cg & TypeEntry::GenerateCode) != 0); } void ShellGenerator::writeTypeInfo(QTextStream &s, const AbstractMetaType *type, Option options) { if ((options & OriginalTypeDescription) && !type->originalTypeDescription().isEmpty()) { s << type->originalTypeDescription(); return; } if (type->isArray()) { writeTypeInfo(s, type->arrayElementType(), options); if (options & ArrayAsPointer) { s << "*"; } else { s << "[" << type->arrayElementCount() << "]"; } return; } const TypeEntry *te = type->typeEntry(); if (type->isConstant() && !(options & ExcludeConst)) s << "const "; if ((options & EnumAsInts) && (te->isEnum() || te->isFlags())) { s << "int"; } else if (te->isFlags()) { s << ((FlagsTypeEntry *) te)->originalName(); } else { s << fixCppTypeName(te->qualifiedCppName()); } if (type->instantiations().size() > 0 && (!type->isContainer() || (static_cast<const ContainerTypeEntry *>(te))->type() != ContainerTypeEntry::StringListContainer)) { s << '<'; QList<AbstractMetaType *> args = type->instantiations(); bool nested_template = false; for (int i=0; i<args.size(); ++i) { if (i != 0) s << ", "; nested_template |= args.at(i)->isContainer(); writeTypeInfo(s, args.at(i)); } if (nested_template) s << ' '; s << '>'; } s << QString(type->indirections(), '*'); if (type->isReference() && !(options & ExcludeReference) && !(options & ConvertReferenceToPtr)) s << "&"; if (type->isReference() && (options & ConvertReferenceToPtr)) { s << "*"; } if (!(options & SkipName)) s << ' '; } void ShellGenerator::writeFunctionArguments(QTextStream &s, const AbstractMetaClass* owner, const AbstractMetaArgumentList &arguments, Option option, int numArguments) { if (numArguments < 0) numArguments = arguments.size(); for (int i=0; i<numArguments; ++i) { if (i != 0) s << ", "; AbstractMetaArgument *arg = arguments.at(i); writeTypeInfo(s, arg->type(), option); if (!(option & SkipName)) s << " " << arg->argumentName(); if ((option & IncludeDefaultExpression) && !arg->originalDefaultValueExpression().isEmpty()) { s << " = "; QString expr = arg->originalDefaultValueExpression(); if (expr != "0") { QString qualifier; if (arg->type()->typeEntry()->isEnum() && expr.indexOf("::") < 0) { qualifier = ((EnumTypeEntry *)arg->type()->typeEntry())->qualifier(); } else if (arg->type()->typeEntry()->isFlags() && expr.indexOf("::") < 0) { qualifier = ((FlagsTypeEntry *)arg->type()->typeEntry())->originator()->qualifier(); } if (!qualifier.isEmpty()) { s << qualifier << "::"; } } if (expr.contains("defaultConnection")) { expr.replace("defaultConnection","QSqlDatabase::defaultConnection"); } if (expr == "MediaSource()") { expr = "Phonon::MediaSource()"; } s << expr; } } } /*! * Writes the function \a meta_function signature to the textstream \a s. * * The \a name_prefix can be used to give the function name a prefix, * like "__public_" or "__override_" and \a classname_prefix can * be used to give the class name a prefix. * * The \a option flags can be used to tweak various parameters, such as * showing static, original vs renamed name, underscores for space etc. * * The \a extra_arguments list is a list of extra arguments on the * form "bool static_call". */ void ShellGenerator::writeFunctionSignature(QTextStream &s, const AbstractMetaFunction *meta_function, const AbstractMetaClass *implementor, const QString &name_prefix, Option option, const QString &classname_prefix, const QStringList &extra_arguments, int numArguments) { // ### remove the implementor AbstractMetaType *function_type = meta_function->type(); if ((option & SkipReturnType) == 0) { if (function_type) { writeTypeInfo(s, function_type, option); s << " "; } else if (!meta_function->isConstructor()) { s << "void "; } } if (implementor) { if (classname_prefix.isEmpty()) s << wrapperClassName(implementor) << "::"; else s << classname_prefix << implementor->name() << "::"; } QString function_name; if (option & OriginalName) function_name = meta_function->originalName(); else function_name = meta_function->name(); if (option & UnderscoreSpaces) function_name = function_name.replace(' ', '_'); if (meta_function->isConstructor()) function_name = meta_function->ownerClass()->name(); if (meta_function->isStatic() && (option & ShowStatic)) { function_name = "static_" + meta_function->ownerClass()->name() + "_" + function_name; } if (function_name.startsWith("operator")) { function_name = meta_function->name(); } s << name_prefix << function_name; if (meta_function->attributes() & AbstractMetaAttributes::SetterFunction) s << "_setter"; else if (meta_function->attributes() & AbstractMetaAttributes::GetterFunction) s << "_getter"; s << "("; if ((option & FirstArgIsWrappedObject) && meta_function->ownerClass() && !meta_function->isConstructor() && !meta_function->isStatic()) { s << meta_function->ownerClass()->qualifiedCppName() << "* theWrappedObject"; if (meta_function->arguments().size() != 0) { s << ", "; } } writeFunctionArguments(s, meta_function->ownerClass(), meta_function->arguments(), Option(option & Option(~ConvertReferenceToPtr)), numArguments); // The extra arguments... for (int i=0; i<extra_arguments.size(); ++i) { if (i > 0 || meta_function->arguments().size() != 0) s << ", "; s << extra_arguments.at(i); } s << ")"; if (meta_function->isConstant()) s << " const"; } AbstractMetaFunctionList ShellGenerator::getFunctionsToWrap(const AbstractMetaClass* meta_class) { AbstractMetaFunctionList functions = meta_class->queryFunctions( AbstractMetaClass::NormalFunctions | AbstractMetaClass::WasPublic | AbstractMetaClass::NotRemovedFromTargetLang | AbstractMetaClass::ClassImplements ); AbstractMetaFunctionList functions2 = meta_class->queryFunctions( AbstractMetaClass::VirtualFunctions | AbstractMetaClass::WasVisible | AbstractMetaClass::NotRemovedFromTargetLang | AbstractMetaClass::ClassImplements ); QSet<AbstractMetaFunction*> set1 = QSet<AbstractMetaFunction*>::fromList(functions); foreach(AbstractMetaFunction* func, functions2) { set1.insert(func); } AbstractMetaFunctionList resultFunctions; foreach(AbstractMetaFunction* func, set1.toList()) { if (!func->isAbstract() && func->implementingClass()==meta_class) { resultFunctions << func; } } return resultFunctions; } AbstractMetaFunctionList ShellGenerator::getVirtualFunctionsForShell(const AbstractMetaClass* meta_class) { AbstractMetaFunctionList functions = meta_class->queryFunctions( AbstractMetaClass::VirtualFunctions | AbstractMetaClass::WasVisible // | AbstractMetaClass::NotRemovedFromTargetLang ); return functions; } AbstractMetaFunctionList ShellGenerator::getProtectedFunctionsThatNeedPromotion(const AbstractMetaClass* meta_class) { AbstractMetaFunctionList functions; AbstractMetaFunctionList functions1 = getFunctionsToWrap(meta_class); foreach(AbstractMetaFunction* func, functions1) { if (!func->isPublic() || func->isVirtual()) { functions << func; } } return functions; } /*! Writes the include defined by \a inc to \a stream. */ void ShellGenerator::writeInclude(QTextStream &stream, const Include &inc) { if (inc.name.isEmpty()) return; if (inc.type == Include::TargetLangImport) return; stream << "#include "; if (inc.type == Include::IncludePath) stream << "<"; else stream << "\""; stream << inc.name; if (inc.type == Include::IncludePath) stream << ">"; else stream << "\""; stream << endl; } /*! Returns true if the given function \a fun is operator>>() or operator<<() that streams from/to a Q{Data,Text}Stream, false otherwise. */ bool ShellGenerator::isSpecialStreamingOperator(const AbstractMetaFunction *fun) { return ((fun->functionType() == AbstractMetaFunction::GlobalScopeFunction) && (fun->arguments().size() == 1) && (((fun->originalName() == "operator>>") && (fun->modifiedName() == "readFrom")) || ((fun->originalName() == "operator<<") && (fun->modifiedName() == "writeTo")))); } bool ShellGenerator::isBuiltIn(const QString& name) { static QSet<QString> builtIn; if (builtIn.isEmpty()) { builtIn.insert("Qt"); builtIn.insert("QFont"); builtIn.insert("QPixmap"); builtIn.insert("QBrush"); builtIn.insert("QBitArray"); builtIn.insert("QPalette"); builtIn.insert("QPen"); builtIn.insert("QIcon"); builtIn.insert("QImage"); builtIn.insert("QPolygon"); builtIn.insert("QRegion"); builtIn.insert("QBitmap"); builtIn.insert("QCursor"); builtIn.insert("QColor"); builtIn.insert("QSizePolicy"); builtIn.insert("QKeySequence"); builtIn.insert("QTextLength"); builtIn.insert("QTextFormat"); builtIn.insert("QMatrix"); builtIn.insert("QDate"); builtIn.insert("QTime"); builtIn.insert("QDateTime"); builtIn.insert("QUrl"); builtIn.insert("QLocale"); builtIn.insert("QRect"); builtIn.insert("QRectF"); builtIn.insert("QSize"); builtIn.insert("QSizeF"); builtIn.insert("QLine"); builtIn.insert("QLineF"); builtIn.insert("QPoint"); builtIn.insert("QPointF"); builtIn.insert("QRegExp"); } return builtIn.contains(name); } <commit_msg>added alphabetic sorting<commit_after>/**************************************************************************** ** ** Copyright (C) 2008-2009 Nokia Corporation and/or its subsidiary(-ies). ** All rights reserved. ** Contact: Nokia Corporation (qt-info@nokia.com) ** ** This file is part of the Qt Script Generator project on Qt Labs. ** ** $QT_BEGIN_LICENSE:LGPL$ ** No Commercial Usage ** This file contains pre-release code and may not be distributed. ** You may use this file in accordance with the terms and conditions ** contained in the Technology Preview License Agreement accompanying ** this package. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Nokia gives you certain additional ** rights. These rights are described in the Nokia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ** If you have questions regarding the use of this file, please contact ** Nokia at qt-info@nokia.com. ** ** ** ** ** ** ** ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #include "shellgenerator.h" #include "reporthandler.h" #include "metaqtscript.h" bool ShellGenerator::shouldGenerate(const AbstractMetaClass *meta_class) const { uint cg = meta_class->typeEntry()->codeGeneration(); if (meta_class->name().startsWith("QtScript")) return false; if (meta_class->name().startsWith("QFuture")) return false; if (meta_class->name().startsWith("Global")) return false; if (meta_class->name().startsWith("QStyleOptionComplex")) return false; if (meta_class->name().startsWith("QTextLayout")) return false; //if (meta_class->name().startsWith("QTextStream")) return false; // because of >> operators //if (meta_class->name().startsWith("QDataStream")) return false; // " return ((cg & TypeEntry::GenerateCode) != 0); } void ShellGenerator::writeTypeInfo(QTextStream &s, const AbstractMetaType *type, Option options) { if ((options & OriginalTypeDescription) && !type->originalTypeDescription().isEmpty()) { s << type->originalTypeDescription(); return; } if (type->isArray()) { writeTypeInfo(s, type->arrayElementType(), options); if (options & ArrayAsPointer) { s << "*"; } else { s << "[" << type->arrayElementCount() << "]"; } return; } const TypeEntry *te = type->typeEntry(); if (type->isConstant() && !(options & ExcludeConst)) s << "const "; if ((options & EnumAsInts) && (te->isEnum() || te->isFlags())) { s << "int"; } else if (te->isFlags()) { s << ((FlagsTypeEntry *) te)->originalName(); } else { s << fixCppTypeName(te->qualifiedCppName()); } if (type->instantiations().size() > 0 && (!type->isContainer() || (static_cast<const ContainerTypeEntry *>(te))->type() != ContainerTypeEntry::StringListContainer)) { s << '<'; QList<AbstractMetaType *> args = type->instantiations(); bool nested_template = false; for (int i=0; i<args.size(); ++i) { if (i != 0) s << ", "; nested_template |= args.at(i)->isContainer(); writeTypeInfo(s, args.at(i)); } if (nested_template) s << ' '; s << '>'; } s << QString(type->indirections(), '*'); if (type->isReference() && !(options & ExcludeReference) && !(options & ConvertReferenceToPtr)) s << "&"; if (type->isReference() && (options & ConvertReferenceToPtr)) { s << "*"; } if (!(options & SkipName)) s << ' '; } void ShellGenerator::writeFunctionArguments(QTextStream &s, const AbstractMetaClass* owner, const AbstractMetaArgumentList &arguments, Option option, int numArguments) { if (numArguments < 0) numArguments = arguments.size(); for (int i=0; i<numArguments; ++i) { if (i != 0) s << ", "; AbstractMetaArgument *arg = arguments.at(i); writeTypeInfo(s, arg->type(), option); if (!(option & SkipName)) s << " " << arg->argumentName(); if ((option & IncludeDefaultExpression) && !arg->originalDefaultValueExpression().isEmpty()) { s << " = "; QString expr = arg->originalDefaultValueExpression(); if (expr != "0") { QString qualifier; if (arg->type()->typeEntry()->isEnum() && expr.indexOf("::") < 0) { qualifier = ((EnumTypeEntry *)arg->type()->typeEntry())->qualifier(); } else if (arg->type()->typeEntry()->isFlags() && expr.indexOf("::") < 0) { qualifier = ((FlagsTypeEntry *)arg->type()->typeEntry())->originator()->qualifier(); } if (!qualifier.isEmpty()) { s << qualifier << "::"; } } if (expr.contains("defaultConnection")) { expr.replace("defaultConnection","QSqlDatabase::defaultConnection"); } if (expr == "MediaSource()") { expr = "Phonon::MediaSource()"; } s << expr; } } } /*! * Writes the function \a meta_function signature to the textstream \a s. * * The \a name_prefix can be used to give the function name a prefix, * like "__public_" or "__override_" and \a classname_prefix can * be used to give the class name a prefix. * * The \a option flags can be used to tweak various parameters, such as * showing static, original vs renamed name, underscores for space etc. * * The \a extra_arguments list is a list of extra arguments on the * form "bool static_call". */ void ShellGenerator::writeFunctionSignature(QTextStream &s, const AbstractMetaFunction *meta_function, const AbstractMetaClass *implementor, const QString &name_prefix, Option option, const QString &classname_prefix, const QStringList &extra_arguments, int numArguments) { // ### remove the implementor AbstractMetaType *function_type = meta_function->type(); if ((option & SkipReturnType) == 0) { if (function_type) { writeTypeInfo(s, function_type, option); s << " "; } else if (!meta_function->isConstructor()) { s << "void "; } } if (implementor) { if (classname_prefix.isEmpty()) s << wrapperClassName(implementor) << "::"; else s << classname_prefix << implementor->name() << "::"; } QString function_name; if (option & OriginalName) function_name = meta_function->originalName(); else function_name = meta_function->name(); if (option & UnderscoreSpaces) function_name = function_name.replace(' ', '_'); if (meta_function->isConstructor()) function_name = meta_function->ownerClass()->name(); if (meta_function->isStatic() && (option & ShowStatic)) { function_name = "static_" + meta_function->ownerClass()->name() + "_" + function_name; } if (function_name.startsWith("operator")) { function_name = meta_function->name(); } s << name_prefix << function_name; if (meta_function->attributes() & AbstractMetaAttributes::SetterFunction) s << "_setter"; else if (meta_function->attributes() & AbstractMetaAttributes::GetterFunction) s << "_getter"; s << "("; if ((option & FirstArgIsWrappedObject) && meta_function->ownerClass() && !meta_function->isConstructor() && !meta_function->isStatic()) { s << meta_function->ownerClass()->qualifiedCppName() << "* theWrappedObject"; if (meta_function->arguments().size() != 0) { s << ", "; } } writeFunctionArguments(s, meta_function->ownerClass(), meta_function->arguments(), Option(option & Option(~ConvertReferenceToPtr)), numArguments); // The extra arguments... for (int i=0; i<extra_arguments.size(); ++i) { if (i > 0 || meta_function->arguments().size() != 0) s << ", "; s << extra_arguments.at(i); } s << ")"; if (meta_function->isConstant()) s << " const"; } AbstractMetaFunctionList ShellGenerator::getFunctionsToWrap(const AbstractMetaClass* meta_class) { AbstractMetaFunctionList functions = meta_class->queryFunctions( AbstractMetaClass::NormalFunctions | AbstractMetaClass::WasPublic | AbstractMetaClass::NotRemovedFromTargetLang | AbstractMetaClass::ClassImplements ); AbstractMetaFunctionList functions2 = meta_class->queryFunctions( AbstractMetaClass::VirtualFunctions | AbstractMetaClass::WasVisible | AbstractMetaClass::NotRemovedFromTargetLang | AbstractMetaClass::ClassImplements ); QSet<AbstractMetaFunction*> set1 = QSet<AbstractMetaFunction*>::fromList(functions); foreach(AbstractMetaFunction* func, functions2) { set1.insert(func); } AbstractMetaFunctionList resultFunctions; foreach(AbstractMetaFunction* func, set1.toList()) { if (!func->isAbstract() && func->implementingClass()==meta_class) { resultFunctions << func; } } qStableSort(resultFunctions); return resultFunctions; } AbstractMetaFunctionList ShellGenerator::getVirtualFunctionsForShell(const AbstractMetaClass* meta_class) { AbstractMetaFunctionList functions = meta_class->queryFunctions( AbstractMetaClass::VirtualFunctions | AbstractMetaClass::WasVisible // | AbstractMetaClass::NotRemovedFromTargetLang ); qStableSort(functions); return functions; } AbstractMetaFunctionList ShellGenerator::getProtectedFunctionsThatNeedPromotion(const AbstractMetaClass* meta_class) { AbstractMetaFunctionList functions; AbstractMetaFunctionList functions1 = getFunctionsToWrap(meta_class); foreach(AbstractMetaFunction* func, functions1) { if (!func->isPublic() || func->isVirtual()) { functions << func; } } qStableSort(functions); return functions; } /*! Writes the include defined by \a inc to \a stream. */ void ShellGenerator::writeInclude(QTextStream &stream, const Include &inc) { if (inc.name.isEmpty()) return; if (inc.type == Include::TargetLangImport) return; stream << "#include "; if (inc.type == Include::IncludePath) stream << "<"; else stream << "\""; stream << inc.name; if (inc.type == Include::IncludePath) stream << ">"; else stream << "\""; stream << endl; } /*! Returns true if the given function \a fun is operator>>() or operator<<() that streams from/to a Q{Data,Text}Stream, false otherwise. */ bool ShellGenerator::isSpecialStreamingOperator(const AbstractMetaFunction *fun) { return ((fun->functionType() == AbstractMetaFunction::GlobalScopeFunction) && (fun->arguments().size() == 1) && (((fun->originalName() == "operator>>") && (fun->modifiedName() == "readFrom")) || ((fun->originalName() == "operator<<") && (fun->modifiedName() == "writeTo")))); } bool ShellGenerator::isBuiltIn(const QString& name) { static QSet<QString> builtIn; if (builtIn.isEmpty()) { builtIn.insert("Qt"); builtIn.insert("QFont"); builtIn.insert("QPixmap"); builtIn.insert("QBrush"); builtIn.insert("QBitArray"); builtIn.insert("QPalette"); builtIn.insert("QPen"); builtIn.insert("QIcon"); builtIn.insert("QImage"); builtIn.insert("QPolygon"); builtIn.insert("QRegion"); builtIn.insert("QBitmap"); builtIn.insert("QCursor"); builtIn.insert("QColor"); builtIn.insert("QSizePolicy"); builtIn.insert("QKeySequence"); builtIn.insert("QTextLength"); builtIn.insert("QTextFormat"); builtIn.insert("QMatrix"); builtIn.insert("QDate"); builtIn.insert("QTime"); builtIn.insert("QDateTime"); builtIn.insert("QUrl"); builtIn.insert("QLocale"); builtIn.insert("QRect"); builtIn.insert("QRectF"); builtIn.insert("QSize"); builtIn.insert("QSizeF"); builtIn.insert("QLine"); builtIn.insert("QLineF"); builtIn.insert("QPoint"); builtIn.insert("QPointF"); builtIn.insert("QRegExp"); } return builtIn.contains(name); } <|endoftext|>
<commit_before><commit_msg>Add the initial template of the first part of question 3.7<commit_after><|endoftext|>
<commit_before>#include "Logging.h" #include "WebInterface.h" #include <string.h> #include <stdio.h> #include <list> #include <sstream> #include "JSON.h" #include <stdlib.h> using namespace Dumais::WebServer; WebInterface::WebInterface(int port,RESTInterface *pRESTInterface, WebNotificationEngine *pWebNotificationEngine) { mpRESTInterface = pRESTInterface; // mpWebNotificationEngine = pWebNotificationEngine; mPort = port; mpWebServer = 0; mpThread = 0; } WebInterface::~WebInterface() { if (mpWebServer) delete mpWebServer; mpWebServer = 0; } void WebInterface::configure(Dumais::JSON::JSON& config) { this->mPasswdFile = config["passwd"].str(); } void WebInterface::stop() { if (mpWebServer) { Logging::log("Attempting to shutdown Web server"); mpWebServer->stop(); } if (mpThread) mpThread->join(); } void WebInterface::onConnectionOpen() { // Logging::log("WebInterface::onConnectionOpen(%i)",sock); if (mpWebServer->getConnectionCount()>10) Logging::log("WARNING: There are %i connections opened on web server",mpWebServer->getConnectionCount()); } void WebInterface::onConnectionClosed() { // Logging::log("WebInterface::onConnectionClosed(%i)",sock); // mpWebNotificationEngine->unsubscribe(sock); } void WebInterface::onResponseSent() { // mpWebNotificationEngine->activateSubscription(sock); } HTTPResponse* WebInterface::processHTTPRequest(HTTPRequest* request) { HTTPResponse *resp; Dumais::JSON::JSON json; std::string method = request->getMethod(); if (method != "GET") { resp = HTTPProtocol::buildBufferedResponse(NotImplemented,"",""); } else { std::string url = request->getURL(); // We will not support SSE anymore because we don't use it. I removed // the code from dumaislib to support persistant connections. There is a backup // in a "backup-server-sent-events" folder with that code /*if (request->accepts("text/event-stream") && url=="/subscribe") { mpWebNotificationEngine->subscribe(id); resp = HTTPProtocol::buildBufferedResponse(OK,"","text/event-stream","keep-alive","chunked"); } else {*/ std::string responseType = "application/json"; bool queryProcessed = mpRESTInterface->processQuery(json,url); if (queryProcessed) { resp = HTTPProtocol::buildBufferedResponse(OK,json.stringify(false),responseType); } else { resp = HTTPProtocol::buildBufferedResponse(NotFound,"",""); } //} } return resp; } // This server accepts one connection at a time only. So sockets are blocking void WebInterface::start() { mpWebServer = new WebServer(mPort, "0.0.0.0",100); mpWebServer->requireAuth(this->mPasswdFile.c_str(), 10); mpWebServer->setListener(this); this->mpWebServer->start(); } <commit_msg>added logging for web server<commit_after>#include "Logging.h" #include "WebInterface.h" #include <string.h> #include <stdio.h> #include <list> #include <sstream> #include "JSON.h" #include <stdlib.h> #include "WebServerLogging.h" using namespace Dumais::WebServer; class WebServerInterfaceLogger: public Dumais::WebServer::IWebServerLogger { virtual void log(const std::string& ss) { Logging::log("%s",ss.c_str()); } }; WebInterface::WebInterface(int port,RESTInterface *pRESTInterface, WebNotificationEngine *pWebNotificationEngine) { mpRESTInterface = pRESTInterface; Dumais::WebServer::WebServerLogging::logger = new WebServerInterfaceLogger(); // mpWebNotificationEngine = pWebNotificationEngine; mPort = port; mpWebServer = 0; mpThread = 0; } WebInterface::~WebInterface() { if (mpWebServer) delete mpWebServer; mpWebServer = 0; } void WebInterface::configure(Dumais::JSON::JSON& config) { this->mPasswdFile = config["passwd"].str(); } void WebInterface::stop() { if (mpWebServer) { Logging::log("Attempting to shutdown Web server"); mpWebServer->stop(); } if (mpThread) mpThread->join(); } void WebInterface::onConnectionOpen() { // Logging::log("WebInterface::onConnectionOpen(%i)",sock); if (mpWebServer->getConnectionCount()>10) Logging::log("WARNING: There are %i connections opened on web server",mpWebServer->getConnectionCount()); } void WebInterface::onConnectionClosed() { // Logging::log("WebInterface::onConnectionClosed(%i)",sock); // mpWebNotificationEngine->unsubscribe(sock); } void WebInterface::onResponseSent() { // mpWebNotificationEngine->activateSubscription(sock); } HTTPResponse* WebInterface::processHTTPRequest(HTTPRequest* request) { HTTPResponse *resp; Dumais::JSON::JSON json; std::string method = request->getMethod(); if (method != "GET") { resp = HTTPProtocol::buildBufferedResponse(NotImplemented,"",""); } else { std::string url = request->getURL(); // We will not support SSE anymore because we don't use it. I removed // the code from dumaislib to support persistant connections. There is a backup // in a "backup-server-sent-events" folder with that code /*if (request->accepts("text/event-stream") && url=="/subscribe") { mpWebNotificationEngine->subscribe(id); resp = HTTPProtocol::buildBufferedResponse(OK,"","text/event-stream","keep-alive","chunked"); } else {*/ std::string responseType = "application/json"; bool queryProcessed = mpRESTInterface->processQuery(json,url); if (queryProcessed) { resp = HTTPProtocol::buildBufferedResponse(OK,json.stringify(false),responseType); } else { resp = HTTPProtocol::buildBufferedResponse(NotFound,"",""); } //} } return resp; } // This server accepts one connection at a time only. So sockets are blocking void WebInterface::start() { mpWebServer = new WebServer(mPort, "0.0.0.0",100); mpWebServer->requireAuth(this->mPasswdFile.c_str(), 10); mpWebServer->setListener(this); this->mpWebServer->start(); } <|endoftext|>
<commit_before>/* Copyright (c) 2016, the Cap authors. * * This file is subject to the Modified BSD License and may not be distributed * without copyright and license information. Please refer to the file LICENSE * for the text and further information on this license. */ #define BOOST_TEST_MODULE EnergyStorageDevice #include "main.cc" #include <cap/energy_storage_device.h> #include <cap/resistor_capacitor.h> #include <boost/test/unit_test.hpp> #include <boost/property_tree/ptree.hpp> #include <boost/property_tree/info_parser.hpp> #include <boost/archive/text_iarchive.hpp> #include <boost/archive/text_oarchive.hpp> #include <boost/serialization/shared_ptr.hpp> #include <boost/serialization/export.hpp> #include <boost/mpi/communicator.hpp> #include <sstream> // list of valid inputs to build an EnergyStorageDevice // These are meant as example std::list<std::string> const valid_device_input = { "series_rc.info", "parallel_rc.info", #ifdef WITH_DEAL_II "super_capacitor.info", #endif }; BOOST_AUTO_TEST_CASE(test_energy_storage_device_builders) { boost::mpi::communicator world; int const size = world.size(); int const rank = world.rank(); std::cout << "hello world from rank " << rank << " of size " << size << "\n"; for (auto const &filename : valid_device_input) { boost::property_tree::ptree ptree; boost::property_tree::info_parser::read_info(filename, ptree); BOOST_CHECK_NO_THROW(cap::EnergyStorageDevice::build(world, ptree)); } // invalid type must throw an exception boost::property_tree::ptree ptree; ptree.put("type", "InvalidDeviceType"); BOOST_CHECK_THROW(cap::EnergyStorageDevice::build(world, ptree), std::runtime_error); } class ExampleInspector : public cap::EnergyStorageDeviceInspector { public: // get the device type and set the voltage to 1.4 volt void inspect(cap::EnergyStorageDevice *device) { // use dynamic_cast to find out the actual type if (dynamic_cast<cap::SeriesRC *>(device) != nullptr) _type = "SeriesRC"; else if (dynamic_cast<cap::ParallelRC *>(device) != nullptr) _type = "ParallelRC"; else throw std::runtime_error("not an equivalent circuit model"); // if we make ExampleInspector friend of the derived // class for the EnergyStorageDevice we could virtually // do anything device->evolve_one_time_step_constant_voltage(1.0, 1.4); } // the type of the device last inspected std::string _type; }; BOOST_AUTO_TEST_CASE(test_energy_storage_device_inspectors) { std::string const filename = "series_rc.info"; boost::mpi::communicator world; boost::property_tree::ptree ptree; boost::property_tree::info_parser::read_info(filename, ptree); auto device = cap::EnergyStorageDevice::build(world, ptree); double voltage; device->get_voltage(voltage); BOOST_TEST(voltage != 1.4); ExampleInspector inspector; device->inspect(&inspector); BOOST_TEST((inspector._type).compare("SeriesRC") == 0); device->get_voltage(voltage); BOOST_TEST(voltage == 1.4); } // TODO: won't work for SuperCapacitor #ifdef WITH_DEAL_II BOOST_AUTO_TEST_CASE_EXPECTED_FAILURES(test_serialization, 1) #endif BOOST_AUTO_TEST_CASE(test_serialization) { for (auto const &filename : valid_device_input) { boost::property_tree::ptree ptree; boost::property_tree::info_parser::read_info(filename, ptree); std::shared_ptr<cap::EnergyStorageDevice> original_device = cap::EnergyStorageDevice::build(boost::mpi::communicator(), ptree); original_device->evolve_one_time_step_constant_voltage(0.1, 2.1); double original_voltage; double original_current; original_device->get_voltage(original_voltage); original_device->get_current(original_current); try { std::stringstream ss; // save device boost::archive::text_oarchive oa(ss); oa.register_type<cap::SeriesRC>(); oa.register_type<cap::ParallelRC>(); oa << original_device; // print the content of the stream to the screen std::cout << ss.str() << "\n"; BOOST_CHECK(!ss.str().empty()); // restore device boost::archive::text_iarchive ia(ss); ia.register_type<cap::SeriesRC>(); ia.register_type<cap::ParallelRC>(); std::shared_ptr<cap::EnergyStorageDevice> restored_device; ia >> restored_device; double restored_voltage; double restored_current; restored_device->get_voltage(restored_voltage); restored_device->get_current(restored_current); BOOST_CHECK_EQUAL(original_voltage, restored_voltage); BOOST_CHECK_EQUAL(original_current, restored_current); } catch (boost::archive::archive_exception e) { BOOST_TEST_MESSAGE("unable to serialize the device"); BOOST_TEST(false); } catch (...) { throw std::runtime_error("unexpected exception occured"); } } } <commit_msg>Improve test_energy_storage_device.<commit_after>/* Copyright (c) 2016, the Cap authors. * * This file is subject to the Modified BSD License and may not be distributed * without copyright and license information. Please refer to the file LICENSE * for the text and further information on this license. */ #define BOOST_TEST_MODULE EnergyStorageDevice #include "main.cc" #include <cap/energy_storage_device.h> #include <cap/resistor_capacitor.h> #include <boost/test/unit_test.hpp> #include <boost/property_tree/ptree.hpp> #include <boost/property_tree/info_parser.hpp> #include <boost/archive/text_iarchive.hpp> #include <boost/archive/text_oarchive.hpp> #include <boost/serialization/shared_ptr.hpp> #include <boost/serialization/export.hpp> #include <boost/mpi/communicator.hpp> #include <sstream> // list of valid inputs to build an EnergyStorageDevice // These are meant as example std::list<std::string> const valid_device_input = { "series_rc.info", "parallel_rc.info", #ifdef WITH_DEAL_II "super_capacitor.info", #endif }; BOOST_AUTO_TEST_CASE(test_energy_storage_device_builders) { boost::mpi::communicator world; int const size = world.size(); int const rank = world.rank(); std::cout << "hello world from rank " << rank << " of size " << size << "\n"; for (auto const &filename : valid_device_input) { boost::property_tree::ptree ptree; boost::property_tree::info_parser::read_info(filename, ptree); BOOST_CHECK_NO_THROW(cap::EnergyStorageDevice::build(world, ptree)); } // invalid type must throw an exception boost::property_tree::ptree ptree; ptree.put("type", "InvalidDeviceType"); BOOST_CHECK_THROW(cap::EnergyStorageDevice::build(world, ptree), std::runtime_error); } class ExampleInspector : public cap::EnergyStorageDeviceInspector { public: // get the device type and set the voltage to 1.4 volt void inspect(cap::EnergyStorageDevice *device) { // use dynamic_cast to find out the actual type if (dynamic_cast<cap::SeriesRC *>(device) != nullptr) _type = "SeriesRC"; else if (dynamic_cast<cap::ParallelRC *>(device) != nullptr) _type = "ParallelRC"; else throw std::runtime_error("not an equivalent circuit model"); // if we make ExampleInspector friend of the derived // class for the EnergyStorageDevice we could virtually // do anything device->evolve_one_time_step_constant_voltage(1.0, 1.4); } // the type of the device last inspected std::string _type; }; BOOST_AUTO_TEST_CASE(test_energy_storage_device_inspectors) { std::vector<std::string> filename(2); filename[0] = "series_rc.info"; filename[1] = "parallel_rc.info"; std::vector<std::string> RC_type(2); RC_type[0] = "SeriesRC"; RC_type[1] = "ParallelRC"; for (unsigned int i = 0; i < 2; ++i) { boost::mpi::communicator world; boost::property_tree::ptree ptree; boost::property_tree::info_parser::read_info(filename[i], ptree); auto device = cap::EnergyStorageDevice::build(world, ptree); double voltage; device->get_voltage(voltage); BOOST_TEST(voltage != 1.4); ExampleInspector inspector; device->inspect(&inspector); BOOST_TEST((inspector._type).compare(RC_type[i]) == 0); device->get_voltage(voltage); BOOST_TEST(voltage == 1.4); } } // TODO: won't work for SuperCapacitor #ifdef WITH_DEAL_II BOOST_AUTO_TEST_CASE_EXPECTED_FAILURES(test_serialization, 1) #endif BOOST_AUTO_TEST_CASE(test_serialization) { for (auto const &filename : valid_device_input) { boost::property_tree::ptree ptree; boost::property_tree::info_parser::read_info(filename, ptree); std::shared_ptr<cap::EnergyStorageDevice> original_device = cap::EnergyStorageDevice::build(boost::mpi::communicator(), ptree); original_device->evolve_one_time_step_constant_voltage(0.1, 2.1); double original_voltage; double original_current; original_device->get_voltage(original_voltage); original_device->get_current(original_current); try { std::stringstream ss; // save device boost::archive::text_oarchive oa(ss); oa.register_type<cap::SeriesRC>(); oa.register_type<cap::ParallelRC>(); oa << original_device; // print the content of the stream to the screen std::cout << ss.str() << "\n"; BOOST_CHECK(!ss.str().empty()); // restore device boost::archive::text_iarchive ia(ss); ia.register_type<cap::SeriesRC>(); ia.register_type<cap::ParallelRC>(); std::shared_ptr<cap::EnergyStorageDevice> restored_device; ia >> restored_device; double restored_voltage; double restored_current; restored_device->get_voltage(restored_voltage); restored_device->get_current(restored_current); BOOST_CHECK_EQUAL(original_voltage, restored_voltage); BOOST_CHECK_EQUAL(original_current, restored_current); } catch (boost::archive::archive_exception e) { BOOST_TEST_MESSAGE("unable to serialize the device"); BOOST_TEST(false); } catch (...) { throw std::runtime_error("unexpected exception occured"); } } } <|endoftext|>
<commit_before>/* * Copyright (c) 2010-2016, MIT Probabilistic Computing Project * * Lead Developers: Dan Lovell and Jay Baxter * Authors: Dan Lovell, Baxter Eaves, Jay Baxter, Vikash Mansinghka * Research Leads: Vikash Mansinghka, Patrick Shafto * * 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. */ #define __STDC_CONSTANT_MACROS // Make <stdint.h> define UINT64_C &c. #include <algorithm> #include <cassert> #include <cmath> #include <stdint.h> #include "RandomNumberGenerator.h" static inline unsigned bitcount64(uint64_t x) { // Count two-bit groups. x -= ((x >> 1) & UINT64_C(0x5555555555555555)); // Add to four-bit groups, carefully masking carries and garbage. x = ((x >> 2) & UINT64_C(0x3333333333333333)) + (x & UINT64_C(0x3333333333333333)); // Add to eight-bit groups. x = (((x >> 4) + x) & UINT64_C(0x0f0f0f0f0f0f0f0f)); // Add all eight-bit groups in the leftmost column of a multiply. // Bit counts are small enough no other columns will carry. return (x * UINT64_C(0x0101010101010101)) >> 56; } static inline unsigned clz64(uint64_t x) { // Round up to a power of two minus one. x |= x >> 1; x |= x >> 2; x |= x >> 4; x |= x >> 8; x |= x >> 16; x |= x >> 32; // Count the bits thus set, and subtract from 64 to count leading // zeros. return 64 - bitcount64(x); } ////////////////////////////////// // return a random real between // 0 and 1 with uniform dist double RandomNumberGenerator::next() { int e = -64; uint64_t s; unsigned d; // Draw a significand from an infinite stream of bits. while ((s = crypto_weakprng_64(&_weakprng)) == 0) { e -= 64; // Just return zero if the exponent is so small there are no // floating-point numbers that tiny. if (e < -1074) return 0; } // Shift leading zeros into the exponent and fill trailing bits of // significand uniformly at random. if ((d = clz64(s)) != 0) { e -= d; s <<= d; s |= crypto_weakprng_64(&_weakprng) >> (64 - d); } // Set sticky bit, since there is (almost surely) another 1 in the // bit stream, to avoid a bias toward `even'. s |= 1; // Return s * 2^e. return ldexp(static_cast<double>(s), e); } ////////////////////////////// // return a random int bewteen // zero and max - 1 with uniform // dist if called with same max int RandomNumberGenerator::nexti(int bound) { assert(0 < bound); return crypto_weakprng_below(&_weakprng, bound); } ///////////////////////////// // standard normal samples // via Box-Muller transform double RandomNumberGenerator::stdnormal() { double u, v; u = next(); v = next(); return sqrt(-2*log(u)) * sin(2*M_PI*v); } ///////////////////////////// // standard Gamma samples // // George Marsaglia & Wai Wan Tsang, `A simple method for // generating gamma variables', ACM Transactions on Mathematical // Software 26(3), September 2000. DOI: 10.1145/358407.358414 // URI: https://dl.acm.org/citation.cfm?doid=358407.358414 double RandomNumberGenerator::stdgamma(double alpha) { const double d = alpha - (double)1/3; const double c = 1/sqrt(9*d); double x, u, v; assert(1 <= alpha); for (;;) { x = stdnormal(); v = 1 + x*c; if (v <= 0) continue; v = v*v*v; u = next(); if (u < 1 - 0.0331*((x*x)*(x*x)) || log(u) < x*x/2 + d - d*v + d*log(v)) return d*v; } } ///////////////////////////// // chi^2 samples double RandomNumberGenerator::chisquare(double nu) { double shape = nu/2; double scale = 2; return scale*stdgamma(shape); } ///////////////////////////// // Student's t-distribution samples double RandomNumberGenerator::student_t(double nu) { return stdnormal() * sqrt(nu/chisquare(nu)); } ///////////////////////////// // control the seed void RandomNumberGenerator::set_seed(std::time_t seed) { uint8_t seedbuf[crypto_weakprng_SEEDBYTES] = {0}; size_t i; for (i = 0; i < std::min(sizeof seedbuf, sizeof seed); i++) seedbuf[i] = seed >> (8*i); crypto_weakprng_seed(&_weakprng, seedbuf); } <commit_msg>Prophylactically grab the alpha boosting note from Marsaglia and Tsang.<commit_after>/* * Copyright (c) 2010-2016, MIT Probabilistic Computing Project * * Lead Developers: Dan Lovell and Jay Baxter * Authors: Dan Lovell, Baxter Eaves, Jay Baxter, Vikash Mansinghka * Research Leads: Vikash Mansinghka, Patrick Shafto * * 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. */ #define __STDC_CONSTANT_MACROS // Make <stdint.h> define UINT64_C &c. #include <algorithm> #include <cassert> #include <cmath> #include <stdint.h> #include "RandomNumberGenerator.h" static inline unsigned bitcount64(uint64_t x) { // Count two-bit groups. x -= ((x >> 1) & UINT64_C(0x5555555555555555)); // Add to four-bit groups, carefully masking carries and garbage. x = ((x >> 2) & UINT64_C(0x3333333333333333)) + (x & UINT64_C(0x3333333333333333)); // Add to eight-bit groups. x = (((x >> 4) + x) & UINT64_C(0x0f0f0f0f0f0f0f0f)); // Add all eight-bit groups in the leftmost column of a multiply. // Bit counts are small enough no other columns will carry. return (x * UINT64_C(0x0101010101010101)) >> 56; } static inline unsigned clz64(uint64_t x) { // Round up to a power of two minus one. x |= x >> 1; x |= x >> 2; x |= x >> 4; x |= x >> 8; x |= x >> 16; x |= x >> 32; // Count the bits thus set, and subtract from 64 to count leading // zeros. return 64 - bitcount64(x); } ////////////////////////////////// // return a random real between // 0 and 1 with uniform dist double RandomNumberGenerator::next() { int e = -64; uint64_t s; unsigned d; // Draw a significand from an infinite stream of bits. while ((s = crypto_weakprng_64(&_weakprng)) == 0) { e -= 64; // Just return zero if the exponent is so small there are no // floating-point numbers that tiny. if (e < -1074) return 0; } // Shift leading zeros into the exponent and fill trailing bits of // significand uniformly at random. if ((d = clz64(s)) != 0) { e -= d; s <<= d; s |= crypto_weakprng_64(&_weakprng) >> (64 - d); } // Set sticky bit, since there is (almost surely) another 1 in the // bit stream, to avoid a bias toward `even'. s |= 1; // Return s * 2^e. return ldexp(static_cast<double>(s), e); } ////////////////////////////// // return a random int bewteen // zero and max - 1 with uniform // dist if called with same max int RandomNumberGenerator::nexti(int bound) { assert(0 < bound); return crypto_weakprng_below(&_weakprng, bound); } ///////////////////////////// // standard normal samples // via Box-Muller transform double RandomNumberGenerator::stdnormal() { double u, v; u = next(); v = next(); return sqrt(-2*log(u)) * sin(2*M_PI*v); } ///////////////////////////// // standard Gamma samples // // George Marsaglia & Wai Wan Tsang, `A simple method for // generating gamma variables', ACM Transactions on Mathematical // Software 26(3), September 2000. DOI: 10.1145/358407.358414 // URI: https://dl.acm.org/citation.cfm?doid=358407.358414 double RandomNumberGenerator::stdgamma(double alpha) { const double d = alpha - (double)1/3; const double c = 1/sqrt(9*d); double x, u, v; // The clients currently do not need alpha < 1. Should they, the // reference contains a note (at the end of Section 6) on how to // boost the alpha parameter: // stdgamma(alpha) = stdgamma(alpha+1) * (uniform() ** (1/alpha)) assert(1 <= alpha); for (;;) { x = stdnormal(); v = 1 + x*c; if (v <= 0) continue; v = v*v*v; u = next(); if (u < 1 - 0.0331*((x*x)*(x*x)) || log(u) < x*x/2 + d - d*v + d*log(v)) return d*v; } } ///////////////////////////// // chi^2 samples double RandomNumberGenerator::chisquare(double nu) { double shape = nu/2; double scale = 2; return scale*stdgamma(shape); } ///////////////////////////// // Student's t-distribution samples double RandomNumberGenerator::student_t(double nu) { return stdnormal() * sqrt(nu/chisquare(nu)); } ///////////////////////////// // control the seed void RandomNumberGenerator::set_seed(std::time_t seed) { uint8_t seedbuf[crypto_weakprng_SEEDBYTES] = {0}; size_t i; for (i = 0; i < std::min(sizeof seedbuf, sizeof seed); i++) seedbuf[i] = seed >> (8*i); crypto_weakprng_seed(&_weakprng, seedbuf); } <|endoftext|>
<commit_before>/****************************************************************************** * This file is part of the Gluon Development Platform * Copyright (c) 2009 Dan Leinir Turthra Jensen <admin@leinir.dk> * Copyright (c) 2010 Arjen Hiemstra <> * * 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 "propertywidget.h" using namespace GluonCreator; #include "propertywidget.h" #include "propertywidgetitem.h" #include "propertywidgetitemfactory.h" #include <core/gluonobject.h> #include <core/debughelper.h> #include <QtCore/QVariant> #include <QtCore/QMetaClassInfo> #include <QtGui/QBoxLayout> #include <QtGui/QGridLayout> #include <QtGui/QGroupBox> #include <QtGui/QLabel> class PropertyWidget::PropertyWidgetPrivate { public: PropertyWidgetPrivate() { object = 0; layout = 0; } GluonCore::GluonObject *object; QVBoxLayout *layout; void appendMetaObject(QWidget* parent, QObject* object, QGridLayout* layout); }; PropertyWidget::PropertyWidget(QWidget* parent): QScrollArea(parent), d(new PropertyWidgetPrivate) { } PropertyWidget::~PropertyWidget() { delete d; } GluonCore::GluonObject *PropertyWidget::object() const { return d->object; } void PropertyWidget::setObject(GluonCore::GluonObject * object) { if (object) { d->object = object; d->layout = new QVBoxLayout(this); d->layout->setSpacing(0); d->layout->setContentsMargins(0, 0, 0, 0); d->layout->setAlignment(Qt::AlignTop); appendObject(object, true); for (int i = 0; i < object->children().count(); i++) { appendObject(object->child(i)); } d->layout->addStretch(); QWidget * containerWidget = new QWidget(this); containerWidget->setLayout(d->layout); setWidget(containerWidget); setWidgetResizable(true); } } void PropertyWidget::clear() { delete widget(); } void PropertyWidget::appendObject(GluonCore::GluonObject *obj, bool first) { if (!first && obj->metaObject()->className() == QString("GluonEngine::GameObject")) { return; } QString classname = obj->metaObject()->className(); classname = classname.right(classname.length() - classname.lastIndexOf(':') - 1); #ifdef __GNUC__ #warning We will need to replace the group box with a custom widget of some type, as we cannot collapse it. Unfortunate, but such is life ;) #endif QGroupBox* objectBox = new QGroupBox(classname, this); objectBox->setFlat(true); objectBox->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding); if (first) { long addr = reinterpret_cast<long>(obj); QColor color; color.setHsv(addr % 255, 255, 192); objectBox->setPalette(QPalette(color)); } d->layout->addWidget(objectBox); QGridLayout* boxLayout = new QGridLayout(objectBox); boxLayout->setSpacing(0); boxLayout->setContentsMargins(0, 0, 0, 0); objectBox->setLayout(boxLayout); d->appendMetaObject(this, obj, boxLayout); } void PropertyWidget::PropertyWidgetPrivate::appendMetaObject(QWidget *parent, QObject *object, QGridLayout* layout) { QString propertyName; QString propertyDescription; QVariant propertyValue; const QMetaObject *metaObject = object->metaObject(); QMetaProperty metaProperty; int row; int count = metaObject->propertyCount(); for (int i = 0; i < count; ++i) { row = layout->rowCount(); metaProperty = metaObject->property(i); if (metaProperty.name() == QString("objectName")) continue; QLabel * nameLabel = new QLabel(parent); nameLabel->setText(metaProperty.name()); nameLabel->setAlignment(Qt::AlignRight | Qt::AlignVCenter); layout->addWidget(nameLabel, row, 0); PropertyWidgetItem *editWidget = PropertyWidgetItemFactory::instance()->create(object, metaProperty.typeName(), parent); editWidget->setEditObject(object); editWidget->setEditProperty(metaProperty.name()); connect(editWidget, SIGNAL(propertyChanged(QObject*, QString, QVariant, QVariant)), parent, SIGNAL(propertyChanged(QObject*, QString, QVariant, QVariant))); editWidget->setMinimumWidth(250); editWidget->setSizePolicy(QSizePolicy::MinimumExpanding, QSizePolicy::Fixed); layout->addWidget(editWidget, row, 1); } foreach(const QByteArray &propName, object->dynamicPropertyNames()) { QString thePropName(propName); row = layout->rowCount(); QLabel * nameLabel = new QLabel(parent); nameLabel->setText(thePropName); nameLabel->setAlignment(Qt::AlignRight | Qt::AlignVCenter); layout->addWidget(nameLabel, row, 0); PropertyWidgetItem *editWidget = PropertyWidgetItemFactory::instance()->create(object, object->property(propName).typeName(), parent); editWidget->setEditObject(object); editWidget->setEditProperty(thePropName); connect(editWidget, SIGNAL(propertyChanged(QObject*, QString, QVariant, QVariant)), parent, SIGNAL(propertyChanged(QObject*, QString, QVariant, QVariant))); editWidget->setMinimumWidth(250); editWidget->setSizePolicy(QSizePolicy::MinimumExpanding, QSizePolicy::Fixed); layout->addWidget(editWidget); } } #include "propertywidget.moc" <commit_msg>Remove the obsolete colouring code<commit_after>/****************************************************************************** * This file is part of the Gluon Development Platform * Copyright (c) 2009 Dan Leinir Turthra Jensen <admin@leinir.dk> * Copyright (c) 2010 Arjen Hiemstra <> * * 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 "propertywidget.h" using namespace GluonCreator; #include "propertywidget.h" #include "propertywidgetitem.h" #include "propertywidgetitemfactory.h" #include <core/gluonobject.h> #include <core/debughelper.h> #include <QtCore/QVariant> #include <QtCore/QMetaClassInfo> #include <QtGui/QBoxLayout> #include <QtGui/QGridLayout> #include <QtGui/QGroupBox> #include <QtGui/QLabel> #include <QtGui/QToolButton> #include <KIcon> #include <klocalizedstring.h> class PropertyWidget::PropertyWidgetPrivate { public: PropertyWidgetPrivate() { object = 0; layout = 0; } GluonCore::GluonObject *object; QVBoxLayout *layout; void appendMetaObject(QWidget* parent, QObject* object, QGridLayout* layout); }; PropertyWidget::PropertyWidget(QWidget* parent): QScrollArea(parent), d(new PropertyWidgetPrivate) { } PropertyWidget::~PropertyWidget() { delete d; } GluonCore::GluonObject *PropertyWidget::object() const { return d->object; } void PropertyWidget::setObject(GluonCore::GluonObject * object) { if (object) { d->object = object; d->layout = new QVBoxLayout(this); d->layout->setSpacing(0); d->layout->setContentsMargins(0, 0, 0, 0); d->layout->setAlignment(Qt::AlignTop); appendObject(object, true); for (int i = 0; i < object->children().count(); i++) { appendObject(object->child(i)); } d->layout->addStretch(); QWidget * containerWidget = new QWidget(this); containerWidget->setLayout(d->layout); setWidget(containerWidget); setWidgetResizable(true); } } void PropertyWidget::clear() { delete widget(); } void PropertyWidget::appendObject(GluonCore::GluonObject *obj, bool first) { if (!first && obj->metaObject()->className() == QString("GluonEngine::GameObject")) { return; } QString classname = obj->metaObject()->className(); classname = classname.right(classname.length() - classname.lastIndexOf(':') - 1); #ifdef __GNUC__ #warning We will need to replace the group box with a custom widget of some type, as we cannot collapse it. Unfortunate, but such is life ;) #endif QGroupBox* objectBox = new QGroupBox(classname, this); objectBox->setFlat(true); objectBox->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding); d->layout->addWidget(objectBox); QGridLayout* boxLayout = new QGridLayout(objectBox); boxLayout->setSpacing(0); boxLayout->setContentsMargins(0, 0, 0, 0); objectBox->setLayout(boxLayout); d->appendMetaObject(this, obj, boxLayout); } void PropertyWidget::PropertyWidgetPrivate::appendMetaObject(QWidget *parent, QObject *object, QGridLayout* layout) { QString propertyName; QString propertyDescription; QVariant propertyValue; const QMetaObject *metaObject = object->metaObject(); QMetaProperty metaProperty; int row; int count = metaObject->propertyCount(); for (int i = 0; i < count; ++i) { row = layout->rowCount(); metaProperty = metaObject->property(i); if (metaProperty.name() == QString("objectName")) continue; QLabel * nameLabel = new QLabel(parent); nameLabel->setText(metaProperty.name()); nameLabel->setAlignment(Qt::AlignRight | Qt::AlignVCenter); layout->addWidget(nameLabel, row, 0); PropertyWidgetItem *editWidget = PropertyWidgetItemFactory::instance()->create(object, metaProperty.typeName(), parent); editWidget->setEditObject(object); editWidget->setEditProperty(metaProperty.name()); connect(editWidget, SIGNAL(propertyChanged(QObject*, QString, QVariant, QVariant)), parent, SIGNAL(propertyChanged(QObject*, QString, QVariant, QVariant))); editWidget->setMinimumWidth(250); editWidget->setSizePolicy(QSizePolicy::MinimumExpanding, QSizePolicy::Fixed); layout->addWidget(editWidget, row, 1); } foreach(const QByteArray &propName, object->dynamicPropertyNames()) { QString thePropName(propName); row = layout->rowCount(); QLabel * nameLabel = new QLabel(parent); nameLabel->setText(thePropName); nameLabel->setAlignment(Qt::AlignRight | Qt::AlignVCenter); layout->addWidget(nameLabel, row, 0); PropertyWidgetItem *editWidget = PropertyWidgetItemFactory::instance()->create(object, object->property(propName).typeName(), parent); editWidget->setEditObject(object); editWidget->setEditProperty(thePropName); connect(editWidget, SIGNAL(propertyChanged(QObject*, QString, QVariant, QVariant)), parent, SIGNAL(propertyChanged(QObject*, QString, QVariant, QVariant))); editWidget->setMinimumWidth(250); editWidget->setSizePolicy(QSizePolicy::MinimumExpanding, QSizePolicy::Fixed); layout->addWidget(editWidget, row, 1); } } #include "propertywidget.moc" <|endoftext|>
<commit_before>/* This file is part of Zanshin Copyright 2014 Kevin Ottens <ervin@kde.org> This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License or (at your option) version 3 or any later version accepted by the membership of KDE e.V. (or its successor approved by the membership of KDE e.V.), which shall act as a proxy defined in Section 14 of version 3 of the license. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include "akonaditagqueries.h" #include "akonadicollectionfetchjobinterface.h" #include "akonadiitemfetchjobinterface.h" #include "akonaditagfetchjobinterface.h" #include "akonadimonitorimpl.h" #include "akonadiserializer.h" #include "akonadistorage.h" #include "utils/jobhandler.h" using namespace Akonadi; TagQueries::TagQueries(QObject *parent) : QObject(parent), m_storage(new Storage), m_serializer(new Serializer), m_monitor(new MonitorImpl), m_fetchContentTypeFilter(StorageInterface::Tasks|StorageInterface::Notes), m_ownInterfaces(true) { connect(m_monitor, SIGNAL(tagAdded(Akonadi::Tag)), this, SLOT(onTagAdded(Akonadi::Tag))); connect(m_monitor, SIGNAL(tagRemoved(Akonadi::Tag)), this, SLOT(onTagRemoved(Akonadi::Tag))); connect(m_monitor, SIGNAL(tagChanged(Akonadi::Tag)), this, SLOT(onTagChanged(Akonadi::Tag))); connect(m_monitor, SIGNAL(itemAdded(Akonadi::Item)), this, SLOT(onItemAdded(Akonadi::Item))); connect(m_monitor, SIGNAL(itemRemoved(Akonadi::Item)), this, SLOT(onItemRemoved(Akonadi::Item))); connect(m_monitor, SIGNAL(itemChanged(Akonadi::Item)), this, SLOT(onItemChanged(Akonadi::Item))); } TagQueries::TagQueries(StorageInterface *storage, SerializerInterface *serializer, MonitorInterface *monitor) : m_storage(storage), m_serializer(serializer), m_monitor(monitor), m_fetchContentTypeFilter(StorageInterface::Tasks|StorageInterface::Notes), m_ownInterfaces(false) { connect(m_monitor, SIGNAL(tagAdded(Akonadi::Tag)), this, SLOT(onTagAdded(Akonadi::Tag))); connect(m_monitor, SIGNAL(tagRemoved(Akonadi::Tag)), this, SLOT(onTagRemoved(Akonadi::Tag))); connect(m_monitor, SIGNAL(tagChanged(Akonadi::Tag)), this, SLOT(onTagChanged(Akonadi::Tag))); connect(monitor, SIGNAL(itemAdded(Akonadi::Item)), this, SLOT(onItemAdded(Akonadi::Item))); connect(monitor, SIGNAL(itemRemoved(Akonadi::Item)), this, SLOT(onItemRemoved(Akonadi::Item))); connect(monitor, SIGNAL(itemChanged(Akonadi::Item)), this, SLOT(onItemChanged(Akonadi::Item))); } TagQueries::~TagQueries() { if (m_ownInterfaces) { delete m_storage; delete m_serializer; delete m_monitor; } } void TagQueries::setApplicationMode(TagQueries::ApplicationMode mode) { if (mode == TasksOnly) { m_fetchContentTypeFilter = StorageInterface::Tasks; } else if (mode == NotesOnly) { m_fetchContentTypeFilter = StorageInterface::Notes; } } TagQueries::TagResult::Ptr TagQueries::findAll() const { if (!m_findAll) { { TagQueries *self = const_cast<TagQueries*>(this); self->m_findAll = self->createTagQuery(); } m_findAll->setFetchFunction([this] (const TagQuery::AddFunction &add) { TagFetchJobInterface *job = m_storage->fetchTags(); Utils::JobHandler::install(job->kjob(), [this, job, add] { for (Akonadi::Tag tag : job->tags()) add(tag); }); }); m_findAll->setConvertFunction([this] (const Akonadi::Tag &tag) { return m_serializer->createTagFromAkonadiTag(tag); }); m_findAll->setUpdateFunction([this] (const Akonadi::Tag &akonadiTag, Domain::Tag::Ptr &tag) { m_serializer->updateTagFromAkonadiTag(tag, akonadiTag); }); m_findAll->setPredicateFunction([this] (const Akonadi::Tag &akonadiTag) { return akonadiTag.type() == Akonadi::Tag::PLAIN; }); m_findAll->setRepresentsFunction([this] (const Akonadi::Tag &akonadiTag, const Domain::Tag::Ptr &tag) { return m_serializer->representsAkonadiTag(tag, akonadiTag); }); } return m_findAll->result(); } TagQueries::ArtifactResult::Ptr TagQueries::findTopLevelArtifacts(Domain::Tag::Ptr tag) const { Akonadi::Tag akonadiTag = m_serializer->createAkonadiTagFromTag(tag); if (!m_findTopLevel.contains(akonadiTag.id())) { ArtifactQuery::Ptr query; { TagQueries *self = const_cast<TagQueries*>(this); query = self->createArtifactQuery(); self->m_findTopLevel.insert(akonadiTag.id(), query); } query->setFetchFunction([this, akonadiTag] (const ArtifactQuery::AddFunction &add) { CollectionFetchJobInterface *job = m_storage->fetchCollections(Akonadi::Collection::root(), StorageInterface::Recursive, m_fetchContentTypeFilter); Utils::JobHandler::install(job->kjob(), [this, job, add] { if (job->kjob()->error() != KJob::NoError) return; for (auto collection : job->collections()) { ItemFetchJobInterface *job = m_storage->fetchItems(collection); Utils::JobHandler::install(job->kjob(), [this, job, add] { if (job->kjob()->error() != KJob::NoError) return; for (auto item : job->items()) add(item); }); } }); }); query->setConvertFunction([this] (const Akonadi::Item &item) { if (m_serializer->isTaskItem(item)) { auto task = m_serializer->createTaskFromItem(item); return Domain::Artifact::Ptr(task); } else if (m_serializer->isNoteItem(item)) { auto note = m_serializer->createNoteFromItem(item); return Domain::Artifact::Ptr(note); } else { return Domain::Artifact::Ptr(); } }); query->setUpdateFunction([this] (const Akonadi::Item &item, Domain::Artifact::Ptr &artifact) { if (auto task = artifact.dynamicCast<Domain::Task>()) { m_serializer->updateTaskFromItem(task, item); } else if (auto note = artifact.dynamicCast<Domain::Note>()) { m_serializer->updateNoteFromItem(note, item); } }); query->setPredicateFunction([this, tag] (const Akonadi::Item &item) { return m_serializer->isTagChild(tag, item); }); query->setRepresentsFunction([this] (const Akonadi::Item &item, const Domain::Artifact::Ptr &artifact) { return m_serializer->representsItem(artifact, item); }); } return m_findTopLevel.value(akonadiTag.id())->result(); } void TagQueries::onTagAdded(const Tag &tag) { foreach (const TagQuery::Ptr &query, m_tagQueries) query->onAdded(tag); } void TagQueries::onTagRemoved(const Tag &tag) { foreach (const TagQuery::Ptr &query, m_tagQueries) query->onRemoved(tag); } void TagQueries::onTagChanged(const Tag &tag) { foreach (const TagQuery::Ptr &query, m_tagQueries) query->onChanged(tag); } void TagQueries::onItemAdded(const Item &item) { foreach (const ArtifactQuery::Ptr &query, m_artifactQueries) query->onAdded(item); } void TagQueries::onItemRemoved(const Item &item) { Q_UNUSED(item); } void TagQueries::onItemChanged(const Item &item) { foreach (const ArtifactQuery::Ptr &query, m_artifactQueries) query->onChanged(item); } TagQueries::TagQuery::Ptr TagQueries::createTagQuery() { auto query = TagQueries::TagQuery::Ptr::create(); m_tagQueries << query; return query; } TagQueries::ArtifactQuery::Ptr TagQueries::createArtifactQuery() { auto query = TagQueries::ArtifactQuery::Ptr::create(); m_artifactQueries << query; return query; } <commit_msg>Avoid an endless loop in tagqueries.<commit_after>/* This file is part of Zanshin Copyright 2014 Kevin Ottens <ervin@kde.org> This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License or (at your option) version 3 or any later version accepted by the membership of KDE e.V. (or its successor approved by the membership of KDE e.V.), which shall act as a proxy defined in Section 14 of version 3 of the license. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include "akonaditagqueries.h" #include "akonadicollectionfetchjobinterface.h" #include "akonadiitemfetchjobinterface.h" #include "akonaditagfetchjobinterface.h" #include "akonadimonitorimpl.h" #include "akonadiserializer.h" #include "akonadistorage.h" #include "utils/jobhandler.h" using namespace Akonadi; TagQueries::TagQueries(QObject *parent) : QObject(parent), m_storage(new Storage), m_serializer(new Serializer), m_monitor(new MonitorImpl), m_fetchContentTypeFilter(StorageInterface::Tasks|StorageInterface::Notes), m_ownInterfaces(true) { connect(m_monitor, SIGNAL(tagAdded(Akonadi::Tag)), this, SLOT(onTagAdded(Akonadi::Tag))); connect(m_monitor, SIGNAL(tagRemoved(Akonadi::Tag)), this, SLOT(onTagRemoved(Akonadi::Tag))); connect(m_monitor, SIGNAL(tagChanged(Akonadi::Tag)), this, SLOT(onTagChanged(Akonadi::Tag))); connect(m_monitor, SIGNAL(itemAdded(Akonadi::Item)), this, SLOT(onItemAdded(Akonadi::Item))); connect(m_monitor, SIGNAL(itemRemoved(Akonadi::Item)), this, SLOT(onItemRemoved(Akonadi::Item))); connect(m_monitor, SIGNAL(itemChanged(Akonadi::Item)), this, SLOT(onItemChanged(Akonadi::Item))); } TagQueries::TagQueries(StorageInterface *storage, SerializerInterface *serializer, MonitorInterface *monitor) : m_storage(storage), m_serializer(serializer), m_monitor(monitor), m_fetchContentTypeFilter(StorageInterface::Tasks|StorageInterface::Notes), m_ownInterfaces(false) { connect(m_monitor, SIGNAL(tagAdded(Akonadi::Tag)), this, SLOT(onTagAdded(Akonadi::Tag))); connect(m_monitor, SIGNAL(tagRemoved(Akonadi::Tag)), this, SLOT(onTagRemoved(Akonadi::Tag))); connect(m_monitor, SIGNAL(tagChanged(Akonadi::Tag)), this, SLOT(onTagChanged(Akonadi::Tag))); connect(monitor, SIGNAL(itemAdded(Akonadi::Item)), this, SLOT(onItemAdded(Akonadi::Item))); connect(monitor, SIGNAL(itemRemoved(Akonadi::Item)), this, SLOT(onItemRemoved(Akonadi::Item))); connect(monitor, SIGNAL(itemChanged(Akonadi::Item)), this, SLOT(onItemChanged(Akonadi::Item))); } TagQueries::~TagQueries() { if (m_ownInterfaces) { delete m_storage; delete m_serializer; delete m_monitor; } } void TagQueries::setApplicationMode(TagQueries::ApplicationMode mode) { if (mode == TasksOnly) { m_fetchContentTypeFilter = StorageInterface::Tasks; } else if (mode == NotesOnly) { m_fetchContentTypeFilter = StorageInterface::Notes; } } TagQueries::TagResult::Ptr TagQueries::findAll() const { if (!m_findAll) { { TagQueries *self = const_cast<TagQueries*>(this); self->m_findAll = self->createTagQuery(); } m_findAll->setFetchFunction([this] (const TagQuery::AddFunction &add) { TagFetchJobInterface *job = m_storage->fetchTags(); Utils::JobHandler::install(job->kjob(), [this, job, add] { for (Akonadi::Tag tag : job->tags()) add(tag); }); }); m_findAll->setConvertFunction([this] (const Akonadi::Tag &tag) { return m_serializer->createTagFromAkonadiTag(tag); }); m_findAll->setUpdateFunction([this] (const Akonadi::Tag &akonadiTag, Domain::Tag::Ptr &tag) { m_serializer->updateTagFromAkonadiTag(tag, akonadiTag); }); m_findAll->setPredicateFunction([this] (const Akonadi::Tag &akonadiTag) { return akonadiTag.type() == Akonadi::Tag::PLAIN; }); m_findAll->setRepresentsFunction([this] (const Akonadi::Tag &akonadiTag, const Domain::Tag::Ptr &tag) { return m_serializer->representsAkonadiTag(tag, akonadiTag); }); } return m_findAll->result(); } TagQueries::ArtifactResult::Ptr TagQueries::findTopLevelArtifacts(Domain::Tag::Ptr tag) const { Akonadi::Tag akonadiTag = m_serializer->createAkonadiTagFromTag(tag); if (!m_findTopLevel.contains(akonadiTag.id())) { ArtifactQuery::Ptr query; { TagQueries *self = const_cast<TagQueries*>(this); query = self->createArtifactQuery(); self->m_findTopLevel.insert(akonadiTag.id(), query); } query->setFetchFunction([this, akonadiTag] (const ArtifactQuery::AddFunction &add) { CollectionFetchJobInterface *job = m_storage->fetchCollections(Akonadi::Collection::root(), StorageInterface::Recursive, m_fetchContentTypeFilter); Utils::JobHandler::install(job->kjob(), [this, job, add] { if (job->kjob()->error() != KJob::NoError) return; for (auto collection : job->collections()) { ItemFetchJobInterface *job = m_storage->fetchItems(collection); Utils::JobHandler::install(job->kjob(), [this, job, add] { if (job->kjob()->error() != KJob::NoError) return; for (auto item : job->items()) add(item); }); } }); }); query->setConvertFunction([this] (const Akonadi::Item &item) { if (m_serializer->isTaskItem(item)) { auto task = m_serializer->createTaskFromItem(item); return Domain::Artifact::Ptr(task); } else if (m_serializer->isNoteItem(item)) { auto note = m_serializer->createNoteFromItem(item); return Domain::Artifact::Ptr(note); } //The conversion must never fail, otherwise we create an endless loop (child of invalid node is invalid). //We therefore catch this case in the predicate. Q_ASSERT(false); return Domain::Artifact::Ptr(); }); query->setUpdateFunction([this] (const Akonadi::Item &item, Domain::Artifact::Ptr &artifact) { if (auto task = artifact.dynamicCast<Domain::Task>()) { m_serializer->updateTaskFromItem(task, item); } else if (auto note = artifact.dynamicCast<Domain::Note>()) { m_serializer->updateNoteFromItem(note, item); } }); query->setPredicateFunction([this, tag] (const Akonadi::Item &item) { if (m_serializer->isTaskItem(item)) { return false; } if (!m_serializer->isNoteItem(item)) { return false; } return m_serializer->isTagChild(tag, item); }); query->setRepresentsFunction([this] (const Akonadi::Item &item, const Domain::Artifact::Ptr &artifact) { return m_serializer->representsItem(artifact, item); }); } return m_findTopLevel.value(akonadiTag.id())->result(); } void TagQueries::onTagAdded(const Tag &tag) { foreach (const TagQuery::Ptr &query, m_tagQueries) query->onAdded(tag); } void TagQueries::onTagRemoved(const Tag &tag) { foreach (const TagQuery::Ptr &query, m_tagQueries) query->onRemoved(tag); } void TagQueries::onTagChanged(const Tag &tag) { foreach (const TagQuery::Ptr &query, m_tagQueries) query->onChanged(tag); } void TagQueries::onItemAdded(const Item &item) { foreach (const ArtifactQuery::Ptr &query, m_artifactQueries) query->onAdded(item); } void TagQueries::onItemRemoved(const Item &item) { Q_UNUSED(item); } void TagQueries::onItemChanged(const Item &item) { foreach (const ArtifactQuery::Ptr &query, m_artifactQueries) query->onChanged(item); } TagQueries::TagQuery::Ptr TagQueries::createTagQuery() { auto query = TagQueries::TagQuery::Ptr::create(); m_tagQueries << query; return query; } TagQueries::ArtifactQuery::Ptr TagQueries::createArtifactQuery() { auto query = TagQueries::ArtifactQuery::Ptr::create(); m_artifactQueries << query; return query; } <|endoftext|>
<commit_before>/* * This file is part of `et engine` * Copyright 2009-2013 by Sergey Reznik * Please, do not modify content without approval. * */ #include <et/core/objectscache.h> #include <et/geometry/geometry.h> #include <et/rendering/rendercontext.h> #include <et/opengl/openglcaps.h> #include <et/threading/threading.h> #include <et/resources/textureloader.h> #include <et/apiobjects/texturefactory.h> #include <et/app/application.h> using namespace et; class et::TextureFactoryPrivate { public: struct Loader : public ObjectLoader { TextureFactory* owner; Loader(TextureFactory* aOwner) : owner(aOwner) { } void reloadObject(LoadableObject::Pointer o, ObjectsCache& c) { owner->reloadObject(o, c); } }; IntrusivePtr<Loader> loader; TextureFactoryPrivate(TextureFactory* owner) : loader(new Loader(owner)) { } }; TextureFactory::TextureFactory(RenderContext* rc) : APIObjectFactory(rc) { _private = new TextureFactoryPrivate(this); _loadingThread = new TextureLoadingThread(this); } TextureFactory::~TextureFactory() { _loadingThread->stop(); _loadingThread->waitForTermination(); delete _private; } ObjectLoader::Pointer TextureFactory::objectLoader() { return _private->loader; } Texture TextureFactory::loadTexture(const std::string& fileName, ObjectsCache& cache, bool async, TextureLoaderDelegate* delegate) { if (fileName.length() == 0) return Texture(); CriticalSectionScope lock(_csTextureLoading); std::string file = application().environment().resolveScalableFileName(fileName, renderContext()->screenScaleFactor()); if (!fileExists(file)) { log::error("Unable to find texture file: %s", file.c_str()); return Texture(); } uint64_t cachedFileProperty = 0; Texture texture = cache.findAnyObject(file, &cachedFileProperty); if (texture.invalid()) { TextureDescription::Pointer desc = async ? et::loadTextureDescription(file, false) : et::loadTexture(file); if (desc.valid()) { bool calledFromAnotherThread = Threading::currentThread() != threading().renderingThread(); texture = Texture(new TextureData(renderContext(), desc, desc->origin(), async || calledFromAnotherThread)); cache.manage(texture, _private->loader); if (async) _loadingThread->addRequest(desc->origin(), texture, delegate); else if (calledFromAnotherThread) assert(false && "ERROR: Unable to load texture synchronously from non-rendering thread."); } } else { auto newProperty = cache.getFileProperty(file); if (cachedFileProperty != newProperty) reloadObject(texture, cache); if (async) { textureDidStartLoading.invokeInMainRunLoop(texture); if (delegate != nullptr) { Invocation1 i; i.setTarget(delegate, &TextureLoaderDelegate::textureDidStartLoading, texture); i.invokeInMainRunLoop(); } textureDidLoad.invokeInMainRunLoop(texture); if (delegate != nullptr) { Invocation1 i; i.setTarget(delegate, &TextureLoaderDelegate::textureDidLoad, texture); i.invokeInMainRunLoop(); } } } return texture; } Texture TextureFactory::genTexture(uint32_t target, int32_t internalformat, const vec2i& size, uint32_t format, uint32_t type, const BinaryDataStorage& data, const std::string& id) { TextureDescription::Pointer desc(new TextureDescription); desc->target = target; desc->format = format; desc->internalformat = internalformat; desc->type = type; desc->size = size; desc->mipMapCount = 1; desc->layersCount = 1; desc->bitsPerPixel = bitsPerPixelForTextureFormat(internalformat, type); desc->data = data; return Texture(new TextureData(renderContext(), desc, id, false)); } Texture TextureFactory::genCubeTexture(int32_t internalformat, GLsizei size, uint32_t format, uint32_t type, const std::string& id) { TextureDescription::Pointer desc(new TextureDescription); desc->target = GL_TEXTURE_CUBE_MAP; desc->format = format; desc->internalformat = internalformat; desc->type = type; desc->size = vec2i(size); desc->mipMapCount = 1; desc->layersCount = 6; desc->bitsPerPixel = bitsPerPixelForTextureFormat(internalformat, type); desc->data = BinaryDataStorage(desc->layersCount * desc->dataSizeForAllMipLevels(), 0); return Texture(new TextureData(renderContext(), desc, id, false)); } Texture TextureFactory::genTexture(TextureDescription::Pointer desc) { return Texture(new TextureData(renderContext(), desc, desc->origin(), false)); } Texture TextureFactory::genNoiseTexture(const vec2i& size, bool norm, const std::string& id) { DataStorage<vec4ub> randata(size.square()); for (size_t i = 0; i < randata.size(); ++i) { vec4 rand_f = vec4(randomFloat(-1.0f, 1.0f), randomFloat(-1.0f, 1.0f), randomFloat(-1.0f, 1.0f), randomFloat(-1.0f, 1.0f)); randata[i] = vec4f_to_4ub(norm ? vec4(rand_f.xyz().normalized(), rand_f.w) : rand_f); } TextureDescription::Pointer desc(new TextureDescription); desc->data = BinaryDataStorage(4 * size.square()); desc->target = GL_TEXTURE_2D; desc->format = GL_RGBA; desc->internalformat = GL_RGBA; desc->type = GL_UNSIGNED_BYTE; desc->size = size; desc->mipMapCount = 1; desc->layersCount = 1; desc->bitsPerPixel = 32; etCopyMemory(desc->data.data(), randata.data(), randata.dataSize()); return Texture(new TextureData(renderContext(), desc, id, false)); } void TextureFactory::textureLoadingThreadDidLoadTextureData(TextureLoadingRequest* request) { CriticalSectionScope lock(_csTextureLoading); request->texture->updateData(renderContext(), request->textureDescription); textureDidLoad.invoke(request->texture); if (request->delegate) request->delegate->textureDidLoad(request->texture); delete request; } Texture TextureFactory::loadTexturesToCubemap(const std::string& posx, const std::string& negx, const std::string& posy, const std::string& negy, const std::string& posz, const std::string& negz, ObjectsCache& cache) { TextureDescription::Pointer layers[6] = { et::loadTexture(application().environment().resolveScalableFileName(posx, renderContext()->screenScaleFactor())), et::loadTexture(application().environment().resolveScalableFileName(negx, renderContext()->screenScaleFactor())), et::loadTexture(application().environment().resolveScalableFileName(negy, renderContext()->screenScaleFactor())), et::loadTexture(application().environment().resolveScalableFileName(posy, renderContext()->screenScaleFactor())), et::loadTexture(application().environment().resolveScalableFileName(posz, renderContext()->screenScaleFactor())), et::loadTexture(application().environment().resolveScalableFileName(negz, renderContext()->screenScaleFactor())) }; int maxCubemapSize = static_cast<int>(openGLCapabilites().maxCubemapTextureSize()); for (size_t l = 0; l < 6; ++l) { if (layers[l].valid()) { if ((layers[l]->size.x > maxCubemapSize) || (layers[l]->size.y > maxCubemapSize)) { log::error("Cubemap %s size of (%d x %d) is larger than allowed %dx%d", layers[l]->origin().c_str(), layers[l]->size.x, layers[l]->size.y, maxCubemapSize, maxCubemapSize); return Texture(); } } else { log::error("Unable to load cubemap face."); return Texture(); } } std::string texId = layers[0]->origin() + ";"; for (size_t l = 1; l < 6; ++l) { texId += (l < 5) ? layers[l]->origin() + ";" : layers[l]->origin(); if ((layers[l-1]->size != layers[l]->size) || (layers[l-1]->format != layers[l]->format) || (layers[l-1]->internalformat != layers[l]->internalformat) || (layers[l-1]->type != layers[l]->type) || (layers[l-1]->mipMapCount != layers[l]->mipMapCount) || (layers[l-1]->compressed != layers[l]->compressed) || (layers[l-1]->data.size() != layers[l]->data.size())) { log::error("Failed to load cubemap textures. Textures `%s` and `%s` aren't identical", layers[l-1]->origin().c_str(), layers[l]->origin().c_str()); return Texture(); } } size_t layerSize = layers[0]->dataSizeForAllMipLevels(); TextureDescription::Pointer desc(new TextureDescription); desc->target = GL_TEXTURE_CUBE_MAP; desc->layersCount = 6; desc->bitsPerPixel = layers[0]->bitsPerPixel; desc->channels = layers[0]->channels; desc->compressed = layers[0]->compressed; desc->format = layers[0]->format; desc->internalformat = layers[0]->internalformat; desc->mipMapCount= layers[0]->mipMapCount; desc->size = layers[0]->size; desc->type = layers[0]->type; desc->data.resize(desc->layersCount * layerSize); for (size_t l = 0; l < desc->layersCount; ++l) etCopyMemory(desc->data.element_ptr(l * layerSize), layers[l]->data.element_ptr(0), layerSize); Texture result(new TextureData(renderContext(), desc, texId, false)); for (size_t i = 0; i < 6; ++i) result->addOrigin(layers[i]->origin()); cache.manage(result, _private->loader); return result; } Texture TextureFactory::createTextureWrapper(uint32_t texture, const vec2i& size, const std::string& name) { return Texture(new TextureData(renderContext(), texture, size, name)); } void TextureFactory::reloadObject(LoadableObject::Pointer object, ObjectsCache&) { TextureDescription::Pointer newData = et::loadTexture(object->origin()); if (newData.valid()) Texture(object)->updateData(renderContext(), newData); } <commit_msg>assert replaced with ET_FAIL in texture factory<commit_after>/* * This file is part of `et engine` * Copyright 2009-2013 by Sergey Reznik * Please, do not modify content without approval. * */ #include <et/core/objectscache.h> #include <et/geometry/geometry.h> #include <et/rendering/rendercontext.h> #include <et/opengl/openglcaps.h> #include <et/threading/threading.h> #include <et/resources/textureloader.h> #include <et/apiobjects/texturefactory.h> #include <et/app/application.h> using namespace et; class et::TextureFactoryPrivate { public: struct Loader : public ObjectLoader { TextureFactory* owner; Loader(TextureFactory* aOwner) : owner(aOwner) { } void reloadObject(LoadableObject::Pointer o, ObjectsCache& c) { owner->reloadObject(o, c); } }; IntrusivePtr<Loader> loader; TextureFactoryPrivate(TextureFactory* owner) : loader(new Loader(owner)) { } }; TextureFactory::TextureFactory(RenderContext* rc) : APIObjectFactory(rc) { _private = new TextureFactoryPrivate(this); _loadingThread = new TextureLoadingThread(this); } TextureFactory::~TextureFactory() { _loadingThread->stop(); _loadingThread->waitForTermination(); delete _private; } ObjectLoader::Pointer TextureFactory::objectLoader() { return _private->loader; } Texture TextureFactory::loadTexture(const std::string& fileName, ObjectsCache& cache, bool async, TextureLoaderDelegate* delegate) { if (fileName.length() == 0) return Texture(); CriticalSectionScope lock(_csTextureLoading); std::string file = application().environment().resolveScalableFileName(fileName, renderContext()->screenScaleFactor()); if (!fileExists(file)) { log::error("Unable to find texture file: %s", file.c_str()); return Texture(); } uint64_t cachedFileProperty = 0; Texture texture = cache.findAnyObject(file, &cachedFileProperty); if (texture.invalid()) { TextureDescription::Pointer desc = async ? et::loadTextureDescription(file, false) : et::loadTexture(file); if (desc.valid()) { bool calledFromAnotherThread = Threading::currentThread() != threading().renderingThread(); texture = Texture(new TextureData(renderContext(), desc, desc->origin(), async || calledFromAnotherThread)); cache.manage(texture, _private->loader); if (async) _loadingThread->addRequest(desc->origin(), texture, delegate); else if (calledFromAnotherThread) ET_FAIL("ERROR: Unable to load texture synchronously from non-rendering thread."); } } else { auto newProperty = cache.getFileProperty(file); if (cachedFileProperty != newProperty) reloadObject(texture, cache); if (async) { textureDidStartLoading.invokeInMainRunLoop(texture); if (delegate != nullptr) { Invocation1 i; i.setTarget(delegate, &TextureLoaderDelegate::textureDidStartLoading, texture); i.invokeInMainRunLoop(); } textureDidLoad.invokeInMainRunLoop(texture); if (delegate != nullptr) { Invocation1 i; i.setTarget(delegate, &TextureLoaderDelegate::textureDidLoad, texture); i.invokeInMainRunLoop(); } } } return texture; } Texture TextureFactory::genTexture(uint32_t target, int32_t internalformat, const vec2i& size, uint32_t format, uint32_t type, const BinaryDataStorage& data, const std::string& id) { TextureDescription::Pointer desc(new TextureDescription); desc->target = target; desc->format = format; desc->internalformat = internalformat; desc->type = type; desc->size = size; desc->mipMapCount = 1; desc->layersCount = 1; desc->bitsPerPixel = bitsPerPixelForTextureFormat(internalformat, type); desc->data = data; return Texture(new TextureData(renderContext(), desc, id, false)); } Texture TextureFactory::genCubeTexture(int32_t internalformat, GLsizei size, uint32_t format, uint32_t type, const std::string& id) { TextureDescription::Pointer desc(new TextureDescription); desc->target = GL_TEXTURE_CUBE_MAP; desc->format = format; desc->internalformat = internalformat; desc->type = type; desc->size = vec2i(size); desc->mipMapCount = 1; desc->layersCount = 6; desc->bitsPerPixel = bitsPerPixelForTextureFormat(internalformat, type); desc->data = BinaryDataStorage(desc->layersCount * desc->dataSizeForAllMipLevels(), 0); return Texture(new TextureData(renderContext(), desc, id, false)); } Texture TextureFactory::genTexture(TextureDescription::Pointer desc) { return Texture(new TextureData(renderContext(), desc, desc->origin(), false)); } Texture TextureFactory::genNoiseTexture(const vec2i& size, bool norm, const std::string& id) { DataStorage<vec4ub> randata(size.square()); for (size_t i = 0; i < randata.size(); ++i) { vec4 rand_f = vec4(randomFloat(-1.0f, 1.0f), randomFloat(-1.0f, 1.0f), randomFloat(-1.0f, 1.0f), randomFloat(-1.0f, 1.0f)); randata[i] = vec4f_to_4ub(norm ? vec4(rand_f.xyz().normalized(), rand_f.w) : rand_f); } TextureDescription::Pointer desc(new TextureDescription); desc->data = BinaryDataStorage(4 * size.square()); desc->target = GL_TEXTURE_2D; desc->format = GL_RGBA; desc->internalformat = GL_RGBA; desc->type = GL_UNSIGNED_BYTE; desc->size = size; desc->mipMapCount = 1; desc->layersCount = 1; desc->bitsPerPixel = 32; etCopyMemory(desc->data.data(), randata.data(), randata.dataSize()); return Texture(new TextureData(renderContext(), desc, id, false)); } void TextureFactory::textureLoadingThreadDidLoadTextureData(TextureLoadingRequest* request) { CriticalSectionScope lock(_csTextureLoading); request->texture->updateData(renderContext(), request->textureDescription); textureDidLoad.invoke(request->texture); if (request->delegate) request->delegate->textureDidLoad(request->texture); delete request; } Texture TextureFactory::loadTexturesToCubemap(const std::string& posx, const std::string& negx, const std::string& posy, const std::string& negy, const std::string& posz, const std::string& negz, ObjectsCache& cache) { TextureDescription::Pointer layers[6] = { et::loadTexture(application().environment().resolveScalableFileName(posx, renderContext()->screenScaleFactor())), et::loadTexture(application().environment().resolveScalableFileName(negx, renderContext()->screenScaleFactor())), et::loadTexture(application().environment().resolveScalableFileName(negy, renderContext()->screenScaleFactor())), et::loadTexture(application().environment().resolveScalableFileName(posy, renderContext()->screenScaleFactor())), et::loadTexture(application().environment().resolveScalableFileName(posz, renderContext()->screenScaleFactor())), et::loadTexture(application().environment().resolveScalableFileName(negz, renderContext()->screenScaleFactor())) }; int maxCubemapSize = static_cast<int>(openGLCapabilites().maxCubemapTextureSize()); for (size_t l = 0; l < 6; ++l) { if (layers[l].valid()) { if ((layers[l]->size.x > maxCubemapSize) || (layers[l]->size.y > maxCubemapSize)) { log::error("Cubemap %s size of (%d x %d) is larger than allowed %dx%d", layers[l]->origin().c_str(), layers[l]->size.x, layers[l]->size.y, maxCubemapSize, maxCubemapSize); return Texture(); } } else { log::error("Unable to load cubemap face."); return Texture(); } } std::string texId = layers[0]->origin() + ";"; for (size_t l = 1; l < 6; ++l) { texId += (l < 5) ? layers[l]->origin() + ";" : layers[l]->origin(); if ((layers[l-1]->size != layers[l]->size) || (layers[l-1]->format != layers[l]->format) || (layers[l-1]->internalformat != layers[l]->internalformat) || (layers[l-1]->type != layers[l]->type) || (layers[l-1]->mipMapCount != layers[l]->mipMapCount) || (layers[l-1]->compressed != layers[l]->compressed) || (layers[l-1]->data.size() != layers[l]->data.size())) { log::error("Failed to load cubemap textures. Textures `%s` and `%s` aren't identical", layers[l-1]->origin().c_str(), layers[l]->origin().c_str()); return Texture(); } } size_t layerSize = layers[0]->dataSizeForAllMipLevels(); TextureDescription::Pointer desc(new TextureDescription); desc->target = GL_TEXTURE_CUBE_MAP; desc->layersCount = 6; desc->bitsPerPixel = layers[0]->bitsPerPixel; desc->channels = layers[0]->channels; desc->compressed = layers[0]->compressed; desc->format = layers[0]->format; desc->internalformat = layers[0]->internalformat; desc->mipMapCount= layers[0]->mipMapCount; desc->size = layers[0]->size; desc->type = layers[0]->type; desc->data.resize(desc->layersCount * layerSize); for (size_t l = 0; l < desc->layersCount; ++l) etCopyMemory(desc->data.element_ptr(l * layerSize), layers[l]->data.element_ptr(0), layerSize); Texture result(new TextureData(renderContext(), desc, texId, false)); for (size_t i = 0; i < 6; ++i) result->addOrigin(layers[i]->origin()); cache.manage(result, _private->loader); return result; } Texture TextureFactory::createTextureWrapper(uint32_t texture, const vec2i& size, const std::string& name) { return Texture(new TextureData(renderContext(), texture, size, name)); } void TextureFactory::reloadObject(LoadableObject::Pointer object, ObjectsCache&) { TextureDescription::Pointer newData = et::loadTexture(object->origin()); if (newData.valid()) Texture(object)->updateData(renderContext(), newData); } <|endoftext|>
<commit_before>/* gpe_scene_particle_class.cpp This file is part of: GAME PENCIL ENGINE https://create.pawbyte.com Copyright (c) 2014-2020 Nathan Hurde, Chase Lee. Copyright (c) 2014-2020 PawByte LLC. Copyright (c) 2014-2020 Game Pencil Engine contributors ( Contributors Page ) 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. -Game Pencil Engine <https://create.pawbyte.com> */ #include "gpe_scene_particle_class.h" GPE_SceneParticleEmitter::GPE_SceneParticleEmitter( GPE_GeneralResourceContainer *pFolder ) { iconTexture = guiRCM->texture_add( APP_DIRECTORY_NAME+"resources/gfx/iconpacks/fontawesome/magic.png") ; branchType = BRANCH_TYPE_PARTIClE_EMITTER; if( projectParentFolder!=NULL) { emmitterInEditor = new GPE_DropDown_Resouce_Menu( "Particle Emitter",projectParentFolder->find_resource_from_name(RESOURCE_TYPE_NAMES[RESOURCE_TYPE_EMITTER]+"s"),-1,true); emmitterInEditor->set_width(192); } else { emmitterInEditor = NULL; } } GPE_SceneParticleEmitter::~GPE_SceneParticleEmitter() { } void GPE_SceneParticleEmitter::add_typed_elements() { if( PANEL_INSPECTOR!=NULL ) { //PANEL_INSPECTOR->add_gui_element( lightIsActive, true ); } } bool GPE_SceneParticleEmitter::build_intohtml5_file(std::ofstream * fileTarget, int leftTabAmount, GPE_GeneralResourceContainer * localResTypeController ) { GPE_SceneBasicClass::build_intohtml5_file( fileTarget, leftTabAmount+1, localResTypeController); return true; } void GPE_SceneParticleEmitter::process_elements() { GPE_SceneBasicClass::process_elements(); } void GPE_SceneParticleEmitter::render_branch() { } bool GPE_SceneParticleEmitter::save_branch_data(std::ofstream * fileTarget, int nestedFoldersIn ) { if( fileTarget!=NULL && fileTarget->is_open() ) { std::string nestedTabsStr = generate_tabs( nestedFoldersIn ); *fileTarget << nestedTabsStr+" GPE_AmbientLight="; if( xPosField!=NULL) { xPosField->make_valid_number(0); *fileTarget << xPosField->get_held_number() << ","; } else { *fileTarget << "-0,"; } if( yPosField!=NULL) { yPosField->make_valid_number(0); *fileTarget << yPosField->get_held_number() << ","; } else { *fileTarget << "-0,"; } if( branchColor!=NULL) { *fileTarget << branchColor->get_hex_string() << ","; } else { *fileTarget << "#FFFF00,"; } if( branchAlpha!=NULL) { *fileTarget << int_to_string( branchAlpha->get_value() )<< ","; } else { *fileTarget << "255,"; } *fileTarget << opName+",,\n"; GPE_SceneBasicClass::save_branch_data( fileTarget, nestedFoldersIn+1 ); return true; } return false; } <commit_msg>Delete gpe_scene_particle_class.cpp<commit_after><|endoftext|>