text
stringlengths
54
60.6k
<commit_before>/* conduitConfigDialog.cc KPilot ** ** Copyright (C) 2001 by Dan Pilone ** ** This file defines a .ui-based configuration dialog for conduits. */ /* ** This program is free software; you can redistribute it and/or modify ** it under the terms of the GNU General Public License as published by ** the Free Software Foundation; either version 2 of the License, or ** (at your option) any later version. ** ** This program is distributed in the hope that it will be useful, ** but WITHOUT ANY WARRANTY; without even the implied warranty of ** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ** GNU General Public License for more details. ** ** You should have received a copy of the GNU General Public License ** along with this program in a file called COPYING; if not, write to ** the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, ** MA 02111-1307, USA. */ /* ** Bug reports and questions can be sent to [email protected] */ static const char *conduitconfigdialog_id = "$Id$"; //#include "options.h" #include <qpushbutton.h> #include <qbuttongroup.h> #include <qcheckbox.h> #include <qlineedit.h> #include <kmessagebox.h> #include <kglobal.h> #include <klocale.h> #include <kconfigskeleton.h> #include "kpilotConfig.h" #include "options.h" #include "kpilotConfigWizard_base1.h" #include "kpilotConfigWizard_base2.h" #include "kpilotConfigWizard_base3.h" #include "kpilotConfigWizard.moc" ConfigWizard::ConfigWizard(QWidget *parent, const char *n) : KWizard(parent, n) { page1=new ConfigWizard_base1(this); addPage( page1, i18n("Select connection type") ); page2=new ConfigWizard_base2(this); addPage( page2, i18n("Pilot info") ); page3=new ConfigWizard_base3(this); addPage( page3, i18n("Application to sync with") ); setFinishEnabled( page3, true ); connect( page2->fProbeButton, SIGNAL( pressed() ), this, SLOT( probeHandheld() ) ); KPilotSettings::self()->readConfig(); page2->fUserName->setText( KPilotSettings::userName() ); page2->fDeviceName->setText( KPilotSettings::pilotDevice() ); page2->fPilotRunningPermanently->setChecked( KPilotSettings::startDaemonAtLogin() ); } ConfigWizard::~ConfigWizard() { } void ConfigWizard::accept() { FUNCTIONSETUP; QString username( page2->fUserName->text() ); QString devicename( page2->fDeviceName->text() ); int devicetype( page1->fConnectionType->selectedId() ); enum eSyncApp { eAppKDE=0, eAppKontact, eAppEvolution } app; app=(eSyncApp)( page3->fAppType->selectedId() ); bool keepPermanently( page2->fPilotRunningPermanently->isChecked() ); #ifdef DEBUG DEBUGCONDUIT<<fname<<"Keep permanently: "<<keepPermanently<<endl; #endif KPilotSettings::setPilotDevice( devicename ); KPilotSettings::setUserName(username); KPilotSettings::setEncoding("iso 8859-15"); KPilotSettings::setDockDaemon( true ); KPilotSettings::setKillDaemonAtExit( !keepPermanently); KPilotSettings::setQuitAfterSync( !keepPermanently ); KPilotSettings::setStartDaemonAtLogin( keepPermanently ); KPilotSettings::setSyncType(0); KPilotSettings::setFullSyncOnPCChange( true ); KPilotSettings::setConflictResolution(0); QStringList conduits = KPilotSettings::installedConduits(); // TODO: enable the right conduits #define APPEND_CONDUIT(a) if (!conduits.contains(a)) conduits.append(a) APPEND_CONDUIT("internal_fileinstall"); APPEND_CONDUIT("todo-conduit"); APPEND_CONDUIT("vcal-conduit"); switch (app) { case eAppEvolution: conduits.remove("knotes-conduit"); // TODO: Once the Evolution abook resource is finished, enable it... conduits.remove("abbrowser_conduit"); // TODO: settings for conduits break; case eAppKDE: case eAppKontact: default: APPEND_CONDUIT("knotes-conduit"); APPEND_CONDUIT("abbrowser_conduit"); // TODO: settings for conduits break; } KPilotSettings::setInstalledConduits( conduits ); #undef APPEND_CONDUIT KPilotSettings::self()->writeConfig(); QDialog::accept(); } void ConfigWizard::probeHandheld() { // TODO KMessageBox::information(this, "Probing the handheld, not yet implemented", "Probing"); } <commit_msg>At the end of the wizard, show a message box that kpilot is now configured to sy nc with {general KDE-PIM,Kontact,Evolution}.<commit_after>/* conduitConfigDialog.cc KPilot ** ** Copyright (C) 2004 by Dan Pilone ** Written 2004 by Reinhold Kainhofer ** ** This file defines a .ui-based configuration dialog for conduits. */ /* ** This program is free software; you can redistribute it and/or modify ** it under the terms of the GNU General Public License as published by ** the Free Software Foundation; either version 2 of the License, or ** (at your option) any later version. ** ** This program is distributed in the hope that it will be useful, ** but WITHOUT ANY WARRANTY; without even the implied warranty of ** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ** GNU General Public License for more details. ** ** You should have received a copy of the GNU General Public License ** along with this program in a file called COPYING; if not, write to ** the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, ** MA 02111-1307, USA. */ /* ** Bug reports and questions can be sent to [email protected] */ static const char *conduitconfigdialog_id = "$Id$"; //#include "options.h" #include <qpushbutton.h> #include <qbuttongroup.h> #include <qcheckbox.h> #include <qlineedit.h> #include <kmessagebox.h> #include <kglobal.h> #include <klocale.h> #include <kconfigskeleton.h> #include "kpilotConfig.h" #include "options.h" #include "kpilotConfigWizard_base1.h" #include "kpilotConfigWizard_base2.h" #include "kpilotConfigWizard_base3.h" #include "kpilotConfigWizard.moc" ConfigWizard::ConfigWizard(QWidget *parent, const char *n) : KWizard(parent, n) { page1=new ConfigWizard_base1(this); addPage( page1, i18n("Select connection type") ); page2=new ConfigWizard_base2(this); addPage( page2, i18n("Pilot info") ); page3=new ConfigWizard_base3(this); addPage( page3, i18n("Application to sync with") ); setFinishEnabled( page3, true ); connect( page2->fProbeButton, SIGNAL( pressed() ), this, SLOT( probeHandheld() ) ); KPilotSettings::self()->readConfig(); page2->fUserName->setText( KPilotSettings::userName() ); page2->fDeviceName->setText( KPilotSettings::pilotDevice() ); page2->fPilotRunningPermanently->setChecked( KPilotSettings::startDaemonAtLogin() ); } ConfigWizard::~ConfigWizard() { } void ConfigWizard::accept() { FUNCTIONSETUP; QString username( page2->fUserName->text() ); QString devicename( page2->fDeviceName->text() ); // int devicetype( page1->fConnectionType->selectedId() ); enum eSyncApp { eAppKDE=0, eAppKontact, eAppEvolution } app; app=(eSyncApp)( page3->fAppType->selectedId() ); bool keepPermanently( page2->fPilotRunningPermanently->isChecked() ); #ifdef DEBUG DEBUGCONDUIT<<fname<<"Keep permanently: "<<keepPermanently<<endl; #endif KPilotSettings::setPilotDevice( devicename ); KPilotSettings::setUserName(username); KPilotSettings::setEncoding("iso 8859-15"); KPilotSettings::setDockDaemon( true ); KPilotSettings::setKillDaemonAtExit( !keepPermanently); KPilotSettings::setQuitAfterSync( !keepPermanently ); KPilotSettings::setStartDaemonAtLogin( keepPermanently ); KPilotSettings::setSyncType(0); KPilotSettings::setFullSyncOnPCChange( true ); KPilotSettings::setConflictResolution(0); QStringList conduits = KPilotSettings::installedConduits(); // TODO: enable the right conduits #define APPEND_CONDUIT(a) if (!conduits.contains(a)) conduits.append(a) QString applicationName(i18n("general KDE-PIM")); APPEND_CONDUIT("internal_fileinstall"); APPEND_CONDUIT("todo-conduit"); APPEND_CONDUIT("vcal-conduit"); switch (app) { case eAppEvolution: applicationName=i18n("Gnome's PIM suite", "Evolution"); conduits.remove("knotes-conduit"); // TODO: Once the Evolution abook resource is finished, enable it... conduits.remove("abbrowser_conduit"); // TODO: settings for conduits break; case eAppKontact: applicationName=i18n("KDE's PIM suite", "Kontact"); case eAppKDE: default: APPEND_CONDUIT("knotes-conduit"); APPEND_CONDUIT("abbrowser_conduit"); // TODO: settings for conduits break; } KPilotSettings::setInstalledConduits( conduits ); #undef APPEND_CONDUIT KMessageBox::information(this, i18n("KPilot is now configured to sync with %1.\n" "The remaining options in the config dialog are advanced options and can " "be used to fine-tune KPilot.").arg(applicationName), i18n("Automatic configuration finished")); KPilotSettings::self()->writeConfig(); QDialog::accept(); } // Devices to probe: // void ConfigWizard::probeHandheld() { // TODO KMessageBox::information(this, "Probing the handheld, not yet implemented", "Probing"); } <|endoftext|>
<commit_before>/* * \copyright Copyright 2014 Xiang Zhang All Rights Reserved. * \license @{ * * 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. * * @} */ #ifndef THUNDER_SERIALIZER_SERIALIZER_HPP_ #define THUNDER_SERIALIZER_SERIALIZER_HPP_ #include <memory> #include <sstream> #include "thunder/serializer/text.hpp" namespace thunder { namespace serializer { template < typename M = ::std::stringstream, typename P = Text< M > > class Serializer { public: typedef M stream_type; typedef typename M::char_type char_type; typedef ::std::shared_ptr(M) stream_pointer; template < typename... G > Serializer(G... g); ~Serializer(); stream_pointer stream(); template < typename T > void save(const T &t); template < typename T > void load (T *t); private: stream_pointer *stream_; ::std::unordered_set< void* > saved_pointers_; ::std::unordered_map< void*, void* > loaded_pointers_; ::std::unordered_map< void*, void* > loaded_shared_; // Const variables to identify types data static const char_type kPrimitive = 0; static const char_type kClass = 1; static const char_type kPointer = 2; static const char_type kShared = 3; }; } // namespace serializer } // namespace thunder #endif // THUNDER_SERIALIZER_SERIALIZER_HPP_ <commit_msg>Removed constants<commit_after>/* * \copyright Copyright 2014 Xiang Zhang All Rights Reserved. * \license @{ * * 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. * * @} */ #ifndef THUNDER_SERIALIZER_SERIALIZER_HPP_ #define THUNDER_SERIALIZER_SERIALIZER_HPP_ #include <memory> #include <sstream> #include "thunder/serializer/text.hpp" namespace thunder { namespace serializer { template < typename M = ::std::stringstream, typename P = Text< M > > class Serializer { public: typedef M stream_type; typedef typename M::char_type char_type; typedef ::std::shared_ptr(M) stream_pointer; template < typename... G > Serializer(G... g); ~Serializer(); stream_pointer stream(); template < typename T > void save(const T &t); template < typename T > void load (T *t); private: stream_pointer *stream_; ::std::unordered_set< void* > saved_pointers_; ::std::unordered_map< void*, void* > loaded_pointers_; ::std::unordered_map< void*, void* > loaded_shared_; }; } // namespace serializer } // namespace thunder #endif // THUNDER_SERIALIZER_SERIALIZER_HPP_ <|endoftext|>
<commit_before>/** @file session_process.cc - encrypt and decrypt sessions @section license License Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to you under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ #include <cmath> #include <cstring> #include <cerrno> #include <openssl/ssl.h> #include <openssl/err.h> #include <openssl/rand.h> #include <ts/ts.h> #include "session_process.h" #include "ssl_utils.h" #include "common.h" const unsigned char salt[] = {115, 97, 108, 117, 0, 85, 137, 229}; int encrypt_session(const char *session_data, int32_t session_data_len, const unsigned char *key, int key_length, std::string &encrypted_data) { size_t len_all = 0; size_t offset = 0; char *pBuf = nullptr; int encrypted_buffer_size = 0; int encrypted_msg_len = 0; unsigned char *encrypted_msg = nullptr; int ret = 0; offset = 0; len_all = sizeof(int64_t) + sizeof(int32_t) + session_data_len; pBuf = new char[len_all]; // Put in a fixed experation time of 7 hours, just to have communication consistency with the original // protocol int64_t expire_time = time(nullptr) + 2 * 3600; memcpy(pBuf + offset, &expire_time, sizeof(expire_time)); offset += sizeof(int64_t); memcpy(pBuf + offset, &session_data_len, sizeof(int32_t)); offset += sizeof(session_data_len); memcpy(pBuf + offset, session_data, session_data_len); // Initialize context EVP_CIPHER_CTX *context = EVP_CIPHER_CTX_new(); unsigned char iv[EVP_MAX_IV_LENGTH]; unsigned char gen_key[EVP_MAX_KEY_LENGTH]; // generate key and iv int generated_key_len = EVP_BytesToKey(EVP_aes_256_cbc(), EVP_md5(), (unsigned char *)salt, key, key_length, 1, gen_key, iv); if (generated_key_len <= 0) { TSDebug(PLUGIN, "Error generating key"); } // Set context AES128 with the generated key and iv if (1 != EVP_EncryptInit_ex(context, EVP_aes_256_cbc(), nullptr, gen_key, iv)) { TSDebug(PLUGIN, "Encryption of session data failed"); ret = -1; goto Cleanup; } int elen; encrypted_buffer_size = ENCRYPT_LEN(len_all); encrypted_msg_len = encrypted_buffer_size; encrypted_msg = new unsigned char[encrypted_buffer_size]; if (1 != EVP_EncryptUpdate(context, (unsigned char *)encrypted_msg, &elen, (unsigned char *)pBuf, len_all)) { TSDebug(PLUGIN, "Encryption of session data failed"); ret = -1; goto Cleanup; } encrypted_msg_len = elen; if (1 != EVP_EncryptFinal_ex(context, encrypted_msg + elen, &elen)) { TSDebug(PLUGIN, "Encryption of session data failed"); ret = -1; goto Cleanup; } encrypted_msg_len += elen; TSDebug(PLUGIN, "Encrypted buffer of size %d to buffer of size %d\n", session_data_len, encrypted_msg_len); encrypted_data.assign((char *)encrypted_msg, encrypted_msg_len); Cleanup: if (pBuf) delete[] pBuf; if (encrypted_msg) delete[] encrypted_msg; if (context) { EVP_CIPHER_CTX_free(context); } return ret; } /** * The initial value of session_data_len is the number of bytes in session_data * The return value of session_data_len is the number of bytes actually stored in session_data * The return value is -1 on error or the number of bytes in the decrypted session data (may be more * than the initial value of sesion_data_len */ int decrypt_session(const std::string &encrypted_data, const unsigned char *key, int key_length, char *session_data, int32_t &session_data_len) { unsigned char *ssl_sess_ptr = nullptr; int decrypted_buffer_size = 0; int decrypted_msg_len = 0; unsigned char *decrypted_msg = nullptr; int ret = 0; // Initialize context // Initialize context EVP_CIPHER_CTX *context = EVP_CIPHER_CTX_new(); unsigned char iv[EVP_MAX_IV_LENGTH]; unsigned char gen_key[EVP_MAX_KEY_LENGTH]; // generate key and iv int generated_key_len = EVP_BytesToKey(EVP_aes_256_cbc(), EVP_md5(), (unsigned char *)salt, key, key_length, 1, gen_key, iv); if (generated_key_len <= 0) { TSDebug(PLUGIN, "Error generating key"); } // set context with the generated key and iv if (1 != EVP_DecryptInit_ex(context, EVP_aes_256_cbc(), nullptr, gen_key, iv)) { TSDebug(PLUGIN, "Decryption of encrypted session data failed"); goto Cleanup; } decrypted_buffer_size = DECRYPT_LEN(encrypted_data.length()); decrypted_msg = (unsigned char *)new char[decrypted_buffer_size + 1]; decrypted_msg_len = decrypted_buffer_size + 1; if (decrypted_msg == nullptr) TSError("decrypted_msg allocate failure"); if (1 != EVP_DecryptUpdate(context, decrypted_msg, &decrypted_msg_len, (unsigned char *)encrypted_data.c_str(), encrypted_data.length())) { TSDebug(PLUGIN, "Decryption of encrypted session data failed"); goto Cleanup; } // Retrieve ssl_session ssl_sess_ptr = (unsigned char *)decrypted_msg; // Skip the expiration time. Just a place holder to interact with the old version ssl_sess_ptr += sizeof(int64_t); // Length ret = *(int32_t *)ssl_sess_ptr; ssl_sess_ptr += sizeof(int32_t); TSDebug(PLUGIN, "Decrypted buffer of size %d from buffer of size %d\n", ret, session_data_len); // If there is less data than the maxiumum buffer size, reduce accordingly if (ret < session_data_len) { session_data_len = ret; } memcpy(session_data, ssl_sess_ptr, session_data_len); Cleanup: if (decrypted_msg) delete[] decrypted_msg; if (context) { EVP_CIPHER_CTX_free(context); } return ret; } int decode_id(const std::string &encoded_id, char *decoded_data, int &decoded_data_len) { size_t decode_len = 0; memset(decoded_data, 0, decoded_data_len); if (TSBase64Decode((const char *)encoded_id.c_str(), encoded_id.length(), (unsigned char *)decoded_data, decoded_data_len, &decode_len) != 0) { TSError("Base 64 decoding failed."); return -1; } decoded_data_len = decode_len; return 0; } int encode_id(const char *id, int idlen, std::string &encoded_data) { char *encoded = new char[ENCODED_LEN(idlen)]; memset(encoded, 0, ENCODED_LEN(idlen)); size_t encoded_len = 0; if (TSBase64Encode((const char *)id, idlen, encoded, ENCODED_LEN(idlen), &encoded_len) != 0) { TSError("Base 64 encoding failed."); if (encoded) delete[] encoded; return -1; } encoded_data.assign(encoded); if (encoded) delete[] encoded; return 0; } int add_session(char *session_id, int session_id_len, const std::string &encrypted_session) { char session_data[SSL_SESSION_MAX_DER]; int32_t session_data_len = SSL_SESSION_MAX_DER; if (decrypt_session(encrypted_session, (unsigned char *)get_key_ptr(), get_key_length(), session_data, session_data_len) < 0) { TSError("Failed to decrypt session %.*s", session_id_len, session_id); return -1; } const unsigned char *loc = reinterpret_cast<const unsigned char *>(session_data); SSL_SESSION *sess = d2i_SSL_SESSION(nullptr, &loc, session_data_len); if (nullptr == sess) { TSError("Failed to transform session buffer %.*s", session_id_len, session_id); } TSSslSessionID sid; memcpy(reinterpret_cast<char *>(sid.bytes), session_id, session_id_len); sid.len = session_id_len; if (sid.len > sizeof(sid.bytes)) { sid.len = sizeof(sid.bytes); } TSSslSessionInsert(&sid, reinterpret_cast<TSSslSession>(sess)); // Free the sesison object created by d2i_SSL_SESSION // We should make an API that just takes the ASN buffer SSL_SESSION_free(sess); return 0; } <commit_msg>Remove unused assignment to satisfy clang-analyzer<commit_after>/** @file session_process.cc - encrypt and decrypt sessions @section license License Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to you under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ #include <cmath> #include <cstring> #include <cerrno> #include <openssl/ssl.h> #include <openssl/err.h> #include <openssl/rand.h> #include <ts/ts.h> #include "session_process.h" #include "ssl_utils.h" #include "common.h" const unsigned char salt[] = {115, 97, 108, 117, 0, 85, 137, 229}; int encrypt_session(const char *session_data, int32_t session_data_len, const unsigned char *key, int key_length, std::string &encrypted_data) { size_t len_all = 0; size_t offset = 0; char *pBuf = nullptr; int encrypted_buffer_size = 0; int encrypted_msg_len = 0; unsigned char *encrypted_msg = nullptr; int ret = 0; offset = 0; len_all = sizeof(int64_t) + sizeof(int32_t) + session_data_len; pBuf = new char[len_all]; // Put in a fixed experation time of 7 hours, just to have communication consistency with the original // protocol int64_t expire_time = time(nullptr) + 2 * 3600; memcpy(pBuf + offset, &expire_time, sizeof(expire_time)); offset += sizeof(int64_t); memcpy(pBuf + offset, &session_data_len, sizeof(int32_t)); offset += sizeof(session_data_len); memcpy(pBuf + offset, session_data, session_data_len); // Initialize context EVP_CIPHER_CTX *context = EVP_CIPHER_CTX_new(); unsigned char iv[EVP_MAX_IV_LENGTH]; unsigned char gen_key[EVP_MAX_KEY_LENGTH]; // generate key and iv int generated_key_len = EVP_BytesToKey(EVP_aes_256_cbc(), EVP_md5(), (unsigned char *)salt, key, key_length, 1, gen_key, iv); if (generated_key_len <= 0) { TSDebug(PLUGIN, "Error generating key"); } // Set context AES128 with the generated key and iv if (1 != EVP_EncryptInit_ex(context, EVP_aes_256_cbc(), nullptr, gen_key, iv)) { TSDebug(PLUGIN, "Encryption of session data failed"); ret = -1; goto Cleanup; } int elen; encrypted_buffer_size = ENCRYPT_LEN(len_all); encrypted_msg = new unsigned char[encrypted_buffer_size]; if (1 != EVP_EncryptUpdate(context, (unsigned char *)encrypted_msg, &elen, (unsigned char *)pBuf, len_all)) { TSDebug(PLUGIN, "Encryption of session data failed"); ret = -1; goto Cleanup; } encrypted_msg_len = elen; if (1 != EVP_EncryptFinal_ex(context, encrypted_msg + elen, &elen)) { TSDebug(PLUGIN, "Encryption of session data failed"); ret = -1; goto Cleanup; } encrypted_msg_len += elen; TSDebug(PLUGIN, "Encrypted buffer of size %d to buffer of size %d\n", session_data_len, encrypted_msg_len); encrypted_data.assign((char *)encrypted_msg, encrypted_msg_len); Cleanup: if (pBuf) delete[] pBuf; if (encrypted_msg) delete[] encrypted_msg; if (context) { EVP_CIPHER_CTX_free(context); } return ret; } /** * The initial value of session_data_len is the number of bytes in session_data * The return value of session_data_len is the number of bytes actually stored in session_data * The return value is -1 on error or the number of bytes in the decrypted session data (may be more * than the initial value of sesion_data_len */ int decrypt_session(const std::string &encrypted_data, const unsigned char *key, int key_length, char *session_data, int32_t &session_data_len) { unsigned char *ssl_sess_ptr = nullptr; int decrypted_buffer_size = 0; int decrypted_msg_len = 0; unsigned char *decrypted_msg = nullptr; int ret = 0; // Initialize context // Initialize context EVP_CIPHER_CTX *context = EVP_CIPHER_CTX_new(); unsigned char iv[EVP_MAX_IV_LENGTH]; unsigned char gen_key[EVP_MAX_KEY_LENGTH]; // generate key and iv int generated_key_len = EVP_BytesToKey(EVP_aes_256_cbc(), EVP_md5(), (unsigned char *)salt, key, key_length, 1, gen_key, iv); if (generated_key_len <= 0) { TSDebug(PLUGIN, "Error generating key"); } // set context with the generated key and iv if (1 != EVP_DecryptInit_ex(context, EVP_aes_256_cbc(), nullptr, gen_key, iv)) { TSDebug(PLUGIN, "Decryption of encrypted session data failed"); goto Cleanup; } decrypted_buffer_size = DECRYPT_LEN(encrypted_data.length()); decrypted_msg = (unsigned char *)new char[decrypted_buffer_size + 1]; decrypted_msg_len = decrypted_buffer_size + 1; if (decrypted_msg == nullptr) TSError("decrypted_msg allocate failure"); if (1 != EVP_DecryptUpdate(context, decrypted_msg, &decrypted_msg_len, (unsigned char *)encrypted_data.c_str(), encrypted_data.length())) { TSDebug(PLUGIN, "Decryption of encrypted session data failed"); goto Cleanup; } // Retrieve ssl_session ssl_sess_ptr = (unsigned char *)decrypted_msg; // Skip the expiration time. Just a place holder to interact with the old version ssl_sess_ptr += sizeof(int64_t); // Length ret = *(int32_t *)ssl_sess_ptr; ssl_sess_ptr += sizeof(int32_t); TSDebug(PLUGIN, "Decrypted buffer of size %d from buffer of size %d\n", ret, session_data_len); // If there is less data than the maxiumum buffer size, reduce accordingly if (ret < session_data_len) { session_data_len = ret; } memcpy(session_data, ssl_sess_ptr, session_data_len); Cleanup: if (decrypted_msg) delete[] decrypted_msg; if (context) { EVP_CIPHER_CTX_free(context); } return ret; } int decode_id(const std::string &encoded_id, char *decoded_data, int &decoded_data_len) { size_t decode_len = 0; memset(decoded_data, 0, decoded_data_len); if (TSBase64Decode((const char *)encoded_id.c_str(), encoded_id.length(), (unsigned char *)decoded_data, decoded_data_len, &decode_len) != 0) { TSError("Base 64 decoding failed."); return -1; } decoded_data_len = decode_len; return 0; } int encode_id(const char *id, int idlen, std::string &encoded_data) { char *encoded = new char[ENCODED_LEN(idlen)]; memset(encoded, 0, ENCODED_LEN(idlen)); size_t encoded_len = 0; if (TSBase64Encode((const char *)id, idlen, encoded, ENCODED_LEN(idlen), &encoded_len) != 0) { TSError("Base 64 encoding failed."); if (encoded) delete[] encoded; return -1; } encoded_data.assign(encoded); if (encoded) delete[] encoded; return 0; } int add_session(char *session_id, int session_id_len, const std::string &encrypted_session) { char session_data[SSL_SESSION_MAX_DER]; int32_t session_data_len = SSL_SESSION_MAX_DER; if (decrypt_session(encrypted_session, (unsigned char *)get_key_ptr(), get_key_length(), session_data, session_data_len) < 0) { TSError("Failed to decrypt session %.*s", session_id_len, session_id); return -1; } const unsigned char *loc = reinterpret_cast<const unsigned char *>(session_data); SSL_SESSION *sess = d2i_SSL_SESSION(nullptr, &loc, session_data_len); if (nullptr == sess) { TSError("Failed to transform session buffer %.*s", session_id_len, session_id); } TSSslSessionID sid; memcpy(reinterpret_cast<char *>(sid.bytes), session_id, session_id_len); sid.len = session_id_len; if (sid.len > sizeof(sid.bytes)) { sid.len = sizeof(sid.bytes); } TSSslSessionInsert(&sid, reinterpret_cast<TSSslSession>(sess)); // Free the sesison object created by d2i_SSL_SESSION // We should make an API that just takes the ASN buffer SSL_SESSION_free(sess); return 0; } <|endoftext|>
<commit_before>/**************************************************************************** * Copyright (c) 2012-2018 by the DataTransferKit authors * * All rights reserved. * * * * This file is part of the DataTransferKit library. DataTransferKit is * * distributed under a BSD 3-clause license. For the licensing terms see * * the LICENSE file in the top-level directory. * * * * SPDX-License-Identifier: BSD-3-Clause * ****************************************************************************/ /*! * \file DTK_Benchmark_MonteCarloMesh.hpp * \brief MonteCarlo mesh interface for the hybrid transport benchmark. */ //---------------------------------------------------------------------------// #ifndef DTK_MONTECARLOMESH_HPP #define DTK_MONTECARLOMESH_HPP #include "DTK_Benchmark_CartesianMesh.hpp" #include <Teuchos_Comm.hpp> #include <Teuchos_RCP.hpp> #include <memory> #include <vector> namespace DataTransferKit { namespace Benchmark { //---------------------------------------------------------------------------// /*! * \class MonteCarloMesh * \brief Mesh and partitioner for Monte Carlo transport simulations. * * Monte Carlo grids are typically subdivided into a small number of "blocks", * which can be interpreted as grid partitions, and "sets" which can be * interpreted as a number of replications of the grid. * * The block decomposition, or spatial partitioning of the mesh, is always * computed with user provided planes indicating the spatial boundaries of * each block. The underlying grid is then subdivided into blocks based on the * plane locations. If a plane intersects a cell, that cell is assigned to * both blocks adjacent to the plane. * * Note that the boundary mesh planes don't have to contain the grid - we will * just use them to carve out partitions from the background grid. * * The resulting partitioning is used to create the needed data in the base * class with mesh data being accessed through the base class * interface. Really think about this class as a decorator for the base class * which provides an initial partitioning. */ class MonteCarloMesh { public: /*! * \brief Uniform cell size constructor. * * Builds a regular grid with a uniform cell size and partitions it using * the input boundary mesh arrays. * * \param comm The communicator over which the mesh will be partitioned. * * \param num_cells_i The global number of mesh cells in the X direction. * * \param num_cells_j The global number of mesh cells in the Y direction. * * \param num_cells_k The global number of mesh cells in the Z direction. * * \param delta_x The size of the mesh cells in the X direction. * * \param delta_y The size of the mesh cells in the Y direction. * * \param delta_z The size of the mesh cells in the Z direction. * * \param x_bnd_mesh The boundary mesh node locations in the x direction. * * \param y_bnd_mesh The boundary mesh node locations in the y direction. * * \param z_bnd_mesh The boundary mesh node locations in the z direction. */ MonteCarloMesh( const Teuchos::RCP<const Teuchos::Comm<int>> &comm, const int num_sets, const int num_cells_i, const int num_cells_j, const int num_cells_k, const double delta_x, const double delta_y, const double delta_z, const std::vector<double> &x_bnd_mesh, const std::vector<double> &y_bnd_mesh, const std::vector<double> &z_bnd_mesh ); /*! * \brief Global edge constructor. A global list of node locations will be * used to create the mesh. The mesh will be partitioned using the input * boundary mesh arrays. * * \param comm The parallel communicator over which the mesh is built. * * \param global_x_edges Global list of node locations in the X direction. * * \param global_y_edges Global list of node locations in the Y direction. * * \param global_z_edges Global list of node locations in the Z direction. * * \param x_bnd_mesh The boundary mesh node locations in the x direction. * * \param y_bnd_mesh The boundary mesh node locations in the y direction. * * \param z_bnd_mesh The boundary mesh node locations in the z direction. */ MonteCarloMesh( const Teuchos::RCP<const Teuchos::Comm<int>> &comm, const int num_sets, const std::vector<double> &global_x_edges, const std::vector<double> &global_y_edges, const std::vector<double> &global_z_edges, const std::vector<double> &x_bnd_mesh, const std::vector<double> &y_bnd_mesh, const std::vector<double> &z_bnd_mesh ); /*! * \brief Get the local Cartesian mesh owned by this process. */ std::shared_ptr<CartesianMesh> cartesianMesh() const { return _cartesian_mesh; } private: // Partition the mesh. void partition( const Teuchos::RCP<const Teuchos::Comm<int>> &comm, const int num_sets, const std::vector<double> &global_x_edges, const std::vector<double> &global_y_edges, const std::vector<double> &global_z_edges, const std::vector<double> &x_bnd_mesh, const std::vector<double> &y_bnd_mesh, const std::vector<double> &z_bnd_mesh ); // Calculate local edge arrays. void computeLocalEdges( const std::vector<double> &global_edges, const std::vector<double> &bnd_mesh, const int my_block, std::vector<double> &local_edges, int &offset ) const; private: // The Cartesian mesh owned by this process. std::shared_ptr<CartesianMesh> _cartesian_mesh; }; //---------------------------------------------------------------------------// } // end namespace Benchmark } // end namespace DataTransferKit #endif // end DTK_MONTECARLOMESH_HPP <commit_msg>adding missing parameter to doxygen for MonteCarloMesh<commit_after>/**************************************************************************** * Copyright (c) 2012-2018 by the DataTransferKit authors * * All rights reserved. * * * * This file is part of the DataTransferKit library. DataTransferKit is * * distributed under a BSD 3-clause license. For the licensing terms see * * the LICENSE file in the top-level directory. * * * * SPDX-License-Identifier: BSD-3-Clause * ****************************************************************************/ /*! * \file DTK_Benchmark_MonteCarloMesh.hpp * \brief MonteCarlo mesh interface for the hybrid transport benchmark. */ //---------------------------------------------------------------------------// #ifndef DTK_MONTECARLOMESH_HPP #define DTK_MONTECARLOMESH_HPP #include "DTK_Benchmark_CartesianMesh.hpp" #include <Teuchos_Comm.hpp> #include <Teuchos_RCP.hpp> #include <memory> #include <vector> namespace DataTransferKit { namespace Benchmark { //---------------------------------------------------------------------------// /*! * \class MonteCarloMesh * \brief Mesh and partitioner for Monte Carlo transport simulations. * * Monte Carlo grids are typically subdivided into a small number of "blocks", * which can be interpreted as grid partitions, and "sets" which can be * interpreted as a number of replications of the grid. * * The block decomposition, or spatial partitioning of the mesh, is always * computed with user provided planes indicating the spatial boundaries of * each block. The underlying grid is then subdivided into blocks based on the * plane locations. If a plane intersects a cell, that cell is assigned to * both blocks adjacent to the plane. * * Note that the boundary mesh planes don't have to contain the grid - we will * just use them to carve out partitions from the background grid. * * The resulting partitioning is used to create the needed data in the base * class with mesh data being accessed through the base class * interface. Really think about this class as a decorator for the base class * which provides an initial partitioning. */ class MonteCarloMesh { public: /*! * \brief Uniform cell size constructor. * * Builds a regular grid with a uniform cell size and partitions it using * the input boundary mesh arrays. * * \param comm The communicator over which the mesh will be partitioned. * * \param num_sets The number of sets over which to decompose the * mesh. This is the total number of times the mesh is replicated. * * \param num_cells_i The global number of mesh cells in the X direction. * * \param num_cells_j The global number of mesh cells in the Y direction. * * \param num_cells_k The global number of mesh cells in the Z direction. * * \param delta_x The size of the mesh cells in the X direction. * * \param delta_y The size of the mesh cells in the Y direction. * * \param delta_z The size of the mesh cells in the Z direction. * * \param x_bnd_mesh The boundary mesh node locations in the x direction. * * \param y_bnd_mesh The boundary mesh node locations in the y direction. * * \param z_bnd_mesh The boundary mesh node locations in the z direction. */ MonteCarloMesh( const Teuchos::RCP<const Teuchos::Comm<int>> &comm, const int num_sets, const int num_cells_i, const int num_cells_j, const int num_cells_k, const double delta_x, const double delta_y, const double delta_z, const std::vector<double> &x_bnd_mesh, const std::vector<double> &y_bnd_mesh, const std::vector<double> &z_bnd_mesh ); /*! * \brief Global edge constructor. A global list of node locations will be * used to create the mesh. The mesh will be partitioned using the input * boundary mesh arrays. * * \param comm The parallel communicator over which the mesh is built. * * \param num_sets The number of sets over which to decompose the * mesh. This is the total number of times the mesh is replicated. * * \param global_x_edges Global list of node locations in the X direction. * * \param global_y_edges Global list of node locations in the Y direction. * * \param global_z_edges Global list of node locations in the Z direction. * * \param x_bnd_mesh The boundary mesh node locations in the x direction. * * \param y_bnd_mesh The boundary mesh node locations in the y direction. * * \param z_bnd_mesh The boundary mesh node locations in the z direction. */ MonteCarloMesh( const Teuchos::RCP<const Teuchos::Comm<int>> &comm, const int num_sets, const std::vector<double> &global_x_edges, const std::vector<double> &global_y_edges, const std::vector<double> &global_z_edges, const std::vector<double> &x_bnd_mesh, const std::vector<double> &y_bnd_mesh, const std::vector<double> &z_bnd_mesh ); /*! * \brief Get the local Cartesian mesh owned by this process. */ std::shared_ptr<CartesianMesh> cartesianMesh() const { return _cartesian_mesh; } private: // Partition the mesh. void partition( const Teuchos::RCP<const Teuchos::Comm<int>> &comm, const int num_sets, const std::vector<double> &global_x_edges, const std::vector<double> &global_y_edges, const std::vector<double> &global_z_edges, const std::vector<double> &x_bnd_mesh, const std::vector<double> &y_bnd_mesh, const std::vector<double> &z_bnd_mesh ); // Calculate local edge arrays. void computeLocalEdges( const std::vector<double> &global_edges, const std::vector<double> &bnd_mesh, const int my_block, std::vector<double> &local_edges, int &offset ) const; private: // The Cartesian mesh owned by this process. std::shared_ptr<CartesianMesh> _cartesian_mesh; }; //---------------------------------------------------------------------------// } // end namespace Benchmark } // end namespace DataTransferKit #endif // end DTK_MONTECARLOMESH_HPP <|endoftext|>
<commit_before>/**************************************************************************** ** ** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies). ** All rights reserved. ** Contact: Nokia Corporation ([email protected]) ** ** This file is part of the Qt Mobility Components. ** ** $QT_BEGIN_LICENSE:LGPL$ ** No Commercial Usage ** This file contains pre-release code and may not be distributed. ** You may use this file in accordance with the terms and conditions ** contained in the Technology Preview License Agreement accompanying ** this package. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Nokia gives you certain additional ** rights. These rights are described in the Nokia Qt LGPL Exception ** version 1.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 [email protected]. ** ** ** ** ** ** ** ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #include <QObject> #include <qmobilityglobal.h> #include <qtorganizer.h> #include <QtTest/QtTest> #include <QDebug> QTM_USE_NAMESPACE const QString m_managerNameSymbian("symbian"); Q_DECLARE_METATYPE(QOrganizerItemRecurrenceRule) Q_DECLARE_METATYPE(QOrganizerItemPriority) Q_DECLARE_METATYPE(QOrganizerItemLocation) class TestItemOccurrence : public QObject { Q_OBJECT private slots: void init(); void cleanup(); private slots: void addOccurrenceDetail_data(); void addOccurrenceDetail(); void addOccurrenceWithException_data(); void addOccurrenceWithException(); void fetchNegative_data(); void fetchNegative(); private: QStringList getAvailableManagers(); void addOccurrenceData(QString managerName, QString itemType); private: QOrganizerItemManager *m_om; }; void TestItemOccurrence::init() { QFETCH(QString, managerName); // Create a new item manager instance m_om = new QOrganizerItemManager(managerName); // Cleanup by deleting all items m_om->removeItems(m_om->itemIds(), 0); } void TestItemOccurrence::cleanup() { if (m_om) { delete m_om; m_om = 0; } } QStringList TestItemOccurrence::getAvailableManagers() { // Get the list of all available item managers QStringList availableManagers = QOrganizerItemManager::availableManagers(); // Remove these since test would fail availableManagers.removeAll("invalid"); availableManagers.removeAll("skeleton"); availableManagers.removeAll("memory"); return availableManagers; } void TestItemOccurrence::addOccurrenceDetail_data() { QStringList availableManagers = getAvailableManagers(); QTest::addColumn<QString>("managerName"); QTest::addColumn<QString>("itemType"); QTest::addColumn<QDateTime>("startTime"); QTest::addColumn<QOrganizerItemRecurrenceRule>("rrule"); foreach(QString manager, availableManagers) { addOccurrenceData(manager, QOrganizerItemType::TypeEvent); } } void TestItemOccurrence::addOccurrenceData(QString managerName, QString itemType) { QOrganizerItemRecurrenceRule rrule; rrule.setFrequency(QOrganizerItemRecurrenceRule::Weekly); rrule.setCount(3); QList<Qt::DayOfWeek> daysOfWeek; daysOfWeek.append(Qt::Wednesday); rrule.setDaysOfWeek(daysOfWeek); QTest::newRow(QString("[%1] weekly on Wednesday for 3 weeks").arg(managerName).toLatin1().constData()) << managerName << itemType << QDateTime(QDate(QDate::currentDate().year() , 9, 1)) << rrule; } void TestItemOccurrence::addOccurrenceDetail() { QFETCH(QString, managerName); QFETCH(QString, itemType); QFETCH(QDateTime, startTime); QFETCH(QOrganizerItemRecurrenceRule, rrule); // Set the item type QOrganizerItem item; item.setType(itemType); QDateTime endTime(QDate(QDate::currentDate().year() , 9, 30)); QOrganizerEventTimeRange timeRange; timeRange.setStartDateTime(startTime); QVERIFY(item.saveDetail(&timeRange)); // Add recurrence rules to the item QList<QOrganizerItemRecurrenceRule> rrules; rrules.append(rrule); QOrganizerItemRecurrence recurrence; recurrence.setRecurrenceRules(rrules); QVERIFY(item.saveDetail(&recurrence)); // Save item with recurrence rule. QVERIFY(m_om->saveItem(&item)); // Fetch the saved item item = m_om->item(item.localId()); // Fetch the item again QList<QOrganizerItem> instanceList = m_om->itemInstances(item,startTime,endTime); QCOMPARE(instanceList.size(), 3); QOrganizerItem lastItem = instanceList.at(2); QCOMPARE(lastItem.type(), QLatin1String(QOrganizerItemType::TypeEventOccurrence)); QOrganizerEventOccurrence thirdEvent = static_cast<QOrganizerEventOccurrence>(lastItem); QCOMPARE(thirdEvent.startDateTime(), QDateTime(QDate(QDate::currentDate().year() , 9, 15))); QCOMPARE(thirdEvent.localId(), (unsigned int)0); QCOMPARE(thirdEvent.parentLocalId(), item.localId()); //Fetch instances using maxcount only. instanceList.clear(); instanceList = m_om->itemInstances(item,startTime,QDateTime(),2); QCOMPARE(instanceList.size(), 2); QOrganizerItem secondItem = instanceList.at(1); QCOMPARE(secondItem.type(), QLatin1String(QOrganizerItemType::TypeEventOccurrence)); QOrganizerEventOccurrence secondEvent = static_cast<QOrganizerEventOccurrence>(secondItem); QCOMPARE(secondEvent.startDateTime(), QDateTime(QDate(QDate::currentDate().year() , 9, 8))); QCOMPARE(secondEvent.localId(), (unsigned int)0); QCOMPARE(secondEvent.parentLocalId(), item.localId()); } void TestItemOccurrence::addOccurrenceWithException_data() { // Get the list of all available item managers QStringList availableManagers = getAvailableManagers(); QTest::addColumn<QString>("managerName"); QTest::addColumn<QString>("itemType"); QTest::addColumn<QDateTime>("startTime"); QTest::addColumn<QDate>("exceptionDate"); QTest::addColumn<QOrganizerItemRecurrenceRule>("rrule"); QTest::addColumn<QOrganizerItemPriority>("priority"); QTest::addColumn<QOrganizerItemLocation>("location"); QString itemType = QOrganizerItemType::TypeEvent; QOrganizerItemPriority priority; priority.setPriority(QOrganizerItemPriority::HighestPriority); QOrganizerItemLocation location; location.setLocationName("checkLocationName"); location.setGeoLocation("20.176876;15.988765"); foreach(QString manager, availableManagers) { QOrganizerItemRecurrenceRule rrule; rrule.setFrequency(QOrganizerItemRecurrenceRule::Daily); rrule.setCount(10); QTest::newRow(QString("[%1] Daily event for 10 occurrences").arg(manager).toLatin1().constData()) << manager << itemType << QDateTime(QDate(QDate::currentDate().year() , 9, 1)) << QDate(QDate::currentDate().year() , 9, 3) << rrule << priority << location; } } void TestItemOccurrence::addOccurrenceWithException() { QFETCH(QString, managerName); QFETCH(QString, itemType); QFETCH(QDateTime, startTime); QFETCH(QDate,exceptionDate ); QFETCH(QOrganizerItemRecurrenceRule, rrule); QFETCH(QOrganizerItemPriority, priority); QFETCH(QOrganizerItemLocation, location); // Set the item type QOrganizerItem item; item.setType(itemType); QOrganizerEventTimeRange timeRange; timeRange.setStartDateTime(startTime); QVERIFY(item.saveDetail(&timeRange)); // Add recurrence rules to the item QList<QOrganizerItemRecurrenceRule> rrules; QList<QDate> exceptionList; rrules.append(rrule); exceptionList.append(exceptionDate); QOrganizerItemRecurrence recurrence; recurrence.setRecurrenceRules(rrules); recurrence.setExceptionDates(exceptionList); QVERIFY(item.saveDetail(&recurrence)); //Add other attributes to the item. item.setDescription("checkoccurrence"); item.saveDetail(&priority); item.saveDetail(&location); // Save item with recurrence rule. QVERIFY(m_om->saveItem(&item)); item = m_om->item(item.localId()); //Fetch instance on the exception date.An empty list should be returned QList<QOrganizerItem> instanceList = m_om->itemInstances(item,QDateTime(exceptionDate),QDateTime(exceptionDate)); QCOMPARE(instanceList.size(),0); // Fetch the item again instanceList.clear(); instanceList = m_om->itemInstances(item,startTime,QDateTime(),rrule.count()); QCOMPARE(instanceList.size(),rrule.count() -1); QOrganizerItem lastItem = instanceList.at(rrule.count()-2); QCOMPARE(lastItem.type(), QLatin1String(QOrganizerItemType::TypeEventOccurrence)); QOrganizerEventOccurrence lastEvent = static_cast<QOrganizerEventOccurrence>(lastItem); QCOMPARE(lastEvent.description(),item.description()); QOrganizerItemPriority itemPriority = item.detail(QOrganizerItemPriority::DefinitionName); QCOMPARE(lastEvent.priority(),priority.priority()); QOrganizerItemLocation itemLocation = item.detail(QOrganizerItemLocation::DefinitionName); QCOMPARE(lastEvent.locationName(),itemLocation.locationName()); QCOMPARE(lastEvent.locationGeoCoordinates(),itemLocation.geoLocation()); } void TestItemOccurrence::fetchNegative_data() { // Get the list of all available item managers QStringList availableManagers = getAvailableManagers(); QTest::addColumn<QString>("managerName"); QTest::addColumn<QString>("itemType"); QTest::addColumn<QDateTime>("startTime"); QString itemType = QOrganizerItemType::TypeEvent; foreach(QString manager, availableManagers) { QTest::newRow(QString("[%1] non repeating entry").arg(manager).toLatin1().constData()) << manager << itemType << QDateTime::currentDateTime().addSecs(3600); } } void TestItemOccurrence::fetchNegative() { //Fetch instances for a non recurring entry QFETCH(QString, managerName); QFETCH(QString, itemType); QFETCH(QDateTime, startTime); // Set the item type QOrganizerItem item; QList<QOrganizerItem> instanceList; item.setType(itemType); QDateTime endTime(startTime); QOrganizerEventTimeRange timeRange; timeRange.setStartDateTime(startTime); QVERIFY(item.saveDetail(&timeRange)); // Save item with recurrence rule. QVERIFY(m_om->saveItem(&item)); // Fetch the saved item item = m_om->item(item.localId()); // Fetch the item instances for a non repeating entry instanceList = m_om->itemInstances(item,startTime,endTime); //Only a single instance should be returned for non-repeating entry QCOMPARE(instanceList.size(), 1); //Fetch instance when end period is less than start period QDateTime previousEndTime(startTime); previousEndTime.setDate(QDate(startTime.date().year() - 2, startTime.date().month(),startTime.date().day())); instanceList = m_om->itemInstances(item,startTime,previousEndTime); QCOMPARE(m_om->error(), QOrganizerItemManager::BadArgumentError); //Fetch iteminstance for invalid itemtype eventoccurrence QOrganizerEventOccurrence invalidItem; instanceList = m_om->itemInstances(invalidItem,startTime,endTime); QCOMPARE(m_om->error(), QOrganizerItemManager::InvalidItemTypeError); // Fetch the item instance with invalid count instanceList = m_om->itemInstances(item,startTime,QDateTime(),-2); QCOMPARE(m_om->error(), QOrganizerItemManager::BadArgumentError); // Fetch the item instance with invalid starttime instanceList = m_om->itemInstances(item,QDateTime(),endTime); QCOMPARE(m_om->error(), QOrganizerItemManager::BadArgumentError); // Fetch the item instance with invalid endtime instanceList = m_om->itemInstances(item,startTime,QDateTime()); QCOMPARE(m_om->error(), QOrganizerItemManager::BadArgumentError); } QTEST_MAIN(TestItemOccurrence); #include "tst_itemoccurrence.moc" <commit_msg>additional test cases for finditeminstances<commit_after>/**************************************************************************** ** ** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies). ** All rights reserved. ** Contact: Nokia Corporation ([email protected]) ** ** This file is part of the Qt Mobility Components. ** ** $QT_BEGIN_LICENSE:LGPL$ ** No Commercial Usage ** This file contains pre-release code and may not be distributed. ** You may use this file in accordance with the terms and conditions ** contained in the Technology Preview License Agreement accompanying ** this package. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Nokia gives you certain additional ** rights. These rights are described in the Nokia Qt LGPL Exception ** version 1.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 [email protected]. ** ** ** ** ** ** ** ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #include <QObject> #include <qmobilityglobal.h> #include <qtorganizer.h> #include <QtTest/QtTest> #include <QDebug> QTM_USE_NAMESPACE const QString m_managerNameSymbian("symbian"); Q_DECLARE_METATYPE(QOrganizerItemRecurrenceRule) Q_DECLARE_METATYPE(QOrganizerItemPriority) Q_DECLARE_METATYPE(QOrganizerItemLocation) class TestItemOccurrence : public QObject { Q_OBJECT private slots: void init(); void cleanup(); private slots: void addOccurrenceDetail_data(); void addOccurrenceDetail(); void addOccurrenceWithException_data(); void addOccurrenceWithException(); void fetchNegative_data(); void fetchNegative(); private: QStringList getAvailableManagers(); void addOccurrenceData(QString managerName, QString itemType); private: QOrganizerItemManager *m_om; }; void TestItemOccurrence::init() { QFETCH(QString, managerName); // Create a new item manager instance m_om = new QOrganizerItemManager(managerName); // Cleanup by deleting all items m_om->removeItems(m_om->itemIds(), 0); } void TestItemOccurrence::cleanup() { if (m_om) { delete m_om; m_om = 0; } } QStringList TestItemOccurrence::getAvailableManagers() { // Get the list of all available item managers QStringList availableManagers = QOrganizerItemManager::availableManagers(); // Remove these since test would fail availableManagers.removeAll("invalid"); availableManagers.removeAll("skeleton"); availableManagers.removeAll("memory"); return availableManagers; } void TestItemOccurrence::addOccurrenceDetail_data() { QStringList availableManagers = getAvailableManagers(); QTest::addColumn<QString>("managerName"); QTest::addColumn<QString>("itemType"); QTest::addColumn<QDateTime>("startTime"); QTest::addColumn<QOrganizerItemRecurrenceRule>("rrule"); foreach(QString manager, availableManagers) { addOccurrenceData(manager, QOrganizerItemType::TypeEvent); } } void TestItemOccurrence::addOccurrenceData(QString managerName, QString itemType) { QOrganizerItemRecurrenceRule rrule; rrule.setFrequency(QOrganizerItemRecurrenceRule::Weekly); rrule.setCount(3); QList<Qt::DayOfWeek> daysOfWeek; daysOfWeek.append(Qt::Wednesday); rrule.setDaysOfWeek(daysOfWeek); QTest::newRow(QString("[%1] weekly on Wednesday for 3 weeks").arg(managerName).toLatin1().constData()) << managerName << itemType << QDateTime(QDate(QDate::currentDate().year() , 9, 1)) << rrule; } void TestItemOccurrence::addOccurrenceDetail() { QFETCH(QString, managerName); QFETCH(QString, itemType); QFETCH(QDateTime, startTime); QFETCH(QOrganizerItemRecurrenceRule, rrule); // Set the item type QOrganizerItem item; item.setType(itemType); QDateTime endTime(QDate(QDate::currentDate().year() , 9, 30)); QOrganizerEventTimeRange timeRange; timeRange.setStartDateTime(startTime); QVERIFY(item.saveDetail(&timeRange)); // Add recurrence rules to the item QList<QOrganizerItemRecurrenceRule> rrules; rrules.append(rrule); QOrganizerItemRecurrence recurrence; recurrence.setRecurrenceRules(rrules); QVERIFY(item.saveDetail(&recurrence)); // Save item with recurrence rule. QVERIFY(m_om->saveItem(&item)); // Fetch the saved item item = m_om->item(item.localId()); // Fetch the item again QList<QOrganizerItem> instanceList = m_om->itemInstances(item,startTime,endTime); QCOMPARE(instanceList.size(), 3); QOrganizerItem lastItem = instanceList.at(2); QCOMPARE(lastItem.type(), QLatin1String(QOrganizerItemType::TypeEventOccurrence)); QOrganizerEventOccurrence thirdEvent = static_cast<QOrganizerEventOccurrence>(lastItem); QCOMPARE(thirdEvent.startDateTime(), QDateTime(QDate(QDate::currentDate().year() , 9, 15))); QCOMPARE(thirdEvent.localId(), (unsigned int)0); QCOMPARE(thirdEvent.parentLocalId(), item.localId()); //Fetch instances using maxcount only. instanceList.clear(); instanceList = m_om->itemInstances(item,startTime,QDateTime(),2); QCOMPARE(instanceList.size(), 2); QOrganizerItem secondItem = instanceList.at(1); QCOMPARE(secondItem.type(), QLatin1String(QOrganizerItemType::TypeEventOccurrence)); QOrganizerEventOccurrence secondEvent = static_cast<QOrganizerEventOccurrence>(secondItem); QCOMPARE(secondEvent.startDateTime(), QDateTime(QDate(QDate::currentDate().year() , 9, 8))); QCOMPARE(secondEvent.localId(), (unsigned int)0); QCOMPARE(secondEvent.parentLocalId(), item.localId()); } void TestItemOccurrence::addOccurrenceWithException_data() { // Get the list of all available item managers QStringList availableManagers = getAvailableManagers(); QTest::addColumn<QString>("managerName"); QTest::addColumn<QString>("itemType"); QTest::addColumn<QDateTime>("startTime"); QTest::addColumn<QDate>("rDate"); QTest::addColumn<QDate>("exceptionDate"); QTest::addColumn<QOrganizerItemRecurrenceRule>("rrule"); QTest::addColumn<QOrganizerItemPriority>("priority"); QTest::addColumn<QOrganizerItemLocation>("location"); QString itemType = QOrganizerItemType::TypeEvent; QOrganizerItemPriority priority; priority.setPriority(QOrganizerItemPriority::HighestPriority); QOrganizerItemLocation location; location.setLocationName("checkLocationName"); location.setGeoLocation("20.176876;15.988765"); foreach(QString manager, availableManagers) { QOrganizerItemRecurrenceRule rrule; rrule.setFrequency(QOrganizerItemRecurrenceRule::Daily); rrule.setCount(10); QDate rDate(QDate::currentDate().year() , 9, 11); QDate exceptionDate(QDate::currentDate().year() , 9, 3); QTest::newRow(QString("[%1] Daily event for 10 occurrences").arg(manager).toLatin1().constData()) << manager << itemType << QDateTime(QDate(QDate::currentDate().year() , 9, 1)) << rDate << exceptionDate << rrule << priority << location; QOrganizerItemRecurrenceRule monthRule; monthRule.setFrequency(QOrganizerItemRecurrenceRule::Monthly); monthRule.setCount(5); QTest::newRow(QString("[%1] Monthly event for 5 occurrences").arg(manager).toLatin1().constData()) << manager << itemType << QDateTime(QDate(QDate::currentDate().year() , 8, 3)) << rDate << exceptionDate << monthRule << priority << location; QOrganizerItemRecurrenceRule yearRule; yearRule.setFrequency(QOrganizerItemRecurrenceRule::Yearly); QList<QOrganizerItemRecurrenceRule::Month> months; months.append(QOrganizerItemRecurrenceRule::September); yearRule.setCount(3); yearRule.setInterval(2); yearRule.setMonths(months); QDate yearException(QDate(QDate::currentDate().year() , 9, 1)); QTest::newRow(QString("[%1] yearly rule every other year").arg(manager).toLatin1().constData()) << manager << itemType << QDateTime(QDate(QDate::currentDate().year() + 2, 9, 1)) << rDate << yearException << yearRule << priority << location; } } void TestItemOccurrence::addOccurrenceWithException() { QFETCH(QString, managerName); QFETCH(QString, itemType); QFETCH(QDateTime, startTime); QFETCH(QDate, rDate); QFETCH(QDate,exceptionDate ); QFETCH(QOrganizerItemRecurrenceRule, rrule); QFETCH(QOrganizerItemPriority, priority); QFETCH(QOrganizerItemLocation, location); // Set the item type QOrganizerItem item; item.setType(itemType); QOrganizerEventTimeRange timeRange; timeRange.setStartDateTime(startTime); QVERIFY(item.saveDetail(&timeRange)); // Add recurrence rules to the item QList<QOrganizerItemRecurrenceRule> rrules; QList<QDate> exceptionList; QList<QDate> rDateList; rrules.append(rrule); rDateList.append(rDate); exceptionList.append(exceptionDate); QOrganizerItemRecurrence recurrence; recurrence.setRecurrenceRules(rrules); recurrence.setExceptionDates(exceptionList); recurrence.setRecurrenceDates(rDateList); QVERIFY(item.saveDetail(&recurrence)); //Add other attributes to the item. item.setDescription("checkoccurrence"); item.saveDetail(&priority); item.saveDetail(&location); // Save item with recurrence rule. QVERIFY(m_om->saveItem(&item)); item = m_om->item(item.localId()); //Fetch instance on the exception date.An empty list should be returned QList<QOrganizerItem> instanceList = m_om->itemInstances(item,QDateTime(exceptionDate),QDateTime(exceptionDate)); QCOMPARE(instanceList.size(),0); //Fetch the instance on rdate should return one instance instanceList.clear(); instanceList = m_om->itemInstances(item,QDateTime(rDate),QDateTime(rDate)); QCOMPARE(instanceList.size(),1); QOrganizerItem rDateItem = instanceList.at(0); QCOMPARE(rDateItem.type(), QLatin1String(QOrganizerItemType::TypeEventOccurrence)); QOrganizerEventOccurrence event = static_cast<QOrganizerEventOccurrence>(rDateItem); QCOMPARE(event.startDateTime(), QDateTime(QDate(QDate::currentDate().year() , 9, 11))); // Fetch the item again instanceList.clear(); instanceList = m_om->itemInstances(item,startTime,QDateTime(),20); QCOMPARE(instanceList.size(),rrule.count()); QOrganizerItem lastItem = instanceList.at(rrule.count()-1); QCOMPARE(lastItem.type(), QLatin1String(QOrganizerItemType::TypeEventOccurrence)); QOrganizerEventOccurrence lastEvent = static_cast<QOrganizerEventOccurrence>(lastItem); QCOMPARE(lastEvent.description(),item.description()); QOrganizerItemPriority itemPriority = item.detail(QOrganizerItemPriority::DefinitionName); QCOMPARE(lastEvent.priority(),priority.priority()); QOrganizerItemLocation itemLocation = item.detail(QOrganizerItemLocation::DefinitionName); QCOMPARE(lastEvent.locationName(),itemLocation.locationName()); QCOMPARE(lastEvent.locationGeoCoordinates(),itemLocation.geoLocation()); //Fetch instance on 1\9\2011.Since interval is 2 the insatnceList size should be 0. instanceList.clear(); QDateTime intervalDate(QDate(QDate::currentDate().year()+ 1 , 9, 1)); instanceList = m_om->itemInstances(item,intervalDate,intervalDate); QCOMPARE(instanceList.size(),0); } void TestItemOccurrence::fetchNegative_data() { // Get the list of all available item managers QStringList availableManagers = getAvailableManagers(); QTest::addColumn<QString>("managerName"); QTest::addColumn<QString>("itemType"); QTest::addColumn<QDateTime>("startTime"); QString itemType = QOrganizerItemType::TypeEvent; foreach(QString manager, availableManagers) { QTest::newRow(QString("[%1] non repeating entry").arg(manager).toLatin1().constData()) << manager << itemType << QDateTime::currentDateTime().addSecs(3600); } } void TestItemOccurrence::fetchNegative() { //Fetch instances for a non recurring entry QFETCH(QString, managerName); QFETCH(QString, itemType); QFETCH(QDateTime, startTime); // Set the item type QOrganizerItem item; QList<QOrganizerItem> instanceList; item.setType(itemType); QDateTime endTime(startTime); QOrganizerEventTimeRange timeRange; timeRange.setStartDateTime(startTime); QVERIFY(item.saveDetail(&timeRange)); // Save item with recurrence rule. QVERIFY(m_om->saveItem(&item)); // Fetch the saved item item = m_om->item(item.localId()); // Fetch the item instances for a non repeating entry instanceList = m_om->itemInstances(item,startTime,endTime); //Only a single instance should be returned for non-repeating entry QCOMPARE(instanceList.size(), 1); //Fetch instance when end period is less than start period QDateTime previousEndTime(startTime); previousEndTime.setDate(QDate(startTime.date().year() - 2, startTime.date().month(),startTime.date().day())); instanceList = m_om->itemInstances(item,startTime,previousEndTime); QCOMPARE(m_om->error(), QOrganizerItemManager::BadArgumentError); //Fetch iteminstance for invalid itemtype eventoccurrence QOrganizerEventOccurrence invalidItem; instanceList = m_om->itemInstances(invalidItem,startTime,endTime); QCOMPARE(m_om->error(), QOrganizerItemManager::InvalidItemTypeError); // Fetch the item instance with invalid count instanceList = m_om->itemInstances(item,startTime,QDateTime(),-2); QCOMPARE(m_om->error(), QOrganizerItemManager::BadArgumentError); // Fetch the item instance with invalid starttime instanceList = m_om->itemInstances(item,QDateTime(),endTime); QCOMPARE(m_om->error(), QOrganizerItemManager::BadArgumentError); // Fetch the item instance with invalid endtime instanceList = m_om->itemInstances(item,startTime,QDateTime()); QCOMPARE(m_om->error(), QOrganizerItemManager::BadArgumentError); } QTEST_MAIN(TestItemOccurrence); #include "tst_itemoccurrence.moc" <|endoftext|>
<commit_before>#include "HaxeRuntime.h" #include "HaxeInit.h" #include "Engine.h" #include <cstdio> #if PLATFORM_WINDOWS || PLATFORM_WINRT || PLATFORM_XBOXONE #include <windows.h> #elif PLATFORM_MAC || PLATFORM_IOS || PLATFORM_LINUX || PLATFORM_ANDROID #include <pthread.h> #else #endif extern "C" void gc_set_top_of_stack(int *inTopOfStack,bool inForce); extern "C" const char *hxRunLibrary(); // void __scriptable_load_cppia(String inCode); #if PLATFORM_WINDOWS || PLATFORM_WINRT || PLATFORM_XBOXONE #define DECLARE_FAST_TLS(name) static __declspec( thread ) void *name #define GET_TLS_VALUE(name) name #define SET_TLS_VALUE(name, value) name = value #elif PLATFORM_LINUX || PLATFORM_ANDROID #define DECLARE_FAST_TLS(name) static thread_local void *name #define GET_TLS_VALUE(name) name #define SET_TLS_VALUE(name, value) name = value #else #define DECLARE_FAST_TLS(name) static uint32 name = FPlatformTLS::AllocTlsSlot() #define GET_TLS_VALUE(name) FPlatformTLS::GetTlsValue(name) #define SET_TLS_VALUE(name, value) FPlatformTLS::SetTlsValue(name, value) #endif static void *get_top_of_stack(void) { #if PLATFORM_WINDOWS || PLATFORM_WINRT || PLATFORM_XBOXONE //TODO: see if XBOXONE really behaves like Windows MEMORY_BASIC_INFORMATION info; VirtualQuery(&info, &info, sizeof(MEMORY_BASIC_INFORMATION)); return (void *) (( (char *) info.BaseAddress) + info.RegionSize); #elif PLATFORM_MAC || PLATFORM_IOS return pthread_get_stackaddr_np(pthread_self()); #elif PLATFORM_LINUX || PLATFORM_ANDROID pthread_t self = pthread_self(); pthread_attr_t attr; void* addr; size_t size; pthread_getattr_np(self, &attr); pthread_attr_getstack(&attr, &addr, &size); pthread_attr_destroy(&attr); return (void *) (((intptr_t)addr) + size); #else //PLATFORM_PS4, PLATFORM_HTML5 return NULL; #endif } static volatile int32 gDidInit = 0; DECLARE_FAST_TLS(tlsDidInit); void check_hx_init() { bool firstInit = true; if (gDidInit || FPlatformAtomics::InterlockedCompareExchange(&gDidInit, 1, 0) != 0) { // check if the thread was registered if (!GET_TLS_VALUE(tlsDidInit)) { SET_TLS_VALUE(tlsDidInit, (void *) (intptr_t) 1); } else { return; } while (gDidInit == 1) { // spin while waiting for the initialization to finish FPlatformProcess::Sleep(0.01f); } firstInit = false; } else { // main thread needs TLS too SET_TLS_VALUE(tlsDidInit, (void *) (intptr_t) 1); } // This code will execute after your module is loaded into memory (but after global variables are initialized, of course.) int x; void *top_of_stack = get_top_of_stack(); if (NULL == top_of_stack) { // UE_LOG(HXR, Error, TEXT("Currently unsupported Haxe runtime platform. Trying to get approximate stack size")); top_of_stack = &x; } #ifdef WITH_HAXE gc_set_top_of_stack((int *)top_of_stack, false); if (firstInit) { const char *error = hxRunLibrary(); if (error) { fprintf(stderr, "Error on Haxe main function: %s", error); } } #endif gDidInit = 2; } <commit_msg>Fail if an error was thrown on initialization<commit_after>#include "HaxeRuntime.h" #include "HaxeInit.h" #include "Engine.h" #include <cstdio> #if PLATFORM_WINDOWS || PLATFORM_WINRT || PLATFORM_XBOXONE #include <windows.h> #elif PLATFORM_MAC || PLATFORM_IOS || PLATFORM_LINUX || PLATFORM_ANDROID #include <pthread.h> #else #endif // DECLARE_LOG_CATEGORY_EXTERN(HaxeInitLog, Log, All); // DEFINE_LOG_CATEGORY(HaxeInitLog); DECLARE_LOG_CATEGORY_EXTERN(HaxeLog, Log, All); extern "C" void gc_set_top_of_stack(int *inTopOfStack,bool inForce); extern "C" const char *hxRunLibrary(); // void __scriptable_load_cppia(String inCode); #if PLATFORM_WINDOWS || PLATFORM_WINRT || PLATFORM_XBOXONE #define DECLARE_FAST_TLS(name) static __declspec( thread ) void *name #define GET_TLS_VALUE(name) name #define SET_TLS_VALUE(name, value) name = value #elif PLATFORM_LINUX || PLATFORM_ANDROID #define DECLARE_FAST_TLS(name) static thread_local void *name #define GET_TLS_VALUE(name) name #define SET_TLS_VALUE(name, value) name = value #else #define DECLARE_FAST_TLS(name) static uint32 name = FPlatformTLS::AllocTlsSlot() #define GET_TLS_VALUE(name) FPlatformTLS::GetTlsValue(name) #define SET_TLS_VALUE(name, value) FPlatformTLS::SetTlsValue(name, value) #endif static void *get_top_of_stack(void) { #if PLATFORM_WINDOWS || PLATFORM_WINRT || PLATFORM_XBOXONE //TODO: see if XBOXONE really behaves like Windows MEMORY_BASIC_INFORMATION info; VirtualQuery(&info, &info, sizeof(MEMORY_BASIC_INFORMATION)); return (void *) (( (char *) info.BaseAddress) + info.RegionSize); #elif PLATFORM_MAC || PLATFORM_IOS return pthread_get_stackaddr_np(pthread_self()); #elif PLATFORM_LINUX || PLATFORM_ANDROID pthread_t self = pthread_self(); pthread_attr_t attr; void* addr; size_t size; pthread_getattr_np(self, &attr); pthread_attr_getstack(&attr, &addr, &size); pthread_attr_destroy(&attr); return (void *) (((intptr_t)addr) + size); #else //PLATFORM_PS4, PLATFORM_HTML5 return NULL; #endif } static volatile int32 gDidInit = 0; DECLARE_FAST_TLS(tlsDidInit); void check_hx_init() { bool firstInit = true; if (gDidInit || FPlatformAtomics::InterlockedCompareExchange(&gDidInit, 1, 0) != 0) { // check if the thread was registered if (!GET_TLS_VALUE(tlsDidInit)) { SET_TLS_VALUE(tlsDidInit, (void *) (intptr_t) 1); } else { return; } while (gDidInit == 1) { // spin while waiting for the initialization to finish FPlatformProcess::Sleep(0.01f); } firstInit = false; } else { // main thread needs TLS too SET_TLS_VALUE(tlsDidInit, (void *) (intptr_t) 1); } // This code will execute after your module is loaded into memory (but after global variables are initialized, of course.) int x; void *top_of_stack = get_top_of_stack(); if (NULL == top_of_stack) { // UE_LOG(HXR, Error, TEXT("Currently unsupported Haxe runtime platform. Trying to get approximate stack size")); top_of_stack = &x; } #ifdef WITH_HAXE gc_set_top_of_stack((int *)top_of_stack, false); if (firstInit) { const char *error = hxRunLibrary(); if (error) { UE_LOG(HaxeLog, Fatal, TEXT("Error on Haxe main function: %s"), UTF8_TO_TCHAR(error)); } } #endif gDidInit = 2; } <|endoftext|>
<commit_before>// Copyright 2019 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include "iree/compiler/IR/Dialect.h" #include "iree/compiler/IR/Interpreter/HLDialect.h" #include "iree/compiler/IR/Interpreter/HLOps.h" #include "iree/compiler/IR/Interpreter/LLDialect.h" #include "iree/compiler/IR/Interpreter/LLOps.h" #include "iree/compiler/IR/Ops.h" #include "iree/compiler/Serialization/BytecodeTables.h" #include "iree/schemas/bytecode/interpreter_bytecode_v0.h" #include "llvm/ADT/DenseSet.h" #include "llvm/ADT/SmallVector.h" #include "llvm/Support/Allocator.h" #include "llvm/Support/Casting.h" #include "mlir/Dialect/StandardOps/Ops.h" #include "mlir/IR/Attributes.h" #include "mlir/IR/BlockAndValueMapping.h" #include "mlir/IR/Location.h" #include "mlir/IR/MLIRContext.h" #include "mlir/IR/PatternMatch.h" #include "mlir/IR/StandardTypes.h" #include "mlir/Pass/Pass.h" #include "mlir/Pass/PassRegistry.h" #include "mlir/Transforms/DialectConversion.h" #include "mlir/Transforms/Utils.h" namespace mlir { namespace iree_compiler { namespace { struct LowerBranchOpPattern : public OpRewritePattern<IREEInterp::HL::BranchOp> { using OpRewritePattern<IREEInterp::HL::BranchOp>::OpRewritePattern; PatternMatchResult matchAndRewrite(IREEInterp::HL::BranchOp op, PatternRewriter &rewriter) const { SmallVector<Value *, 8> operands{op.getOperation()->getOperands()}; rewriter.replaceOpWithNewOp<IREEInterp::LL::BranchOp>(op, op.getDest(), operands); return matchSuccess(); } }; struct LowerCondCondBranchOpPattern : public OpRewritePattern<IREEInterp::HL::CondBranchOp> { using OpRewritePattern<IREEInterp::HL::CondBranchOp>::OpRewritePattern; PatternMatchResult matchAndRewrite(IREEInterp::HL::CondBranchOp op, PatternRewriter &rewriter) const { SmallVector<Value *, 8> trueOperands{op.getTrueOperands()}; SmallVector<Value *, 8> falseOperands{op.getFalseOperands()}; rewriter.replaceOpWithNewOp<IREEInterp::LL::CondBranchOp>( op, op.getCondition(), op.getTrueDest(), trueOperands, op.getFalseDest(), falseOperands); return matchSuccess(); } }; // Returns true if the op defined by |opName| (like 'iree_ll_interp.reshape') // uses output operands for results (like iree_ll_interp.add_i) or returns real // results. bool opTakesOutputOperands(llvm::StringRef opName) { if (!opName.consume_front("iree_ll_interp.")) { assert(false && "op not part of IREE LL Interpreter dialect"); return false; } auto opcode = GetInterpreterOpcodeByName(opName.str()); assert(opcode.hasValue() && "op has no corresponding opcode"); const auto &info = GetInterpreterOpcodeInfo(opcode.getValue()); for (auto &operand : info.operands) { if (operand == iree::OperandEncoding::kOutputSlot || operand == iree::OperandEncoding::kVariadicOutputSlots) { return true; } } return false; } template <typename SrcOp, typename DstOp> class SimpleOpLowering : public OpRewritePattern<SrcOp> { using OpRewritePattern<SrcOp>::OpRewritePattern; PatternMatchResult matchAndRewrite(SrcOp op, PatternRewriter &rewriter) const { SmallVector<Value *, 8> operands{op.getOperation()->getOperands()}; // Most ops take results as output operands to populate during execution. // Certain ops, like reshape, return references to existing memrefs and // should still retain their results. if (!opTakesOutputOperands(DstOp::getOperationName())) { SmallVector<Type, 8> resultTypes{op.getOperation()->getResultTypes()}; rewriter.replaceOpWithNewOp<DstOp>(op, resultTypes, operands, op.getAttrs()); return this->matchSuccess(); } for (Value *result : op.getOperation()->getResults()) { auto memRefType = result->getType().cast<MemRefType>(); if (!memRefType.hasStaticShape()) { // TODO(benvanik): real thing here - dynamic shaping required. // This should emit a shape calculation based on the operation. Most // are likely simple and by running DCE after this we can clean up // parts that are static or unused. op.emitOpError() << "uses unsupported dynamic shapes"; return this->matchFailure(); } ArrayRef<Value *> dim_pieces; auto allocOp = rewriter.create<IREEInterp::LL::AllocHeapOp>( op.getLoc(), memRefType, dim_pieces); operands.push_back(allocOp); result->replaceAllUsesWith(allocOp); } ArrayRef<Type> resultTypes; rewriter.create<DstOp>(op.getLoc(), resultTypes, operands, op.getAttrs()); op.erase(); return this->matchSuccess(); } }; } // namespace void populateInterpreterLoweringPatterns(OwningRewritePatternList &patterns, MLIRContext *ctx) { patterns.insert<LowerBranchOpPattern, LowerCondCondBranchOpPattern>(ctx); patterns.insert< SimpleOpLowering<IREE::ConstantOp, IREEInterp::LL::ConstantOp>, SimpleOpLowering<IREEInterp::HL::CopyOp, IREEInterp::LL::DynamicCopyOp>, SimpleOpLowering<IREEInterp::HL::SliceOp, IREEInterp::LL::DynamicSliceOp>>(ctx); #define SAME_NAME_SIMPLE_PATTERN(op_name) \ SimpleOpLowering<IREEInterp::HL::op_name, IREEInterp::LL::op_name> // clang-format off patterns.insert< SAME_NAME_SIMPLE_PATTERN(AssignOp), SAME_NAME_SIMPLE_PATTERN(AbsFOp), SAME_NAME_SIMPLE_PATTERN(AbsIOp), SAME_NAME_SIMPLE_PATTERN(AddFOp), SAME_NAME_SIMPLE_PATTERN(AddIOp), SAME_NAME_SIMPLE_PATTERN(AllocHeapOp), SAME_NAME_SIMPLE_PATTERN(AndOp), SAME_NAME_SIMPLE_PATTERN(Atan2FOp), SAME_NAME_SIMPLE_PATTERN(BreakOp), SAME_NAME_SIMPLE_PATTERN(BroadcastOp), SAME_NAME_SIMPLE_PATTERN(CallOp), SAME_NAME_SIMPLE_PATTERN(CallIndirectOp), SAME_NAME_SIMPLE_PATTERN(CeilFOp), SAME_NAME_SIMPLE_PATTERN(ClampFOp), SAME_NAME_SIMPLE_PATTERN(CloneOp), SAME_NAME_SIMPLE_PATTERN(CmpFOp), SAME_NAME_SIMPLE_PATTERN(CmpIOp), SAME_NAME_SIMPLE_PATTERN(CondAssignOp), SAME_NAME_SIMPLE_PATTERN(ConvertSSOp), SAME_NAME_SIMPLE_PATTERN(ConvertUUOp), SAME_NAME_SIMPLE_PATTERN(ConvertSUOp), SAME_NAME_SIMPLE_PATTERN(ConvertUSOp), SAME_NAME_SIMPLE_PATTERN(CondBreakOp), SAME_NAME_SIMPLE_PATTERN(CosFOp), SAME_NAME_SIMPLE_PATTERN(DimOp), SAME_NAME_SIMPLE_PATTERN(DivFOp), SAME_NAME_SIMPLE_PATTERN(DivISOp), SAME_NAME_SIMPLE_PATTERN(DivIUOp), SAME_NAME_SIMPLE_PATTERN(ExpFOp), SAME_NAME_SIMPLE_PATTERN(LogFOp), SAME_NAME_SIMPLE_PATTERN(RsqrtFOp), SAME_NAME_SIMPLE_PATTERN(FloorFOp), SAME_NAME_SIMPLE_PATTERN(LengthOp), SAME_NAME_SIMPLE_PATTERN(MatMulFOp), SAME_NAME_SIMPLE_PATTERN(MatMulIOp), SAME_NAME_SIMPLE_PATTERN(MaxFOp), SAME_NAME_SIMPLE_PATTERN(MaxISOp), SAME_NAME_SIMPLE_PATTERN(MaxIUOp), SAME_NAME_SIMPLE_PATTERN(MinFOp), SAME_NAME_SIMPLE_PATTERN(MinISOp), SAME_NAME_SIMPLE_PATTERN(MinIUOp), SAME_NAME_SIMPLE_PATTERN(MulAddFOp), SAME_NAME_SIMPLE_PATTERN(MulAddIOp), SAME_NAME_SIMPLE_PATTERN(MulFOp), SAME_NAME_SIMPLE_PATTERN(MulIOp), SAME_NAME_SIMPLE_PATTERN(NotOp), SAME_NAME_SIMPLE_PATTERN(OrOp), SAME_NAME_SIMPLE_PATTERN(PadOp), SAME_NAME_SIMPLE_PATTERN(RankOp), SAME_NAME_SIMPLE_PATTERN(ReduceSumIOp), SAME_NAME_SIMPLE_PATTERN(ReduceSumFOp), SAME_NAME_SIMPLE_PATTERN(ReduceMinIOp), SAME_NAME_SIMPLE_PATTERN(ReduceMinFOp), SAME_NAME_SIMPLE_PATTERN(ReduceMaxIOp), SAME_NAME_SIMPLE_PATTERN(ReduceMaxFOp), SAME_NAME_SIMPLE_PATTERN(ReshapeOp), SAME_NAME_SIMPLE_PATTERN(ReturnOp), SAME_NAME_SIMPLE_PATTERN(SelectOp), SAME_NAME_SIMPLE_PATTERN(ShapeOp), SAME_NAME_SIMPLE_PATTERN(ShiftLeftOp), SAME_NAME_SIMPLE_PATTERN(ShiftRightArithmeticOp), SAME_NAME_SIMPLE_PATTERN(ShiftRightLogicalOp), SAME_NAME_SIMPLE_PATTERN(SinFOp), SAME_NAME_SIMPLE_PATTERN(SplitOp), SAME_NAME_SIMPLE_PATTERN(SubFOp), SAME_NAME_SIMPLE_PATTERN(SubIOp), SAME_NAME_SIMPLE_PATTERN(TanhFOp), SAME_NAME_SIMPLE_PATTERN(TileOp), SAME_NAME_SIMPLE_PATTERN(TraceOp), SAME_NAME_SIMPLE_PATTERN(TransposeOp), SAME_NAME_SIMPLE_PATTERN(ReverseOp), SAME_NAME_SIMPLE_PATTERN(XorOp)>(ctx); // clang-format on #undef SAME_NAME_SIMPLE_PATTERN } namespace { class LowerInterpreterDialectPass : public FunctionPass<LowerInterpreterDialectPass> { public: void runOnFunction() override { OwningRewritePatternList patterns; populateInterpreterLoweringPatterns(patterns, &getContext()); ConversionTarget target(getContext()); target.addLegalDialect<IREELLInterpreterDialect>(); target.addLegalOp<FuncOp, IREE::ReturnOp>(); if (failed(applyFullConversion(getFunction(), target, patterns))) { return signalPassFailure(); } } }; } // namespace std::unique_ptr<OpPassBase<FuncOp>> createLowerInterpreterDialectPass() { return std::make_unique<LowerInterpreterDialectPass>(); } static PassRegistration<LowerInterpreterDialectPass> pass( "lower-iree-interpreter-hl-to-ll", "Lowers IREE HL ops to IREE LL ops"); } // namespace iree_compiler } // namespace mlir <commit_msg>Replace inline replacement with use of 'replaceOp'.<commit_after>// Copyright 2019 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include "iree/compiler/IR/Dialect.h" #include "iree/compiler/IR/Interpreter/HLDialect.h" #include "iree/compiler/IR/Interpreter/HLOps.h" #include "iree/compiler/IR/Interpreter/LLDialect.h" #include "iree/compiler/IR/Interpreter/LLOps.h" #include "iree/compiler/IR/Ops.h" #include "iree/compiler/Serialization/BytecodeTables.h" #include "iree/schemas/bytecode/interpreter_bytecode_v0.h" #include "llvm/ADT/DenseSet.h" #include "llvm/ADT/SmallVector.h" #include "llvm/Support/Allocator.h" #include "llvm/Support/Casting.h" #include "mlir/Dialect/StandardOps/Ops.h" #include "mlir/IR/Attributes.h" #include "mlir/IR/BlockAndValueMapping.h" #include "mlir/IR/Location.h" #include "mlir/IR/MLIRContext.h" #include "mlir/IR/PatternMatch.h" #include "mlir/IR/StandardTypes.h" #include "mlir/Pass/Pass.h" #include "mlir/Pass/PassRegistry.h" #include "mlir/Transforms/DialectConversion.h" #include "mlir/Transforms/Utils.h" namespace mlir { namespace iree_compiler { namespace { struct LowerBranchOpPattern : public OpRewritePattern<IREEInterp::HL::BranchOp> { using OpRewritePattern<IREEInterp::HL::BranchOp>::OpRewritePattern; PatternMatchResult matchAndRewrite(IREEInterp::HL::BranchOp op, PatternRewriter &rewriter) const { SmallVector<Value *, 8> operands{op.getOperation()->getOperands()}; rewriter.replaceOpWithNewOp<IREEInterp::LL::BranchOp>(op, op.getDest(), operands); return matchSuccess(); } }; struct LowerCondCondBranchOpPattern : public OpRewritePattern<IREEInterp::HL::CondBranchOp> { using OpRewritePattern<IREEInterp::HL::CondBranchOp>::OpRewritePattern; PatternMatchResult matchAndRewrite(IREEInterp::HL::CondBranchOp op, PatternRewriter &rewriter) const { SmallVector<Value *, 8> trueOperands{op.getTrueOperands()}; SmallVector<Value *, 8> falseOperands{op.getFalseOperands()}; rewriter.replaceOpWithNewOp<IREEInterp::LL::CondBranchOp>( op, op.getCondition(), op.getTrueDest(), trueOperands, op.getFalseDest(), falseOperands); return matchSuccess(); } }; // Returns true if the op defined by |opName| (like 'iree_ll_interp.reshape') // uses output operands for results (like iree_ll_interp.add_i) or returns real // results. bool opTakesOutputOperands(llvm::StringRef opName) { if (!opName.consume_front("iree_ll_interp.")) { assert(false && "op not part of IREE LL Interpreter dialect"); return false; } auto opcode = GetInterpreterOpcodeByName(opName.str()); assert(opcode.hasValue() && "op has no corresponding opcode"); const auto &info = GetInterpreterOpcodeInfo(opcode.getValue()); for (auto &operand : info.operands) { if (operand == iree::OperandEncoding::kOutputSlot || operand == iree::OperandEncoding::kVariadicOutputSlots) { return true; } } return false; } template <typename SrcOp, typename DstOp> class SimpleOpLowering : public OpRewritePattern<SrcOp> { using OpRewritePattern<SrcOp>::OpRewritePattern; PatternMatchResult matchAndRewrite(SrcOp op, PatternRewriter &rewriter) const { SmallVector<Value *, 8> operands{op.getOperation()->getOperands()}; // Most ops take results as output operands to populate during execution. // Certain ops, like reshape, return references to existing memrefs and // should still retain their results. if (!opTakesOutputOperands(DstOp::getOperationName())) { SmallVector<Type, 8> resultTypes{op.getOperation()->getResultTypes()}; rewriter.replaceOpWithNewOp<DstOp>(op, resultTypes, operands, op.getAttrs()); return this->matchSuccess(); } SmallVector<Value *, 4> replacementValues; for (Value *result : op.getOperation()->getResults()) { auto memRefType = result->getType().cast<MemRefType>(); if (!memRefType.hasStaticShape()) { // TODO(benvanik): real thing here - dynamic shaping required. // This should emit a shape calculation based on the operation. Most // are likely simple and by running DCE after this we can clean up // parts that are static or unused. op.emitOpError() << "uses unsupported dynamic shapes"; return this->matchFailure(); } ArrayRef<Value *> dim_pieces; auto allocOp = rewriter.create<IREEInterp::LL::AllocHeapOp>( op.getLoc(), memRefType, dim_pieces); operands.push_back(allocOp); replacementValues.push_back(allocOp); } ArrayRef<Type> resultTypes; rewriter.create<DstOp>(op.getLoc(), resultTypes, operands, op.getAttrs()); rewriter.replaceOp(op, replacementValues); return this->matchSuccess(); } }; } // namespace void populateInterpreterLoweringPatterns(OwningRewritePatternList &patterns, MLIRContext *ctx) { patterns.insert<LowerBranchOpPattern, LowerCondCondBranchOpPattern>(ctx); patterns.insert< SimpleOpLowering<IREE::ConstantOp, IREEInterp::LL::ConstantOp>, SimpleOpLowering<IREEInterp::HL::CopyOp, IREEInterp::LL::DynamicCopyOp>, SimpleOpLowering<IREEInterp::HL::SliceOp, IREEInterp::LL::DynamicSliceOp>>(ctx); #define SAME_NAME_SIMPLE_PATTERN(op_name) \ SimpleOpLowering<IREEInterp::HL::op_name, IREEInterp::LL::op_name> // clang-format off patterns.insert< SAME_NAME_SIMPLE_PATTERN(AssignOp), SAME_NAME_SIMPLE_PATTERN(AbsFOp), SAME_NAME_SIMPLE_PATTERN(AbsIOp), SAME_NAME_SIMPLE_PATTERN(AddFOp), SAME_NAME_SIMPLE_PATTERN(AddIOp), SAME_NAME_SIMPLE_PATTERN(AllocHeapOp), SAME_NAME_SIMPLE_PATTERN(AndOp), SAME_NAME_SIMPLE_PATTERN(Atan2FOp), SAME_NAME_SIMPLE_PATTERN(BreakOp), SAME_NAME_SIMPLE_PATTERN(BroadcastOp), SAME_NAME_SIMPLE_PATTERN(CallOp), SAME_NAME_SIMPLE_PATTERN(CallIndirectOp), SAME_NAME_SIMPLE_PATTERN(CeilFOp), SAME_NAME_SIMPLE_PATTERN(ClampFOp), SAME_NAME_SIMPLE_PATTERN(CloneOp), SAME_NAME_SIMPLE_PATTERN(CmpFOp), SAME_NAME_SIMPLE_PATTERN(CmpIOp), SAME_NAME_SIMPLE_PATTERN(CondAssignOp), SAME_NAME_SIMPLE_PATTERN(ConvertSSOp), SAME_NAME_SIMPLE_PATTERN(ConvertUUOp), SAME_NAME_SIMPLE_PATTERN(ConvertSUOp), SAME_NAME_SIMPLE_PATTERN(ConvertUSOp), SAME_NAME_SIMPLE_PATTERN(CondBreakOp), SAME_NAME_SIMPLE_PATTERN(CosFOp), SAME_NAME_SIMPLE_PATTERN(DimOp), SAME_NAME_SIMPLE_PATTERN(DivFOp), SAME_NAME_SIMPLE_PATTERN(DivISOp), SAME_NAME_SIMPLE_PATTERN(DivIUOp), SAME_NAME_SIMPLE_PATTERN(ExpFOp), SAME_NAME_SIMPLE_PATTERN(LogFOp), SAME_NAME_SIMPLE_PATTERN(RsqrtFOp), SAME_NAME_SIMPLE_PATTERN(FloorFOp), SAME_NAME_SIMPLE_PATTERN(LengthOp), SAME_NAME_SIMPLE_PATTERN(MatMulFOp), SAME_NAME_SIMPLE_PATTERN(MatMulIOp), SAME_NAME_SIMPLE_PATTERN(MaxFOp), SAME_NAME_SIMPLE_PATTERN(MaxISOp), SAME_NAME_SIMPLE_PATTERN(MaxIUOp), SAME_NAME_SIMPLE_PATTERN(MinFOp), SAME_NAME_SIMPLE_PATTERN(MinISOp), SAME_NAME_SIMPLE_PATTERN(MinIUOp), SAME_NAME_SIMPLE_PATTERN(MulAddFOp), SAME_NAME_SIMPLE_PATTERN(MulAddIOp), SAME_NAME_SIMPLE_PATTERN(MulFOp), SAME_NAME_SIMPLE_PATTERN(MulIOp), SAME_NAME_SIMPLE_PATTERN(NotOp), SAME_NAME_SIMPLE_PATTERN(OrOp), SAME_NAME_SIMPLE_PATTERN(PadOp), SAME_NAME_SIMPLE_PATTERN(RankOp), SAME_NAME_SIMPLE_PATTERN(ReduceSumIOp), SAME_NAME_SIMPLE_PATTERN(ReduceSumFOp), SAME_NAME_SIMPLE_PATTERN(ReduceMinIOp), SAME_NAME_SIMPLE_PATTERN(ReduceMinFOp), SAME_NAME_SIMPLE_PATTERN(ReduceMaxIOp), SAME_NAME_SIMPLE_PATTERN(ReduceMaxFOp), SAME_NAME_SIMPLE_PATTERN(ReshapeOp), SAME_NAME_SIMPLE_PATTERN(ReturnOp), SAME_NAME_SIMPLE_PATTERN(SelectOp), SAME_NAME_SIMPLE_PATTERN(ShapeOp), SAME_NAME_SIMPLE_PATTERN(ShiftLeftOp), SAME_NAME_SIMPLE_PATTERN(ShiftRightArithmeticOp), SAME_NAME_SIMPLE_PATTERN(ShiftRightLogicalOp), SAME_NAME_SIMPLE_PATTERN(SinFOp), SAME_NAME_SIMPLE_PATTERN(SplitOp), SAME_NAME_SIMPLE_PATTERN(SubFOp), SAME_NAME_SIMPLE_PATTERN(SubIOp), SAME_NAME_SIMPLE_PATTERN(TanhFOp), SAME_NAME_SIMPLE_PATTERN(TileOp), SAME_NAME_SIMPLE_PATTERN(TraceOp), SAME_NAME_SIMPLE_PATTERN(TransposeOp), SAME_NAME_SIMPLE_PATTERN(ReverseOp), SAME_NAME_SIMPLE_PATTERN(XorOp)>(ctx); // clang-format on #undef SAME_NAME_SIMPLE_PATTERN } namespace { class LowerInterpreterDialectPass : public FunctionPass<LowerInterpreterDialectPass> { public: void runOnFunction() override { OwningRewritePatternList patterns; populateInterpreterLoweringPatterns(patterns, &getContext()); ConversionTarget target(getContext()); target.addLegalDialect<IREELLInterpreterDialect>(); target.addLegalOp<FuncOp, IREE::ReturnOp>(); if (failed(applyFullConversion(getFunction(), target, patterns))) { return signalPassFailure(); } } }; } // namespace std::unique_ptr<OpPassBase<FuncOp>> createLowerInterpreterDialectPass() { return std::make_unique<LowerInterpreterDialectPass>(); } static PassRegistration<LowerInterpreterDialectPass> pass( "lower-iree-interpreter-hl-to-ll", "Lowers IREE HL ops to IREE LL ops"); } // namespace iree_compiler } // namespace mlir <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: QueryViewSwitch.hxx,v $ * * $Revision: 1.12 $ * * last change: $Author: rt $ $Date: 2005-09-08 15:31:11 $ * * 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 DBAUI_QUERYVIEWSWITCH_HXX #define DBAUI_QUERYVIEWSWITCH_HXX #ifndef DBAUI_QUERYVIEW_HXX #include "queryview.hxx" #endif namespace dbaui { class OQueryDesignView; class OQueryTextView; class OAddTableDlg; class OQueryContainerWindow; class OQueryViewSwitch { OQueryDesignView* m_pDesignView; OQueryTextView* m_pTextView; sal_Bool m_bAddTableDialogWasVisible; // true if so public: OQueryViewSwitch(OQueryContainerWindow* pParent, OQueryController* _pController,const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& ); virtual ~OQueryViewSwitch(); virtual sal_Bool isCutAllowed(); virtual sal_Bool isPasteAllowed(); virtual sal_Bool isCopyAllowed(); virtual void copy(); virtual void cut(); virtual void paste(); // clears the whole query virtual void clear(); // set the view readonly or not virtual void setReadOnly(sal_Bool _bReadOnly); // check if the statement is correct when not returning false virtual sal_Bool checkStatement(); // set the statement for representation virtual void setStatement(const ::rtl::OUString& _rsStatement); // returns the current sql statement virtual ::rtl::OUString getStatement(); /// late construction virtual void Construct(); virtual void initialize(); /** show the text or the design view @return <TRUE/> when all went right otherwise <FALSE/> which implies an aditional call of switchView from the controller to restore the old state */ sal_Bool switchView(); sal_Bool isSlotEnabled(sal_Int32 _nSlotId); void setSlotEnabled(sal_Int32 _nSlotId,sal_Bool _bEnable); void setNoneVisbleRow(sal_Int32 _nRows); // returs the add table dialog from the design view OAddTableDlg* getAddTableDialog(); BOOL IsAddAllowed(); void zoomTableView(const Fraction& _rFraction); void SaveUIConfig(); void clearDesignView(); void GetFocus(); void reset(); void GrabFocus(); OQueryDesignView* getDesignView() const { return m_pDesignView; } OQueryContainerWindow* getContainer() const; Window* getActive() const; void SetPosSizePixel( Point _rPt,Size _rSize); ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory > getORB() const; protected: // return the Rectangle where I can paint myself virtual void resizeDocumentView(Rectangle& rRect); }; } #endif // DBAUI_QUERYVIEWSWITCH_HXX <commit_msg>INTEGRATION: CWS dba23a (1.12.254); FILE MERGED 2007/02/26 10:34:00 fs 1.12.254.1: remove unused code Issue number: #i74776# Submitted by: [email protected] Reviewed by: [email protected]<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: QueryViewSwitch.hxx,v $ * * $Revision: 1.13 $ * * last change: $Author: kz $ $Date: 2007-05-10 10:28:48 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ #ifndef DBAUI_QUERYVIEWSWITCH_HXX #define DBAUI_QUERYVIEWSWITCH_HXX #ifndef DBAUI_QUERYVIEW_HXX #include "queryview.hxx" #endif namespace dbaui { class OQueryDesignView; class OQueryTextView; class OAddTableDlg; class OQueryContainerWindow; class OQueryViewSwitch { OQueryDesignView* m_pDesignView; OQueryTextView* m_pTextView; sal_Bool m_bAddTableDialogWasVisible; // true if so public: OQueryViewSwitch(OQueryContainerWindow* pParent, OQueryController* _pController,const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& ); virtual ~OQueryViewSwitch(); virtual sal_Bool isCutAllowed(); virtual sal_Bool isPasteAllowed(); virtual sal_Bool isCopyAllowed(); virtual void copy(); virtual void cut(); virtual void paste(); // clears the whole query virtual void clear(); // set the view readonly or not virtual void setReadOnly(sal_Bool _bReadOnly); // check if the statement is correct when not returning false virtual sal_Bool checkStatement(); // set the statement for representation virtual void setStatement(const ::rtl::OUString& _rsStatement); // returns the current sql statement virtual ::rtl::OUString getStatement(); /// late construction virtual void Construct(); virtual void initialize(); /** show the text or the design view @return <TRUE/> when all went right otherwise <FALSE/> which implies an aditional call of switchView from the controller to restore the old state */ sal_Bool switchView(); sal_Bool isSlotEnabled(sal_Int32 _nSlotId); void setSlotEnabled(sal_Int32 _nSlotId,sal_Bool _bEnable); void setNoneVisbleRow(sal_Int32 _nRows); // returs the add table dialog from the design view OAddTableDlg* getAddTableDialog(); void SaveUIConfig(); void reset(); void GrabFocus(); OQueryDesignView* getDesignView() const { return m_pDesignView; } OQueryContainerWindow* getContainer() const; void SetPosSizePixel( Point _rPt,Size _rSize); ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory > getORB() const; protected: // return the Rectangle where I can paint myself virtual void resizeDocumentView(Rectangle& rRect); }; } #endif // DBAUI_QUERYVIEWSWITCH_HXX <|endoftext|>
<commit_before>//---------------------------------------------------------------- // $Id$ // Version: $Name$ // // Copyright (C) 2001, 2002 by the deal.II authors // // This file is subject to QPL and may not be distributed // without copyright and license information. Please refer // to the file deal.II/doc/license.html for the text and // further information on this license. // //---------------------------------------------------------------- // only compile this file if in 2d #if deal_II_dimension == 2 #include <fe/fe_nedelec.h> // Transfer matrices for finite elements: have one matrix for each of // the four child cells which tells us how the degrees of freedom on // the child cell are obtained from the degrees of freedom on the // mother cell // // TODO: [Anna] check whether the following paragraph is correct. if so, then please multiply the values in the four following matrices by two // note the following: since the shape functions themselves and not // only the gradients are transformed using the mapping object from // the unit cell to the real cell, the actual values of the function // on the real cell is degree of freedom times value of the shape // function on the unit cell times Jacobian. Thus, what has the DoF // value 1 on the mother cell must have the DoF value 2 on the child // cell since the latter is smaller by a (linear scaling) factor of // two. namespace FE_Nedelec_2d { static const double q1_into_q1_refined_0[] = { 1., 0, 0, 0, 0, 0.5,0, 0.5, 0.5, 0, 0.5,0, 0, 0, 0, 1 }; static const double q1_into_q1_refined_1[] = { 1., 0., 0., 0., 0., 1., 0., 0., 0.5, 0., 0.5, 0., 0., 0.5, 0., 0.5, }; static const double q1_into_q1_refined_2[] = { 0.5, 0., 0.5, 0., 0., 1., 0., 0., 0., 0., 1., 0., 0., 0.5, 0., 0.5, }; static const double q1_into_q1_refined_3[] = { 0.5, 0., 0.5, 0., 0., 0.5, 0., 0.5, 0., 0., 1., 0., 0., 0., 0., 1., }; }; // namespace FE_Nedelec_2d // embedding matrices template <> const double * const FE_Nedelec<2>::Matrices::embedding[][GeometryInfo<2>::children_per_cell] = { { FE_Nedelec_2d::q1_into_q1_refined_0, FE_Nedelec_2d::q1_into_q1_refined_1, FE_Nedelec_2d::q1_into_q1_refined_2, FE_Nedelec_2d::q1_into_q1_refined_3 } }; template <> const unsigned int FE_Nedelec<2>::Matrices::n_embedding_matrices = sizeof(FE_Nedelec<2>::Matrices::embedding) / sizeof(FE_Nedelec<2>::Matrices::embedding[0]); // Constraint matrices: how do the new value on child faces depend on // the values on the mother face if that face has a hanging node // // Here, the same applies as for the embedding matrices: since the DoF // values are not only multiplied by the values of the shape function // on the unit cell, but also by the transformation, we have to // multiply the value on the large face by two to get the same value // back on the small face namespace FE_Nedelec_2d { static const double constraint_q1[] = { // the function is constant // along each edge, so each // degree of freedom on the // refined edge has the same // value as that on the // coarse edge, modulo the // issue with the // transformation described // above 2., 2. }; }; template <> const double * const FE_Nedelec<2>::Matrices::constraint_matrices[] = { FE_Nedelec_2d::constraint_q1 }; template <> const unsigned int FE_Nedelec<2>::Matrices::n_constraint_matrices = sizeof(FE_Nedelec<2>::Matrices::constraint_matrices) / sizeof(FE_Nedelec<2>::Matrices::constraint_matrices[0]); #else // #if deal_II_dimension // On gcc2.95 on Alpha OSF1, the native assembler does not like empty // files, so provide some dummy code namespace { void dummy () {}; }; #endif // #if deal_II_dimension == 2 <commit_msg>Fix constraint matrices.<commit_after>//---------------------------------------------------------------- // $Id$ // Version: $Name$ // // Copyright (C) 2001, 2002 by the deal.II authors // // This file is subject to QPL and may not be distributed // without copyright and license information. Please refer // to the file deal.II/doc/license.html for the text and // further information on this license. // //---------------------------------------------------------------- // only compile this file if in 2d #if deal_II_dimension == 2 #include <fe/fe_nedelec.h> // Transfer matrices for finite elements: have one matrix for each of // the four child cells which tells us how the degrees of freedom on // the child cell are obtained from the degrees of freedom on the // mother cell // // TODO: [Anna] check whether the following paragraph is correct. if so, then please multiply the values in the four following matrices by two // note the following: since the shape functions themselves and not // only the gradients are transformed using the mapping object from // the unit cell to the real cell, the actual values of the function // on the real cell is degree of freedom times value of the shape // function on the unit cell times Jacobian. Thus, what has the DoF // value 1 on the mother cell must have the DoF value 2 on the child // cell since the latter is smaller by a (linear scaling) factor of // two. namespace FE_Nedelec_2d { static const double q1_into_q1_refined_0[] = { 1., 0, 0, 0, 0, 0.5,0, 0.5, 0.5, 0, 0.5,0, 0, 0, 0, 1 }; static const double q1_into_q1_refined_1[] = { 1., 0., 0., 0., 0., 1., 0., 0., 0.5, 0., 0.5, 0., 0., 0.5, 0., 0.5, }; static const double q1_into_q1_refined_2[] = { 0.5, 0., 0.5, 0., 0., 1., 0., 0., 0., 0., 1., 0., 0., 0.5, 0., 0.5, }; static const double q1_into_q1_refined_3[] = { 0.5, 0., 0.5, 0., 0., 0.5, 0., 0.5, 0., 0., 1., 0., 0., 0., 0., 1., }; }; // namespace FE_Nedelec_2d // embedding matrices template <> const double * const FE_Nedelec<2>::Matrices::embedding[][GeometryInfo<2>::children_per_cell] = { { FE_Nedelec_2d::q1_into_q1_refined_0, FE_Nedelec_2d::q1_into_q1_refined_1, FE_Nedelec_2d::q1_into_q1_refined_2, FE_Nedelec_2d::q1_into_q1_refined_3 } }; template <> const unsigned int FE_Nedelec<2>::Matrices::n_embedding_matrices = sizeof(FE_Nedelec<2>::Matrices::embedding) / sizeof(FE_Nedelec<2>::Matrices::embedding[0]); // Constraint matrices: how do the new value on child faces depend on // the values on the mother face if that face has a hanging node // // Here, the same applies as for the embedding matrices: since the DoF // values are not only multiplied by the values of the shape function // on the unit cell, but also by the transformation, we have to // multiply the value on the large face by 1/2 to get the same value // back on the small face. in other words, if a DoF has weight 1 on // the big cell, then it has to have weight 1/2 on the small ones, in // order to give the same value of the shape function in real space namespace FE_Nedelec_2d { static const double constraint_q1[] = { // the function is constant // along each edge, so each // degree of freedom on the // refined edge has the same // value as that on the // coarse edge, modulo the // issue with the // transformation described // above 1./2., 1./2. }; }; template <> const double * const FE_Nedelec<2>::Matrices::constraint_matrices[] = { FE_Nedelec_2d::constraint_q1 }; template <> const unsigned int FE_Nedelec<2>::Matrices::n_constraint_matrices = sizeof(FE_Nedelec<2>::Matrices::constraint_matrices) / sizeof(FE_Nedelec<2>::Matrices::constraint_matrices[0]); #else // #if deal_II_dimension // On gcc2.95 on Alpha OSF1, the native assembler does not like empty // files, so provide some dummy code namespace { void dummy () {}; }; #endif // #if deal_II_dimension == 2 <|endoftext|>
<commit_before>// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/common/extensions/permissions/media_galleries_permission.h" #include <algorithm> #include "base/logging.h" #include "base/memory/scoped_ptr.h" #include "base/stl_util.h" #include "base/values.h" #include "chrome/common/extensions/extension.h" #include "chrome/common/extensions/extension_messages.h" #include "chrome/common/extensions/permissions/api_permission.h" #include "chrome/common/extensions/permissions/permission_message.h" #include "chrome/common/extensions/permissions/permissions_info.h" #include "grit/generated_resources.h" #include "ui/base/l10n/l10n_util.h" namespace { const char kAllAutoDetectedString[] = "allAutoDetected"; const char kReadString[] = "read"; const char kInvalidString[] = "invalid"; } // namespace namespace extensions { MediaGalleriesPermission::MediaGalleriesPermission( const APIPermissionInfo* info) : APIPermission(info) { } MediaGalleriesPermission::~MediaGalleriesPermission() { } // static bool MediaGalleriesPermission::HasReadAccess(const Extension& extension) { CheckParam read_param(kRead); return extension.CheckAPIPermissionWithParam( extensions::APIPermission::kMediaGalleries, &read_param); } // static bool MediaGalleriesPermission::HasAllGalleriesAccess( const Extension& extension) { CheckParam all_param(kAllAutoDetected); return extension.CheckAPIPermissionWithParam( extensions::APIPermission::kMediaGalleries, &all_param); } // static MediaGalleriesPermission::PermissionTypes MediaGalleriesPermission::PermissionStringToType(const std::string& str) { if (str == kAllAutoDetectedString) return kAllAutoDetected; if (str == kReadString) return kRead; return kNone; } // static const char* MediaGalleriesPermission::PermissionTypeToString( PermissionTypes type) { switch (type) { case kAllAutoDetected: return kAllAutoDetectedString; case kRead: return kReadString; default: NOTREACHED(); return kInvalidString; } } bool MediaGalleriesPermission::HasMessages() const { CheckParam param(kAllAutoDetected); return Check(&param); } PermissionMessages MediaGalleriesPermission::GetMessages() const { CheckParam param(kAllAutoDetected); if (Check(&param)) { PermissionMessages result; result.push_back(PermissionMessage( PermissionMessage::kMediaGalleriesAllGalleries, l10n_util::GetStringUTF16( IDS_EXTENSION_PROMPT_WARNING_MEDIA_GALLERIES_ALL_GALLERIES))); return result; } NOTREACHED(); PermissionMessages result; result.push_back(PermissionMessage(PermissionMessage::kUnknown, string16())); return result; } bool MediaGalleriesPermission::Check( const APIPermission::CheckParam* param) const { const CheckParam* media_galleries_param = static_cast<const CheckParam*>(param); return ContainsKey(permissions_, media_galleries_param->permission); } bool MediaGalleriesPermission::Contains(const APIPermission* rhs) const { CHECK_EQ(rhs->info(), info()); const MediaGalleriesPermission* perm = static_cast<const MediaGalleriesPermission*>(rhs); return std::includes(permissions_.begin(), permissions_.end(), perm->permissions_.begin(), perm->permissions_.end()); } bool MediaGalleriesPermission::Equal(const APIPermission* rhs) const { CHECK(rhs->info() == info()); const MediaGalleriesPermission* perm = static_cast<const MediaGalleriesPermission*>(rhs); return permissions_ == perm->permissions_; } bool MediaGalleriesPermission::FromValue(const base::Value* value) { permissions_.clear(); if (!value) return false; const base::ListValue* list = NULL; if (!value->GetAsList(&list) || list->GetSize() == 0) return false; for (size_t i = 0; i < list->GetSize(); ++i) { std::string str; if (!list->GetString(i, &str)) return false; PermissionTypes type = PermissionStringToType(str); if (type == kNone) return false; permissions_.insert(type); } return true; } void MediaGalleriesPermission::ToValue(base::Value** value) const { base::ListValue* list = new ListValue(); for (std::set<PermissionTypes>::const_iterator it = permissions_.begin(); it != permissions_.end(); ++it) { list->Append(base::Value::CreateStringValue(PermissionTypeToString(*it))); } *value = list; } APIPermission* MediaGalleriesPermission::Clone() const { MediaGalleriesPermission* result = new MediaGalleriesPermission(info()); result->permissions_ = permissions_; return result; } APIPermission* MediaGalleriesPermission::Diff(const APIPermission* rhs) const { CHECK(rhs->info() == info()); const MediaGalleriesPermission* perm = static_cast<const MediaGalleriesPermission*>(rhs); scoped_ptr<MediaGalleriesPermission> result( new MediaGalleriesPermission(info())); std::set_difference(permissions_.begin(), permissions_.end(), perm->permissions_.begin(), perm->permissions_.end(), std::inserter<std::set<PermissionTypes> >( result->permissions_, result->permissions_.begin())); return result->permissions_.empty() ? NULL : result.release(); } APIPermission* MediaGalleriesPermission::Union(const APIPermission* rhs) const { CHECK(rhs->info() == info()); const MediaGalleriesPermission* perm = static_cast<const MediaGalleriesPermission*>(rhs); scoped_ptr<MediaGalleriesPermission> result( new MediaGalleriesPermission(info())); std::set_union(permissions_.begin(), permissions_.end(), perm->permissions_.begin(), perm->permissions_.end(), std::inserter<std::set<PermissionTypes> >( result->permissions_, result->permissions_.begin())); return result->permissions_.empty() ? NULL : result.release(); } APIPermission* MediaGalleriesPermission::Intersect( const APIPermission* rhs) const { CHECK(rhs->info() == info()); const MediaGalleriesPermission* perm = static_cast<const MediaGalleriesPermission*>(rhs); scoped_ptr<MediaGalleriesPermission> result( new MediaGalleriesPermission(info())); std::set_intersection(permissions_.begin(), permissions_.end(), perm->permissions_.begin(), perm->permissions_.end(), std::inserter<std::set<PermissionTypes> >( result->permissions_, result->permissions_.begin())); return result->permissions_.empty() ? NULL : result.release(); } void MediaGalleriesPermission::Write(IPC::Message* m) const { IPC::WriteParam(m, permissions_); } bool MediaGalleriesPermission::Read(const IPC::Message* m, PickleIterator* iter) { return IPC::ReadParam(m, iter, &permissions_); } void MediaGalleriesPermission::Log(std::string* log) const { IPC::LogParam(permissions_, log); } } // namespace extensions <commit_msg>Temporarily add back all-auto-detected as an alias for allAutoDetected to make transition easier.<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/common/extensions/permissions/media_galleries_permission.h" #include <algorithm> #include "base/logging.h" #include "base/memory/scoped_ptr.h" #include "base/stl_util.h" #include "base/values.h" #include "chrome/common/extensions/extension.h" #include "chrome/common/extensions/extension_messages.h" #include "chrome/common/extensions/permissions/api_permission.h" #include "chrome/common/extensions/permissions/permission_message.h" #include "chrome/common/extensions/permissions/permissions_info.h" #include "grit/generated_resources.h" #include "ui/base/l10n/l10n_util.h" namespace { const char kAllAutoDetectedString[] = "allAutoDetected"; const char kAllAutoDetectedAliasString[] = "all-auto-detected"; const char kReadString[] = "read"; const char kInvalidString[] = "invalid"; } // namespace namespace extensions { MediaGalleriesPermission::MediaGalleriesPermission( const APIPermissionInfo* info) : APIPermission(info) { } MediaGalleriesPermission::~MediaGalleriesPermission() { } // static bool MediaGalleriesPermission::HasReadAccess(const Extension& extension) { CheckParam read_param(kRead); return extension.CheckAPIPermissionWithParam( extensions::APIPermission::kMediaGalleries, &read_param); } // static bool MediaGalleriesPermission::HasAllGalleriesAccess( const Extension& extension) { CheckParam all_param(kAllAutoDetected); return extension.CheckAPIPermissionWithParam( extensions::APIPermission::kMediaGalleries, &all_param); } // static MediaGalleriesPermission::PermissionTypes MediaGalleriesPermission::PermissionStringToType(const std::string& str) { if (str == kAllAutoDetectedString) return kAllAutoDetected; if (str == kAllAutoDetectedAliasString) return kAllAutoDetected; if (str == kReadString) return kRead; return kNone; } // static const char* MediaGalleriesPermission::PermissionTypeToString( PermissionTypes type) { switch (type) { case kAllAutoDetected: return kAllAutoDetectedString; case kRead: return kReadString; default: NOTREACHED(); return kInvalidString; } } bool MediaGalleriesPermission::HasMessages() const { CheckParam param(kAllAutoDetected); return Check(&param); } PermissionMessages MediaGalleriesPermission::GetMessages() const { CheckParam param(kAllAutoDetected); if (Check(&param)) { PermissionMessages result; result.push_back(PermissionMessage( PermissionMessage::kMediaGalleriesAllGalleries, l10n_util::GetStringUTF16( IDS_EXTENSION_PROMPT_WARNING_MEDIA_GALLERIES_ALL_GALLERIES))); return result; } NOTREACHED(); PermissionMessages result; result.push_back(PermissionMessage(PermissionMessage::kUnknown, string16())); return result; } bool MediaGalleriesPermission::Check( const APIPermission::CheckParam* param) const { const CheckParam* media_galleries_param = static_cast<const CheckParam*>(param); return ContainsKey(permissions_, media_galleries_param->permission); } bool MediaGalleriesPermission::Contains(const APIPermission* rhs) const { CHECK_EQ(rhs->info(), info()); const MediaGalleriesPermission* perm = static_cast<const MediaGalleriesPermission*>(rhs); return std::includes(permissions_.begin(), permissions_.end(), perm->permissions_.begin(), perm->permissions_.end()); } bool MediaGalleriesPermission::Equal(const APIPermission* rhs) const { CHECK(rhs->info() == info()); const MediaGalleriesPermission* perm = static_cast<const MediaGalleriesPermission*>(rhs); return permissions_ == perm->permissions_; } bool MediaGalleriesPermission::FromValue(const base::Value* value) { permissions_.clear(); if (!value) return false; const base::ListValue* list = NULL; if (!value->GetAsList(&list) || list->GetSize() == 0) return false; for (size_t i = 0; i < list->GetSize(); ++i) { std::string str; if (!list->GetString(i, &str)) return false; PermissionTypes type = PermissionStringToType(str); if (type == kNone) return false; permissions_.insert(type); } return true; } void MediaGalleriesPermission::ToValue(base::Value** value) const { base::ListValue* list = new ListValue(); for (std::set<PermissionTypes>::const_iterator it = permissions_.begin(); it != permissions_.end(); ++it) { list->Append(base::Value::CreateStringValue(PermissionTypeToString(*it))); } *value = list; } APIPermission* MediaGalleriesPermission::Clone() const { MediaGalleriesPermission* result = new MediaGalleriesPermission(info()); result->permissions_ = permissions_; return result; } APIPermission* MediaGalleriesPermission::Diff(const APIPermission* rhs) const { CHECK(rhs->info() == info()); const MediaGalleriesPermission* perm = static_cast<const MediaGalleriesPermission*>(rhs); scoped_ptr<MediaGalleriesPermission> result( new MediaGalleriesPermission(info())); std::set_difference(permissions_.begin(), permissions_.end(), perm->permissions_.begin(), perm->permissions_.end(), std::inserter<std::set<PermissionTypes> >( result->permissions_, result->permissions_.begin())); return result->permissions_.empty() ? NULL : result.release(); } APIPermission* MediaGalleriesPermission::Union(const APIPermission* rhs) const { CHECK(rhs->info() == info()); const MediaGalleriesPermission* perm = static_cast<const MediaGalleriesPermission*>(rhs); scoped_ptr<MediaGalleriesPermission> result( new MediaGalleriesPermission(info())); std::set_union(permissions_.begin(), permissions_.end(), perm->permissions_.begin(), perm->permissions_.end(), std::inserter<std::set<PermissionTypes> >( result->permissions_, result->permissions_.begin())); return result->permissions_.empty() ? NULL : result.release(); } APIPermission* MediaGalleriesPermission::Intersect( const APIPermission* rhs) const { CHECK(rhs->info() == info()); const MediaGalleriesPermission* perm = static_cast<const MediaGalleriesPermission*>(rhs); scoped_ptr<MediaGalleriesPermission> result( new MediaGalleriesPermission(info())); std::set_intersection(permissions_.begin(), permissions_.end(), perm->permissions_.begin(), perm->permissions_.end(), std::inserter<std::set<PermissionTypes> >( result->permissions_, result->permissions_.begin())); return result->permissions_.empty() ? NULL : result.release(); } void MediaGalleriesPermission::Write(IPC::Message* m) const { IPC::WriteParam(m, permissions_); } bool MediaGalleriesPermission::Read(const IPC::Message* m, PickleIterator* iter) { return IPC::ReadParam(m, iter, &permissions_); } void MediaGalleriesPermission::Log(std::string* log) const { IPC::LogParam(permissions_, log); } } // namespace extensions <|endoftext|>
<commit_before>/* * Copyright (C) 2015 German Aerospace Center (DLR/SC) * * Created: 2015-10-20 Martin Siggel <[email protected]> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "CTiglWingBuilder.h" #include "CTiglMakeLoft.h" #include "CCPACSWingSegment.h" #include "CTiglLogging.h" #include "CNamedShape.h" #include "tiglcommonfunctions.h" #include <TopExp.hxx> #include <TopoDS_Iterator.hxx> #include <TopTools_IndexedMapOfShape.hxx> #include <BRepBuilderAPI_MakeWire.hxx> #include <BRepBuilderAPI_MakeEdge.hxx> #include <BRepOffsetAPI_ThruSections.hxx> #include <BRepBuilderAPI_Sewing.hxx> #include <BRepClass3d_SolidClassifier.hxx> #include <BRep_Builder.hxx> #include <BRepBuilderAPI_FindPlane.hxx> #include <BRepBuilderAPI_MakeFace.hxx> #include <BRepLib.hxx> #include <Geom_Plane.hxx> #include <cassert> #define NO_EXPLICIT_TE_MODELING namespace tigl { Standard_Boolean CreateSideCap(const TopoDS_Wire& W, const Standard_Real presPln, TopoDS_Face& theFace); CTiglWingBuilder::CTiglWingBuilder(const CCPACSWing& wing) : _wing(wing) { } #ifndef NO_EXPLICIT_TE_MODELING PNamedShape CTiglWingBuilder::BuildShape() { const CCPACSWingSegments& segments = _wing.m_segments; // check whether we have a blunt TE or not const CCPACSWingProfile& innerProfile = segments.GetSegment(1).GetInnerConnection().GetProfile(); TopoDS_Compound guideCurves = _wing.GetGuideCurveWires(); std::vector<TopoDS_Wire> guides; for (TopoDS_Iterator anIter(guideCurves); anIter.More(); anIter.Next()) { TopoDS_Wire aSh = TopoDS::Wire(anIter.Value()); guides.push_back(aSh); } // we assume, that all profiles of one wing are either blunt or not // this is checked during cpacs loading of each wing segment bool hasBluntTE = innerProfile.HasBluntTE(); bool hasGuideCurves = guides.size() > 0; CTiglMakeLoft lofter; lofter.setMakeSolid(false); std::vector<gp_Pnt> upperTEPoints, lowerTEPoints; for (int i=1; i <= segments.GetSegmentCount(); i++) { const TopoDS_Wire& startWire = segments.GetSegment(i).GetInnerWire(); // extract trailing edge, in case of a blunt TE // we assume, that the TE is the last edge of the wire if (hasBluntTE) { BRepBuilderAPI_MakeWire wireMaker; TopTools_IndexedMapOfShape edgeMap; TopExp::MapShapes(startWire, TopAbs_EDGE, edgeMap); for (int i = 1; i <= edgeMap.Extent(); ++i) { const TopoDS_Edge& e = TopoDS::Edge(edgeMap(i)); if (i < edgeMap.Extent()) { wireMaker.Add(e); } } TopoDS_Wire aeroProfile = wireMaker.Wire(); lofter.addProfiles(aeroProfile); upperTEPoints.push_back(GetLastPoint(aeroProfile)); lowerTEPoints.push_back(GetFirstPoint(aeroProfile)); } else { lofter.addProfiles(startWire); } } TopoDS_Wire endWire = segments.GetSegment(segments.GetSegmentCount()).GetOuterWire(); if (hasBluntTE) { // extract the wire without the trailing edge BRepBuilderAPI_MakeWire wireMaker; TopTools_IndexedMapOfShape edgeMap; TopExp::MapShapes(endWire, TopAbs_EDGE, edgeMap); for (int i = 1; i <= edgeMap.Extent(); ++i) { const TopoDS_Edge& e = TopoDS::Edge(edgeMap(i)); if (i < edgeMap.Extent()) { wireMaker.Add(e); } } TopoDS_Wire aeroProfile = wireMaker.Wire(); lofter.addProfiles(aeroProfile); upperTEPoints.push_back(GetLastPoint(aeroProfile)); lowerTEPoints.push_back(GetFirstPoint(aeroProfile)); } else { lofter.addProfiles(endWire); } // add guide curves lofter.addGuides(guideCurves); TopoDS_Shape aeroShape = lofter.Shape(); BRepBuilderAPI_Sewing sewingAlgo; sewingAlgo.Add(aeroShape); // If blunt trailing edge is available, model it explicitly if (hasBluntTE) { TopoDS_Wire upperTE, lowerTE; if (hasGuideCurves) { // The guide curves are sorted in the order of the relative starting coordinate // at the innermost section upperTE = guides.back(); lowerTE = guides.front(); } else { // model the edges by taking the first and last profile points assert(lowerTEPoints.size() == upperTEPoints.size()); assert(lowerTEPoints.size() > 1); // build upper edge BRepBuilderAPI_MakeWire upperWireMaker, lowerWireMaker; for (unsigned int i = 0; i < upperTEPoints.size() - 1; ++i) { upperWireMaker.Add(BRepBuilderAPI_MakeEdge(upperTEPoints.at(i), upperTEPoints.at(i+1))); lowerWireMaker.Add(BRepBuilderAPI_MakeEdge(lowerTEPoints.at(i), lowerTEPoints.at(i+1))); } upperTE = upperWireMaker.Wire(); lowerTE = lowerWireMaker.Wire(); } // the TE is build using a ruled loft BRepOffsetAPI_ThruSections trailingEdgeBuilder(Standard_False, Standard_True); trailingEdgeBuilder.AddWire(upperTE); trailingEdgeBuilder.AddWire(lowerTE); trailingEdgeBuilder.Build(); TopoDS_Shape trailingEdge = trailingEdgeBuilder.Shape(); sewingAlgo.Add(trailingEdge); } // hasBluntTE // get the profiles TopoDS_Wire innerWire = segments.GetSegment(1).GetInnerWire(); TopoDS_Wire outerWire = segments.GetSegment(segments.GetSegmentCount()).GetOuterWire(); TopoDS_Face innerFace, outerFace; CreateSideCap(innerWire, 1e-6, innerFace); CreateSideCap(outerWire, 1e-6, outerFace); sewingAlgo.Add(innerFace); sewingAlgo.Add(outerFace); sewingAlgo.Perform(); TopoDS_Shape shellClosed = sewingAlgo.SewedShape(); shellClosed.Closed(Standard_True); // make solid from shell TopoDS_Solid solid; BRep_Builder solidMaker; solidMaker.MakeSolid(solid); solidMaker.Add(solid, shellClosed); // verify the orientation the solid BRepClass3d_SolidClassifier clas3d(solid); clas3d.PerformInfinitePoint(Precision::Confusion()); if (clas3d.State() == TopAbs_IN) { solidMaker.MakeSolid(solid); TopoDS_Shape aLocalShape = shellClosed.Reversed(); solidMaker.Add(solid, TopoDS::Shell(aLocalShape)); } solid.Closed(Standard_True); BRepLib::EncodeRegularity(solid); std::string loftName = _wing.GetUID(); std::string loftShortName = _wing.GetShortShapeName(); PNamedShape loft(new CNamedShape(solid, loftName.c_str(), loftShortName.c_str())); SetFaceTraits(_wing.GetUID(), loft, hasBluntTE); return loft; } #else PNamedShape CTiglWingBuilder::BuildShape() { const CCPACSWingSegments& segments = _wing.GetSegments(); const CCPACSWingProfile& innerProfile = segments.GetSegment(1).GetInnerConnection().GetProfile(); // we assume, that all profiles of one wing are either blunt or not // this is checked during cpacs loading of each wing segment bool hasBluntTE = innerProfile.HasBluntTE(); CTiglMakeLoft lofter; lofter.setMakeSolid(true); for (int i=1; i <= segments.GetSegmentCount(); i++) { const TopoDS_Shape& startWire = segments.GetSegment(i).GetInnerWire(); lofter.addProfiles(startWire); } TopoDS_Wire endWire = segments.GetSegment(segments.GetSegmentCount()).GetOuterWire(); lofter.addProfiles(endWire); // add guide curves lofter.addGuides(_wing.GetGuideCurveWires()); TopoDS_Shape loftShape = lofter.Shape(); std::string loftName = _wing.GetUID(); std::string loftShortName = _wing.GetShortShapeName(); PNamedShape loft(new CNamedShape(loftShape, loftName.c_str(), loftShortName.c_str())); SetFaceTraits(_wing.GetUID(), loft, hasBluntTE); return loft; } #endif CTiglWingBuilder::operator PNamedShape() { return BuildShape(); } // Set the name of each wing face void CTiglWingBuilder::SetFaceTraits (const std::string& wingUID, PNamedShape loft, bool hasBluntTE) { unsigned int nSegments = _wing.GetSegmentCount(); // designated names of the faces std::vector<std::string> names(3); names[0]="Bottom"; names[1]="Top"; names[2]="TrailingEdge"; std::vector<std::string> endnames(2); endnames[0]="Inside"; endnames[1]="Outside"; unsigned int nFaces = GetNumberOfFaces(loft->Shape()); for (unsigned int i = 0; i < nFaces; i++) { loft->FaceTraits(i).SetComponentUID(wingUID); } // check if number of faces without inside and outside surface (nFaces-2) // is a multiple of 2 (without Trailing Edges) or 3 (with Trailing Edges) if (!((nFaces-2)/nSegments == 2 || (nFaces-2)/nSegments == 3) || nFaces < 4) { LOG(ERROR) << "CCPACSWingBuilder: Unable to determine wing face names from wing loft."; return; } #ifndef NO_EXPLICIT_TE_MODELING unsigned int nTEFaces = hasBluntTE ? nSegments : 0; unsigned int nAeroFaces = nFaces - nTEFaces - 2; // assign "Top" and "Bottom" to face traits for (unsigned int i = 0; i < nAeroFaces; i++) { CFaceTraits traits = loft->GetFaceTraits(i); traits.SetName(names[i%2].c_str()); loft->SetFaceTraits(i, traits); } // assign TE to face traits for (unsigned int i = nAeroFaces; i < nAeroFaces + nTEFaces; ++i) { CFaceTraits traits = loft->GetFaceTraits(i); traits.SetName(names[2].c_str()); loft->SetFaceTraits(i, traits); } #else // remove trailing edge name if there is no trailing edge if (!hasBluntTE) { names.pop_back(); } // assign "Top" and "Bottom" to face traits for (unsigned int i = 0; i < nFaces-2; i++) { CFaceTraits traits = loft->GetFaceTraits(i); traits.SetName(names[i%names.size()].c_str()); loft->SetFaceTraits(i, traits); } #endif // assign "Inside" and "Outside" to face traits for (unsigned int i = nFaces-2; i < nFaces; i++) { CFaceTraits traits = loft->GetFaceTraits(i); traits.SetName(endnames[i-nFaces+2].c_str()); loft->SetFaceTraits(i, traits); } } // creates the inside and outside cap of the wing Standard_Boolean CreateSideCap(const TopoDS_Wire& W, const Standard_Real presPln, TopoDS_Face& theFace) { Standard_Boolean isDegen = Standard_True; TopoDS_Iterator iter(W); for (; iter.More(); iter.Next()) { const TopoDS_Edge& anEdge = TopoDS::Edge(iter.Value()); if (!BRep_Tool::Degenerated(anEdge)) isDegen = Standard_False; } if (isDegen) return Standard_True; Standard_Boolean Ok = Standard_False; if (!W.IsNull()) { BRepBuilderAPI_FindPlane Searcher( W, presPln ); if (Searcher.Found()) { theFace = BRepBuilderAPI_MakeFace(Searcher.Plane(), W); Ok = Standard_True; } else { // try to find another surface BRepBuilderAPI_MakeFace MF( W ); if (MF.IsDone()) { theFace = MF.Face(); Ok = Standard_True; } } } return Ok; } } //namespace tigl <commit_msg>added check for shell in CTiglWingBuilder<commit_after>/* * Copyright (C) 2015 German Aerospace Center (DLR/SC) * * Created: 2015-10-20 Martin Siggel <[email protected]> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "CTiglWingBuilder.h" #include "CTiglMakeLoft.h" #include "CCPACSWingSegment.h" #include "CTiglLogging.h" #include "CNamedShape.h" #include "tiglcommonfunctions.h" #include <TopExp.hxx> #include <TopoDS_Iterator.hxx> #include <TopTools_IndexedMapOfShape.hxx> #include <BRepBuilderAPI_MakeWire.hxx> #include <BRepBuilderAPI_MakeEdge.hxx> #include <BRepOffsetAPI_ThruSections.hxx> #include <BRepBuilderAPI_Sewing.hxx> #include <BRepClass3d_SolidClassifier.hxx> #include <BRep_Builder.hxx> #include <BRepBuilderAPI_FindPlane.hxx> #include <BRepBuilderAPI_MakeFace.hxx> #include <BRepLib.hxx> #include <Geom_Plane.hxx> #include <cassert> #define NO_EXPLICIT_TE_MODELING namespace tigl { Standard_Boolean CreateSideCap(const TopoDS_Wire& W, const Standard_Real presPln, TopoDS_Face& theFace); CTiglWingBuilder::CTiglWingBuilder(const CCPACSWing& wing) : _wing(wing) { } #ifndef NO_EXPLICIT_TE_MODELING PNamedShape CTiglWingBuilder::BuildShape() { const CCPACSWingSegments& segments = _wing.m_segments; // check whether we have a blunt TE or not const CCPACSWingProfile& innerProfile = segments.GetSegment(1).GetInnerConnection().GetProfile(); TopoDS_Compound guideCurves = _wing.GetGuideCurveWires(); std::vector<TopoDS_Wire> guides; for (TopoDS_Iterator anIter(guideCurves); anIter.More(); anIter.Next()) { TopoDS_Wire aSh = TopoDS::Wire(anIter.Value()); guides.push_back(aSh); } // we assume, that all profiles of one wing are either blunt or not // this is checked during cpacs loading of each wing segment bool hasBluntTE = innerProfile.HasBluntTE(); bool hasGuideCurves = guides.size() > 0; CTiglMakeLoft lofter; lofter.setMakeSolid(false); std::vector<gp_Pnt> upperTEPoints, lowerTEPoints; for (int i=1; i <= segments.GetSegmentCount(); i++) { const TopoDS_Wire& startWire = segments.GetSegment(i).GetInnerWire(); // extract trailing edge, in case of a blunt TE // we assume, that the TE is the last edge of the wire if (hasBluntTE) { BRepBuilderAPI_MakeWire wireMaker; TopTools_IndexedMapOfShape edgeMap; TopExp::MapShapes(startWire, TopAbs_EDGE, edgeMap); for (int i = 1; i <= edgeMap.Extent(); ++i) { const TopoDS_Edge& e = TopoDS::Edge(edgeMap(i)); if (i < edgeMap.Extent()) { wireMaker.Add(e); } } TopoDS_Wire aeroProfile = wireMaker.Wire(); lofter.addProfiles(aeroProfile); upperTEPoints.push_back(GetLastPoint(aeroProfile)); lowerTEPoints.push_back(GetFirstPoint(aeroProfile)); } else { lofter.addProfiles(startWire); } } TopoDS_Wire endWire = segments.GetSegment(segments.GetSegmentCount()).GetOuterWire(); if (hasBluntTE) { // extract the wire without the trailing edge BRepBuilderAPI_MakeWire wireMaker; TopTools_IndexedMapOfShape edgeMap; TopExp::MapShapes(endWire, TopAbs_EDGE, edgeMap); for (int i = 1; i <= edgeMap.Extent(); ++i) { const TopoDS_Edge& e = TopoDS::Edge(edgeMap(i)); if (i < edgeMap.Extent()) { wireMaker.Add(e); } } TopoDS_Wire aeroProfile = wireMaker.Wire(); lofter.addProfiles(aeroProfile); upperTEPoints.push_back(GetLastPoint(aeroProfile)); lowerTEPoints.push_back(GetFirstPoint(aeroProfile)); } else { lofter.addProfiles(endWire); } // add guide curves lofter.addGuides(guideCurves); TopoDS_Shape aeroShape = lofter.Shape(); BRepBuilderAPI_Sewing sewingAlgo; sewingAlgo.Add(aeroShape); // If blunt trailing edge is available, model it explicitly if (hasBluntTE) { TopoDS_Wire upperTE, lowerTE; if (hasGuideCurves) { // The guide curves are sorted in the order of the relative starting coordinate // at the innermost section upperTE = guides.back(); lowerTE = guides.front(); } else { // model the edges by taking the first and last profile points assert(lowerTEPoints.size() == upperTEPoints.size()); assert(lowerTEPoints.size() > 1); // build upper edge BRepBuilderAPI_MakeWire upperWireMaker, lowerWireMaker; for (unsigned int i = 0; i < upperTEPoints.size() - 1; ++i) { upperWireMaker.Add(BRepBuilderAPI_MakeEdge(upperTEPoints.at(i), upperTEPoints.at(i+1))); lowerWireMaker.Add(BRepBuilderAPI_MakeEdge(lowerTEPoints.at(i), lowerTEPoints.at(i+1))); } upperTE = upperWireMaker.Wire(); lowerTE = lowerWireMaker.Wire(); } // the TE is build using a ruled loft BRepOffsetAPI_ThruSections trailingEdgeBuilder(Standard_False, Standard_True); trailingEdgeBuilder.AddWire(upperTE); trailingEdgeBuilder.AddWire(lowerTE); trailingEdgeBuilder.Build(); TopoDS_Shape trailingEdge = trailingEdgeBuilder.Shape(); sewingAlgo.Add(trailingEdge); } // hasBluntTE // get the profiles TopoDS_Wire innerWire = segments.GetSegment(1).GetInnerWire(); TopoDS_Wire outerWire = segments.GetSegment(segments.GetSegmentCount()).GetOuterWire(); TopoDS_Face innerFace, outerFace; CreateSideCap(innerWire, 1e-6, innerFace); CreateSideCap(outerWire, 1e-6, outerFace); sewingAlgo.Add(innerFace); sewingAlgo.Add(outerFace); sewingAlgo.Perform(); TopoDS_Shape shellClosed = sewingAlgo.SewedShape(); if (shellClosed.ShapeType() != TopAbs_SHELL) throw CTiglError("Expected sewing algo to construct a shell when building wing loft"); shellClosed.Closed(Standard_True); // make solid from shell TopoDS_Solid solid; BRep_Builder solidMaker; solidMaker.MakeSolid(solid); solidMaker.Add(solid, shellClosed); // verify the orientation the solid BRepClass3d_SolidClassifier clas3d(solid); clas3d.PerformInfinitePoint(Precision::Confusion()); if (clas3d.State() == TopAbs_IN) { solidMaker.MakeSolid(solid); TopoDS_Shape aLocalShape = shellClosed.Reversed(); solidMaker.Add(solid, TopoDS::Shell(aLocalShape)); } solid.Closed(Standard_True); BRepLib::EncodeRegularity(solid); std::string loftName = _wing.GetUID(); std::string loftShortName = _wing.GetShortShapeName(); PNamedShape loft(new CNamedShape(solid, loftName.c_str(), loftShortName.c_str())); SetFaceTraits(_wing.GetUID(), loft, hasBluntTE); return loft; } #else PNamedShape CTiglWingBuilder::BuildShape() { const CCPACSWingSegments& segments = _wing.GetSegments(); const CCPACSWingProfile& innerProfile = segments.GetSegment(1).GetInnerConnection().GetProfile(); // we assume, that all profiles of one wing are either blunt or not // this is checked during cpacs loading of each wing segment bool hasBluntTE = innerProfile.HasBluntTE(); CTiglMakeLoft lofter; lofter.setMakeSolid(true); for (int i=1; i <= segments.GetSegmentCount(); i++) { const TopoDS_Shape& startWire = segments.GetSegment(i).GetInnerWire(); lofter.addProfiles(startWire); } TopoDS_Wire endWire = segments.GetSegment(segments.GetSegmentCount()).GetOuterWire(); lofter.addProfiles(endWire); // add guide curves lofter.addGuides(_wing.GetGuideCurveWires()); TopoDS_Shape loftShape = lofter.Shape(); std::string loftName = _wing.GetUID(); std::string loftShortName = _wing.GetShortShapeName(); PNamedShape loft(new CNamedShape(loftShape, loftName.c_str(), loftShortName.c_str())); SetFaceTraits(_wing.GetUID(), loft, hasBluntTE); return loft; } #endif CTiglWingBuilder::operator PNamedShape() { return BuildShape(); } // Set the name of each wing face void CTiglWingBuilder::SetFaceTraits (const std::string& wingUID, PNamedShape loft, bool hasBluntTE) { unsigned int nSegments = _wing.GetSegmentCount(); // designated names of the faces std::vector<std::string> names(3); names[0]="Bottom"; names[1]="Top"; names[2]="TrailingEdge"; std::vector<std::string> endnames(2); endnames[0]="Inside"; endnames[1]="Outside"; unsigned int nFaces = GetNumberOfFaces(loft->Shape()); for (unsigned int i = 0; i < nFaces; i++) { loft->FaceTraits(i).SetComponentUID(wingUID); } // check if number of faces without inside and outside surface (nFaces-2) // is a multiple of 2 (without Trailing Edges) or 3 (with Trailing Edges) if (!((nFaces-2)/nSegments == 2 || (nFaces-2)/nSegments == 3) || nFaces < 4) { LOG(ERROR) << "CCPACSWingBuilder: Unable to determine wing face names from wing loft."; return; } #ifndef NO_EXPLICIT_TE_MODELING unsigned int nTEFaces = hasBluntTE ? nSegments : 0; unsigned int nAeroFaces = nFaces - nTEFaces - 2; // assign "Top" and "Bottom" to face traits for (unsigned int i = 0; i < nAeroFaces; i++) { CFaceTraits traits = loft->GetFaceTraits(i); traits.SetName(names[i%2].c_str()); loft->SetFaceTraits(i, traits); } // assign TE to face traits for (unsigned int i = nAeroFaces; i < nAeroFaces + nTEFaces; ++i) { CFaceTraits traits = loft->GetFaceTraits(i); traits.SetName(names[2].c_str()); loft->SetFaceTraits(i, traits); } #else // remove trailing edge name if there is no trailing edge if (!hasBluntTE) { names.pop_back(); } // assign "Top" and "Bottom" to face traits for (unsigned int i = 0; i < nFaces-2; i++) { CFaceTraits traits = loft->GetFaceTraits(i); traits.SetName(names[i%names.size()].c_str()); loft->SetFaceTraits(i, traits); } #endif // assign "Inside" and "Outside" to face traits for (unsigned int i = nFaces-2; i < nFaces; i++) { CFaceTraits traits = loft->GetFaceTraits(i); traits.SetName(endnames[i-nFaces+2].c_str()); loft->SetFaceTraits(i, traits); } } // creates the inside and outside cap of the wing Standard_Boolean CreateSideCap(const TopoDS_Wire& W, const Standard_Real presPln, TopoDS_Face& theFace) { Standard_Boolean isDegen = Standard_True; TopoDS_Iterator iter(W); for (; iter.More(); iter.Next()) { const TopoDS_Edge& anEdge = TopoDS::Edge(iter.Value()); if (!BRep_Tool::Degenerated(anEdge)) isDegen = Standard_False; } if (isDegen) return Standard_True; Standard_Boolean Ok = Standard_False; if (!W.IsNull()) { BRepBuilderAPI_FindPlane Searcher( W, presPln ); if (Searcher.Found()) { theFace = BRepBuilderAPI_MakeFace(Searcher.Plane(), W); Ok = Standard_True; } else { // try to find another surface BRepBuilderAPI_MakeFace MF( W ); if (MF.IsDone()) { theFace = MF.Face(); Ok = Standard_True; } } } return Ok; } } //namespace tigl <|endoftext|>
<commit_before>#include <memory> #include <string> #include <vector> #include <unordered_map> #include <utility> #include <iomanip> #include <CoreServices/CoreServices.h> #include "platform.h" #include "worker_thread.h" #include "../log.h" #include "../message.h" using std::vector; using std::string; using std::endl; using std::unique_ptr; using std::move; using std::pair; using std::make_pair; using std::unordered_map; using std::hex; static const CFAbsoluteTime LATENCY = 0.001; static const FSEventStreamEventFlags CREATE_FLAGS = kFSEventStreamEventFlagItemCreated; static const FSEventStreamEventFlags DELETED_FLAGS = kFSEventStreamEventFlagItemRemoved; static const FSEventStreamEventFlags MODIFY_FLAGS = kFSEventStreamEventFlagItemInodeMetaMod | kFSEventStreamEventFlagItemFinderInfoMod | kFSEventStreamEventFlagItemChangeOwner | kFSEventStreamEventFlagItemXattrMod | kFSEventStreamEventFlagItemModified; static const FSEventStreamEventFlags RENAME_FLAGS = kFSEventStreamEventFlagItemRenamed; static const FSEventStreamEventFlags IS_FILE = kFSEventStreamEventFlagItemIsFile; static const FSEventStreamEventFlags IS_DIRECTORY = kFSEventStreamEventFlagItemIsDir; static void command_perform_helper(void *info); static void event_stream_helper( ConstFSEventStreamRef event_stream, void *info, size_t num_events, void *event_paths, const FSEventStreamEventFlags *event_flags, const FSEventStreamEventId *event_ids); struct Subscription { WorkerPlatform *platform; ChannelID channel; FSEventStreamRef event_stream; Subscription(WorkerPlatform *platform, ChannelID channel) : platform{platform}, channel{channel}, event_stream{NULL} { // } }; class MacOSWorkerPlatform : public WorkerPlatform { public: MacOSWorkerPlatform(WorkerThread *thread) : WorkerPlatform(thread), run_loop{nullptr}, command_source{nullptr} { // }; ~MacOSWorkerPlatform() override { if (command_source) CFRelease(command_source); if (run_loop) CFRelease(run_loop); } void wake() override { CFRunLoopSourceSignal(command_source); CFRunLoopWakeUp(run_loop); } void listen() override { run_loop = CFRunLoopGetCurrent(); CFRetain(run_loop); CFRunLoopSourceContext command_context = { 0, // version this, // info NULL, // retain NULL, // release NULL, // copyDescription NULL, // equal NULL, // hash NULL, // schedule NULL, // cancel command_perform_helper // perform }; command_source = CFRunLoopSourceCreate(kCFAllocatorDefault, 1, &command_context); CFRunLoopAddSource(run_loop, command_source, kCFRunLoopDefaultMode); CFRunLoopRun(); LOGGER << "Run loop ended unexpectedly." << endl; } void handle_add_command(const ChannelID channel, const string &root_path) override { LOGGER << "Adding watcher for path " << root_path << " at channel " << channel << "." << endl; Subscription *subscription = new Subscription(this, channel); FSEventStreamContext stream_context = { 0, // version subscription, // info NULL, // retain NULL, // release NULL // copyDescription }; CFStringRef watch_root = CFStringCreateWithBytes( kCFAllocatorDefault, reinterpret_cast<const UInt8*>(root_path.c_str()), root_path.size(), kCFStringEncodingUTF8, false ); if (watch_root == NULL) { // TODO report error back in Ack return; } CFArrayRef watch_roots = CFArrayCreate( kCFAllocatorDefault, reinterpret_cast<const void**>(&watch_root), 1, NULL ); if (watch_roots == NULL) { // TODO report error back in Ack CFRelease(watch_root); return; } FSEventStreamRef event_stream = FSEventStreamCreate( kCFAllocatorDefault, event_stream_helper, &stream_context, watch_roots, kFSEventStreamEventIdSinceNow, LATENCY, kFSEventStreamCreateFlagNoDefer | kFSEventStreamCreateFlagFileEvents ); subscription->event_stream = event_stream; subscriptions.insert(make_pair(channel, subscription)); FSEventStreamScheduleWithRunLoop(event_stream, run_loop, kCFRunLoopDefaultMode); if (!FSEventStreamStart(event_stream)) { // TODO Report error back in Ack } CFRelease(watch_roots); CFRelease(watch_root); } void handle_remove_command(const ChannelID channel) override { LOGGER << "Removing watcher for channel " << channel << "." << endl; auto maybe_subscription = subscriptions.find(channel); if (maybe_subscription == subscriptions.end()) { LOGGER << "No subscription for channel " << channel << "." << endl; return; } Subscription *subscription = maybe_subscription->second; subscriptions.erase(maybe_subscription); FSEventStreamStop(subscription->event_stream); FSEventStreamInvalidate(subscription->event_stream); FSEventStreamRelease(subscription->event_stream); delete subscription; } void handle_fs_event( ChannelID channel, ConstFSEventStreamRef event_stream, size_t num_events, void *event_paths, const FSEventStreamEventFlags *event_flags, const FSEventStreamEventId *event_ids) { char **paths = reinterpret_cast<char**>(event_paths); vector<Message> messages; messages.reserve(num_events); for (size_t i = 0; i < num_events; i++) { bool created = (event_flags[i] & CREATE_FLAGS) != 0; bool deleted = (event_flags[i] & DELETED_FLAGS) != 0; bool modified = (event_flags[i] & MODIFY_FLAGS) != 0; bool renamed = (event_flags[i] & RENAME_FLAGS) != 0; bool is_file = (event_flags[i] & IS_FILE) != 0; bool is_directory = (event_flags[i] & IS_DIRECTORY) != 0; LOGGER << "Received event: " << (is_directory ? "directory" : "file") << " at [" << paths[i] << "]" << " created=" << created << " deleted=" << deleted << " modified=" << modified << " renamed=" << renamed << " flags=" << hex << event_flags[i] << endl; FileSystemAction action; if (created) { action = ACTION_CREATED; } else if (deleted) { action = ACTION_DELETED; } else if (modified) { action = ACTION_MODIFIED; } else if (renamed) { action = ACTION_RENAMED; } else { LOGGER << "Unknown filesystem event action from flags " << hex << event_flags[i] << "." << endl; continue; } EntryKind kind; if (is_file) { kind = KIND_FILE; } else if (is_directory) { kind = KIND_DIRECTORY; } else { LOGGER << "Unknown filesystem event entry kind from flags" << hex << event_flags[i] << "." << endl; continue; } string old_path(paths[i]); string new_path; FileSystemPayload payload(channel, action, kind, move(old_path), move(new_path)); Message event_message(move(payload)); LOGGER << "Emitting filesystem message " << event_message << endl; messages.push_back(move(event_message)); } emit_all(messages.begin(), messages.end()); } private: CFRunLoopRef run_loop; CFRunLoopSourceRef command_source; unordered_map<ChannelID, Subscription*> subscriptions; }; static void command_perform_helper(void *info) { MacOSWorkerPlatform *platform = reinterpret_cast<MacOSWorkerPlatform*>(info); platform->handle_commands(); } static void event_stream_helper( ConstFSEventStreamRef event_stream, void *info, size_t num_events, void *event_paths, const FSEventStreamEventFlags *event_flags, const FSEventStreamEventId *event_ids) { Subscription *sub = reinterpret_cast<Subscription*>(info); MacOSWorkerPlatform *platform = static_cast<MacOSWorkerPlatform*>(sub->platform); platform->handle_fs_event(sub->channel, event_stream, num_events, event_paths, event_flags, event_ids); } unique_ptr<WorkerPlatform> WorkerPlatform::for_worker(WorkerThread *thread) { return unique_ptr<WorkerPlatform>(new MacOSWorkerPlatform(thread)); } <commit_msg>Use a cache of recently seen paths to disambiguate coalesced Mac events<commit_after>#include <memory> #include <string> #include <vector> #include <unordered_set> #include <unordered_map> #include <map> #include <chrono> #include <utility> #include <iomanip> #include <CoreServices/CoreServices.h> #include <sys/stat.h> #include <errno.h> #include "platform.h" #include "worker_thread.h" #include "../log.h" #include "../message.h" using std::vector; using std::string; using std::endl; using std::unique_ptr; using std::move; using std::pair; using std::make_pair; using std::unordered_set; using std::unordered_map; using std::multimap; using std::hex; using std::chrono::steady_clock; using std::chrono::time_point; using std::chrono::duration; using std::chrono::seconds; static const CFAbsoluteTime LATENCY = 0; static const FSEventStreamEventFlags CREATE_FLAGS = kFSEventStreamEventFlagItemCreated; static const FSEventStreamEventFlags DELETED_FLAGS = kFSEventStreamEventFlagItemRemoved; static const FSEventStreamEventFlags MODIFY_FLAGS = kFSEventStreamEventFlagItemInodeMetaMod | kFSEventStreamEventFlagItemFinderInfoMod | kFSEventStreamEventFlagItemChangeOwner | kFSEventStreamEventFlagItemXattrMod | kFSEventStreamEventFlagItemModified; static const FSEventStreamEventFlags RENAME_FLAGS = kFSEventStreamEventFlagItemRenamed; static const FSEventStreamEventFlags IS_FILE = kFSEventStreamEventFlagItemIsFile; static const FSEventStreamEventFlags IS_DIRECTORY = kFSEventStreamEventFlagItemIsDir; static void command_perform_helper(void *info); static void event_stream_helper( ConstFSEventStreamRef event_stream, void *info, size_t num_events, void *event_paths, const FSEventStreamEventFlags *event_flags, const FSEventStreamEventId *event_ids); struct Subscription { WorkerPlatform *platform; ChannelID channel; FSEventStreamRef event_stream; Subscription(WorkerPlatform *platform, ChannelID channel) : platform{platform}, channel{channel}, event_stream{NULL} { // } }; class RecentFileCache { public: void does_exist(const string &path) { bool inserted = seen_paths.insert(path).second; if (inserted) { time_point<steady_clock> ts = steady_clock::now(); by_timestamp.insert({ts, path}); } } void does_not_exist(const string &path) { seen_paths.erase(path); } bool has_been_seen(const string &path) { return seen_paths.find(path) != seen_paths.end(); } void purge() { time_point<steady_clock> oldest = steady_clock::now() - seconds(5); auto to_keep = by_timestamp.upper_bound(oldest); for (auto it = by_timestamp.begin(); it != to_keep && it != by_timestamp.end(); ++it) { seen_paths.erase(it->second); } if (to_keep != by_timestamp.begin()) { by_timestamp.erase(by_timestamp.begin(), to_keep); } } private: unordered_set<string> seen_paths; multimap<time_point<steady_clock>, string> by_timestamp; }; class MacOSWorkerPlatform : public WorkerPlatform { public: MacOSWorkerPlatform(WorkerThread *thread) : WorkerPlatform(thread), run_loop{nullptr}, command_source{nullptr} { // }; ~MacOSWorkerPlatform() override { if (command_source) CFRelease(command_source); if (run_loop) CFRelease(run_loop); } void wake() override { CFRunLoopSourceSignal(command_source); CFRunLoopWakeUp(run_loop); } void listen() override { run_loop = CFRunLoopGetCurrent(); CFRetain(run_loop); CFRunLoopSourceContext command_context = { 0, // version this, // info NULL, // retain NULL, // release NULL, // copyDescription NULL, // equal NULL, // hash NULL, // schedule NULL, // cancel command_perform_helper // perform }; command_source = CFRunLoopSourceCreate(kCFAllocatorDefault, 1, &command_context); CFRunLoopAddSource(run_loop, command_source, kCFRunLoopDefaultMode); CFRunLoopRun(); LOGGER << "Run loop ended unexpectedly." << endl; } void handle_add_command(const ChannelID channel, const string &root_path) override { LOGGER << "Adding watcher for path " << root_path << " at channel " << channel << "." << endl; Subscription *subscription = new Subscription(this, channel); FSEventStreamContext stream_context = { 0, // version subscription, // info NULL, // retain NULL, // release NULL // copyDescription }; CFStringRef watch_root = CFStringCreateWithBytes( kCFAllocatorDefault, reinterpret_cast<const UInt8*>(root_path.c_str()), root_path.size(), kCFStringEncodingUTF8, false ); if (watch_root == NULL) { // TODO report error back in Ack return; } CFArrayRef watch_roots = CFArrayCreate( kCFAllocatorDefault, reinterpret_cast<const void**>(&watch_root), 1, NULL ); if (watch_roots == NULL) { // TODO report error back in Ack CFRelease(watch_root); return; } FSEventStreamRef event_stream = FSEventStreamCreate( kCFAllocatorDefault, event_stream_helper, &stream_context, watch_roots, kFSEventStreamEventIdSinceNow, LATENCY, kFSEventStreamCreateFlagNoDefer | kFSEventStreamCreateFlagFileEvents ); subscription->event_stream = event_stream; subscriptions.insert(make_pair(channel, subscription)); FSEventStreamScheduleWithRunLoop(event_stream, run_loop, kCFRunLoopDefaultMode); if (!FSEventStreamStart(event_stream)) { // TODO Report error back in Ack } CFRelease(watch_roots); CFRelease(watch_root); } void handle_remove_command(const ChannelID channel) override { LOGGER << "Removing watcher for channel " << channel << "." << endl; auto maybe_subscription = subscriptions.find(channel); if (maybe_subscription == subscriptions.end()) { LOGGER << "No subscription for channel " << channel << "." << endl; return; } Subscription *subscription = maybe_subscription->second; subscriptions.erase(maybe_subscription); FSEventStreamStop(subscription->event_stream); FSEventStreamInvalidate(subscription->event_stream); FSEventStreamRelease(subscription->event_stream); delete subscription; } void handle_fs_event( ChannelID channel, ConstFSEventStreamRef event_stream, size_t num_events, void *event_paths, const FSEventStreamEventFlags *event_flags, const FSEventStreamEventId *event_ids) { char **paths = reinterpret_cast<char**>(event_paths); vector<Message> messages; messages.reserve(num_events); LOGGER << "Filesystem event batch of size " << num_events << " received." << endl; for (size_t i = 0; i < num_events; i++) { bool created = (event_flags[i] & CREATE_FLAGS) != 0; bool deleted = (event_flags[i] & DELETED_FLAGS) != 0; bool modified = (event_flags[i] & MODIFY_FLAGS) != 0; bool renamed = (event_flags[i] & RENAME_FLAGS) != 0; bool is_file = (event_flags[i] & IS_FILE) != 0; bool is_directory = (event_flags[i] & IS_DIRECTORY) != 0; string event_path(paths[i]); bool stat_performed = false; int stat_errno = 0; struct stat path_stat; LOGGER << "Received event: " << event_ids[i] << " => " << (is_directory ? "directory" : "file") << " at [" << event_path << "]" << " created=" << created << " deleted=" << deleted << " modified=" << modified << " renamed=" << renamed << " flags=" << hex << event_flags[i] << endl; EntryKind kind; if (is_file && !is_directory) { kind = KIND_FILE; } else if (is_directory && !is_file) { kind = KIND_DIRECTORY; } else { // FIXME will file and directory events ever be coalesced? // FIXME handle symlinks, named pipes, etc LOGGER << "Unknown or ambiguous filesystem event entry kind from flags " << hex << event_flags[i] << "." << endl; if (lstat(event_path.c_str(), &path_stat) != 0) { stat_errno = errno; } stat_performed = true; // FIXME handle stat errors if ((path_stat.st_mode & S_IFDIR) != 0) { kind = KIND_DIRECTORY; } else if ((path_stat.st_mode & S_IFREG) != 0) { kind = KIND_FILE; } else { LOGGER << "Unhandled stat() flags " << hex << path_stat.st_mode << "." << endl; continue; } } // Uncoalesed, single-event flags. if (created && !(deleted || modified || renamed)) { cache.does_exist(event_path); enqueue_creation(messages, channel, kind, event_path); continue; } if (deleted && !(created || modified || renamed)) { cache.does_not_exist(event_path); enqueue_deletion(messages, channel, kind, event_path); continue; } if (modified && !(created || deleted || renamed)) { cache.does_exist(event_path); enqueue_modification(messages, channel, kind, event_path); continue; } // Call lstat() to note the final state of the entry. if (!stat_performed) { if (lstat(event_path.c_str(), &path_stat) != 0) { stat_errno = errno; } stat_performed = true; } if (stat_errno == ENOENT) { // The entry no longer exists. Emit a creation event if it has never been seen before, then emit a deletion // event. if (!cache.has_been_seen(event_path)) { enqueue_creation(messages, channel, kind, event_path); } enqueue_deletion(messages, channel, kind, event_path); continue; } // The entry currently exists. Determine if a creation or a modification event is appropriate. bool seen_before = cache.has_been_seen(event_path); cache.does_exist(event_path); if (seen_before) { // This is *not* the first time an event at this path has been seen. if (deleted) { // Rapid creation and deletion. There may be a lost modification event just before deletion or just after // recreation. enqueue_deletion(messages, channel, kind, event_path); enqueue_creation(messages, channel, kind, event_path); } else { // Modification of an existing file. enqueue_modification(messages, channel, kind, event_path); } } else { // This *is* the first time an event has been seen at this path. if (deleted) { // The only way for the deletion flag to be set on a file we haven't seen before is for the file to // be rapidly created, deleted, and created again. enqueue_creation(messages, channel, kind, event_path); enqueue_deletion(messages, channel, kind, event_path); enqueue_creation(messages, channel, kind, event_path); } else { // Otherwise, it must have been created. This may conceal a separate modification event just after // the file's creation. enqueue_creation(messages, channel, kind, event_path); } } } emit_all(messages.begin(), messages.end()); LOGGER << "Filesystem event batch of size " << num_events << " completed. " << messages.size() << " message(s) produced." << endl; cache.purge(); } private: void enqueue_creation( vector<Message> &messages, const ChannelID &channel, const EntryKind &kind, string created_path) { string empty_path; FileSystemPayload payload(channel, ACTION_CREATED, kind, move(created_path), move(empty_path)); Message event_message(move(payload)); LOGGER << "Emitting filesystem message " << event_message << endl; messages.push_back(move(event_message)); } void enqueue_modification( vector<Message> &messages, const ChannelID &channel, const EntryKind &kind, string modified_path) { string empty_path; FileSystemPayload payload(channel, ACTION_MODIFIED, kind, move(modified_path), move(empty_path)); Message event_message(move(payload)); LOGGER << "Emitting filesystem message " << event_message << endl; messages.push_back(move(event_message)); } void enqueue_deletion( vector<Message> &messages, const ChannelID &channel, const EntryKind &kind, string deleted_path) { string empty_path; FileSystemPayload payload(channel, ACTION_DELETED, kind, move(deleted_path), move(empty_path)); Message event_message(move(payload)); LOGGER << "Emitting filesystem message " << event_message << endl; messages.push_back(move(event_message)); } void enqueue_rename( vector<Message> &messages, const ChannelID &channel, const EntryKind &kind, string old_path, string new_path) { FileSystemPayload payload(channel, ACTION_DELETED, kind, move(old_path), move(new_path)); Message event_message(move(payload)); LOGGER << "Emitting filesystem message " << event_message << endl; messages.push_back(move(event_message)); } CFRunLoopRef run_loop; CFRunLoopSourceRef command_source; unordered_map<ChannelID, Subscription*> subscriptions; RecentFileCache cache; }; static void command_perform_helper(void *info) { MacOSWorkerPlatform *platform = reinterpret_cast<MacOSWorkerPlatform*>(info); platform->handle_commands(); } static void event_stream_helper( ConstFSEventStreamRef event_stream, void *info, size_t num_events, void *event_paths, const FSEventStreamEventFlags *event_flags, const FSEventStreamEventId *event_ids) { Subscription *sub = reinterpret_cast<Subscription*>(info); MacOSWorkerPlatform *platform = static_cast<MacOSWorkerPlatform*>(sub->platform); platform->handle_fs_event(sub->channel, event_stream, num_events, event_paths, event_flags, event_ids); } unique_ptr<WorkerPlatform> WorkerPlatform::for_worker(WorkerThread *thread) { return unique_ptr<WorkerPlatform>(new MacOSWorkerPlatform(thread)); } <|endoftext|>
<commit_before>/*========================================================================= * * Copyright NumFOCUS * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0.txt * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * *=========================================================================*/ #ifndef itkRelabelComponentImageFilter_hxx #define itkRelabelComponentImageFilter_hxx #include "itkRelabelComponentImageFilter.h" #include "itkImageRegionIterator.h" #include "itkNumericTraits.h" #include "itkProgressReporter.h" #include "itkProgressTransformer.h" #include "itkImageScanlineIterator.h" #include <map> #include <utility> namespace itk { template <typename TInputImage, typename TOutputImage> void RelabelComponentImageFilter<TInputImage, TOutputImage>::GenerateInputRequestedRegion() { // call the superclass' implementation of this method Superclass::GenerateInputRequestedRegion(); // We need all the input. InputImagePointer input = const_cast<InputImageType *>(this->GetInput()); if (input) { input->SetRequestedRegion(input->GetLargestPossibleRegion()); } } template <typename TInputImage, typename TOutputImage> void RelabelComponentImageFilter<TInputImage, TOutputImage>::ParallelComputeLabels(const RegionType & inputRegionForThread) { RelabelComponentObjectType initialSize; initialSize.m_SizeInPixels = 0; // walk the input ImageScanlineConstIterator<InputImageType> it(this->GetInput(), inputRegionForThread); MapType localSizeMap; auto mapIt = localSizeMap.end(); while (!it.IsAtEnd()) { while (!it.IsAtEndOfLine()) { // Get the input pixel value const auto inputValue = it.Get(); // if the input pixel is not the background if (inputValue != NumericTraits<LabelType>::ZeroValue()) { // label is not currently in the map mapIt = localSizeMap.insert(mapIt, { inputValue, initialSize }); // label is already in the map, update the values ++(mapIt->second.m_SizeInPixels); } // increment the iterator ++it; } it.NextLine(); } // Merge localStatistics and m_LabelStatistics concurrently safe in a // local copy, this thread may do multiple merges. while (true) { std::unique_lock<std::mutex> lock(m_Mutex); if (m_SizeMap.empty()) { swap(m_SizeMap, localSizeMap); break; } else { // copy the output map to thread local storage MapType toMerge; swap(m_SizeMap, toMerge); // allow other threads to merge data lock.unlock(); // Merge toMerge into localSizeMap, locally for (auto & sizePair : toMerge) { localSizeMap[sizePair.first] += sizePair.second; } } } // release lock } template <typename TInputImage, typename TOutputImage> void RelabelComponentImageFilter<TInputImage, TOutputImage>::GenerateData() { using LabelComponentPairType = std::pair<LabelType, RelabelComponentObjectType>; // Get the input and the output const TInputImage * input = this->GetInput(); TOutputImage * output = this->GetOutput(); // Calculate the size of pixel float physicalPixelSize = 1.0; for (unsigned int i = 0; i < TInputImage::ImageDimension; ++i) { physicalPixelSize *= input->GetSpacing()[i]; } // Walk the entire input image and compute used labels and the number of each label. ProgressTransformer progressTransformer1(0.0f, 0.5f, this); this->GetMultiThreader()->template ParallelizeImageRegion<ImageDimension>( input->GetRequestedRegion(), [this](const RegionType & inputRegion) { this->ParallelComputeLabels(inputRegion); }, progressTransformer1.GetProcessObject()); // Construct an array of the label, component information pair to sort auto sizeVector = std::vector<LabelComponentPairType>(m_SizeMap.begin(), m_SizeMap.end()); // free memory by swapping to a default constructed object. MapType().swap(m_SizeMap); // Sort the objects by size by default, unless m_SortByObjectSize // is set to false. if (m_SortByObjectSize) { std::sort(sizeVector.begin(), sizeVector.end(), [](const LabelComponentPairType & a, const LabelComponentPairType & b) -> bool { return a.second.m_SizeInPixels > b.second.m_SizeInPixels || (!(a.second.m_SizeInPixels < b.second.m_SizeInPixels) && a.first < b.first); }); } // A map from the input pixel labels to the output labels using RelabelMapType = std::map<LabelType, OutputPixelType>; RelabelMapType relabelMap; // create a lookup table to map the input label to the output label. // cache the object sizes for later access by the user m_NumberOfObjects = sizeVector.size(); m_OriginalNumberOfObjects = sizeVector.size(); m_SizeOfObjectsInPixels.clear(); m_SizeOfObjectsInPixels.resize(m_NumberOfObjects); SizeValueType NumberOfObjectsRemoved = 0; OutputPixelType outputLabel = 0; for (const auto & sizeVectorPair : sizeVector) { // skip objects that are too small ( but don't increment the output label ) if (m_MinimumObjectSize > 0 && sizeVectorPair.second.m_SizeInPixels < m_MinimumObjectSize) { // map small objects to the background ++NumberOfObjectsRemoved; relabelMap.insert({ sizeVectorPair.first, NumericTraits<OutputPixelType>::ZeroValue() }); } else { if (outputLabel == NumericTraits<OutputPixelType>::max()) { itkExceptionMacro("Output range exceeded!"); } // map for input labels to output labels (Note we use i+1 in the // map since index 0 is the background) relabelMap.insert({ sizeVectorPair.first, outputLabel + 1 }); // cache object sizes for later access by the user m_SizeOfObjectsInPixels[outputLabel] = sizeVectorPair.second.m_SizeInPixels; ++outputLabel; } } // update number of objects and resize vectors if we have removed small // objects m_NumberOfObjects -= NumberOfObjectsRemoved; if (NumberOfObjectsRemoved > 0) { m_SizeOfObjectsInPixels.resize(m_NumberOfObjects); } // compute the object sizes in physical space too m_SizeOfObjectsInPhysicalUnits.resize(m_NumberOfObjects); std::transform(m_SizeOfObjectsInPixels.begin(), m_SizeOfObjectsInPixels.end(), m_SizeOfObjectsInPhysicalUnits.begin(), [physicalPixelSize](ObjectSizeType sizeInPixels) { return sizeInPixels * physicalPixelSize; }); // After the objects stats are computed add in the background label so the relabelMap can be directly applied. relabelMap.insert({ NumericTraits<LabelType>::ZeroValue(), NumericTraits<OutputPixelType>::ZeroValue() }); // Second pass: walk just the output requested region and relabel // the necessary pixels. // // Allocate the output this->AllocateOutputs(); // In parallel apply the relabling map ProgressTransformer progressTransformer2(0.5f, 1.0f, this); this->GetMultiThreader()->template ParallelizeImageRegion<ImageDimension>( output->GetRequestedRegion(), [this, &relabelMap](const RegionType & outputRegionForThread) { ImageScanlineIterator<OutputImageType> oit(this->GetOutput(), outputRegionForThread); ImageScanlineConstIterator<InputImageType> it(this->GetInput(), outputRegionForThread); auto mapIt = relabelMap.cbegin(); while (!oit.IsAtEnd()) { while (!oit.IsAtEndOfLine()) { const auto && inputValue = it.Get(); if (mapIt->first != inputValue) { mapIt = relabelMap.find(inputValue); } // no new labels should be encountered in the input assert(mapIt != relabelMap.cend()); oit.Set(mapIt->second); ++oit; ++it; } oit.NextLine(); it.NextLine(); } }, progressTransformer2.GetProcessObject()); } template <typename TInputImage, typename TOutputImage> void RelabelComponentImageFilter<TInputImage, TOutputImage>::PrintSelf(std::ostream & os, Indent indent) const { Superclass::PrintSelf(os, indent); os << indent << "NumberOfObjects: " << m_NumberOfObjects << std::endl; os << indent << "OriginalNumberOfObjects: " << m_OriginalNumberOfObjects << std::endl; os << indent << "NumberOfObjectsToPrint: " << m_NumberOfObjectsToPrint << std::endl; os << indent << "MinimumObjectSizes: " << m_MinimumObjectSize << std::endl; os << indent << "SortByObjectSize: " << m_SortByObjectSize << std::endl; typename ObjectSizeInPixelsContainerType::const_iterator it; ObjectSizeInPhysicalUnitsContainerType::const_iterator fit; SizeValueType i; // limit the number of objects to print SizeValueType numPrint = std::min(m_NumberOfObjectsToPrint, m_SizeOfObjectsInPixels.size()); for (i = 0, it = m_SizeOfObjectsInPixels.begin(), fit = m_SizeOfObjectsInPhysicalUnits.begin(); i < numPrint; ++it, ++fit, ++i) { os << indent << "Object #" << i + 1 << ": " << *it << " pixels, " << *fit << " physical units" << std::endl; } if (numPrint < m_SizeOfObjectsInPixels.size()) { os << indent << "..." << std::endl; } } } // end namespace itk #endif <commit_msg>COMP: Need to explicitly define std::min<> template values<commit_after>/*========================================================================= * * Copyright NumFOCUS * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0.txt * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * *=========================================================================*/ #ifndef itkRelabelComponentImageFilter_hxx #define itkRelabelComponentImageFilter_hxx #include "itkRelabelComponentImageFilter.h" #include "itkImageRegionIterator.h" #include "itkNumericTraits.h" #include "itkProgressReporter.h" #include "itkProgressTransformer.h" #include "itkImageScanlineIterator.h" #include <map> #include <utility> namespace itk { template <typename TInputImage, typename TOutputImage> void RelabelComponentImageFilter<TInputImage, TOutputImage>::GenerateInputRequestedRegion() { // call the superclass' implementation of this method Superclass::GenerateInputRequestedRegion(); // We need all the input. InputImagePointer input = const_cast<InputImageType *>(this->GetInput()); if (input) { input->SetRequestedRegion(input->GetLargestPossibleRegion()); } } template <typename TInputImage, typename TOutputImage> void RelabelComponentImageFilter<TInputImage, TOutputImage>::ParallelComputeLabels(const RegionType & inputRegionForThread) { RelabelComponentObjectType initialSize; initialSize.m_SizeInPixels = 0; // walk the input ImageScanlineConstIterator<InputImageType> it(this->GetInput(), inputRegionForThread); MapType localSizeMap; auto mapIt = localSizeMap.end(); while (!it.IsAtEnd()) { while (!it.IsAtEndOfLine()) { // Get the input pixel value const auto inputValue = it.Get(); // if the input pixel is not the background if (inputValue != NumericTraits<LabelType>::ZeroValue()) { // label is not currently in the map mapIt = localSizeMap.insert(mapIt, { inputValue, initialSize }); // label is already in the map, update the values ++(mapIt->second.m_SizeInPixels); } // increment the iterator ++it; } it.NextLine(); } // Merge localStatistics and m_LabelStatistics concurrently safe in a // local copy, this thread may do multiple merges. while (true) { std::unique_lock<std::mutex> lock(m_Mutex); if (m_SizeMap.empty()) { swap(m_SizeMap, localSizeMap); break; } else { // copy the output map to thread local storage MapType toMerge; swap(m_SizeMap, toMerge); // allow other threads to merge data lock.unlock(); // Merge toMerge into localSizeMap, locally for (auto & sizePair : toMerge) { localSizeMap[sizePair.first] += sizePair.second; } } } // release lock } template <typename TInputImage, typename TOutputImage> void RelabelComponentImageFilter<TInputImage, TOutputImage>::GenerateData() { using LabelComponentPairType = std::pair<LabelType, RelabelComponentObjectType>; // Get the input and the output const TInputImage * input = this->GetInput(); TOutputImage * output = this->GetOutput(); // Calculate the size of pixel float physicalPixelSize = 1.0; for (unsigned int i = 0; i < TInputImage::ImageDimension; ++i) { physicalPixelSize *= input->GetSpacing()[i]; } // Walk the entire input image and compute used labels and the number of each label. ProgressTransformer progressTransformer1(0.0f, 0.5f, this); this->GetMultiThreader()->template ParallelizeImageRegion<ImageDimension>( input->GetRequestedRegion(), [this](const RegionType & inputRegion) { this->ParallelComputeLabels(inputRegion); }, progressTransformer1.GetProcessObject()); // Construct an array of the label, component information pair to sort auto sizeVector = std::vector<LabelComponentPairType>(m_SizeMap.begin(), m_SizeMap.end()); // free memory by swapping to a default constructed object. MapType().swap(m_SizeMap); // Sort the objects by size by default, unless m_SortByObjectSize // is set to false. if (m_SortByObjectSize) { std::sort(sizeVector.begin(), sizeVector.end(), [](const LabelComponentPairType & a, const LabelComponentPairType & b) -> bool { return a.second.m_SizeInPixels > b.second.m_SizeInPixels || (!(a.second.m_SizeInPixels < b.second.m_SizeInPixels) && a.first < b.first); }); } // A map from the input pixel labels to the output labels using RelabelMapType = std::map<LabelType, OutputPixelType>; RelabelMapType relabelMap; // create a lookup table to map the input label to the output label. // cache the object sizes for later access by the user m_NumberOfObjects = sizeVector.size(); m_OriginalNumberOfObjects = sizeVector.size(); m_SizeOfObjectsInPixels.clear(); m_SizeOfObjectsInPixels.resize(m_NumberOfObjects); SizeValueType NumberOfObjectsRemoved = 0; OutputPixelType outputLabel = 0; for (const auto & sizeVectorPair : sizeVector) { // skip objects that are too small ( but don't increment the output label ) if (m_MinimumObjectSize > 0 && sizeVectorPair.second.m_SizeInPixels < m_MinimumObjectSize) { // map small objects to the background ++NumberOfObjectsRemoved; relabelMap.insert({ sizeVectorPair.first, NumericTraits<OutputPixelType>::ZeroValue() }); } else { if (outputLabel == NumericTraits<OutputPixelType>::max()) { itkExceptionMacro("Output range exceeded!"); } // map for input labels to output labels (Note we use i+1 in the // map since index 0 is the background) relabelMap.insert({ sizeVectorPair.first, outputLabel + 1 }); // cache object sizes for later access by the user m_SizeOfObjectsInPixels[outputLabel] = sizeVectorPair.second.m_SizeInPixels; ++outputLabel; } } // update number of objects and resize vectors if we have removed small // objects m_NumberOfObjects -= NumberOfObjectsRemoved; if (NumberOfObjectsRemoved > 0) { m_SizeOfObjectsInPixels.resize(m_NumberOfObjects); } // compute the object sizes in physical space too m_SizeOfObjectsInPhysicalUnits.resize(m_NumberOfObjects); std::transform(m_SizeOfObjectsInPixels.begin(), m_SizeOfObjectsInPixels.end(), m_SizeOfObjectsInPhysicalUnits.begin(), [physicalPixelSize](ObjectSizeType sizeInPixels) { return sizeInPixels * physicalPixelSize; }); // After the objects stats are computed add in the background label so the relabelMap can be directly applied. relabelMap.insert({ NumericTraits<LabelType>::ZeroValue(), NumericTraits<OutputPixelType>::ZeroValue() }); // Second pass: walk just the output requested region and relabel // the necessary pixels. // // Allocate the output this->AllocateOutputs(); // In parallel apply the relabling map ProgressTransformer progressTransformer2(0.5f, 1.0f, this); this->GetMultiThreader()->template ParallelizeImageRegion<ImageDimension>( output->GetRequestedRegion(), [this, &relabelMap](const RegionType & outputRegionForThread) { ImageScanlineIterator<OutputImageType> oit(this->GetOutput(), outputRegionForThread); ImageScanlineConstIterator<InputImageType> it(this->GetInput(), outputRegionForThread); auto mapIt = relabelMap.cbegin(); while (!oit.IsAtEnd()) { while (!oit.IsAtEndOfLine()) { const auto && inputValue = it.Get(); if (mapIt->first != inputValue) { mapIt = relabelMap.find(inputValue); } // no new labels should be encountered in the input assert(mapIt != relabelMap.cend()); oit.Set(mapIt->second); ++oit; ++it; } oit.NextLine(); it.NextLine(); } }, progressTransformer2.GetProcessObject()); } template <typename TInputImage, typename TOutputImage> void RelabelComponentImageFilter<TInputImage, TOutputImage>::PrintSelf(std::ostream & os, Indent indent) const { Superclass::PrintSelf(os, indent); os << indent << "NumberOfObjects: " << m_NumberOfObjects << std::endl; os << indent << "OriginalNumberOfObjects: " << m_OriginalNumberOfObjects << std::endl; os << indent << "NumberOfObjectsToPrint: " << m_NumberOfObjectsToPrint << std::endl; os << indent << "MinimumObjectSizes: " << m_MinimumObjectSize << std::endl; os << indent << "SortByObjectSize: " << m_SortByObjectSize << std::endl; typename ObjectSizeInPixelsContainerType::const_iterator it; ObjectSizeInPhysicalUnitsContainerType::const_iterator fit; SizeValueType i; // limit the number of objects to print SizeValueType numPrint = std::min<SizeValueType>(m_NumberOfObjectsToPrint, m_SizeOfObjectsInPixels.size()); for (i = 0, it = m_SizeOfObjectsInPixels.begin(), fit = m_SizeOfObjectsInPhysicalUnits.begin(); i < numPrint; ++it, ++fit, ++i) { os << indent << "Object #" << i + 1 << ": " << *it << " pixels, " << *fit << " physical units" << std::endl; } if (numPrint < m_SizeOfObjectsInPixels.size()) { os << indent << "..." << std::endl; } } } // end namespace itk #endif <|endoftext|>
<commit_before>#ifndef STAN_MATH_REV_FUN_OWENS_T_HPP #define STAN_MATH_REV_FUN_OWENS_T_HPP #include <stan/math/rev/meta.hpp> #include <stan/math/rev/core.hpp> #include <stan/math/prim/fun/constants.hpp> #include <stan/math/prim/fun/erf.hpp> #include <stan/math/prim/fun/owens_t.hpp> #include <stan/math/prim/fun/square.hpp> #include <cmath> namespace stan { namespace math { /** * The Owen's T function of h and a. * * Used to compute the cumulative density function for the skew normal * distribution. * * @tparam Var1 A scalar or Eigen type whose `scalar_type` is an var. * @tparam Var2 A scalar or Eigen type whose `scalar_type` is an var. * @param h var parameter. * @param a var parameter. * @return The Owen's T function. */ template <typename Var1, typename Var2, require_all_st_var<Var1, Var2>* = nullptr, require_all_not_std_vector_t<Var1, Var2>* = nullptr> inline auto owens_t(const Var1& h, const Var2& a) { auto h_arena = to_arena(h); auto a_arena = to_arena(a); using return_type = return_var_matrix_t<decltype(owens_t(h_arena.val(), a_arena.val())), Var1, Var2>; arena_t<return_type> ret = owens_t(h_arena.val(), a_arena.val()); reverse_pass_callback([h_arena, a_arena, ret]() mutable { const auto& h_val = as_value_array_or_scalar(h_arena); const auto& a_val = as_value_array_or_scalar(a_arena); const auto neg_h_sq_div_2 = stan::math::eval(-square(h_val) * 0.5); const auto one_p_a_sq = stan::math::eval(1.0 + square(a_val)); as_array_or_scalar(h_arena).adj() += possibly_sum<is_stan_scalar<Var1>>( as_array_or_scalar(ret.adj()) * erf(a_val * h_val * INV_SQRT_TWO) * exp(neg_h_sq_div_2) * INV_SQRT_TWO_PI * -0.5); as_array_or_scalar(a_arena).adj() += possibly_sum<is_stan_scalar<Var2>>( as_array_or_scalar(ret.adj()) * exp(neg_h_sq_div_2 * one_p_a_sq) / (one_p_a_sq * TWO_PI)); }); return return_type(ret); } /** * The Owen's T function of h and a. * * Used to compute the cumulative density function for the skew normal * distribution. * * @tparam Var A scalar or Eigen type whose `scalar_type` is an var. * @tparam Arith A scalar or Eigen type with an inner arirthmetic scalar value. * @param h var parameter. * @param a double parameter. * @return The Owen's T function. */ template <typename Var, typename Arith, require_st_arithmetic<Arith>* = nullptr, require_all_not_std_vector_t<Var, Arith>* = nullptr, require_st_var<Var>* = nullptr> inline auto owens_t(const Var& h, const Arith& a) { auto h_arena = to_arena(h); auto a_arena = to_arena(a); using return_type = return_var_matrix_t<decltype(owens_t(h_arena.val(), a_arena)), Var, Arith>; arena_t<return_type> ret = owens_t(h_arena.val(), a_arena); reverse_pass_callback([h_arena, a_arena, ret]() mutable { const auto& h_val = as_value_array_or_scalar(h_arena); as_array_or_scalar(h_arena).adj() += possibly_sum<is_stan_scalar<Var>>( as_array_or_scalar(ret.adj()) * erf(as_array_or_scalar(a_arena) * h_val * INV_SQRT_TWO) * exp(-square(h_val) * 0.5) * INV_SQRT_TWO_PI * -0.5); }); return return_type(ret); } /** * The Owen's T function of h and a. * * Used to compute the cumulative density function for the skew normal * distribution. * * @tparam Var A scalar or Eigen type whose `scalar_type` is an var. * @tparam Arith A scalar or Eigen type with an inner arithmetic scalar value. * @param h double parameter. * @param a var parameter. * @return The Owen's T function. */ template <typename Arith, typename Var, require_st_arithmetic<Arith>* = nullptr, require_all_not_std_vector_t<Var, Arith>* = nullptr, require_st_var<Var>* = nullptr> inline auto owens_t(const Arith& h, const Var& a) { auto h_arena = to_arena(h); auto a_arena = to_arena(a); using return_type = return_var_matrix_t<decltype(owens_t(h_arena, a_arena.val())), Var, Arith>; arena_t<return_type> ret = owens_t(h_arena, a_arena.val()); reverse_pass_callback([h_arena, a_arena, ret]() mutable { const auto one_p_a_sq = eval(1.0 + square(as_value_array_or_scalar(a_arena))); as_array_or_scalar(a_arena).adj() += possibly_sum<is_stan_scalar<Var>>( as_array_or_scalar(ret.adj()) * exp(-0.5 * square(as_array_or_scalar(h_arena)) * one_p_a_sq) / (one_p_a_sq * TWO_PI)); }); return return_type(ret); } } // namespace math } // namespace stan #endif <commit_msg>add eval header to owens_t<commit_after>#ifndef STAN_MATH_REV_FUN_OWENS_T_HPP #define STAN_MATH_REV_FUN_OWENS_T_HPP #include <stan/math/rev/meta.hpp> #include <stan/math/rev/core.hpp> #include <stan/math/prim/fun/constants.hpp> #include <stan/math/prim/fun/erf.hpp> #include <stan/math/prim/fun/eval.hpp> #include <stan/math/prim/fun/owens_t.hpp> #include <stan/math/prim/fun/square.hpp> #include <cmath> namespace stan { namespace math { /** * The Owen's T function of h and a. * * Used to compute the cumulative density function for the skew normal * distribution. * * @tparam Var1 A scalar or Eigen type whose `scalar_type` is an var. * @tparam Var2 A scalar or Eigen type whose `scalar_type` is an var. * @param h var parameter. * @param a var parameter. * @return The Owen's T function. */ template <typename Var1, typename Var2, require_all_st_var<Var1, Var2>* = nullptr, require_all_not_std_vector_t<Var1, Var2>* = nullptr> inline auto owens_t(const Var1& h, const Var2& a) { auto h_arena = to_arena(h); auto a_arena = to_arena(a); using return_type = return_var_matrix_t<decltype(owens_t(h_arena.val(), a_arena.val())), Var1, Var2>; arena_t<return_type> ret = owens_t(h_arena.val(), a_arena.val()); reverse_pass_callback([h_arena, a_arena, ret]() mutable { const auto& h_val = as_value_array_or_scalar(h_arena); const auto& a_val = as_value_array_or_scalar(a_arena); const auto neg_h_sq_div_2 = stan::math::eval(-square(h_val) * 0.5); const auto one_p_a_sq = stan::math::eval(1.0 + square(a_val)); as_array_or_scalar(h_arena).adj() += possibly_sum<is_stan_scalar<Var1>>( as_array_or_scalar(ret.adj()) * erf(a_val * h_val * INV_SQRT_TWO) * exp(neg_h_sq_div_2) * INV_SQRT_TWO_PI * -0.5); as_array_or_scalar(a_arena).adj() += possibly_sum<is_stan_scalar<Var2>>( as_array_or_scalar(ret.adj()) * exp(neg_h_sq_div_2 * one_p_a_sq) / (one_p_a_sq * TWO_PI)); }); return return_type(ret); } /** * The Owen's T function of h and a. * * Used to compute the cumulative density function for the skew normal * distribution. * * @tparam Var A scalar or Eigen type whose `scalar_type` is an var. * @tparam Arith A scalar or Eigen type with an inner arirthmetic scalar value. * @param h var parameter. * @param a double parameter. * @return The Owen's T function. */ template <typename Var, typename Arith, require_st_arithmetic<Arith>* = nullptr, require_all_not_std_vector_t<Var, Arith>* = nullptr, require_st_var<Var>* = nullptr> inline auto owens_t(const Var& h, const Arith& a) { auto h_arena = to_arena(h); auto a_arena = to_arena(a); using return_type = return_var_matrix_t<decltype(owens_t(h_arena.val(), a_arena)), Var, Arith>; arena_t<return_type> ret = owens_t(h_arena.val(), a_arena); reverse_pass_callback([h_arena, a_arena, ret]() mutable { const auto& h_val = as_value_array_or_scalar(h_arena); as_array_or_scalar(h_arena).adj() += possibly_sum<is_stan_scalar<Var>>( as_array_or_scalar(ret.adj()) * erf(as_array_or_scalar(a_arena) * h_val * INV_SQRT_TWO) * exp(-square(h_val) * 0.5) * INV_SQRT_TWO_PI * -0.5); }); return return_type(ret); } /** * The Owen's T function of h and a. * * Used to compute the cumulative density function for the skew normal * distribution. * * @tparam Var A scalar or Eigen type whose `scalar_type` is an var. * @tparam Arith A scalar or Eigen type with an inner arithmetic scalar value. * @param h double parameter. * @param a var parameter. * @return The Owen's T function. */ template <typename Arith, typename Var, require_st_arithmetic<Arith>* = nullptr, require_all_not_std_vector_t<Var, Arith>* = nullptr, require_st_var<Var>* = nullptr> inline auto owens_t(const Arith& h, const Var& a) { auto h_arena = to_arena(h); auto a_arena = to_arena(a); using return_type = return_var_matrix_t<decltype(owens_t(h_arena, a_arena.val())), Var, Arith>; arena_t<return_type> ret = owens_t(h_arena, a_arena.val()); reverse_pass_callback([h_arena, a_arena, ret]() mutable { const auto one_p_a_sq = eval(1.0 + square(as_value_array_or_scalar(a_arena))); as_array_or_scalar(a_arena).adj() += possibly_sum<is_stan_scalar<Var>>( as_array_or_scalar(ret.adj()) * exp(-0.5 * square(as_array_or_scalar(h_arena)) * one_p_a_sq) / (one_p_a_sq * TWO_PI)); }); return return_type(ret); } } // namespace math } // namespace stan #endif <|endoftext|>
<commit_before>/* * A Viewer Object * Copyright © 2010, Théo de la Hogue * * License: This code is licensed under the terms of the "New BSD License" * http://creativecommons.org/licenses/BSD/ */ #include "TTViewer.h" #define thisTTClass TTViewer #define thisTTClassName "Viewer" #define thisTTClassTags "viewer" TT_MODULAR_CONSTRUCTOR, mAddress(kTTAdrsEmpty), mDescription(kTTSymEmpty), mType(kTTSymEmpty), mTag(kTTSymEmpty), mHighlight(NO), mFreeze(NO), mDataspace(kTTSym_none), mDataspaceUnit(kTTSym_none), mDataspaceConverter(NULL), mDataspaceObserver(NULL), mDataspaceUnitObserver(NULL), mEnable(YES), mReturnedValue(kTTValNONE), mReceiver(NULL), mSender(NULL), mReturnValueCallback(NULL) { if(arguments.getSize() == 1) arguments.get(0, (TTPtr*)&mReturnValueCallback); addAttributeWithSetter(Address, kTypeSymbol); addAttribute(Description, kTypeSymbol); addAttribute(Type, kTypeSymbol); addAttribute(Tag, kTypeSymbol); addAttribute(Highlight, kTypeBoolean); addAttributeWithSetter(Freeze, kTypeBoolean); addAttribute(Dataspace, kTypeSymbol); addAttributeProperty(Dataspace, readOnly, YES); addAttributeWithSetter(DataspaceUnit, kTypeSymbol); addAttributeWithSetter(Enable, kTypeBoolean); addAttributeWithSetter(ReturnedValue, kTypeLocalValue); addAttributeProperty(ReturnedValue, readOnly, YES); addAttributeProperty(ReturnedValue, hidden, YES); addMessage(Refresh); addMessageWithArguments(Send); addMessageProperty(Send, hidden, YES); TTObjectInstantiate(TT("dataspace"), &mDataspaceConverter, kTTValNONE); } TTViewer::~TTViewer() // TODO : delete things... { if (mReturnValueCallback) { delete (TTValuePtr)mReturnValueCallback->getBaton(); TTObjectRelease(TTObjectHandle(&mReturnValueCallback)); } if (mDataspaceConverter) TTObjectRelease(TTObjectHandle(&mDataspaceConverter)); if (mDataspaceObserver) TTObjectRelease(TTObjectHandle(&mDataspaceObserver)); if (mDataspaceUnitObserver) TTObjectRelease(TTObjectHandle(&mDataspaceUnitObserver)); if (mSender) TTObjectRelease(TTObjectHandle(&mSender)); if (mReceiver) TTObjectRelease(TTObjectHandle(&mReceiver)); } TTErr TTViewer::setAddress(const TTValue& value) { value.get(0, &mAddress); bind(); return kTTErrNone; } TTErr TTViewer::bind() { TTValue args, v; TTObjectPtr returnAddressCallback, returnValueCallback; TTValuePtr returnAddressBaton, returnValueBaton; // Prepare arguments if (mAddress == kTTAdrsEmpty) return kTTErrGeneric; // The default attribute to bind is value if (mAddress->getAttribute() == NO_ATTRIBUTE) mAddress->appendAttribute(kTTSym_value); // Replace a TTSender object if (mSender) TTObjectRelease(TTObjectHandle(&mSender)); mSender = NULL; // without this, TTObjectInstantiate try to release an oldObject that doesn't exist ... Is it good ? TTObjectInstantiate(TT("Sender"), TTObjectHandle(&mSender), kTTValNONE); mSender->setAttributeValue(kTTSym_address, mAddress); // Replace a TTReceiver object if (mReceiver) TTObjectRelease(TTObjectHandle(&mReceiver)); returnAddressCallback = NULL; // without this, TTObjectInstantiate try to release an oldObject that doesn't exist ... Is it good ? TTObjectInstantiate(TT("callback"), &returnAddressCallback, kTTValNONE); returnAddressBaton = new TTValue(TTPtr(this)); returnAddressCallback->setAttributeValue(kTTSym_baton, TTPtr(returnAddressBaton)); returnAddressCallback->setAttributeValue(kTTSym_function, TTPtr(&TTViewerReceiveAddressCallback)); args.append(returnAddressCallback); returnValueCallback = NULL; // without this, TTObjectInstantiate try to release an oldObject that doesn't exist ... Is it good ? TTObjectInstantiate(TT("callback"), &returnValueCallback, kTTValNONE); returnValueBaton = new TTValue(TTPtr(this)); returnValueCallback->setAttributeValue(kTTSym_baton, TTPtr(returnValueBaton)); returnValueCallback->setAttributeValue(kTTSym_function, TTPtr(&TTViewerReceiveValueCallback)); args.append(returnValueCallback); mReceiver = NULL; // without this, TTObjectInstantiate try to release an oldObject that doesn't exist ... Is it good ? TTObjectInstantiate(TT("Receiver"), TTObjectHandle(&mReceiver), args); mReceiver->setAttributeValue(kTTSym_address, mAddress); observeDataspace(); observeDataspaceUnit(); return kTTErrNone; } TTErr TTViewer::observeDataspace() { TTValue args; TTObjectPtr returnDataspaceCallback; TTValuePtr returnDataspaceBaton; if (mDataspaceObserver) TTObjectRelease(TTObjectHandle(&mDataspaceObserver)); // Make a TTReceiver object args.append(NULL); returnDataspaceCallback = NULL; // without this, TTObjectInstantiate try to release an oldObject that doesn't exist ... Is it good ? TTObjectInstantiate(TT("callback"), &returnDataspaceCallback, kTTValNONE); returnDataspaceBaton = new TTValue(TTPtr(this)); returnDataspaceCallback->setAttributeValue(kTTSym_baton, TTPtr(returnDataspaceBaton)); returnDataspaceCallback->setAttributeValue(kTTSym_function, TTPtr(&TTViewerDataspaceCallback)); args.append(returnDataspaceCallback); mDataspaceObserver = NULL; TTObjectInstantiate(TT("Receiver"), TTObjectHandle(&mDataspaceObserver), args); mDataspaceObserver->setAttributeValue(kTTSym_address, mAddress->appendAttribute(kTTSym_dataspace)); mDataspaceObserver->sendMessage(kTTSym_Get); return kTTErrNone; } TTErr TTViewer::observeDataspaceUnit() { TTValue args; TTObjectPtr returnDataspaceUnitCallback; TTValuePtr returnDataspaceUnitBaton; if (mDataspaceUnitObserver) TTObjectRelease(TTObjectHandle(&mDataspaceUnitObserver)); // Make a TTReceiver object args.append(NULL); returnDataspaceUnitCallback = NULL; // without this, TTObjectInstantiate try to release an oldObject that doesn't exist ... Is it good ? TTObjectInstantiate(TT("callback"), &returnDataspaceUnitCallback, kTTValNONE); returnDataspaceUnitBaton = new TTValue(TTPtr(this)); returnDataspaceUnitCallback->setAttributeValue(kTTSym_baton, TTPtr(returnDataspaceUnitBaton)); returnDataspaceUnitCallback->setAttributeValue(kTTSym_function, TTPtr(&TTViewerDataspaceUnitCallback)); args.append(returnDataspaceUnitCallback); mDataspaceUnitObserver = NULL; TTObjectInstantiate(TT("Receiver"), TTObjectHandle(&mDataspaceUnitObserver), args); mDataspaceUnitObserver->setAttributeValue(kTTSym_address, mAddress->appendAttribute(kTTSym_dataspaceUnit)); mDataspaceUnitObserver->sendMessage(kTTSym_Get); return kTTErrNone; } TTErr TTViewer::setEnable(const TTValue& value) { mEnable = value; if (mReceiver) mReceiver->setAttributeValue(kTTSym_enable, mEnable); return kTTErrNone; } TTErr TTViewer::setFreeze(const TTValue& value) { mFreeze = value; return kTTErrNone; } TTErr TTViewer::setReturnedValue(const TTValue& value) { TTAttributePtr anAttribute = NULL; TTErr err; mReturnedValue = value; err = this->findAttribute(kTTSym_returnedValue, &anAttribute); if (!err) anAttribute->sendNotification(kTTSym_notify, mReturnedValue); // we use kTTSym_notify because we know that observers are TTCallback return kTTErrNone; } TTErr TTViewer::Refresh() { if (mReceiver) return mReceiver->sendMessage(kTTSym_Get); return kTTErrGeneric; } TTErr TTViewer::Send(const TTValue& inputValue, TTValue& outputValue) { if (mSender) { TTValue valueToSend = inputValue; // append view unit if (mDataspaceUnit != kTTSym_none) valueToSend.append(mDataspaceUnit); return mSender->sendMessage(kTTSym_Send, valueToSend, kTTValNONE); } return kTTErrGeneric; } TTErr TTViewer::setDataspaceUnit(const TTValue& value) { TTValue n = value; // use new value to protect the attribute mDataspaceUnit = value; if (mDataspaceConverter) mDataspaceConverter->setAttributeValue(TT("outputUnit"), mDataspaceUnit); // TODO : notifyObservers(kTTSym_dataspaceUnit, n); return kTTErrNone; } TTErr TTViewer::convertUnit(const TTValue& inputValue, TTValue& outputValue) { if (mDataspaceConverter) return mDataspaceConverter->sendMessage(TT("convert"), inputValue, outputValue); return kTTErrNone; } #if 0 #pragma mark - #pragma mark Some Methods #endif TTErr TTViewerReceiveAddressCallback(TTPtr baton, TTValue& data) { return kTTErrGeneric; } TTErr TTViewerReceiveValueCallback(TTPtr baton, TTValue& data) { TTViewerPtr aViewer; TTValuePtr b; TTValue converted; // unpack baton (a TTViewer) b = (TTValuePtr)baton; b->get(0, (TTPtr*)&aViewer); if (aViewer->mEnable) { if (!aViewer->mFreeze) // convert data aViewer->convertUnit(data, converted); else // use last data converted = aViewer->mReturnedValue; // return value if (aViewer->mReturnValueCallback) { aViewer->mReturnValueCallback->notify(converted, kTTValNONE); aViewer->setReturnedValue(converted); } } return kTTErrNone; } TTErr TTViewerDataspaceCallback(TTPtr baton, TTValue& data) { TTViewerPtr aViewer; TTValuePtr b; TTValue v; TTErr err; // unpack baton (a TTViewer) b = (TTValuePtr)baton; b->get(0, (TTPtr*)&aViewer); aViewer->mDataspace = data; if (aViewer->mDataspaceConverter) { aViewer->mDataspaceConverter->setAttributeValue(TT("dataspace"), aViewer->mDataspace); err = aViewer->mDataspaceConverter->setAttributeValue(TT("outputUnit"), aViewer->mDataspaceUnit); if (err) { aViewer->mDataspaceConverter->getAttributeValue(TT("outputUnit"), v); v.get(0, &aViewer->mDataspaceUnit); aViewer->mDataspaceConverter->setAttributeValue(TT("outputUnit"), aViewer->mDataspaceUnit); } } return kTTErrNone; } TTErr TTViewerDataspaceUnitCallback(TTPtr baton, TTValue& data) { TTViewerPtr aViewer; TTValuePtr b; TTValue v; // unpack baton (a TTViewer) b = (TTValuePtr)baton; b->get(0, (TTPtr*)&aViewer); if (aViewer->mDataspaceConverter) aViewer->mDataspaceConverter->setAttributeValue(TT("inputUnit"), data); return kTTErrNone; } <commit_msg>Fixing Bug 1138<commit_after>/* * A Viewer Object * Copyright © 2010, Théo de la Hogue * * License: This code is licensed under the terms of the "New BSD License" * http://creativecommons.org/licenses/BSD/ */ #include "TTViewer.h" #define thisTTClass TTViewer #define thisTTClassName "Viewer" #define thisTTClassTags "viewer" TT_MODULAR_CONSTRUCTOR, mAddress(kTTAdrsEmpty), mDescription(kTTSymEmpty), mType(kTTSymEmpty), mTag(kTTSymEmpty), mHighlight(NO), mFreeze(NO), mDataspace(kTTSym_none), mDataspaceUnit(kTTSym_none), mDataspaceConverter(NULL), mDataspaceObserver(NULL), mDataspaceUnitObserver(NULL), mEnable(YES), mReturnedValue(kTTValNONE), mReceiver(NULL), mSender(NULL), mReturnValueCallback(NULL) { if(arguments.getSize() == 1) arguments.get(0, (TTPtr*)&mReturnValueCallback); addAttributeWithSetter(Address, kTypeSymbol); addAttribute(Description, kTypeSymbol); addAttribute(Type, kTypeSymbol); addAttribute(Tag, kTypeSymbol); addAttribute(Highlight, kTypeBoolean); addAttributeWithSetter(Freeze, kTypeBoolean); addAttribute(Dataspace, kTypeSymbol); addAttributeProperty(Dataspace, readOnly, YES); addAttributeWithSetter(DataspaceUnit, kTypeSymbol); addAttributeWithSetter(Enable, kTypeBoolean); addAttributeWithSetter(ReturnedValue, kTypeLocalValue); addAttributeProperty(ReturnedValue, readOnly, YES); addAttributeProperty(ReturnedValue, hidden, YES); addMessage(Refresh); addMessageWithArguments(Send); addMessageProperty(Send, hidden, YES); TTObjectInstantiate(TT("dataspace"), &mDataspaceConverter, kTTValNONE); } TTViewer::~TTViewer() // TODO : delete things... { if (mReturnValueCallback) { delete (TTValuePtr)mReturnValueCallback->getBaton(); TTObjectRelease(TTObjectHandle(&mReturnValueCallback)); } if (mDataspaceConverter) TTObjectRelease(TTObjectHandle(&mDataspaceConverter)); if (mDataspaceObserver) TTObjectRelease(TTObjectHandle(&mDataspaceObserver)); if (mDataspaceUnitObserver) TTObjectRelease(TTObjectHandle(&mDataspaceUnitObserver)); if (mSender) TTObjectRelease(TTObjectHandle(&mSender)); if (mReceiver) TTObjectRelease(TTObjectHandle(&mReceiver)); } TTErr TTViewer::setAddress(const TTValue& value) { value.get(0, &mAddress); bind(); return kTTErrNone; } TTErr TTViewer::bind() { TTValue args, v; TTObjectPtr returnAddressCallback, returnValueCallback; TTValuePtr returnAddressBaton, returnValueBaton; // Prepare arguments if (mAddress == kTTAdrsEmpty) return kTTErrGeneric; // The default attribute to bind is value if (mAddress->getAttribute() == NO_ATTRIBUTE) mAddress->appendAttribute(kTTSym_value); // Replace a TTSender object if (mSender) TTObjectRelease(TTObjectHandle(&mSender)); mSender = NULL; // without this, TTObjectInstantiate try to release an oldObject that doesn't exist ... Is it good ? TTObjectInstantiate(TT("Sender"), TTObjectHandle(&mSender), kTTValNONE); mSender->setAttributeValue(kTTSym_address, mAddress); // Replace a TTReceiver object if (mReceiver) TTObjectRelease(TTObjectHandle(&mReceiver)); returnAddressCallback = NULL; // without this, TTObjectInstantiate try to release an oldObject that doesn't exist ... Is it good ? TTObjectInstantiate(TT("callback"), &returnAddressCallback, kTTValNONE); returnAddressBaton = new TTValue(TTPtr(this)); returnAddressCallback->setAttributeValue(kTTSym_baton, TTPtr(returnAddressBaton)); returnAddressCallback->setAttributeValue(kTTSym_function, TTPtr(&TTViewerReceiveAddressCallback)); args.append(returnAddressCallback); returnValueCallback = NULL; // without this, TTObjectInstantiate try to release an oldObject that doesn't exist ... Is it good ? TTObjectInstantiate(TT("callback"), &returnValueCallback, kTTValNONE); returnValueBaton = new TTValue(TTPtr(this)); returnValueCallback->setAttributeValue(kTTSym_baton, TTPtr(returnValueBaton)); returnValueCallback->setAttributeValue(kTTSym_function, TTPtr(&TTViewerReceiveValueCallback)); args.append(returnValueCallback); mReceiver = NULL; // without this, TTObjectInstantiate try to release an oldObject that doesn't exist ... Is it good ? TTObjectInstantiate(TT("Receiver"), TTObjectHandle(&mReceiver), args); mReceiver->setAttributeValue(kTTSym_address, mAddress); observeDataspace(); observeDataspaceUnit(); return kTTErrNone; } TTErr TTViewer::observeDataspace() { TTValue args; TTObjectPtr returnDataspaceCallback; TTValuePtr returnDataspaceBaton; if (mDataspaceObserver) TTObjectRelease(TTObjectHandle(&mDataspaceObserver)); // Make a TTReceiver object args.append(NULL); returnDataspaceCallback = NULL; // without this, TTObjectInstantiate try to release an oldObject that doesn't exist ... Is it good ? TTObjectInstantiate(TT("callback"), &returnDataspaceCallback, kTTValNONE); returnDataspaceBaton = new TTValue(TTPtr(this)); returnDataspaceCallback->setAttributeValue(kTTSym_baton, TTPtr(returnDataspaceBaton)); returnDataspaceCallback->setAttributeValue(kTTSym_function, TTPtr(&TTViewerDataspaceCallback)); args.append(returnDataspaceCallback); mDataspaceObserver = NULL; TTObjectInstantiate(TT("Receiver"), TTObjectHandle(&mDataspaceObserver), args); mDataspaceObserver->setAttributeValue(kTTSym_address, mAddress->appendAttribute(kTTSym_dataspace)); mDataspaceObserver->sendMessage(kTTSym_Get); return kTTErrNone; } TTErr TTViewer::observeDataspaceUnit() { TTValue args; TTObjectPtr returnDataspaceUnitCallback; TTValuePtr returnDataspaceUnitBaton; if (mDataspaceUnitObserver) TTObjectRelease(TTObjectHandle(&mDataspaceUnitObserver)); // Make a TTReceiver object args.append(NULL); returnDataspaceUnitCallback = NULL; // without this, TTObjectInstantiate try to release an oldObject that doesn't exist ... Is it good ? TTObjectInstantiate(TT("callback"), &returnDataspaceUnitCallback, kTTValNONE); returnDataspaceUnitBaton = new TTValue(TTPtr(this)); returnDataspaceUnitCallback->setAttributeValue(kTTSym_baton, TTPtr(returnDataspaceUnitBaton)); returnDataspaceUnitCallback->setAttributeValue(kTTSym_function, TTPtr(&TTViewerDataspaceUnitCallback)); args.append(returnDataspaceUnitCallback); mDataspaceUnitObserver = NULL; TTObjectInstantiate(TT("Receiver"), TTObjectHandle(&mDataspaceUnitObserver), args); mDataspaceUnitObserver->setAttributeValue(kTTSym_address, mAddress->appendAttribute(kTTSym_dataspaceUnit)); mDataspaceUnitObserver->sendMessage(kTTSym_Get); return kTTErrNone; } TTErr TTViewer::setEnable(const TTValue& value) { mEnable = value; if (mReceiver) mReceiver->setAttributeValue(kTTSym_enable, mEnable); return kTTErrNone; } TTErr TTViewer::setFreeze(const TTValue& value) { mFreeze = value; return kTTErrNone; } TTErr TTViewer::setReturnedValue(const TTValue& value) { TTAttributePtr anAttribute = NULL; TTErr err; mReturnedValue = value; err = this->findAttribute(kTTSym_returnedValue, &anAttribute); if (!err) anAttribute->sendNotification(kTTSym_notify, mReturnedValue); // we use kTTSym_notify because we know that observers are TTCallback return kTTErrNone; } TTErr TTViewer::Refresh() { if (mReceiver) return mReceiver->sendMessage(kTTSym_Get); return kTTErrGeneric; } TTErr TTViewer::Send(const TTValue& inputValue, TTValue& outputValue) { if (mSender) { TTValue valueToSend = inputValue; // append view unit if (mDataspaceUnit != kTTSym_none) valueToSend.append(mDataspaceUnit); return mSender->sendMessage(kTTSym_Send, valueToSend, kTTValNONE); } return kTTErrGeneric; } TTErr TTViewer::setDataspaceUnit(const TTValue& value) { TTValue n = value; // use new value to protect the attribute mDataspaceUnit = value; if (mDataspaceConverter) mDataspaceConverter->setAttributeValue(TT("outputUnit"), mDataspaceUnit); // TODO : notifyObservers(kTTSym_dataspaceUnit, n); return kTTErrNone; } TTErr TTViewer::convertUnit(const TTValue& inputValue, TTValue& outputValue) { if (mDataspaceConverter) return mDataspaceConverter->sendMessage(TT("convert"), inputValue, outputValue); return kTTErrNone; } #if 0 #pragma mark - #pragma mark Some Methods #endif TTErr TTViewerReceiveAddressCallback(TTPtr baton, TTValue& data) { return kTTErrGeneric; } TTErr TTViewerReceiveValueCallback(TTPtr baton, TTValue& data) { TTViewerPtr aViewer; TTValuePtr b; TTValue converted; // unpack baton (a TTViewer) b = (TTValuePtr)baton; b->get(0, (TTPtr*)&aViewer); if (aViewer->mEnable) { if (!aViewer->mFreeze) // convert data aViewer->convertUnit(data, converted); else // use last data converted = aViewer->mReturnedValue; // return value if (aViewer->mReturnValueCallback) { aViewer->mReturnValueCallback->notify(converted, kTTValNONE); aViewer->setReturnedValue(converted); } } return kTTErrNone; } TTErr TTViewerDataspaceCallback(TTPtr baton, TTValue& data) { TTViewerPtr aViewer; TTValuePtr b; TTValue v; // unpack baton (a TTViewer) b = (TTValuePtr)baton; b->get(0, (TTPtr*)&aViewer); aViewer->mDataspace = data; if (aViewer->mDataspaceConverter) aViewer->mDataspaceConverter->setAttributeValue(TT("dataspace"), aViewer->mDataspace); return kTTErrNone; } TTErr TTViewerDataspaceUnitCallback(TTPtr baton, TTValue& data) { TTViewerPtr aViewer; TTValuePtr b; TTValue v; TTErr err; // unpack baton (a TTViewer) b = (TTValuePtr)baton; b->get(0, (TTPtr*)&aViewer); if (aViewer->mDataspaceConverter) { // set input unit like the data unit aViewer->mDataspaceConverter->setAttributeValue(TT("inputUnit"), data); // if no unit : set the output unit like the the data unit if (aViewer->mDataspaceUnit == kTTSym_none) aViewer->mDataspaceUnit = data; // if the unit is wrong : use the default unit err = aViewer->mDataspaceConverter->setAttributeValue(TT("outputUnit"), aViewer->mDataspaceUnit); if (err) { aViewer->mDataspaceConverter->getAttributeValue(TT("outputUnit"), v); v.get(0, &aViewer->mDataspaceUnit); aViewer->mDataspaceConverter->setAttributeValue(TT("outputUnit"), aViewer->mDataspaceUnit); } } return kTTErrNone; } <|endoftext|>
<commit_before>/* * Copyright (c) 2017 FinChain, Inc., and contributors. * * The MIT License * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ #pragma once #include <graphene/chain/protocol/base.hpp> #include <graphene/chain/protocol/memo.hpp> namespace graphene { namespace chain { /** * @ingroup operations * * @brief lock an amount of one asset for period to get profile gived by system or ... * * Fees are paid by the "from" account * * @pre amount.amount > 0 * @pre fee.amount >= 0 * @pre from != to * @post from account's balance will be reduced by fee and amount * @post to account's balance will be increased by amount * @return n/a */ struct lock_balance_operation : public base_operation { struct fee_parameters_type { uint64_t fee = 20 * GRAPHENE_BLOCKCHAIN_PRECISION; uint32_t price_per_kbyte = 10 * GRAPHENE_BLOCKCHAIN_PRECISION; /// only required for large memos. }; asset fee; /// Account that lock balance account_id_type issuer; /// The amount of asset to operation asset amount; uint32_t period; extensions_type extensions; account_id_type fee_payer()const { return issuer; } void validate()const; share_type calculate_fee(const fee_parameters_type& k)const; }; struct set_lock_data_operation : public base_operation { struct fee_parameters_type { uint64_t fee = 20 * GRAPHENE_BLOCKCHAIN_PRECISION; uint32_t price_per_kbyte = 10 * GRAPHENE_BLOCKCHAIN_PRECISION; /// only required for large memos. }; asset fee; /// Account that lock balance account_id_type issuer; uint64_t nominal_interest_rate; // uint16_t reward_coefficient; asset init_interest_pool; extensions_type extensions; account_id_type fee_payer()const { return issuer; } void validate()const; share_type calculate_fee(const fee_parameters_type& k)const; }; }} // graphene::chain FC_REFLECT( graphene::chain::lock_balance_operation::fee_parameters_type, (fee)(price_per_kbyte) ) FC_REFLECT( graphene::chain::lock_balance_operation, (fee)(issuer)(amount)(extensions) ) FC_REFLECT( graphene::chain::set_lock_data_operation::fee_parameters_type, (fee)(price_per_kbyte) ) FC_REFLECT( graphene::chain::set_lock_data_operation, (fee)(issuer)(nominal_interest_rate)(reward_coefficient)(init_interest_pool)(extensions) ) <commit_msg>add unlock_balance_operation<commit_after>/* * Copyright (c) 2017 FinChain, Inc., and contributors. * * The MIT License * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ #pragma once #include <graphene/chain/protocol/base.hpp> #include <graphene/chain/protocol/memo.hpp> namespace graphene { namespace chain { /** * @ingroup operations * * @brief lock an amount of one asset for period to get profile gived by system or ... * * Fees are paid by the "from" account * * @pre amount.amount > 0 * @pre fee.amount >= 0 * @pre from != to * @post from account's balance will be reduced by fee and amount * @post to account's balance will be increased by amount * @return n/a */ struct lock_balance_operation : public base_operation { struct fee_parameters_type { uint64_t fee = 20 * GRAPHENE_BLOCKCHAIN_PRECISION; uint32_t price_per_kbyte = 10 * GRAPHENE_BLOCKCHAIN_PRECISION; /// only required for large memos. }; asset fee; /// Account that lock balance account_id_type issuer; /// The amount of asset to operation asset amount; uint32_t period; extensions_type extensions; account_id_type fee_payer()const { return issuer; } void validate()const; share_type calculate_fee(const fee_parameters_type& k)const; }; struct set_lock_data_operation : public base_operation { struct fee_parameters_type { uint64_t fee = 20 * GRAPHENE_BLOCKCHAIN_PRECISION; uint32_t price_per_kbyte = 10 * GRAPHENE_BLOCKCHAIN_PRECISION; /// only required for large memos. }; asset fee; /// Account that lock balance account_id_type issuer; uint64_t nominal_interest_rate; // uint16_t reward_coefficient; asset init_interest_pool; extensions_type extensions; account_id_type fee_payer()const { return issuer; } void validate()const; share_type calculate_fee(const fee_parameters_type& k)const; }; struct unlock_balance_operation : public base_operation { struct fee_parameters_type { uint64_t fee = 20 * GRAPHENE_BLOCKCHAIN_PRECISION; uint32_t price_per_kbyte = 10 * GRAPHENE_BLOCKCHAIN_PRECISION; /// only required for large memos. }; enum unlock_type{ expire, in_advance }; struct unlock_detail{ locked_balance_id_type locked_id; unlock_type type; }; asset fee; /// Account that lock balance account_id_type issuer; /// The amount of asset to operation vector<unlock_detail> locked; extensions_type extensions; account_id_type fee_payer()const { return issuer; } void validate()const; share_type calculate_fee(const fee_parameters_type& k)const; }; }} // graphene::chain FC_REFLECT( graphene::chain::lock_balance_operation::fee_parameters_type, (fee)(price_per_kbyte) ) FC_REFLECT( graphene::chain::lock_balance_operation, (fee)(issuer)(amount)(extensions) ) FC_REFLECT( graphene::chain::set_lock_data_operation::fee_parameters_type, (fee)(price_per_kbyte) ) FC_REFLECT( graphene::chain::set_lock_data_operation, (fee)(issuer)(nominal_interest_rate)(reward_coefficient)(init_interest_pool)(extensions) ) <|endoftext|>
<commit_before>/*************************************************************************/ /* message_queue.cpp */ /*************************************************************************/ /* This file is part of: */ /* GODOT ENGINE */ /* https://godotengine.org */ /*************************************************************************/ /* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */ /* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */ /* */ /* 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 "message_queue.h" #include "core/project_settings.h" #include "core/script_language.h" MessageQueue *MessageQueue::singleton = NULL; MessageQueue *MessageQueue::get_singleton() { return singleton; } Error MessageQueue::push_call(ObjectID p_id, const StringName &p_method, const Variant **p_args, int p_argcount, bool p_show_error) { _THREAD_SAFE_METHOD_ int room_needed = sizeof(Message) + sizeof(Variant) * p_argcount; if ((buffer_end + room_needed) >= buffer_size) { String type; if (ObjectDB::get_instance(p_id)) type = ObjectDB::get_instance(p_id)->get_class(); print_line("Failed method: " + type + ":" + p_method + " target ID: " + itos(p_id)); statistics(); ERR_FAIL_V_MSG(ERR_OUT_OF_MEMORY, "Message queue out of memory. Try increasing 'memory/limits/message_queue/max_size_kb' in project settings."); } Message *msg = memnew_placement(&buffer[buffer_end], Message); msg->args = p_argcount; msg->instance_id = p_id; msg->target = p_method; msg->type = TYPE_CALL; if (p_show_error) msg->type |= FLAG_SHOW_ERROR; buffer_end += sizeof(Message); for (int i = 0; i < p_argcount; i++) { Variant *v = memnew_placement(&buffer[buffer_end], Variant); buffer_end += sizeof(Variant); *v = *p_args[i]; } return OK; } Error MessageQueue::push_call(ObjectID p_id, const StringName &p_method, VARIANT_ARG_DECLARE) { VARIANT_ARGPTRS; int argc = 0; for (int i = 0; i < VARIANT_ARG_MAX; i++) { if (argptr[i]->get_type() == Variant::NIL) break; argc++; } return push_call(p_id, p_method, argptr, argc, false); } Error MessageQueue::push_set(ObjectID p_id, const StringName &p_prop, const Variant &p_value) { _THREAD_SAFE_METHOD_ uint8_t room_needed = sizeof(Message) + sizeof(Variant); if ((buffer_end + room_needed) >= buffer_size) { String type; if (ObjectDB::get_instance(p_id)) type = ObjectDB::get_instance(p_id)->get_class(); print_line("Failed set: " + type + ":" + p_prop + " target ID: " + itos(p_id)); statistics(); ERR_FAIL_V_MSG(ERR_OUT_OF_MEMORY, "Message queue out of memory. Try increasing 'memory/limits/message_queue/max_size_kb' in project settings."); } Message *msg = memnew_placement(&buffer[buffer_end], Message); msg->args = 1; msg->instance_id = p_id; msg->target = p_prop; msg->type = TYPE_SET; buffer_end += sizeof(Message); Variant *v = memnew_placement(&buffer[buffer_end], Variant); buffer_end += sizeof(Variant); *v = p_value; return OK; } Error MessageQueue::push_notification(ObjectID p_id, int p_notification) { _THREAD_SAFE_METHOD_ ERR_FAIL_COND_V(p_notification < 0, ERR_INVALID_PARAMETER); uint8_t room_needed = sizeof(Message); if ((buffer_end + room_needed) >= buffer_size) { print_line("Failed notification: " + itos(p_notification) + " target ID: " + itos(p_id)); statistics(); ERR_FAIL_V_MSG(ERR_OUT_OF_MEMORY, "Message queue out of memory. Try increasing 'memory/limits/message_queue/max_size_kb' in project settings."); } Message *msg = memnew_placement(&buffer[buffer_end], Message); msg->type = TYPE_NOTIFICATION; msg->instance_id = p_id; //msg->target; msg->notification = p_notification; buffer_end += sizeof(Message); return OK; } Error MessageQueue::push_call(Object *p_object, const StringName &p_method, VARIANT_ARG_DECLARE) { return push_call(p_object->get_instance_id(), p_method, VARIANT_ARG_PASS); } Error MessageQueue::push_notification(Object *p_object, int p_notification) { return push_notification(p_object->get_instance_id(), p_notification); } Error MessageQueue::push_set(Object *p_object, const StringName &p_prop, const Variant &p_value) { return push_set(p_object->get_instance_id(), p_prop, p_value); } void MessageQueue::statistics() { Map<StringName, int> set_count; Map<int, int> notify_count; Map<StringName, int> call_count; int null_count = 0; uint32_t read_pos = 0; while (read_pos < buffer_end) { Message *message = (Message *)&buffer[read_pos]; Object *target = ObjectDB::get_instance(message->instance_id); if (target != NULL) { switch (message->type & FLAG_MASK) { case TYPE_CALL: { if (!call_count.has(message->target)) call_count[message->target] = 0; call_count[message->target]++; } break; case TYPE_NOTIFICATION: { if (!notify_count.has(message->notification)) notify_count[message->notification] = 0; notify_count[message->notification]++; } break; case TYPE_SET: { if (!set_count.has(message->target)) set_count[message->target] = 0; set_count[message->target]++; } break; } } else { //object was deleted print_line("Object was deleted while awaiting a callback"); null_count++; } read_pos += sizeof(Message); if ((message->type & FLAG_MASK) != TYPE_NOTIFICATION) read_pos += sizeof(Variant) * message->args; } print_line("TOTAL BYTES: " + itos(buffer_end)); print_line("NULL count: " + itos(null_count)); for (Map<StringName, int>::Element *E = set_count.front(); E; E = E->next()) { print_line("SET " + E->key() + ": " + itos(E->get())); } for (Map<StringName, int>::Element *E = call_count.front(); E; E = E->next()) { print_line("CALL " + E->key() + ": " + itos(E->get())); } for (Map<int, int>::Element *E = notify_count.front(); E; E = E->next()) { print_line("NOTIFY " + itos(E->key()) + ": " + itos(E->get())); } } int MessageQueue::get_max_buffer_usage() const { return buffer_max_used; } void MessageQueue::_call_function(Object *p_target, const StringName &p_func, const Variant *p_args, int p_argcount, bool p_show_error) { const Variant **argptrs = NULL; if (p_argcount) { argptrs = (const Variant **)alloca(sizeof(Variant *) * p_argcount); for (int i = 0; i < p_argcount; i++) { argptrs[i] = &p_args[i]; } } Variant::CallError ce; p_target->call(p_func, argptrs, p_argcount, ce); if (p_show_error && ce.error != Variant::CallError::CALL_OK) { ERR_PRINTS("Error calling deferred method: " + Variant::get_call_error_text(p_target, p_func, argptrs, p_argcount, ce) + "."); } } void MessageQueue::flush() { if (buffer_end > buffer_max_used) { buffer_max_used = buffer_end; } uint32_t read_pos = 0; //using reverse locking strategy _THREAD_SAFE_LOCK_ ERR_FAIL_COND(flushing); //already flushing, you did something odd flushing = true; while (read_pos < buffer_end) { //lock on each iteration, so a call can re-add itself to the message queue Message *message = (Message *)&buffer[read_pos]; uint32_t advance = sizeof(Message); if ((message->type & FLAG_MASK) != TYPE_NOTIFICATION) advance += sizeof(Variant) * message->args; //pre-advance so this function is reentrant read_pos += advance; _THREAD_SAFE_UNLOCK_ Object *target = ObjectDB::get_instance(message->instance_id); if (target != NULL) { switch (message->type & FLAG_MASK) { case TYPE_CALL: { Variant *args = (Variant *)(message + 1); // messages don't expect a return value _call_function(target, message->target, args, message->args, message->type & FLAG_SHOW_ERROR); } break; case TYPE_NOTIFICATION: { // messages don't expect a return value target->notification(message->notification); } break; case TYPE_SET: { Variant *arg = (Variant *)(message + 1); // messages don't expect a return value target->set(message->target, *arg); } break; } } if ((message->type & FLAG_MASK) != TYPE_NOTIFICATION) { Variant *args = (Variant *)(message + 1); for (int i = 0; i < message->args; i++) { args[i].~Variant(); } } message->~Message(); _THREAD_SAFE_LOCK_ } buffer_end = 0; // reset buffer flushing = false; _THREAD_SAFE_UNLOCK_ } bool MessageQueue::is_flushing() const { return flushing; } MessageQueue::MessageQueue() { ERR_FAIL_COND_MSG(singleton != NULL, "MessageQueue singleton already exist."); singleton = this; flushing = false; buffer_end = 0; buffer_max_used = 0; buffer_size = GLOBAL_DEF_RST("memory/limits/message_queue/max_size_kb", DEFAULT_QUEUE_SIZE_KB); ProjectSettings::get_singleton()->set_custom_property_info("memory/limits/message_queue/max_size_kb", PropertyInfo(Variant::INT, "memory/limits/message_queue/max_size_kb", PROPERTY_HINT_RANGE, "0,2048,1,or_greater")); buffer_size *= 1024; buffer = memnew_arr(uint8_t, buffer_size); } MessageQueue::~MessageQueue() { uint32_t read_pos = 0; while (read_pos < buffer_end) { Message *message = (Message *)&buffer[read_pos]; Variant *args = (Variant *)(message + 1); int argc = message->args; if ((message->type & FLAG_MASK) != TYPE_NOTIFICATION) { for (int i = 0; i < argc; i++) args[i].~Variant(); } message->~Message(); read_pos += sizeof(Message); if ((message->type & FLAG_MASK) != TYPE_NOTIFICATION) read_pos += sizeof(Variant) * message->args; } singleton = NULL; memdelete_arr(buffer); } <commit_msg>Tweak the message queue maximum size property hint<commit_after>/*************************************************************************/ /* message_queue.cpp */ /*************************************************************************/ /* This file is part of: */ /* GODOT ENGINE */ /* https://godotengine.org */ /*************************************************************************/ /* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */ /* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */ /* */ /* 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 "message_queue.h" #include "core/project_settings.h" #include "core/script_language.h" MessageQueue *MessageQueue::singleton = NULL; MessageQueue *MessageQueue::get_singleton() { return singleton; } Error MessageQueue::push_call(ObjectID p_id, const StringName &p_method, const Variant **p_args, int p_argcount, bool p_show_error) { _THREAD_SAFE_METHOD_ int room_needed = sizeof(Message) + sizeof(Variant) * p_argcount; if ((buffer_end + room_needed) >= buffer_size) { String type; if (ObjectDB::get_instance(p_id)) type = ObjectDB::get_instance(p_id)->get_class(); print_line("Failed method: " + type + ":" + p_method + " target ID: " + itos(p_id)); statistics(); ERR_FAIL_V_MSG(ERR_OUT_OF_MEMORY, "Message queue out of memory. Try increasing 'memory/limits/message_queue/max_size_kb' in project settings."); } Message *msg = memnew_placement(&buffer[buffer_end], Message); msg->args = p_argcount; msg->instance_id = p_id; msg->target = p_method; msg->type = TYPE_CALL; if (p_show_error) msg->type |= FLAG_SHOW_ERROR; buffer_end += sizeof(Message); for (int i = 0; i < p_argcount; i++) { Variant *v = memnew_placement(&buffer[buffer_end], Variant); buffer_end += sizeof(Variant); *v = *p_args[i]; } return OK; } Error MessageQueue::push_call(ObjectID p_id, const StringName &p_method, VARIANT_ARG_DECLARE) { VARIANT_ARGPTRS; int argc = 0; for (int i = 0; i < VARIANT_ARG_MAX; i++) { if (argptr[i]->get_type() == Variant::NIL) break; argc++; } return push_call(p_id, p_method, argptr, argc, false); } Error MessageQueue::push_set(ObjectID p_id, const StringName &p_prop, const Variant &p_value) { _THREAD_SAFE_METHOD_ uint8_t room_needed = sizeof(Message) + sizeof(Variant); if ((buffer_end + room_needed) >= buffer_size) { String type; if (ObjectDB::get_instance(p_id)) type = ObjectDB::get_instance(p_id)->get_class(); print_line("Failed set: " + type + ":" + p_prop + " target ID: " + itos(p_id)); statistics(); ERR_FAIL_V_MSG(ERR_OUT_OF_MEMORY, "Message queue out of memory. Try increasing 'memory/limits/message_queue/max_size_kb' in project settings."); } Message *msg = memnew_placement(&buffer[buffer_end], Message); msg->args = 1; msg->instance_id = p_id; msg->target = p_prop; msg->type = TYPE_SET; buffer_end += sizeof(Message); Variant *v = memnew_placement(&buffer[buffer_end], Variant); buffer_end += sizeof(Variant); *v = p_value; return OK; } Error MessageQueue::push_notification(ObjectID p_id, int p_notification) { _THREAD_SAFE_METHOD_ ERR_FAIL_COND_V(p_notification < 0, ERR_INVALID_PARAMETER); uint8_t room_needed = sizeof(Message); if ((buffer_end + room_needed) >= buffer_size) { print_line("Failed notification: " + itos(p_notification) + " target ID: " + itos(p_id)); statistics(); ERR_FAIL_V_MSG(ERR_OUT_OF_MEMORY, "Message queue out of memory. Try increasing 'memory/limits/message_queue/max_size_kb' in project settings."); } Message *msg = memnew_placement(&buffer[buffer_end], Message); msg->type = TYPE_NOTIFICATION; msg->instance_id = p_id; //msg->target; msg->notification = p_notification; buffer_end += sizeof(Message); return OK; } Error MessageQueue::push_call(Object *p_object, const StringName &p_method, VARIANT_ARG_DECLARE) { return push_call(p_object->get_instance_id(), p_method, VARIANT_ARG_PASS); } Error MessageQueue::push_notification(Object *p_object, int p_notification) { return push_notification(p_object->get_instance_id(), p_notification); } Error MessageQueue::push_set(Object *p_object, const StringName &p_prop, const Variant &p_value) { return push_set(p_object->get_instance_id(), p_prop, p_value); } void MessageQueue::statistics() { Map<StringName, int> set_count; Map<int, int> notify_count; Map<StringName, int> call_count; int null_count = 0; uint32_t read_pos = 0; while (read_pos < buffer_end) { Message *message = (Message *)&buffer[read_pos]; Object *target = ObjectDB::get_instance(message->instance_id); if (target != NULL) { switch (message->type & FLAG_MASK) { case TYPE_CALL: { if (!call_count.has(message->target)) call_count[message->target] = 0; call_count[message->target]++; } break; case TYPE_NOTIFICATION: { if (!notify_count.has(message->notification)) notify_count[message->notification] = 0; notify_count[message->notification]++; } break; case TYPE_SET: { if (!set_count.has(message->target)) set_count[message->target] = 0; set_count[message->target]++; } break; } } else { //object was deleted print_line("Object was deleted while awaiting a callback"); null_count++; } read_pos += sizeof(Message); if ((message->type & FLAG_MASK) != TYPE_NOTIFICATION) read_pos += sizeof(Variant) * message->args; } print_line("TOTAL BYTES: " + itos(buffer_end)); print_line("NULL count: " + itos(null_count)); for (Map<StringName, int>::Element *E = set_count.front(); E; E = E->next()) { print_line("SET " + E->key() + ": " + itos(E->get())); } for (Map<StringName, int>::Element *E = call_count.front(); E; E = E->next()) { print_line("CALL " + E->key() + ": " + itos(E->get())); } for (Map<int, int>::Element *E = notify_count.front(); E; E = E->next()) { print_line("NOTIFY " + itos(E->key()) + ": " + itos(E->get())); } } int MessageQueue::get_max_buffer_usage() const { return buffer_max_used; } void MessageQueue::_call_function(Object *p_target, const StringName &p_func, const Variant *p_args, int p_argcount, bool p_show_error) { const Variant **argptrs = NULL; if (p_argcount) { argptrs = (const Variant **)alloca(sizeof(Variant *) * p_argcount); for (int i = 0; i < p_argcount; i++) { argptrs[i] = &p_args[i]; } } Variant::CallError ce; p_target->call(p_func, argptrs, p_argcount, ce); if (p_show_error && ce.error != Variant::CallError::CALL_OK) { ERR_PRINTS("Error calling deferred method: " + Variant::get_call_error_text(p_target, p_func, argptrs, p_argcount, ce) + "."); } } void MessageQueue::flush() { if (buffer_end > buffer_max_used) { buffer_max_used = buffer_end; } uint32_t read_pos = 0; //using reverse locking strategy _THREAD_SAFE_LOCK_ ERR_FAIL_COND(flushing); //already flushing, you did something odd flushing = true; while (read_pos < buffer_end) { //lock on each iteration, so a call can re-add itself to the message queue Message *message = (Message *)&buffer[read_pos]; uint32_t advance = sizeof(Message); if ((message->type & FLAG_MASK) != TYPE_NOTIFICATION) advance += sizeof(Variant) * message->args; //pre-advance so this function is reentrant read_pos += advance; _THREAD_SAFE_UNLOCK_ Object *target = ObjectDB::get_instance(message->instance_id); if (target != NULL) { switch (message->type & FLAG_MASK) { case TYPE_CALL: { Variant *args = (Variant *)(message + 1); // messages don't expect a return value _call_function(target, message->target, args, message->args, message->type & FLAG_SHOW_ERROR); } break; case TYPE_NOTIFICATION: { // messages don't expect a return value target->notification(message->notification); } break; case TYPE_SET: { Variant *arg = (Variant *)(message + 1); // messages don't expect a return value target->set(message->target, *arg); } break; } } if ((message->type & FLAG_MASK) != TYPE_NOTIFICATION) { Variant *args = (Variant *)(message + 1); for (int i = 0; i < message->args; i++) { args[i].~Variant(); } } message->~Message(); _THREAD_SAFE_LOCK_ } buffer_end = 0; // reset buffer flushing = false; _THREAD_SAFE_UNLOCK_ } bool MessageQueue::is_flushing() const { return flushing; } MessageQueue::MessageQueue() { ERR_FAIL_COND_MSG(singleton != NULL, "A MessageQueue singleton already exists."); singleton = this; flushing = false; buffer_end = 0; buffer_max_used = 0; buffer_size = GLOBAL_DEF_RST("memory/limits/message_queue/max_size_kb", DEFAULT_QUEUE_SIZE_KB); ProjectSettings::get_singleton()->set_custom_property_info("memory/limits/message_queue/max_size_kb", PropertyInfo(Variant::INT, "memory/limits/message_queue/max_size_kb", PROPERTY_HINT_RANGE, "1024,4096,1,or_greater")); buffer_size *= 1024; buffer = memnew_arr(uint8_t, buffer_size); } MessageQueue::~MessageQueue() { uint32_t read_pos = 0; while (read_pos < buffer_end) { Message *message = (Message *)&buffer[read_pos]; Variant *args = (Variant *)(message + 1); int argc = message->args; if ((message->type & FLAG_MASK) != TYPE_NOTIFICATION) { for (int i = 0; i < argc; i++) args[i].~Variant(); } message->~Message(); read_pos += sizeof(Message); if ((message->type & FLAG_MASK) != TYPE_NOTIFICATION) read_pos += sizeof(Variant) * message->args; } singleton = NULL; memdelete_arr(buffer); } <|endoftext|>
<commit_before>/****************************************************************************** * Copyright (c) 2013 Aitor Aldoma, Thomas Faeulhammer * * 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 <pcl/common/angles.h> #include <pcl/common/io.h> #include <pcl/common/transforms.h> #include <pcl/filters/filter.h> #include <pcl/visualization/pcl_visualizer.h> #include <v4r/registration/noise_model_based_cloud_integration.h> #include <v4r/common/organized_edge_detection.h> #include <glog/logging.h> namespace v4r { template<typename PointT> void NMBasedCloudIntegration<PointT>::collectInfo () { for(size_t i=0; i < input_clouds_.size(); i++) { pcl::PointCloud<PointT> cloud_aligned; pcl::transformPointCloud(*input_clouds_[i], cloud_aligned, transformations_to_global_[i]); pcl::PointCloud<pcl::Normal> normals_aligned; transformNormals(*input_normals_[i], normals_aligned, transformations_to_global_[i]); size_t existing_pts = big_cloud_info_.size(); size_t kept_new_pts = 0; if (indices_.empty()) { big_cloud_info_.resize( existing_pts + cloud_aligned.points.size()); for(size_t jj=0; jj<cloud_aligned.points.size(); jj++) { if ( !pcl::isFinite(cloud_aligned.points[jj])) continue; PointInfo &pt = big_cloud_info_ [ existing_pts + kept_new_pts ]; pt.pt = cloud_aligned.points[jj]; pt.normal = normals_aligned.points[jj]; pt.sigma_lateral = pt_properties_[i][jj][0]; pt.sigma_axial = pt_properties_[i][jj][1]; pt.distance_to_depth_discontinuity = pt_properties_[i][jj][2]; kept_new_pts++; } } else { big_cloud_info_.resize( existing_pts + indices_[i].size()); for(const auto idx : indices_[i]) { if(!pcl::isFinite(cloud_aligned.points[idx])) continue; PointInfo &pt = big_cloud_info_ [ existing_pts + kept_new_pts ]; pt.pt = cloud_aligned.points[idx]; pt.normal = normals_aligned.points[ idx ]; pt.sigma_lateral = pt_properties_[i][idx][0]; pt.sigma_axial = pt_properties_[i][idx][1]; pt.distance_to_depth_discontinuity = pt_properties_[i][idx][2]; kept_new_pts++; } } big_cloud_info_.resize( existing_pts + kept_new_pts); // compute and store remaining information for(size_t jj=0; jj<kept_new_pts; jj++) { PointInfo &pt = big_cloud_info_ [ existing_pts + jj ]; pt.origin = i; Eigen::Matrix3f sigma = Eigen::Matrix3f::Zero(), sigma_aligned = Eigen::Matrix3f::Zero(); sigma(0,0) = pt.sigma_lateral; sigma(1,1) = pt.sigma_lateral; sigma(2,2) = pt.sigma_axial; const Eigen::Matrix4f &tf = transformations_to_global_[ i ]; Eigen::Matrix3f rotation = tf.block<3,3>(0,0); // or inverse? sigma_aligned = rotation * sigma * rotation.transpose(); pt.probability = 1/ sqrt(2 * M_PI * sigma_aligned.determinant()); } } } template<typename PointT> void NMBasedCloudIntegration<PointT>::reasonAboutPts () { const int width = input_clouds_[0]->width; const int height = input_clouds_[0]->height; const float cx = static_cast<float> (width) / 2.f;// - 0.5f; const float cy = static_cast<float> (height) / 2.f;// - 0.5f; // pcl::visualization::PCLVisualizer vis; for (size_t i=0; i<big_cloud_info_.size(); i++) { PointInfo &pt = big_cloud_info_[i]; const PointT &ptt = pt.pt; for (size_t cloud=0; cloud<input_clouds_.size(); cloud++) { if( pt.origin == cloud) // we don't have to reason about the point with respect to the original cloud continue; // reproject point onto the cloud's image plane and check if its within FOV and if so, if it can be seen or is occluded const Eigen::Matrix4f &tf = transformations_to_global_[cloud].inverse() * transformations_to_global_[pt.origin]; float x = static_cast<float> (tf (0, 0) * ptt.x + tf (0, 1) * ptt.y + tf (0, 2) * ptt.z + tf (0, 3)); float y = static_cast<float> (tf (1, 0) * ptt.x + tf (1, 1) * ptt.y + tf (1, 2) * ptt.z + tf (1, 3)); float z = static_cast<float> (tf (2, 0) * ptt.x + tf (2, 1) * ptt.y + tf (2, 2) * ptt.z + tf (2, 3)); int u = static_cast<int> (param_.focal_length_ * x / z + cx); int v = static_cast<int> (param_.focal_length_ * y / z + cy); std::cout << "u: " <<u << ", v: " << v << std::endl; PointT ptt_aligned; ptt_aligned.x = x; ptt_aligned.y = y; ptt_aligned.z = z; if( u<0 || v <0 || u>=width || v >= height ) pt.occluded_++; else { float thresh = param_.threshold_explained_; if( z > 1.f ) thresh+= param_.threshold_explained_ * (z-1.f) * (z-1.f); const float z_c = input_clouds_[cloud]->points[ v*width + u ].z; if ( std::abs(z_c - z) < thresh ) pt.explained_++; else if (z_c > z ) { pt.violated_ ++; // vis.removeAllShapes(); // vis.removeAllPointClouds(); // vis.addPointCloud(input_clouds_[cloud]); // vis.addSphere(ptt_aligned, 0.03f, 1.f, 0.f, 0.f); // vis.spin(); } else pt.occluded_ ++; } } } } template<typename PointT> void NMBasedCloudIntegration<PointT>::compute (PointTPtr & output) { if(input_clouds_.empty()) { std::cerr << "No input clouds set for cloud integration!" << std::endl; return; } big_cloud_info_.clear(); collectInfo(); if(param_.reason_about_points_) reasonAboutPts(); pcl::octree::OctreePointCloudPointVector<PointT> octree( param_.octree_resolution_ ); PointTPtr big_cloud ( new pcl::PointCloud<PointT>()); big_cloud->width = big_cloud_info_.size(); big_cloud->height = 1; big_cloud->points.resize( big_cloud_info_.size() ); for(size_t i=0; i < big_cloud_info_.size(); i++) big_cloud->points[i] = big_cloud_info_[i].pt; octree.setInputCloud( big_cloud ); octree.addPointsFromInputCloud(); typename pcl::octree::OctreePointCloudPointVector<PointT>::LeafNodeIterator leaf_it; const typename pcl::octree::OctreePointCloudPointVector<PointT>::LeafNodeIterator it2_end = octree.leaf_end(); output->points.resize( big_cloud_info_.size() ); output_normals_.reset(new pcl::PointCloud<pcl::Normal>); output_normals_->points.resize( big_cloud_info_.size()); size_t kept = 0; size_t total_used = 0; for (leaf_it = octree.leaf_begin(); leaf_it != it2_end; ++leaf_it) { pcl::octree::OctreeContainerPointIndices& container = leaf_it.getLeafContainer(); // add points from leaf node to indexVector std::vector<int> indexVector; container.getPointIndices (indexVector); if(indexVector.empty() || indexVector.size() < param_.min_points_per_voxel_) continue; std::vector<PointInfo> voxel_pts ( indexVector.size() ); for(size_t k=0; k < indexVector.size(); k++) voxel_pts[k] = big_cloud_info_ [indexVector[k]]; PointT p; pcl::Normal n; if(param_.average_) { p.getVector3fMap() = Eigen::Vector3f::Zero(); p.r = p.g = p.b = 0.f; n.getNormalVector3fMap() = Eigen::Vector3f::Zero(); n.curvature = 0.f; for(const PointInfo &pt_tmp : voxel_pts) { p.getVector3fMap() = p.getVector3fMap() + pt_tmp.pt.getVector3fMap(); p.r += pt_tmp.pt.r; p.g += pt_tmp.pt.g; p.b += pt_tmp.pt.b; Eigen::Vector3f normal = pt_tmp.normal.getNormalVector3fMap(); normal.normalize(); n.getNormalVector3fMap() = n.getNormalVector3fMap() + normal; n.curvature += pt_tmp.normal.curvature; } p.getVector3fMap() = p.getVector3fMap() / indexVector.size(); p.r /= indexVector.size(); p.g /= indexVector.size(); p.b /= indexVector.size(); n.getNormalVector3fMap() = n.getNormalVector3fMap() / indexVector.size(); n.curvature /= indexVector.size(); total_used += indexVector.size(); } else // take only point with max probability { std::sort(voxel_pts.begin(), voxel_pts.end()); bool found_good_pt = false; for(const PointInfo &pt_tmp : voxel_pts) { if (pt_tmp.distance_to_depth_discontinuity > param_.edge_radius_px_) { p.getVector3fMap() = pt_tmp.pt.getVector3fMap(); p.r = pt_tmp.pt.r; p.g = pt_tmp.pt.g; p.b = pt_tmp.pt.b; n.getNormalVector3fMap() = pt_tmp.normal.getNormalVector3fMap(); n.curvature = pt_tmp.normal.curvature; found_good_pt = true; break; } } if( !found_good_pt ) continue; total_used++; } output->points[kept] = p; output_normals_->points[kept] = n; kept++; } std::cout << "Number of points in final model:" << kept << " used:" << total_used << std::endl; output->points.resize(kept); output_normals_->points.resize(kept); output->width = output_normals_->width = kept; output->height = output_normals_->height = 1; output->is_dense = output_normals_->is_dense = true; cleanUp(); } template class V4R_EXPORTS NMBasedCloudIntegration<pcl::PointXYZRGB>; } <commit_msg>Speed-up info collection in NMBasedCloudIntegration<commit_after>/****************************************************************************** * Copyright (c) 2013 Aitor Aldoma, Thomas Faeulhammer * * 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 <pcl/common/angles.h> #include <pcl/common/io.h> #include <pcl/common/transforms.h> #include <pcl/filters/filter.h> #include <pcl/visualization/pcl_visualizer.h> #include <v4r/registration/noise_model_based_cloud_integration.h> #include <v4r/common/organized_edge_detection.h> #include <glog/logging.h> namespace v4r { template<typename PointT> void NMBasedCloudIntegration<PointT>::collectInfo () { size_t total_point_count = 0; for(size_t i = 0; i < input_clouds_.size(); i++) total_point_count += indices_.empty() ? input_clouds_[i]->size() : indices_[i].size(); big_cloud_info_.resize(total_point_count); size_t point_count = 0; for(size_t i=0; i < input_clouds_.size(); i++) { pcl::PointCloud<PointT> cloud_aligned; pcl::transformPointCloud(*input_clouds_[i], cloud_aligned, transformations_to_global_[i]); pcl::PointCloud<pcl::Normal> normals_aligned; transformNormals(*input_normals_[i], normals_aligned, transformations_to_global_[i]); size_t kept_new_pts = 0; if (indices_.empty()) { for(size_t jj=0; jj<cloud_aligned.points.size(); jj++) { if ( !pcl::isFinite(cloud_aligned.points[jj])) continue; PointInfo &pt = big_cloud_info_[point_count + kept_new_pts]; pt.pt = cloud_aligned.points[jj]; pt.normal = normals_aligned.points[jj]; pt.sigma_lateral = pt_properties_[i][jj][0]; pt.sigma_axial = pt_properties_[i][jj][1]; pt.distance_to_depth_discontinuity = pt_properties_[i][jj][2]; kept_new_pts++; } } else { for(const auto idx : indices_[i]) { if(!pcl::isFinite(cloud_aligned.points[idx])) continue; PointInfo &pt = big_cloud_info_[point_count + kept_new_pts]; pt.pt = cloud_aligned.points[idx]; pt.normal = normals_aligned.points[ idx ]; pt.sigma_lateral = pt_properties_[i][idx][0]; pt.sigma_axial = pt_properties_[i][idx][1]; pt.distance_to_depth_discontinuity = pt_properties_[i][idx][2]; kept_new_pts++; } } // compute and store remaining information for(size_t jj=0; jj<kept_new_pts; jj++) { PointInfo &pt = big_cloud_info_ [point_count + jj]; pt.origin = i; Eigen::Matrix3f sigma = Eigen::Matrix3f::Zero(), sigma_aligned = Eigen::Matrix3f::Zero(); sigma(0,0) = pt.sigma_lateral; sigma(1,1) = pt.sigma_lateral; sigma(2,2) = pt.sigma_axial; const Eigen::Matrix4f &tf = transformations_to_global_[ i ]; Eigen::Matrix3f rotation = tf.block<3,3>(0,0); // or inverse? sigma_aligned = rotation * sigma * rotation.transpose(); pt.probability = 1/ sqrt(2 * M_PI * sigma_aligned.determinant()); } point_count += kept_new_pts; } big_cloud_info_.resize(point_count); } template<typename PointT> void NMBasedCloudIntegration<PointT>::reasonAboutPts () { const int width = input_clouds_[0]->width; const int height = input_clouds_[0]->height; const float cx = static_cast<float> (width) / 2.f;// - 0.5f; const float cy = static_cast<float> (height) / 2.f;// - 0.5f; // pcl::visualization::PCLVisualizer vis; for (size_t i=0; i<big_cloud_info_.size(); i++) { PointInfo &pt = big_cloud_info_[i]; const PointT &ptt = pt.pt; for (size_t cloud=0; cloud<input_clouds_.size(); cloud++) { if( pt.origin == cloud) // we don't have to reason about the point with respect to the original cloud continue; // reproject point onto the cloud's image plane and check if its within FOV and if so, if it can be seen or is occluded const Eigen::Matrix4f &tf = transformations_to_global_[cloud].inverse() * transformations_to_global_[pt.origin]; float x = static_cast<float> (tf (0, 0) * ptt.x + tf (0, 1) * ptt.y + tf (0, 2) * ptt.z + tf (0, 3)); float y = static_cast<float> (tf (1, 0) * ptt.x + tf (1, 1) * ptt.y + tf (1, 2) * ptt.z + tf (1, 3)); float z = static_cast<float> (tf (2, 0) * ptt.x + tf (2, 1) * ptt.y + tf (2, 2) * ptt.z + tf (2, 3)); int u = static_cast<int> (param_.focal_length_ * x / z + cx); int v = static_cast<int> (param_.focal_length_ * y / z + cy); std::cout << "u: " <<u << ", v: " << v << std::endl; PointT ptt_aligned; ptt_aligned.x = x; ptt_aligned.y = y; ptt_aligned.z = z; if( u<0 || v <0 || u>=width || v >= height ) pt.occluded_++; else { float thresh = param_.threshold_explained_; if( z > 1.f ) thresh+= param_.threshold_explained_ * (z-1.f) * (z-1.f); const float z_c = input_clouds_[cloud]->points[ v*width + u ].z; if ( std::abs(z_c - z) < thresh ) pt.explained_++; else if (z_c > z ) { pt.violated_ ++; // vis.removeAllShapes(); // vis.removeAllPointClouds(); // vis.addPointCloud(input_clouds_[cloud]); // vis.addSphere(ptt_aligned, 0.03f, 1.f, 0.f, 0.f); // vis.spin(); } else pt.occluded_ ++; } } } } template<typename PointT> void NMBasedCloudIntegration<PointT>::compute (PointTPtr & output) { if(input_clouds_.empty()) { std::cerr << "No input clouds set for cloud integration!" << std::endl; return; } big_cloud_info_.clear(); collectInfo(); if(param_.reason_about_points_) reasonAboutPts(); pcl::octree::OctreePointCloudPointVector<PointT> octree( param_.octree_resolution_ ); PointTPtr big_cloud ( new pcl::PointCloud<PointT>()); big_cloud->width = big_cloud_info_.size(); big_cloud->height = 1; big_cloud->points.resize( big_cloud_info_.size() ); for(size_t i=0; i < big_cloud_info_.size(); i++) big_cloud->points[i] = big_cloud_info_[i].pt; octree.setInputCloud( big_cloud ); octree.addPointsFromInputCloud(); typename pcl::octree::OctreePointCloudPointVector<PointT>::LeafNodeIterator leaf_it; const typename pcl::octree::OctreePointCloudPointVector<PointT>::LeafNodeIterator it2_end = octree.leaf_end(); output->points.resize( big_cloud_info_.size() ); output_normals_.reset(new pcl::PointCloud<pcl::Normal>); output_normals_->points.resize( big_cloud_info_.size()); size_t kept = 0; size_t total_used = 0; for (leaf_it = octree.leaf_begin(); leaf_it != it2_end; ++leaf_it) { pcl::octree::OctreeContainerPointIndices& container = leaf_it.getLeafContainer(); // add points from leaf node to indexVector std::vector<int> indexVector; container.getPointIndices (indexVector); if(indexVector.empty() || indexVector.size() < param_.min_points_per_voxel_) continue; std::vector<PointInfo> voxel_pts ( indexVector.size() ); for(size_t k=0; k < indexVector.size(); k++) voxel_pts[k] = big_cloud_info_ [indexVector[k]]; PointT p; pcl::Normal n; if(param_.average_) { p.getVector3fMap() = Eigen::Vector3f::Zero(); p.r = p.g = p.b = 0.f; n.getNormalVector3fMap() = Eigen::Vector3f::Zero(); n.curvature = 0.f; for(const PointInfo &pt_tmp : voxel_pts) { p.getVector3fMap() = p.getVector3fMap() + pt_tmp.pt.getVector3fMap(); p.r += pt_tmp.pt.r; p.g += pt_tmp.pt.g; p.b += pt_tmp.pt.b; Eigen::Vector3f normal = pt_tmp.normal.getNormalVector3fMap(); normal.normalize(); n.getNormalVector3fMap() = n.getNormalVector3fMap() + normal; n.curvature += pt_tmp.normal.curvature; } p.getVector3fMap() = p.getVector3fMap() / indexVector.size(); p.r /= indexVector.size(); p.g /= indexVector.size(); p.b /= indexVector.size(); n.getNormalVector3fMap() = n.getNormalVector3fMap() / indexVector.size(); n.curvature /= indexVector.size(); total_used += indexVector.size(); } else // take only point with max probability { std::sort(voxel_pts.begin(), voxel_pts.end()); bool found_good_pt = false; for(const PointInfo &pt_tmp : voxel_pts) { if (pt_tmp.distance_to_depth_discontinuity > param_.edge_radius_px_) { p.getVector3fMap() = pt_tmp.pt.getVector3fMap(); p.r = pt_tmp.pt.r; p.g = pt_tmp.pt.g; p.b = pt_tmp.pt.b; n.getNormalVector3fMap() = pt_tmp.normal.getNormalVector3fMap(); n.curvature = pt_tmp.normal.curvature; found_good_pt = true; break; } } if( !found_good_pt ) continue; total_used++; } output->points[kept] = p; output_normals_->points[kept] = n; kept++; } std::cout << "Number of points in final model:" << kept << " used:" << total_used << std::endl; output->points.resize(kept); output_normals_->points.resize(kept); output->width = output_normals_->width = kept; output->height = output_normals_->height = 1; output->is_dense = output_normals_->is_dense = true; cleanUp(); } template class V4R_EXPORTS NMBasedCloudIntegration<pcl::PointXYZRGB>; } <|endoftext|>
<commit_before>/****************************************************************/ /* MOOSE - Multiphysics Object Oriented Simulation Environment */ /* */ /* All contents are licensed under LGPL V2.1 */ /* See LICENSE for full restrictions */ /****************************************************************/ #include "ComputeElasticityTensor.h" #include "RotationTensor.h" template<> InputParameters validParams<ComputeElasticityTensor>() { InputParameters params = validParams<ComputeElasticityTensorBase>(); params.addClassDescription("Compute an elasticity tensor."); params.addRequiredParam<std::vector<Real> >("C_ijkl", "Stiffness tensor for material"); params.addParam<MooseEnum>("fill_method", RankFourTensor::fillMethodEnum() = "symmetric9", "The fill method"); params.addParam<Real>("euler_angle_1", 0.0, "Euler angle in direction 1"); params.addParam<Real>("euler_angle_2", 0.0, "Euler angle in direction 2"); params.addParam<Real>("euler_angle_3", 0.0, "Euler angle in direction 3"); return params; } ComputeElasticityTensor::ComputeElasticityTensor(const std::string & name, InputParameters parameters) : ComputeElasticityTensorBase(name, parameters), _Euler_angles(getParam<Real>("euler_angle_1"), getParam<Real>("euler_angle_2"), getParam<Real>("euler_angle_3")), _Cijkl(getParam<std::vector<Real> >("C_ijkl"), (RankFourTensor::FillMethod)(int)getParam<MooseEnum>("fill_method")) { } void ComputeElasticityTensor::computeQpElasticityTensor() { // Define a rotation according to Euler angle parameters RotationTensor R(_Euler_angles); // R type: RealTensorValue //Assign elasticity tensor at a given quad point _elasticity_tensor[_qp] = _Cijkl; //Rotate tensor _elasticity_tensor[_qp].rotate(R); } <commit_msg>Avoid repeated rotation ops in ComputeElasticityTensorBase (#5171)<commit_after>/****************************************************************/ /* MOOSE - Multiphysics Object Oriented Simulation Environment */ /* */ /* All contents are licensed under LGPL V2.1 */ /* See LICENSE for full restrictions */ /****************************************************************/ #include "ComputeElasticityTensor.h" #include "RotationTensor.h" template<> InputParameters validParams<ComputeElasticityTensor>() { InputParameters params = validParams<ComputeElasticityTensorBase>(); params.addClassDescription("Compute an elasticity tensor."); params.addRequiredParam<std::vector<Real> >("C_ijkl", "Stiffness tensor for material"); params.addParam<MooseEnum>("fill_method", RankFourTensor::fillMethodEnum() = "symmetric9", "The fill method"); params.addParam<Real>("euler_angle_1", 0.0, "Euler angle in direction 1"); params.addParam<Real>("euler_angle_2", 0.0, "Euler angle in direction 2"); params.addParam<Real>("euler_angle_3", 0.0, "Euler angle in direction 3"); return params; } ComputeElasticityTensor::ComputeElasticityTensor(const std::string & name, InputParameters parameters) : ComputeElasticityTensorBase(name, parameters), _Euler_angles(getParam<Real>("euler_angle_1"), getParam<Real>("euler_angle_2"), getParam<Real>("euler_angle_3")), _Cijkl(getParam<std::vector<Real> >("C_ijkl"), (RankFourTensor::FillMethod)(int)getParam<MooseEnum>("fill_method")) { // Define a rotation according to Euler angle parameters RotationTensor R(_Euler_angles); // R type: RealTensorValue // rotate elasticity tensor _Cijkl.rotate(R); } void ComputeElasticityTensor::computeQpElasticityTensor() { //Assign elasticity tensor at a given quad point _elasticity_tensor[_qp] = _Cijkl; } <|endoftext|>
<commit_before>/*========================================================================= Program: Visualization Toolkit Module: vtkTkAppInit.cxx Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen All rights reserved. See Copyright.txt or http://www.kitware.com/Copyright.htm for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notice for more information. =========================================================================*/ /* * tkAppInit.c -- * * Provides a default version of the Tcl_AppInit procedure for * use in wish and similar Tk-based applications. * * Copyright (c) 1993 The Regents of the University of California. * Copyright (c) 1994 Sun Microsystems, Inc. * * See the file "license.terms" for information on usage and redistribution * of this file, and for a DISCLAIMER OF ALL WARRANTIES. */ #ifdef VTK_COMPILED_USING_MPI # include <mpi.h> # include "vtkMPIController.h" #endif // VTK_COMPILED_USING_MPI #include "vtkSystemIncludes.h" #include "vtkToolkits.h" #include "Wrapping/Tcl/vtkTkAppInitConfigure.h" #if defined(CMAKE_INTDIR) # define VTK_TCL_PACKAGE_DIR VTK_TCL_PACKAGE_DIR_BUILD "/" CMAKE_INTDIR #else # define VTK_TCL_PACKAGE_DIR VTK_TCL_PACKAGE_DIR_BUILD #endif #ifdef VTK_USE_RENDERING # include "vtkTk.h" #else # include "vtkTcl.h" #endif /* * Make sure all the kits register their classes with vtkInstantiator. */ #include "vtkCommonInstantiator.h" #include "vtkFilteringInstantiator.h" #include "vtkIOInstantiator.h" #include "vtkImagingInstantiator.h" #include "vtkGraphicsInstantiator.h" #ifdef VTK_USE_RENDERING #include "vtkRenderingInstantiator.h" #endif #ifdef VTK_USE_PATENTED #include "vtkPatentedInstantiator.h" #endif #ifdef VTK_USE_HYBRID #include "vtkHybridInstantiator.h" #endif #ifdef VTK_USE_PARALLEL #include "vtkParallelInstantiator.h" #endif static void vtkTkAppInitEnableMSVCDebugHook(); /* *---------------------------------------------------------------------- * * main -- * * This is the main program for the application. * * Results: * None: Tk_Main never returns here, so this procedure never * returns either. * * Side effects: * Whatever the application does. * *---------------------------------------------------------------------- */ #ifdef VTK_COMPILED_USING_MPI class vtkMPICleanup { public: vtkMPICleanup() { this->Controller = 0; } void Initialize(int *argc, char ***argv) { MPI_Init(argc, argv); this->Controller = vtkMPIController::New(); this->Controller->Initialize(argc, argv, 1); vtkMultiProcessController::SetGlobalController(this->Controller); } ~vtkMPICleanup() { if ( this->Controller ) { this->Controller->Finalize(); this->Controller->Delete(); } } private: vtkMPIController *Controller; }; static vtkMPICleanup VTKMPICleanup; #endif // VTK_COMPILED_USING_MPI int main(int argc, char **argv) { ios::sync_with_stdio(); vtkTkAppInitEnableMSVCDebugHook(); #ifdef VTK_COMPILED_USING_MPI VTKMPICleanup.Initialize(&argc, &argv); #endif // VTK_COMPILED_USING_MPI #ifdef VTK_USE_RENDERING Tk_Main(argc, argv, Tcl_AppInit); #else Tcl_Main(argc, argv, Tcl_AppInit); #endif return 0; /* Needed only to prevent compiler warning. */ } /* *---------------------------------------------------------------------- * * Tcl_AppInit -- * * This procedure performs application-specific initialization. * Most applications, especially those that incorporate additional * packages, will have their own version of this procedure. * * Results: * Returns a standard Tcl completion code, and leaves an error * message in interp->result if an error occurs. * * Side effects: * Depends on the startup script. * *---------------------------------------------------------------------- */ extern "C" int Vtkcommontcl_Init(Tcl_Interp *interp); extern "C" int Vtkfilteringtcl_Init(Tcl_Interp *interp); extern "C" int Vtkimagingtcl_Init(Tcl_Interp *interp); extern "C" int Vtkgraphicstcl_Init(Tcl_Interp *interp); extern "C" int Vtkiotcl_Init(Tcl_Interp *interp); #ifdef VTK_USE_RENDERING extern "C" int Vtkrenderingtcl_Init(Tcl_Interp *interp); #if defined(VTK_DISABLE_TK_INIT) && !defined(VTK_USE_COCOA) extern "C" int Vtktkrenderwidget_Init(Tcl_Interp *interp); extern "C" int Vtktkimageviewerwidget_Init(Tcl_Interp *interp); #endif #endif #ifdef VTK_USE_PATENTED extern "C" int Vtkpatentedtcl_Init(Tcl_Interp *interp); #endif #ifdef VTK_USE_HYBRID extern "C" int Vtkhybridtcl_Init(Tcl_Interp *interp); #endif #ifdef VTK_USE_PARALLEL extern "C" int Vtkparalleltcl_Init(Tcl_Interp *interp); #endif void help() { } int Tcl_AppInit(Tcl_Interp *interp) { #ifdef __CYGWIN__ Tcl_SetVar(interp, "tclDefaultLibrary", "/usr/share/tcl" TCL_VERSION, TCL_GLOBAL_ONLY); #endif if (Tcl_Init(interp) == TCL_ERROR) { return TCL_ERROR; } #ifdef VTK_USE_RENDERING if (Tk_Init(interp) == TCL_ERROR) { return TCL_ERROR; } #endif /* init the core vtk stuff */ if (Vtkcommontcl_Init(interp) == TCL_ERROR) { return TCL_ERROR; } if (Vtkfilteringtcl_Init(interp) == TCL_ERROR) { return TCL_ERROR; } if (Vtkimagingtcl_Init(interp) == TCL_ERROR) { return TCL_ERROR; } if (Vtkgraphicstcl_Init(interp) == TCL_ERROR) { return TCL_ERROR; } if (Vtkiotcl_Init(interp) == TCL_ERROR) { return TCL_ERROR; } #ifdef VTK_USE_RENDERING if (Vtkrenderingtcl_Init(interp) == TCL_ERROR) { return TCL_ERROR; } #if defined(VTK_DISABLE_TK_INIT) && !defined(VTK_USE_COCOA) // Need to init here because rendering did not when this option is on if (Vtktkrenderwidget_Init(interp) == TCL_ERROR) { return TCL_ERROR; } if (Vtktkimageviewerwidget_Init(interp) == TCL_ERROR) { return TCL_ERROR; } #endif #endif #ifdef VTK_USE_PATENTED if (Vtkpatentedtcl_Init(interp) == TCL_ERROR) { return TCL_ERROR; } #endif #ifdef VTK_USE_HYBRID if (Vtkhybridtcl_Init(interp) == TCL_ERROR) { return TCL_ERROR; } #endif #ifdef VTK_USE_PARALLEL if (Vtkparalleltcl_Init(interp) == TCL_ERROR) { return TCL_ERROR; } #endif /* * Append path to VTK packages to auto_path */ static char script[] = "foreach dir [list {" VTK_TCL_PACKAGE_DIR "} {" VTK_TCL_INSTALL_DIR "}" " [file join [file dirname [file dirname [info nameofexecutable]]] Wrapping Tcl]" " [file join [file dirname [file dirname [info nameofexecutable]]] lib vtk tcl]" " ] {\n" " if {[file isdirectory $dir]} {\n" " lappend auto_path $dir\n" " }\n" "}\n" "rename package package.orig\n" "proc package {args} {\n" " if {[catch {set package_res [eval package.orig $args]} catch_res]} {\n" " global errorInfo env\n" " if {[lindex $args 0] == \"require\"} {\n" " set expecting {can\'t find package vtk}\n" " if {![string compare -length [string length $expecting] $catch_res $expecting]} {\n" " set msg {The Tcl interpreter was probably not able to find the" " VTK packages. Please check that your TCLLIBPATH environment variable" " includes the path to your VTK Tcl directory. You might find it under" " your VTK binary directory in Wrapping/Tcl, or under your" " site-specific {CMAKE_INSTALL_PREFIX}/lib/vtk/tcl directory.}\n" " if {[info exists env(TCLLIBPATH)]} {\n" " append msg \" The TCLLIBPATH current value is: $env(TCLLIBPATH).\"\n" " }\n" " set errorInfo \"$msg The TCLLIBPATH variable is a set of" " space separated paths (hence, path containing spaces should be" " surrounded by quotes first). Windows users should use forward" " (Unix-style) slashes \'/\' instead of the usual backward slashes. " " More informations can be found in the Wrapping/Tcl/README source" " file (also available online at" " http://www.vtk.org/cgi-bin/cvsweb.cgi/~checkout~/VTK/Wrapping/Tcl/README).\n" "$errorInfo\"\n" " }\n" " }\n" " error $catch_res $errorInfo\n" " }\n" " return $package_res\n" "}\n"; Tcl_Eval(interp, script); /* * Specify a user-specific startup file to invoke if the application * is run interactively. Typically the startup file is "~/.apprc" * where "app" is the name of the application. If this line is deleted * then no user-specific startup file will be run under any conditions. */ Tcl_SetVar(interp, (char *) "tcl_rcFileName", (char *) "~/.vtkrc", TCL_GLOBAL_ONLY); return TCL_OK; } // For a DEBUG build on MSVC, add a hook to prevent error dialogs when // being run from DART. #if defined(_MSC_VER) && defined(_DEBUG) # include <crtdbg.h> static int vtkTkAppInitDebugReport(int, char* message, int*) { fprintf(stderr, message); exit(1); } void vtkTkAppInitEnableMSVCDebugHook() { if(getenv("DART_TEST_FROM_DART")) { _CrtSetReportHook(vtkTkAppInitDebugReport); } } #else void vtkTkAppInitEnableMSVCDebugHook() { } #endif <commit_msg>FIX: help Tcl/Tk finding its support files when building VTK against Tcl/Tk *static*. If TCL_LIBRARY or TK_LIBRARY are not defined, search inside [path to vtk.exe]/TclTk/lib, which will be populated in the future (or right now by ParaViewComplete)<commit_after>/*========================================================================= Program: Visualization Toolkit Module: vtkTkAppInit.cxx Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen All rights reserved. See Copyright.txt or http://www.kitware.com/Copyright.htm for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notice for more information. =========================================================================*/ /* * tkAppInit.c -- * * Provides a default version of the Tcl_AppInit procedure for * use in wish and similar Tk-based applications. * * Copyright (c) 1993 The Regents of the University of California. * Copyright (c) 1994 Sun Microsystems, Inc. * * See the file "license.terms" for information on usage and redistribution * of this file, and for a DISCLAIMER OF ALL WARRANTIES. */ #ifdef VTK_COMPILED_USING_MPI # include <mpi.h> # include "vtkMPIController.h" #endif // VTK_COMPILED_USING_MPI #include "vtkSystemIncludes.h" #include "vtkToolkits.h" #include "Wrapping/Tcl/vtkTkAppInitConfigure.h" #ifdef VTK_TCL_TK_STATIC #include <sys/stat.h> #endif #if defined(CMAKE_INTDIR) # define VTK_TCL_PACKAGE_DIR VTK_TCL_PACKAGE_DIR_BUILD "/" CMAKE_INTDIR #else # define VTK_TCL_PACKAGE_DIR VTK_TCL_PACKAGE_DIR_BUILD #endif #ifdef VTK_USE_RENDERING # include "vtkTk.h" #else # include "vtkTcl.h" #endif /* * Make sure all the kits register their classes with vtkInstantiator. */ #include "vtkCommonInstantiator.h" #include "vtkFilteringInstantiator.h" #include "vtkIOInstantiator.h" #include "vtkImagingInstantiator.h" #include "vtkGraphicsInstantiator.h" #ifdef VTK_USE_RENDERING #include "vtkRenderingInstantiator.h" #endif #ifdef VTK_USE_PATENTED #include "vtkPatentedInstantiator.h" #endif #ifdef VTK_USE_HYBRID #include "vtkHybridInstantiator.h" #endif #ifdef VTK_USE_PARALLEL #include "vtkParallelInstantiator.h" #endif static void vtkTkAppInitEnableMSVCDebugHook(); /* *---------------------------------------------------------------------- * * main -- * * This is the main program for the application. * * Results: * None: Tk_Main never returns here, so this procedure never * returns either. * * Side effects: * Whatever the application does. * *---------------------------------------------------------------------- */ #ifdef VTK_COMPILED_USING_MPI class vtkMPICleanup { public: vtkMPICleanup() { this->Controller = 0; } void Initialize(int *argc, char ***argv) { MPI_Init(argc, argv); this->Controller = vtkMPIController::New(); this->Controller->Initialize(argc, argv, 1); vtkMultiProcessController::SetGlobalController(this->Controller); } ~vtkMPICleanup() { if ( this->Controller ) { this->Controller->Finalize(); this->Controller->Delete(); } } private: vtkMPIController *Controller; }; static vtkMPICleanup VTKMPICleanup; #endif // VTK_COMPILED_USING_MPI int main(int argc, char **argv) { ios::sync_with_stdio(); vtkTkAppInitEnableMSVCDebugHook(); #ifdef VTK_COMPILED_USING_MPI VTKMPICleanup.Initialize(&argc, &argv); #endif // VTK_COMPILED_USING_MPI // This is mandatory *now*, it does more than just finding the executable // (like finding the encodings, setting variables depending on the value // of TCL_LIBRARY, TK_LIBRARY Tcl_FindExecutable(argv[0]); #ifdef VTK_USE_RENDERING Tk_Main(argc, argv, Tcl_AppInit); #else Tcl_Main(argc, argv, Tcl_AppInit); #endif return 0; /* Needed only to prevent compiler warning. */ } /* *---------------------------------------------------------------------- * * Tcl_AppInit -- * * This procedure performs application-specific initialization. * Most applications, especially those that incorporate additional * packages, will have their own version of this procedure. * * Results: * Returns a standard Tcl completion code, and leaves an error * message in interp->result if an error occurs. * * Side effects: * Depends on the startup script. * *---------------------------------------------------------------------- */ extern "C" int Vtkcommontcl_Init(Tcl_Interp *interp); extern "C" int Vtkfilteringtcl_Init(Tcl_Interp *interp); extern "C" int Vtkimagingtcl_Init(Tcl_Interp *interp); extern "C" int Vtkgraphicstcl_Init(Tcl_Interp *interp); extern "C" int Vtkiotcl_Init(Tcl_Interp *interp); #ifdef VTK_USE_RENDERING extern "C" int Vtkrenderingtcl_Init(Tcl_Interp *interp); #if defined(VTK_DISABLE_TK_INIT) && !defined(VTK_USE_COCOA) extern "C" int Vtktkrenderwidget_Init(Tcl_Interp *interp); extern "C" int Vtktkimageviewerwidget_Init(Tcl_Interp *interp); #endif #endif #ifdef VTK_USE_PATENTED extern "C" int Vtkpatentedtcl_Init(Tcl_Interp *interp); #endif #ifdef VTK_USE_HYBRID extern "C" int Vtkhybridtcl_Init(Tcl_Interp *interp); #endif #ifdef VTK_USE_PARALLEL extern "C" int Vtkparalleltcl_Init(Tcl_Interp *interp); #endif void help() { } #ifdef VTK_TCL_TK_STATIC int vtkTkAppInitFileExists(const char *filename) { struct stat fs; return (filename && !stat(filename, &fs)) ? 1 : 0; } const char* vtkTkAppInitGetFilenamePath(const char *filename, char *path) { if (!path) { return path; } if (!filename || !strlen(filename)) { path[0] = '\0'; return path; } const char *ptr = filename + strlen(filename) - 1; while (ptr > filename && *ptr != '/' && *ptr != '\\') { ptr--; } size_t length = ptr - filename; if (length) { strncpy(path, filename, length); } path[length] = '\0'; return path; } const char* vtkTkAppInitConvertToUnixSlashes(const char* path, char *unix_path) { if (!unix_path) { return unix_path; } unix_path[0] = '\0'; if (!path) { return unix_path; } if (path[0] == '~') { const char* home = getenv("HOME"); if(home) { strcpy(unix_path, home); } } strcat(unix_path, path); size_t length = strlen(unix_path); if (length < 1) { return unix_path; } size_t i; for (i = 0; i < length; ++i) { if(unix_path[i] == '\\') { unix_path[i] = '/'; } } if (unix_path[length - 1] == '/') { unix_path[length - 1] = '\0'; } return unix_path; } #endif int Tcl_AppInit(Tcl_Interp *interp) { #ifdef __CYGWIN__ Tcl_SetVar(interp, "tclDefaultLibrary", "/usr/share/tcl" TCL_VERSION, TCL_GLOBAL_ONLY); #endif /* Tcl/Tk requires support files to work (set of tcl files). When an app is linked against Tcl/Tk shared libraries, the path to the libraries is used by Tcl/Tk to search for its support files. For example, on Windows, if bin/tcl84.dll is the shared lib, support files will be searched in bin/../lib/tcl8.4, which is where they are usually installed. If an app is linked against Tcl/Tk *static* libraries, there is no way for Tcl/Tk to find its support files. In that case, it will use the TCL_LIBRARY and TK_LIBRARY environment variable (those should point to the support files dir, ex: c:/tcl/lib/tcl8.4, c:/tk/lib/tcl8.4). The above code will also make Tcl/Tk search inside VTK's build/install directory, more precisely inside a TclTk/lib sub dir. ex: [path to vtk.exe]/TclTk/lib/tcl8.4, [path to vtk.exe]/TclTk/lib/tk8.4 If we provide support files in the future, or if they are provided by turn-key apps (ParaView or VolView), this is where they are going to be copied. */ #ifdef VTK_TCL_TK_STATIC int has_tcllibpath_env = getenv("TCL_LIBRARY") ? 1 : 0; int has_tklibpath_env = getenv("TK_LIBRARY") ? 1 : 0; if (!has_tcllibpath_env || !has_tklibpath_env) { const char *nameofexec = Tcl_GetNameOfExecutable(); if (nameofexec && vtkTkAppInitFileExists(nameofexec)) { char dir[1024], dir_unix[1024], buffer[1024]; vtkTkAppInitGetFilenamePath(nameofexec, dir); vtkTkAppInitConvertToUnixSlashes(dir, dir_unix); sprintf(buffer, "%s/TclTk", dir_unix); if (vtkTkAppInitFileExists(buffer)) { if (!has_tcllibpath_env) { char tcl_library[1024] = ""; sprintf(tcl_library, "%s/lib/tcl%s", buffer, TCL_VERSION); if (vtkTkAppInitFileExists(tcl_library)) { // Setting TCL_LIBRARY won't do the trick, it's too late Tcl_SetVar(interp, "tcl_library", tcl_library, TCL_GLOBAL_ONLY | TCL_LEAVE_ERR_MSG); } } #ifdef VTK_USE_RENDERING if (!has_tklibpath_env) { char tk_library[1024] = ""; sprintf(tk_library, "%s/lib/tk%s", buffer, TK_VERSION); if (vtkTkAppInitFileExists(tk_library)) { // Setting TK_LIBRARY won't do the trick, it's too late Tcl_SetVar(interp, "tk_library", tk_library, TCL_GLOBAL_ONLY | TCL_LEAVE_ERR_MSG); } } #endif } } } #endif if (Tcl_Init(interp) == TCL_ERROR) { return TCL_ERROR; } #ifdef VTK_USE_RENDERING if (Tk_Init(interp) == TCL_ERROR) { return TCL_ERROR; } #endif /* init the core vtk stuff */ if (Vtkcommontcl_Init(interp) == TCL_ERROR) { return TCL_ERROR; } if (Vtkfilteringtcl_Init(interp) == TCL_ERROR) { return TCL_ERROR; } if (Vtkimagingtcl_Init(interp) == TCL_ERROR) { return TCL_ERROR; } if (Vtkgraphicstcl_Init(interp) == TCL_ERROR) { return TCL_ERROR; } if (Vtkiotcl_Init(interp) == TCL_ERROR) { return TCL_ERROR; } #ifdef VTK_USE_RENDERING if (Vtkrenderingtcl_Init(interp) == TCL_ERROR) { return TCL_ERROR; } #if defined(VTK_DISABLE_TK_INIT) && !defined(VTK_USE_COCOA) // Need to init here because rendering did not when this option is on if (Vtktkrenderwidget_Init(interp) == TCL_ERROR) { return TCL_ERROR; } if (Vtktkimageviewerwidget_Init(interp) == TCL_ERROR) { return TCL_ERROR; } #endif #endif #ifdef VTK_USE_PATENTED if (Vtkpatentedtcl_Init(interp) == TCL_ERROR) { return TCL_ERROR; } #endif #ifdef VTK_USE_HYBRID if (Vtkhybridtcl_Init(interp) == TCL_ERROR) { return TCL_ERROR; } #endif #ifdef VTK_USE_PARALLEL if (Vtkparalleltcl_Init(interp) == TCL_ERROR) { return TCL_ERROR; } #endif /* * Append path to VTK packages to auto_path */ static char script[] = "foreach dir [list {" VTK_TCL_PACKAGE_DIR "} {" VTK_TCL_INSTALL_DIR "}" " [file join [file dirname [file dirname [info nameofexecutable]]] Wrapping Tcl]" " [file join [file dirname [file dirname [info nameofexecutable]]] lib vtk tcl]" " ] {\n" " if {[file isdirectory $dir]} {\n" " lappend auto_path $dir\n" " }\n" "}\n" "rename package package.orig\n" "proc package {args} {\n" " if {[catch {set package_res [eval package.orig $args]} catch_res]} {\n" " global errorInfo env\n" " if {[lindex $args 0] == \"require\"} {\n" " set expecting {can\'t find package vtk}\n" " if {![string compare -length [string length $expecting] $catch_res $expecting]} {\n" " set msg {The Tcl interpreter was probably not able to find the" " VTK packages. Please check that your TCLLIBPATH environment variable" " includes the path to your VTK Tcl directory. You might find it under" " your VTK binary directory in Wrapping/Tcl, or under your" " site-specific {CMAKE_INSTALL_PREFIX}/lib/vtk/tcl directory.}\n" " if {[info exists env(TCLLIBPATH)]} {\n" " append msg \" The TCLLIBPATH current value is: $env(TCLLIBPATH).\"\n" " }\n" " set errorInfo \"$msg The TCLLIBPATH variable is a set of" " space separated paths (hence, path containing spaces should be" " surrounded by quotes first). Windows users should use forward" " (Unix-style) slashes \'/\' instead of the usual backward slashes. " " More informations can be found in the Wrapping/Tcl/README source" " file (also available online at" " http://www.vtk.org/cgi-bin/cvsweb.cgi/~checkout~/VTK/Wrapping/Tcl/README).\n" "$errorInfo\"\n" " }\n" " }\n" " error $catch_res $errorInfo\n" " }\n" " return $package_res\n" "}\n"; Tcl_Eval(interp, script); /* * Specify a user-specific startup file to invoke if the application * is run interactively. Typically the startup file is "~/.apprc" * where "app" is the name of the application. If this line is deleted * then no user-specific startup file will be run under any conditions. */ Tcl_SetVar(interp, (char *) "tcl_rcFileName", (char *) "~/.vtkrc", TCL_GLOBAL_ONLY); return TCL_OK; } // For a DEBUG build on MSVC, add a hook to prevent error dialogs when // being run from DART. #if defined(_MSC_VER) && defined(_DEBUG) # include <crtdbg.h> static int vtkTkAppInitDebugReport(int, char* message, int*) { fprintf(stderr, message); exit(1); } void vtkTkAppInitEnableMSVCDebugHook() { if(getenv("DART_TEST_FROM_DART")) { _CrtSetReportHook(vtkTkAppInitDebugReport); } } #else void vtkTkAppInitEnableMSVCDebugHook() { } #endif <|endoftext|>
<commit_before>#include <YCommon/Headers/stdincludes.h> #include "StringTable.h" #include <YCommon/YContainers/AtomicHashTable.h> namespace YEngine { namespace YCore { namespace { YCommon::YContainers::AtomicHashTable gHashTable; size_t max_string_size = 0; } size_t GetAllocationSize(size_t max_string_size, size_t table_size) { return YCommon::YContainers::AtomicHashTable::GetAllocationSize( table_size, max_string_size); } void StringTable::Initialize(size_t max_string_size, size_t table_size, void* buffer, size_t buffer_size) { gHashTable.Init(buffer, buffer_size, table_size, max_string_size); max_string_size = max_string_size; } void StringTable::Terminate() { gHashTable.Reset(); max_string_size = 0; } uint64_t StringTable::AddString(const char* string, size_t string_size) { YDEBUG_CHECK(string_size <= max_string_size, "Cannot exceed maximum string size: %u > %u", static_cast<uint32_t>(string_size), static_cast<uint32_t>(max_string_size)); uint64_t hash_key = 0; gHashTable.Insert(string, string_size, string, string_size, &hash_key); return hash_key; } const char* StringTable::StringLookup(uint64_t string_hash) { const void* value = gHashTable.GetValue(string_hash); YDEBUG_CHECK(value != NULL, "Cannot lookup string which does not exist!"); return static_cast<const char*>(value); } }} // namespace YEngine { namespace YCore { <commit_msg>Fixed string table initialization.<commit_after>#include <YCommon/Headers/stdincludes.h> #include "StringTable.h" #include <YCommon/YContainers/AtomicHashTable.h> namespace YEngine { namespace YCore { namespace { YCommon::YContainers::AtomicHashTable gHashTable; size_t gMaxStringSize = 0; } size_t GetAllocationSize(size_t max_string_size, size_t table_size) { return YCommon::YContainers::AtomicHashTable::GetAllocationSize( table_size, max_string_size); } void StringTable::Initialize(size_t max_string_size, size_t table_size, void* buffer, size_t buffer_size) { YDEBUG_CHECK(max_string_size > 0 && table_size > 0, "Invalid StringTable initialization values."); gHashTable.Init(buffer, buffer_size, table_size, max_string_size); gMaxStringSize = max_string_size; } void StringTable::Terminate() { gHashTable.Reset(); gMaxStringSize = 0; } uint64_t StringTable::AddString(const char* string, size_t string_size) { YDEBUG_CHECK(string_size <= gMaxStringSize, "Cannot exceed maximum string size: %u > %u", static_cast<uint32_t>(string_size), static_cast<uint32_t>(gMaxStringSize)); uint64_t hash_key = 0; gHashTable.Insert(string, string_size, string, string_size, &hash_key); return hash_key; } const char* StringTable::StringLookup(uint64_t string_hash) { const void* value = gHashTable.GetValue(string_hash); YDEBUG_CHECK(value != NULL, "Cannot lookup string which does not exist!"); return static_cast<const char*>(value); } }} // namespace YEngine { namespace YCore { <|endoftext|>
<commit_before>#include "CSourceParser.h" #include <iostream> #include <antlr3.h> #include <CLexer.h> #include <CParser.h> #include <stdio.h> CSourceParser::CSourceParser() { } CSourceParser::~CSourceParser() { } void CSourceParser::Parse(std::string fileName) { ANTLR3_UINT8 *fName = (pANTLR3_UINT8)fileName.c_str(); ANTLR3_INPUT_STREAM *input = antlr3FileStreamNew(fName, ANTLR3_ENC_UTF8); if (input == NULL) { ANTLR3_FPRINTF(stderr, "Unable to open file %s.\n", (char *)fName); exit(ANTLR3_ERR_NOMEM); } CLexer *lxr = CLexerNew(input); // CLexerNew is generated by ANTLR if (lxr == NULL) { ANTLR3_FPRINTF(stderr, "Unable to create the lexer due to malloc() failure1\n"); exit(ANTLR3_ERR_NOMEM); } ANTLR3_COMMON_TOKEN_STREAM *tstream = antlr3CommonTokenStreamSourceNew(ANTLR3_SIZE_HINT, TOKENSOURCE(lxr)); if (tstream == NULL) { ANTLR3_FPRINTF(stderr, "Out of memory trying to allocate token stream\n"); exit(ANTLR3_ERR_NOMEM); } CParser *psr = CParserNew(tstream); CompilationContext::GetInstance()->CurrentParser = psr->pParser; CompilationContext::GetInstance()->CodeDom = psr->translation_unit(psr); CompilationContext::GetInstance()->CurrentParser = NULL; psr ->free(psr); psr = NULL; tstream ->free(tstream); tstream = NULL; lxr ->free(lxr); lxr = NULL; input ->close(input); input = NULL; } <commit_msg>add option to print more information if -g is enabled<commit_after>#include "CSourceParser.h" #include <iostream> #include <antlr3.h> #include <CLexer.h> #include <CParser.h> #include <stdio.h> CSourceParser::CSourceParser() { } CSourceParser::~CSourceParser() { } void CSourceParser::Parse(std::string fileName) { ANTLR3_UINT8 *fName = (pANTLR3_UINT8)fileName.c_str(); ANTLR3_INPUT_STREAM *input = antlr3FileStreamNew(fName, ANTLR3_ENC_UTF8); if (input == NULL) { ANTLR3_FPRINTF(stderr, "Unable to open file %s.\n", (char *)fName); exit(ANTLR3_ERR_NOMEM); } CLexer *lxr = CLexerNew(input); // CLexerNew is generated by ANTLR if (lxr == NULL) { ANTLR3_FPRINTF(stderr, "Unable to create the lexer due to malloc() failure1\n"); exit(ANTLR3_ERR_NOMEM); } if(CompilationContext::GetInstance()->Debug) std::cout << "Calling altlr3CommonTokenStreamSourceNew..." << std::endl; ANTLR3_COMMON_TOKEN_STREAM *tstream = antlr3CommonTokenStreamSourceNew(ANTLR3_SIZE_HINT, TOKENSOURCE(lxr)); if (tstream == NULL) { ANTLR3_FPRINTF(stderr, "Out of memory trying to allocate token stream\n"); exit(ANTLR3_ERR_NOMEM); } if(CompilationContext::GetInstance()->Debug) std::cout << "Called altlr3CommonTokenStreamSourceNew..." << std::endl; CParser *psr = CParserNew(tstream); CompilationContext::GetInstance()->CurrentParser = psr->pParser; if(CompilationContext::GetInstance()->Debug) { printf("Parse: calling translation_unit...\n"); } CompilationContext::GetInstance()->CodeDom = psr->translation_unit(psr); CompilationContext::GetInstance()->CurrentParser = NULL; if(CompilationContext::GetInstance()->Debug) { printf("Parse: cleanup\n"); } psr ->free(psr); psr = NULL; tstream ->free(tstream); tstream = NULL; lxr ->free(lxr); lxr = NULL; input ->close(input); input = NULL; if(CompilationContext::GetInstance()->Debug) { printf("finished Parse\n"); } } <|endoftext|>
<commit_before>//* This file is part of the MOOSE framework //* https://www.mooseframework.org //* //* All rights reserved, see COPYRIGHT for full restrictions //* https://github.com/idaholab/moose/blob/master/COPYRIGHT //* //* Licensed under LGPL 2.1, please see LICENSE for details //* https://www.gnu.org/licenses/lgpl-2.1.html #include "PolycrystalVariablesAction.h" #include "AddVariableAction.h" #include "Conversion.h" #include "Factory.h" #include "FEProblem.h" #include "libmesh/string_to_enum.h" registerMooseAction("PhaseFieldApp", PolycrystalVariablesAction, "add_variable"); template <> InputParameters validParams<PolycrystalVariablesAction>() { InputParameters params = validParams<Action>(); params.addClassDescription("Set up order parameter variables for a polycrystal simulation"); // Get MooseEnums for the possible order/family options for this variable MooseEnum families(AddVariableAction::getNonlinearVariableFamilies()); MooseEnum orders(AddVariableAction::getNonlinearVariableOrders()); params.addParam<MooseEnum>("family", families, "Specifies the family of FE " "shape function to use for the order parameters"); params.addParam<MooseEnum>("order", orders, "Specifies the order of the FE " "shape function to use for the order parameters"); params.addParam<Real>("scaling", 1.0, "Specifies a scaling factor to apply to this variable"); params.addRequiredParam<unsigned int>("op_num", "specifies the number of order parameters to create"); params.addRequiredParam<std::string>("var_name_base", "specifies the base name of the variables"); return params; } PolycrystalVariablesAction::PolycrystalVariablesAction(const InputParameters & params) : Action(params), _op_num(getParam<unsigned int>("op_num")), _var_name_base(getParam<std::string>("var_name_base")) { } void PolycrystalVariablesAction::act() { // Loop through the number of order parameters for (unsigned int op = 0; op < _op_num; op++) { // Create variable names std::string var_name = _var_name_base + Moose::stringify(op); // Add the variable _problem->addVariable(var_name, FEType(Utility::string_to_enum<Order>(getParam<MooseEnum>("order")), Utility::string_to_enum<FEFamily>(getParam<MooseEnum>("family"))), getParam<Real>("scaling")); } } <commit_msg>Add initial from file option (#12294)<commit_after>//* This file is part of the MOOSE framework //* https://www.mooseframework.org //* //* All rights reserved, see COPYRIGHT for full restrictions //* https://github.com/idaholab/moose/blob/master/COPYRIGHT //* //* Licensed under LGPL 2.1, please see LICENSE for details //* https://www.gnu.org/licenses/lgpl-2.1.html #include "PolycrystalVariablesAction.h" #include "AddVariableAction.h" #include "Conversion.h" #include "Factory.h" #include "FEProblem.h" #include "NonlinearSystemBase.h" #include "libmesh/string_to_enum.h" registerMooseAction("PhaseFieldApp", PolycrystalVariablesAction, "add_variable"); registerMooseAction("PhaseFieldApp", PolycrystalVariablesAction, "copy_nodal_vars"); registerMooseAction("PhaseFieldApp", PolycrystalVariablesAction, "check_copy_nodal_vars"); template <> InputParameters validParams<PolycrystalVariablesAction>() { InputParameters params = validParams<Action>(); params.addClassDescription("Set up order parameter variables for a polycrystal simulation"); // Get MooseEnums for the possible order/family options for this variable MooseEnum families(AddVariableAction::getNonlinearVariableFamilies()); MooseEnum orders(AddVariableAction::getNonlinearVariableOrders()); params.addParam<MooseEnum>("family", families, "Specifies the family of FE " "shape function to use for the order parameters"); params.addParam<MooseEnum>("order", orders, "Specifies the order of the FE " "shape function to use for the order parameters"); params.addParam<bool>( "initial_from_file", false, "Take the initial condition of all polycrystal variables from the mesh file"); params.addParam<Real>("scaling", 1.0, "Specifies a scaling factor to apply to this variable"); params.addRequiredParam<unsigned int>("op_num", "specifies the number of order parameters to create"); params.addRequiredParam<std::string>("var_name_base", "specifies the base name of the variables"); return params; } PolycrystalVariablesAction::PolycrystalVariablesAction(const InputParameters & params) : Action(params), _op_num(getParam<unsigned int>("op_num")), _var_name_base(getParam<std::string>("var_name_base")) { } void PolycrystalVariablesAction::act() { // take initial values from file? bool initial_from_file = getParam<bool>("initial_from_file"); // Loop through the number of order parameters for (unsigned int op = 0; op < _op_num; op++) { // Create variable names std::string var_name = _var_name_base + Moose::stringify(op); // Add the variable if (_current_task == "add_variable") { _problem->addVariable( var_name, FEType(Utility::string_to_enum<Order>(getParam<MooseEnum>("order")), Utility::string_to_enum<FEFamily>(getParam<MooseEnum>("family"))), getParam<Real>("scaling")); } // Setup initial from file if requested if (initial_from_file) { if (_current_task == "check_copy_nodal_vars") _app.setFileRestart() = true; if (_current_task == "copy_nodal_vars") { auto * system = &_problem->getNonlinearSystemBase(); system->addVariableToCopy(var_name, var_name, "LATEST"); } } } } <|endoftext|>
<commit_before>/****************************************************************************** * Copyright 2017 The Apollo Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************/ /** * @file trajectory_stitcher.cc **/ #include "modules/planning/trajectory_stitcher/trajectory_stitcher.h" #include <algorithm> #include "modules/common/log.h" #include "modules/planning/common/planning_gflags.h" #include "modules/planning/math/double.h" namespace apollo { namespace planning { using VehicleState = apollo::common::VehicleState; namespace { std::vector<common::TrajectoryPoint> compute_reinit_stitching_trajectory() { common::TrajectoryPoint init_point; init_point.mutable_path_point()->set_x(VehicleState::instance()->x()); init_point.mutable_path_point()->set_y(VehicleState::instance()->y()); init_point.mutable_path_point()->set_z(VehicleState::instance()->z()); init_point.mutable_path_point()->set_theta( VehicleState::instance()->heading()); init_point.mutable_path_point()->set_kappa(VehicleState::instance()->kappa()); init_point.set_v(VehicleState::instance()->linear_velocity()); init_point.set_a(VehicleState::instance()->linear_acceleration()); init_point.set_relative_time(0.0); DCHECK(!std::isnan(init_point.path_point().x())); DCHECK(!std::isnan(init_point.path_point().y())); DCHECK(!std::isnan(init_point.path_point().z())); DCHECK(!std::isnan(init_point.path_point().theta())); DCHECK(!std::isnan(init_point.path_point().kappa())); DCHECK(!std::isnan(init_point.v())); DCHECK(!std::isnan(init_point.a())); return std::vector<common::TrajectoryPoint>(1, init_point); } } // Planning from current vehicle state: // if 1. the auto-driving mode is off or // 2. we don't have the trajectory from last planning cycle or // 3. the position deviation from actual and target is too high std::vector<common::TrajectoryPoint> TrajectoryStitcher::ComputeStitchingTrajectory( const bool is_on_auto_mode, const double current_timestamp, const double planning_cycle_time, const PublishableTrajectory& prev_trajectory) { if (!is_on_auto_mode) { return compute_reinit_stitching_trajectory(); } std::size_t prev_trajectory_size = prev_trajectory.NumOfPoints(); if (prev_trajectory_size == 0) { AWARN << "Projected trajectory at time [" << prev_trajectory.header_time() << "] size is zero! Previous planning not exist or failed. Use " "origin car status instead."; return compute_reinit_stitching_trajectory(); } const double veh_rel_time = current_timestamp - prev_trajectory.header_time(); std::size_t matched_index = prev_trajectory.QueryNearestPoint(veh_rel_time); if (matched_index == prev_trajectory_size) { AWARN << "The previous trajectory is not long enough, something is wrong"; return compute_reinit_stitching_trajectory(); } if (matched_index == 0 && veh_rel_time < prev_trajectory.StartPoint().relative_time()) { AWARN << "the previous trajectory doesn't cover current time"; return compute_reinit_stitching_trajectory(); } auto matched_point = prev_trajectory.TrajectoryPointAt(matched_index); const double position_diff = common::math::Vec2d( matched_point.path_point().x() - VehicleState::instance()->x(), matched_point.path_point().y() - VehicleState::instance()->y()) .Length(); if (position_diff > FLAGS_replan_distance_threshold) { AWARN << "the distance between matched point and actual position is too " "large"; return compute_reinit_stitching_trajectory(); } double forward_rel_time = veh_rel_time + planning_cycle_time; std::size_t forward_index = prev_trajectory.QueryNearestPoint(forward_rel_time); std::vector<common::TrajectoryPoint> stitching_trajectory( prev_trajectory.trajectory_points().begin() + matched_index, prev_trajectory.trajectory_points().begin() + forward_index + 1); double zero_time = prev_trajectory.TrajectoryPointAt(matched_index).relative_time(); std::for_each(stitching_trajectory.begin(), stitching_trajectory.end(), [&zero_time](common::TrajectoryPoint& tp) { tp.set_relative_time(tp.relative_time() - zero_time); }); double zero_s = prev_trajectory.TrajectoryPointAt(forward_index).path_point().s(); std::for_each(stitching_trajectory.begin(), stitching_trajectory.end(), [&zero_s](common::TrajectoryPoint& tp) { double s = tp.path_point().s(); tp.mutable_path_point()->set_s(s - zero_s); }); return stitching_trajectory; } } // namespace planning } // namespace apollo <commit_msg>planning: trajectory stitcher coding style fix.<commit_after>/****************************************************************************** * Copyright 2017 The Apollo Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************/ /** * @file trajectory_stitcher.cc **/ #include "modules/planning/trajectory_stitcher/trajectory_stitcher.h" #include <algorithm> #include "modules/common/log.h" #include "modules/planning/common/planning_gflags.h" #include "modules/planning/math/double.h" namespace apollo { namespace planning { using VehicleState = apollo::common::VehicleState; namespace { std::vector<common::TrajectoryPoint> ComputeReinitStitchingTrajectory() { common::TrajectoryPoint init_point; init_point.mutable_path_point()->set_x(VehicleState::instance()->x()); init_point.mutable_path_point()->set_y(VehicleState::instance()->y()); init_point.mutable_path_point()->set_z(VehicleState::instance()->z()); init_point.mutable_path_point()->set_theta( VehicleState::instance()->heading()); init_point.mutable_path_point()->set_kappa(VehicleState::instance()->kappa()); init_point.set_v(VehicleState::instance()->linear_velocity()); init_point.set_a(VehicleState::instance()->linear_acceleration()); init_point.set_relative_time(0.0); DCHECK(!std::isnan(init_point.path_point().x())); DCHECK(!std::isnan(init_point.path_point().y())); DCHECK(!std::isnan(init_point.path_point().z())); DCHECK(!std::isnan(init_point.path_point().theta())); DCHECK(!std::isnan(init_point.path_point().kappa())); DCHECK(!std::isnan(init_point.v())); DCHECK(!std::isnan(init_point.a())); return std::vector<common::TrajectoryPoint>(1, init_point); } } // Planning from current vehicle state: // if 1. the auto-driving mode is off or // 2. we don't have the trajectory from last planning cycle or // 3. the position deviation from actual and target is too high std::vector<common::TrajectoryPoint> TrajectoryStitcher::ComputeStitchingTrajectory( const bool is_on_auto_mode, const double current_timestamp, const double planning_cycle_time, const PublishableTrajectory& prev_trajectory) { if (!is_on_auto_mode) { return ComputeReinitStitchingTrajectory(); } std::size_t prev_trajectory_size = prev_trajectory.NumOfPoints(); if (prev_trajectory_size == 0) { AWARN << "Projected trajectory at time [" << prev_trajectory.header_time() << "] size is zero! Previous planning not exist or failed. Use " "origin car status instead."; return ComputeReinitStitchingTrajectory(); } const double veh_rel_time = current_timestamp - prev_trajectory.header_time(); std::size_t matched_index = prev_trajectory.QueryNearestPoint(veh_rel_time); if (matched_index == prev_trajectory_size) { AWARN << "The previous trajectory is not long enough, something is wrong"; return ComputeReinitStitchingTrajectory(); } if (matched_index == 0 && veh_rel_time < prev_trajectory.StartPoint().relative_time()) { AWARN << "the previous trajectory doesn't cover current time"; return ComputeReinitStitchingTrajectory(); } auto matched_point = prev_trajectory.TrajectoryPointAt(matched_index); const double position_diff = common::math::Vec2d( matched_point.path_point().x() - VehicleState::instance()->x(), matched_point.path_point().y() - VehicleState::instance()->y()) .Length(); if (position_diff > FLAGS_replan_distance_threshold) { AWARN << "the distance between matched point and actual position is too " "large"; return ComputeReinitStitchingTrajectory(); } double forward_rel_time = veh_rel_time + planning_cycle_time; std::size_t forward_index = prev_trajectory.QueryNearestPoint(forward_rel_time); std::vector<common::TrajectoryPoint> stitching_trajectory( prev_trajectory.trajectory_points().begin() + matched_index, prev_trajectory.trajectory_points().begin() + forward_index + 1); double zero_time = prev_trajectory.TrajectoryPointAt(matched_index).relative_time(); std::for_each(stitching_trajectory.begin(), stitching_trajectory.end(), [&zero_time](common::TrajectoryPoint& tp) { tp.set_relative_time(tp.relative_time() - zero_time); }); double zero_s = prev_trajectory.TrajectoryPointAt(forward_index).path_point().s(); std::for_each(stitching_trajectory.begin(), stitching_trajectory.end(), [&zero_s](common::TrajectoryPoint& tp) { double s = tp.path_point().s(); tp.mutable_path_point()->set_s(s - zero_s); }); return stitching_trajectory; } } // namespace planning } // namespace apollo <|endoftext|>
<commit_before>/****************************************************************************** * Copyright 2017 The Apollo Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************/ #include "modules/prediction/predictor/sequence/sequence_predictor.h" #include <cmath> #include <limits> #include <memory> #include <utility> #include "modules/common/adapters/proto/adapter_config.pb.h" #include "modules/common/math/vec2d.h" #include "modules/prediction/common/prediction_gflags.h" #include "modules/prediction/common/prediction_map.h" #include "modules/prediction/common/road_graph.h" #include "modules/prediction/container/adc_trajectory/adc_trajectory_container.h" #include "modules/prediction/container/container_manager.h" #include "modules/prediction/container/pose/pose_container.h" namespace apollo { namespace prediction { using ::apollo::common::PathPoint; using ::apollo::common::TrajectoryPoint; using ::apollo::common::adapter::AdapterConfig; using ::apollo::common::math::Vec2d; using ::apollo::hdmap::LaneInfo; void SequencePredictor::Predict(Obstacle* obstacle) { Clear(); CHECK_NOTNULL(obstacle); CHECK_GT(obstacle->history_size(), 0); } void SequencePredictor::Clear() { Predictor::Clear(); } std::string SequencePredictor::ToString(const LaneSequence& sequence) { std::string str_lane_sequence = ""; if (sequence.lane_segment_size() > 0) { str_lane_sequence += sequence.lane_segment(0).lane_id(); } for (int i = 1; i < sequence.lane_segment_size(); ++i) { str_lane_sequence += ("->" + sequence.lane_segment(i).lane_id()); } return str_lane_sequence; } void SequencePredictor::FilterLaneSequences( const LaneGraph& lane_graph, const std::string& lane_id, std::vector<bool>* enable_lane_sequence) { int num_lane_sequence = lane_graph.lane_sequence_size(); std::vector<LaneChangeType> lane_change_type(num_lane_sequence, LaneChangeType::INVALID); std::pair<int, double> change(-1, -1.0); std::pair<int, double> all(-1, -1.0); for (int i = 0; i < num_lane_sequence; ++i) { const LaneSequence& sequence = lane_graph.lane_sequence(i); lane_change_type[i] = GetLaneChangeType(lane_id, sequence); if (lane_change_type[i] != LaneChangeType::LEFT && lane_change_type[i] != LaneChangeType::RIGHT && lane_change_type[i] != LaneChangeType::ONTO_LANE) { ADEBUG "Ignore lane sequence [" << ToString(sequence) << "]."; continue; } // The obstacle has interference with ADC within a small distance double distance = GetLaneChangeDistanceWithADC(sequence); ADEBUG << "Distance to ADC " << std::fixed << std::setprecision(6) << distance; if (distance < FLAGS_lane_change_dist) { (*enable_lane_sequence)[i] = false; ADEBUG << "Filter trajectory [" << ToString(sequence) << "] due to small distance " << distance << "."; } } for (int i = 0; i < num_lane_sequence; ++i) { const LaneSequence& sequence = lane_graph.lane_sequence(i); if (!(*enable_lane_sequence)[i]) { ADEBUG << "Disabled lane sequence [" << ToString(sequence) << "]."; continue; } double probability = sequence.probability(); if (LaneSequenceWithMaxProb(lane_change_type[i], probability, all.second)) { all.first = i; all.second = probability; } if (LaneChangeWithMaxProb(lane_change_type[i], probability, change.second)) { change.first = i; change.second = probability; } } for (int i = 0; i < num_lane_sequence; ++i) { const LaneSequence& sequence = lane_graph.lane_sequence(i); if (!(*enable_lane_sequence)[i]) { ADEBUG << "Disabled lane sequence [" << ToString(sequence) << "]."; continue; } double probability = sequence.probability(); if (probability < FLAGS_lane_sequence_threshold && i != all.first) { (*enable_lane_sequence)[i] = false; } else if (change.first >= 0 && change.first < num_lane_sequence && (lane_change_type[i] == LaneChangeType::LEFT || lane_change_type[i] == LaneChangeType::RIGHT) && lane_change_type[i] != lane_change_type[change.first]) { (*enable_lane_sequence)[i] = false; } } } SequencePredictor::LaneChangeType SequencePredictor::GetLaneChangeType( const std::string& lane_id, const LaneSequence& lane_sequence) { PredictionMap* map = PredictionMap::instance(); if (lane_id.empty()) { return LaneChangeType::ONTO_LANE; } std::string lane_change_id = lane_sequence.lane_segment(0).lane_id(); if (lane_id == lane_change_id) { return LaneChangeType::STRAIGHT; } else { if (map->IsLeftNeighborLane(map->LaneById(lane_change_id), map->LaneById(lane_id))) { return LaneChangeType::LEFT; } else if (map->IsRightNeighborLane(map->LaneById(lane_change_id), map->LaneById(lane_id))) { return LaneChangeType::RIGHT; } } return LaneChangeType::INVALID; } double SequencePredictor::GetLaneChangeDistanceWithADC( const LaneSequence& lane_sequence) { PoseContainer* pose_container = dynamic_cast<PoseContainer*>( ContainerManager::instance()->GetContainer(AdapterConfig::LOCALIZATION)); ADCTrajectoryContainer* adc_container = dynamic_cast<ADCTrajectoryContainer*>( ContainerManager::instance()->GetContainer( AdapterConfig::PLANNING_TRAJECTORY)); CHECK_NOTNULL(pose_container); CHECK_NOTNULL(adc_container); Eigen::Vector2d adc_position; if (pose_container->ToPerceptionObstacle() != nullptr) { adc_position[0] = pose_container->ToPerceptionObstacle()->position().x(); adc_position[1] = pose_container->ToPerceptionObstacle()->position().y(); PredictionMap* map = PredictionMap::instance(); std::string obstacle_lane_id = lane_sequence.lane_segment(0).lane_id(); double obstacle_lane_s = lane_sequence.lane_segment(0).start_s(); double lane_s = 0.0; double lane_l = 0.0; ADEBUG << "Obstacle lane " << obstacle_lane_id << " and s " << obstacle_lane_s; if (map->GetProjection(adc_position, map->LaneById(obstacle_lane_id), &lane_s, &lane_l)) { ADEBUG << "ADC on lane s " << lane_s; return std::fabs(lane_s - obstacle_lane_s); } } return std::numeric_limits<double>::max(); } bool SequencePredictor::LaneSequenceWithMaxProb(const LaneChangeType& type, const double& probability, const double& max_prob) { if (probability > max_prob) { return true; } else { double prob_diff = std::abs(probability - max_prob); if (prob_diff <= std::numeric_limits<double>::epsilon() && type == LaneChangeType::STRAIGHT) { return true; } } return false; } bool SequencePredictor::LaneChangeWithMaxProb(const LaneChangeType& type, const double& probability, const double& max_prob) { if (type == LaneChangeType::LEFT || type == LaneChangeType::RIGHT) { if (probability > max_prob) { return true; } } return false; } } // namespace prediction } // namespace apollo <commit_msg>Prediction: fix adc trajectory overlap<commit_after>/****************************************************************************** * Copyright 2017 The Apollo Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************/ #include "modules/prediction/predictor/sequence/sequence_predictor.h" #include <cmath> #include <limits> #include <memory> #include <utility> #include "modules/common/adapters/proto/adapter_config.pb.h" #include "modules/common/math/vec2d.h" #include "modules/prediction/common/prediction_gflags.h" #include "modules/prediction/common/prediction_map.h" #include "modules/prediction/common/road_graph.h" #include "modules/prediction/container/adc_trajectory/adc_trajectory_container.h" #include "modules/prediction/container/container_manager.h" #include "modules/prediction/container/pose/pose_container.h" namespace apollo { namespace prediction { using ::apollo::common::PathPoint; using ::apollo::common::TrajectoryPoint; using ::apollo::common::adapter::AdapterConfig; using ::apollo::common::math::Vec2d; using ::apollo::hdmap::LaneInfo; void SequencePredictor::Predict(Obstacle* obstacle) { Clear(); CHECK_NOTNULL(obstacle); CHECK_GT(obstacle->history_size(), 0); } void SequencePredictor::Clear() { Predictor::Clear(); } std::string SequencePredictor::ToString(const LaneSequence& sequence) { std::string str_lane_sequence = ""; if (sequence.lane_segment_size() > 0) { str_lane_sequence += sequence.lane_segment(0).lane_id(); } for (int i = 1; i < sequence.lane_segment_size(); ++i) { str_lane_sequence += ("->" + sequence.lane_segment(i).lane_id()); } return str_lane_sequence; } void SequencePredictor::FilterLaneSequences( const LaneGraph& lane_graph, const std::string& lane_id, std::vector<bool>* enable_lane_sequence) { int num_lane_sequence = lane_graph.lane_sequence_size(); std::vector<LaneChangeType> lane_change_type(num_lane_sequence, LaneChangeType::INVALID); std::pair<int, double> change(-1, -1.0); std::pair<int, double> all(-1, -1.0); for (int i = 0; i < num_lane_sequence; ++i) { const LaneSequence& sequence = lane_graph.lane_sequence(i); lane_change_type[i] = GetLaneChangeType(lane_id, sequence); if (lane_change_type[i] != LaneChangeType::LEFT && lane_change_type[i] != LaneChangeType::RIGHT && lane_change_type[i] != LaneChangeType::ONTO_LANE) { ADEBUG "Ignore lane sequence [" << ToString(sequence) << "]."; continue; } // The obstacle has interference with ADC within a small distance double distance = GetLaneChangeDistanceWithADC(sequence); ADEBUG << "Distance to ADC " << std::fixed << std::setprecision(6) << distance; if (distance < FLAGS_lane_change_dist) { (*enable_lane_sequence)[i] = false; ADEBUG << "Filter trajectory [" << ToString(sequence) << "] due to small distance " << distance << "."; } } for (int i = 0; i < num_lane_sequence; ++i) { const LaneSequence& sequence = lane_graph.lane_sequence(i); if (!(*enable_lane_sequence)[i]) { ADEBUG << "Disabled lane sequence [" << ToString(sequence) << "]."; continue; } double probability = sequence.probability(); if (LaneSequenceWithMaxProb(lane_change_type[i], probability, all.second)) { all.first = i; all.second = probability; } if (LaneChangeWithMaxProb(lane_change_type[i], probability, change.second)) { change.first = i; change.second = probability; } } for (int i = 0; i < num_lane_sequence; ++i) { const LaneSequence& sequence = lane_graph.lane_sequence(i); if (!(*enable_lane_sequence)[i]) { ADEBUG << "Disabled lane sequence [" << ToString(sequence) << "]."; continue; } double probability = sequence.probability(); if (probability < FLAGS_lane_sequence_threshold && i != all.first) { (*enable_lane_sequence)[i] = false; } else if (change.first >= 0 && change.first < num_lane_sequence && (lane_change_type[i] == LaneChangeType::LEFT || lane_change_type[i] == LaneChangeType::RIGHT) && lane_change_type[i] != lane_change_type[change.first]) { (*enable_lane_sequence)[i] = false; } } } SequencePredictor::LaneChangeType SequencePredictor::GetLaneChangeType( const std::string& lane_id, const LaneSequence& lane_sequence) { PredictionMap* map = PredictionMap::instance(); if (lane_id.empty()) { return LaneChangeType::ONTO_LANE; } std::string lane_change_id = lane_sequence.lane_segment(0).lane_id(); if (lane_id == lane_change_id) { return LaneChangeType::STRAIGHT; } else { if (map->IsLeftNeighborLane(map->LaneById(lane_change_id), map->LaneById(lane_id))) { return LaneChangeType::LEFT; } else if (map->IsRightNeighborLane(map->LaneById(lane_change_id), map->LaneById(lane_id))) { return LaneChangeType::RIGHT; } } return LaneChangeType::INVALID; } double SequencePredictor::GetLaneChangeDistanceWithADC( const LaneSequence& lane_sequence) { PoseContainer* pose_container = dynamic_cast<PoseContainer*>( ContainerManager::instance()->GetContainer(AdapterConfig::LOCALIZATION)); ADCTrajectoryContainer* adc_container = dynamic_cast<ADCTrajectoryContainer*>( ContainerManager::instance()->GetContainer( AdapterConfig::PLANNING_TRAJECTORY)); CHECK_NOTNULL(pose_container); CHECK_NOTNULL(adc_container); if (!adc_container->HasOverlap(lane_sequence)) { return std::numeric_limits<double>::max(); } Eigen::Vector2d adc_position; if (pose_container->ToPerceptionObstacle() != nullptr) { adc_position[0] = pose_container->ToPerceptionObstacle()->position().x(); adc_position[1] = pose_container->ToPerceptionObstacle()->position().y(); PredictionMap* map = PredictionMap::instance(); std::string obstacle_lane_id = lane_sequence.lane_segment(0).lane_id(); double obstacle_lane_s = lane_sequence.lane_segment(0).start_s(); double lane_s = 0.0; double lane_l = 0.0; ADEBUG << "Obstacle lane " << obstacle_lane_id << " and s " << obstacle_lane_s; if (map->GetProjection(adc_position, map->LaneById(obstacle_lane_id), &lane_s, &lane_l)) { ADEBUG << "ADC on lane s " << lane_s; return std::fabs(lane_s - obstacle_lane_s); } } return std::numeric_limits<double>::max(); } bool SequencePredictor::LaneSequenceWithMaxProb(const LaneChangeType& type, const double& probability, const double& max_prob) { if (probability > max_prob) { return true; } else { double prob_diff = std::abs(probability - max_prob); if (prob_diff <= std::numeric_limits<double>::epsilon() && type == LaneChangeType::STRAIGHT) { return true; } } return false; } bool SequencePredictor::LaneChangeWithMaxProb(const LaneChangeType& type, const double& probability, const double& max_prob) { if (type == LaneChangeType::LEFT || type == LaneChangeType::RIGHT) { if (probability > max_prob) { return true; } } return false; } } // namespace prediction } // namespace apollo <|endoftext|>
<commit_before>/* * Copyright (c) 2011 The WebRTC project authors. All Rights Reserved. * * Use of this source code is governed by a BSD-style license * that can be found in the LICENSE file in the root of the source * tree. An additional intellectual property rights grant can be found * in the file PATENTS. All contributing project authors may * be found in the AUTHORS file in the root of the source tree. */ #include "video_x11_channel.h" #include "critical_section_wrapper.h" #include "trace.h" namespace webrtc { #define DISP_MAX 128 static Display *dispArray[DISP_MAX]; static int dispCount = 0; VideoX11Channel::VideoX11Channel(WebRtc_Word32 id) : _crit(*CriticalSectionWrapper::CreateCriticalSection()), _videoInterpolator(NULL), _display(NULL), _xvport(), _shminfo(), _image(NULL), _window(NULL), _width(DEFAULT_RENDER_FRAME_WIDTH), _height(DEFAULT_RENDER_FRAME_HEIGHT), _outWidth(0), _outHeight(0), _xPos(0), _yPos(0), _prepared(false), _dispCount(0), _buffer(NULL), _Id(id) { } VideoX11Channel::~VideoX11Channel() { if (_prepared) { _crit.Enter(); RemoveRenderer(); _crit.Leave(); } delete &_crit; if (_videoInterpolator) { delete _videoInterpolator; } } WebRtc_Word32 VideoX11Channel::RenderFrame(const WebRtc_UWord32 streamId, VideoFrame& videoFrame) { CriticalSectionScoped cs(_crit); if (_width != (WebRtc_Word32) videoFrame.Width() || _height != (WebRtc_Word32) videoFrame.Height()) { if (FrameSizeChange(videoFrame.Width(), videoFrame.Height(), 1) == -1) { return -1; } } return DeliverFrame(videoFrame.Buffer(), videoFrame.Length(), videoFrame.TimeStamp()); } WebRtc_Word32 VideoX11Channel::FrameSizeChange(WebRtc_Word32 width, WebRtc_Word32 height, WebRtc_Word32 /*numberOfStreams */) { CriticalSectionScoped cs(_crit); if (_prepared) { RemoveRenderer(); } if (CreateLocalRenderer(width, height) == -1) { return -1; } return 0; } WebRtc_Word32 VideoX11Channel::DeliverFrame(unsigned char* buffer, WebRtc_Word32 bufferSize, unsigned WebRtc_Word32 /*timeStamp90kHz*/) { CriticalSectionScoped cs(_crit); if (!_prepared) { return 0; } if (!dispArray[_dispCount]) { return -1; } unsigned char *pBuf = buffer; // convert to RGB32 ConvertI420ToARGB(pBuf, _buffer, _width, _height, 0); // put image in window XShmPutImage(_display, _window, _gc, _image, 0, 0, _xPos, _yPos, _width, _height, True); // very important for the image to update properly! XSync(_display, false); return 0; } WebRtc_Word32 VideoX11Channel::GetFrameSize(WebRtc_Word32& width, WebRtc_Word32& height) { width = _width; height = _height; return 0; } WebRtc_Word32 VideoX11Channel::Init(Window window, float left, float top, float right, float bottom) { WEBRTC_TRACE(kTraceInfo, kTraceVideoRenderer, _Id, "%s", __FUNCTION__); CriticalSectionScoped cs(_crit); _window = window; _left = left; _right = _right; _top = top; _bottom = _bottom; _display = XOpenDisplay(NULL); // Use default display if (!_window || !_display) { return -1; } if (dispCount < DISP_MAX) { dispArray[dispCount] = _display; _dispCount = dispCount; dispCount++; } else { return -1; } if ((1 < left || left < 0) || (1 < top || top < 0) || (1 < right || right < 0) || (1 < bottom || bottom < 0)) { return -1; } // calculate position and size of rendered video int x, y; unsigned int winWidth, winHeight, borderwidth, depth; Window rootret; if (XGetGeometry(_display, _window, &rootret, &x, &y, &winWidth, &winHeight, &borderwidth, &depth) == 0) { return -1; } _xPos = (WebRtc_Word32) (winWidth * left); _yPos = (WebRtc_Word32) (winHeight * top); _outWidth = (WebRtc_Word32) (winWidth * (right - left)); _outHeight = (WebRtc_Word32) (winHeight * (bottom - top)); if (_outWidth % 2) _outWidth++; // the renderer want's sizes that are multiples of two if (_outHeight % 2) _outHeight++; if (CreateLocalRenderer(winWidth, winHeight) == -1) { return -1; } return 0; } WebRtc_Word32 VideoX11Channel::ChangeWindow(Window window) { WEBRTC_TRACE(kTraceInfo, kTraceVideoRenderer, _Id, "%s", __FUNCTION__); CriticalSectionScoped cs(_crit); // Stop the rendering, if we are rendering... RemoveRenderer(); _window = window; // calculate position and size of rendered video int x, y; unsigned int winWidth, winHeight, borderwidth, depth; Window rootret; if (XGetGeometry(_display, _window, &rootret, &x, &y, &winWidth, &winHeight, &borderwidth, &depth) == -1) { return -1; } _xPos = (int) (winWidth * _left); _yPos = (int) (winHeight * _top); _outWidth = (int) (winWidth * (_right - _left)); _outHeight = (int) (winHeight * (_bottom - _top)); if (_outWidth % 2) _outWidth++; // the renderer want's sizes that are multiples of two if (_outHeight % 2) _outHeight++; // Prepare rendering using the if (CreateLocalRenderer(_width, _height) == -1) { return -1; } return 0; } WebRtc_Word32 VideoX11Channel::ReleaseWindow() { WEBRTC_TRACE(kTraceInfo, kTraceVideoRenderer, _Id, "%s", __FUNCTION__); CriticalSectionScoped cs(_crit); RemoveRenderer(); if (_display) { XCloseDisplay(_display); _display = NULL; } return 0; } WebRtc_Word32 VideoX11Channel::CreateLocalRenderer(WebRtc_Word32 width, WebRtc_Word32 height) { WEBRTC_TRACE(kTraceInfo, kTraceVideoRenderer, _Id, "%s", __FUNCTION__); CriticalSectionScoped cs(_crit); if (!_window || !_display) { return -1; } if (_prepared) { WEBRTC_TRACE(kTraceWarning, kTraceVideoRenderer, _Id, "Renderer already prepared, exits."); return -1; } _width = width; _height = height; // create a graphics context in the window _gc = XCreateGC(_display, _window, 0, 0); // create shared memory image _image = XShmCreateImage(_display, CopyFromParent, 24, ZPixmap, NULL, &_shminfo, _width, _height); // this parameter needs to be the same for some reason. _shminfo.shmid = shmget(IPC_PRIVATE, (_image->bytes_per_line * _image->height), IPC_CREAT | 0777); _shminfo.shmaddr = _image->data = (char*) shmat(_shminfo.shmid, 0, 0); _buffer = (unsigned char*) _image->data; _shminfo.readOnly = False; // attach image to display if (!XShmAttach(_display, &_shminfo)) { //printf("XShmAttach failed !\n"); return -1; } _prepared = true; return 0; } WebRtc_Word32 VideoX11Channel::RemoveRenderer() { WEBRTC_TRACE(kTraceInfo, kTraceVideoRenderer, _Id, "%s", __FUNCTION__); if (!_prepared) { return 0; } _prepared = false; // free and closse Xwindow and XShm XShmDetach(_display, &_shminfo); XDestroyImage( _image ); shmdt(_shminfo.shmaddr); XFreeGC(_display, _gc); return 0; } WebRtc_Word32 VideoX11Channel::GetStreamProperties(WebRtc_UWord32& zOrder, float& left, float& top, float& right, float& bottom) const { WEBRTC_TRACE(kTraceInfo, kTraceVideoRenderer, _Id, "%s", __FUNCTION__); zOrder = 0; // no z-order support yet left = _left; top = _top; right = _right; bottom = _bottom; return 0; } } //namespace webrtc <commit_msg>Fix Issue 59. Fix a constructor cast warning in video_X11_channel.cc. http://code.google.com/p/webrtc/issues/detail?id=59. Review URL: http://webrtc-codereview.appspot.com/122002<commit_after>/* * Copyright (c) 2011 The WebRTC project authors. All Rights Reserved. * * Use of this source code is governed by a BSD-style license * that can be found in the LICENSE file in the root of the source * tree. An additional intellectual property rights grant can be found * in the file PATENTS. All contributing project authors may * be found in the AUTHORS file in the root of the source tree. */ #include "video_x11_channel.h" #include "critical_section_wrapper.h" #include "trace.h" namespace webrtc { #define DISP_MAX 128 static Display *dispArray[DISP_MAX]; static int dispCount = 0; VideoX11Channel::VideoX11Channel(WebRtc_Word32 id) : _crit(*CriticalSectionWrapper::CreateCriticalSection()), _videoInterpolator(NULL), _display(NULL), _xvport(), _shminfo(), _image(NULL), _window(0L), _width(DEFAULT_RENDER_FRAME_WIDTH), _height(DEFAULT_RENDER_FRAME_HEIGHT), _outWidth(0), _outHeight(0), _xPos(0), _yPos(0), _prepared(false), _dispCount(0), _buffer(NULL), _Id(id) { } VideoX11Channel::~VideoX11Channel() { if (_prepared) { _crit.Enter(); RemoveRenderer(); _crit.Leave(); } delete &_crit; if (_videoInterpolator) { delete _videoInterpolator; } } WebRtc_Word32 VideoX11Channel::RenderFrame(const WebRtc_UWord32 streamId, VideoFrame& videoFrame) { CriticalSectionScoped cs(_crit); if (_width != (WebRtc_Word32) videoFrame.Width() || _height != (WebRtc_Word32) videoFrame.Height()) { if (FrameSizeChange(videoFrame.Width(), videoFrame.Height(), 1) == -1) { return -1; } } return DeliverFrame(videoFrame.Buffer(), videoFrame.Length(), videoFrame.TimeStamp()); } WebRtc_Word32 VideoX11Channel::FrameSizeChange(WebRtc_Word32 width, WebRtc_Word32 height, WebRtc_Word32 /*numberOfStreams */) { CriticalSectionScoped cs(_crit); if (_prepared) { RemoveRenderer(); } if (CreateLocalRenderer(width, height) == -1) { return -1; } return 0; } WebRtc_Word32 VideoX11Channel::DeliverFrame(unsigned char* buffer, WebRtc_Word32 bufferSize, unsigned WebRtc_Word32 /*timeStamp90kHz*/) { CriticalSectionScoped cs(_crit); if (!_prepared) { return 0; } if (!dispArray[_dispCount]) { return -1; } unsigned char *pBuf = buffer; // convert to RGB32 ConvertI420ToARGB(pBuf, _buffer, _width, _height, 0); // put image in window XShmPutImage(_display, _window, _gc, _image, 0, 0, _xPos, _yPos, _width, _height, True); // very important for the image to update properly! XSync(_display, false); return 0; } WebRtc_Word32 VideoX11Channel::GetFrameSize(WebRtc_Word32& width, WebRtc_Word32& height) { width = _width; height = _height; return 0; } WebRtc_Word32 VideoX11Channel::Init(Window window, float left, float top, float right, float bottom) { WEBRTC_TRACE(kTraceInfo, kTraceVideoRenderer, _Id, "%s", __FUNCTION__); CriticalSectionScoped cs(_crit); _window = window; _left = left; _right = _right; _top = top; _bottom = _bottom; _display = XOpenDisplay(NULL); // Use default display if (!_window || !_display) { return -1; } if (dispCount < DISP_MAX) { dispArray[dispCount] = _display; _dispCount = dispCount; dispCount++; } else { return -1; } if ((1 < left || left < 0) || (1 < top || top < 0) || (1 < right || right < 0) || (1 < bottom || bottom < 0)) { return -1; } // calculate position and size of rendered video int x, y; unsigned int winWidth, winHeight, borderwidth, depth; Window rootret; if (XGetGeometry(_display, _window, &rootret, &x, &y, &winWidth, &winHeight, &borderwidth, &depth) == 0) { return -1; } _xPos = (WebRtc_Word32) (winWidth * left); _yPos = (WebRtc_Word32) (winHeight * top); _outWidth = (WebRtc_Word32) (winWidth * (right - left)); _outHeight = (WebRtc_Word32) (winHeight * (bottom - top)); if (_outWidth % 2) _outWidth++; // the renderer want's sizes that are multiples of two if (_outHeight % 2) _outHeight++; if (CreateLocalRenderer(winWidth, winHeight) == -1) { return -1; } return 0; } WebRtc_Word32 VideoX11Channel::ChangeWindow(Window window) { WEBRTC_TRACE(kTraceInfo, kTraceVideoRenderer, _Id, "%s", __FUNCTION__); CriticalSectionScoped cs(_crit); // Stop the rendering, if we are rendering... RemoveRenderer(); _window = window; // calculate position and size of rendered video int x, y; unsigned int winWidth, winHeight, borderwidth, depth; Window rootret; if (XGetGeometry(_display, _window, &rootret, &x, &y, &winWidth, &winHeight, &borderwidth, &depth) == -1) { return -1; } _xPos = (int) (winWidth * _left); _yPos = (int) (winHeight * _top); _outWidth = (int) (winWidth * (_right - _left)); _outHeight = (int) (winHeight * (_bottom - _top)); if (_outWidth % 2) _outWidth++; // the renderer want's sizes that are multiples of two if (_outHeight % 2) _outHeight++; // Prepare rendering using the if (CreateLocalRenderer(_width, _height) == -1) { return -1; } return 0; } WebRtc_Word32 VideoX11Channel::ReleaseWindow() { WEBRTC_TRACE(kTraceInfo, kTraceVideoRenderer, _Id, "%s", __FUNCTION__); CriticalSectionScoped cs(_crit); RemoveRenderer(); if (_display) { XCloseDisplay(_display); _display = NULL; } return 0; } WebRtc_Word32 VideoX11Channel::CreateLocalRenderer(WebRtc_Word32 width, WebRtc_Word32 height) { WEBRTC_TRACE(kTraceInfo, kTraceVideoRenderer, _Id, "%s", __FUNCTION__); CriticalSectionScoped cs(_crit); if (!_window || !_display) { return -1; } if (_prepared) { WEBRTC_TRACE(kTraceWarning, kTraceVideoRenderer, _Id, "Renderer already prepared, exits."); return -1; } _width = width; _height = height; // create a graphics context in the window _gc = XCreateGC(_display, _window, 0, 0); // create shared memory image _image = XShmCreateImage(_display, CopyFromParent, 24, ZPixmap, NULL, &_shminfo, _width, _height); // this parameter needs to be the same for some reason. _shminfo.shmid = shmget(IPC_PRIVATE, (_image->bytes_per_line * _image->height), IPC_CREAT | 0777); _shminfo.shmaddr = _image->data = (char*) shmat(_shminfo.shmid, 0, 0); _buffer = (unsigned char*) _image->data; _shminfo.readOnly = False; // attach image to display if (!XShmAttach(_display, &_shminfo)) { //printf("XShmAttach failed !\n"); return -1; } _prepared = true; return 0; } WebRtc_Word32 VideoX11Channel::RemoveRenderer() { WEBRTC_TRACE(kTraceInfo, kTraceVideoRenderer, _Id, "%s", __FUNCTION__); if (!_prepared) { return 0; } _prepared = false; // free and closse Xwindow and XShm XShmDetach(_display, &_shminfo); XDestroyImage( _image ); shmdt(_shminfo.shmaddr); XFreeGC(_display, _gc); return 0; } WebRtc_Word32 VideoX11Channel::GetStreamProperties(WebRtc_UWord32& zOrder, float& left, float& top, float& right, float& bottom) const { WEBRTC_TRACE(kTraceInfo, kTraceVideoRenderer, _Id, "%s", __FUNCTION__); zOrder = 0; // no z-order support yet left = _left; top = _top; right = _right; bottom = _bottom; return 0; } } //namespace webrtc <|endoftext|>
<commit_before>/* * Copyright 2013 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ // Author: [email protected] (Maksim Orlovich) // Unit tests for GoogleFontCssInlineFilter #include "net/instaweb/http/public/ua_sensitive_test_fetcher.h" #include "net/instaweb/rewriter/public/domain_lawyer.h" #include "net/instaweb/rewriter/public/rewrite_driver.h" #include "net/instaweb/rewriter/public/rewrite_options.h" #include "net/instaweb/rewriter/public/rewrite_test_base.h" #include "net/instaweb/rewriter/public/server_context.h" #include "pagespeed/kernel/base/gtest.h" #include "pagespeed/kernel/base/mock_message_handler.h" #include "pagespeed/kernel/base/string_util.h" #include "pagespeed/kernel/base/timer.h" #include "pagespeed/kernel/http/content_type.h" #include "pagespeed/kernel/http/response_headers.h" namespace net_instaweb { namespace { const char kRoboto[] = "http://fonts.googleapis.com/css?family=Roboto"; class GoogleFontCssInlineFilterTestBase : public RewriteTestBase { protected: virtual void SetUp() { RewriteTestBase::SetUp(); } void SetUpForFontFilterTest(RewriteOptions::Filter filter_to_enable) { AddFilter(filter_to_enable); // We want to enable debug after AddFilters, since we don't want the // standard debug filter output, just that from the font filter. options()->ClearSignatureForTesting(); options()->EnableFilter(RewriteOptions::kDebug); server_context()->ComputeSignature(options()); rewrite_driver()->SetSessionFetcher( new UserAgentSensitiveTestFetcher(rewrite_driver()->async_fetcher())); // Font loader CSS gets Cache-Control:private, max-age=86400 ResponseHeaders response_headers; SetDefaultLongCacheHeaders(&kContentTypeCss, &response_headers); response_headers.SetDateAndCaching( timer()->NowMs(), 86400 * Timer::kSecondMs, ", private"); // Now upload some UA-specific CSS where UaSensitiveFetcher will find it, // for two fake UAs: Chromezilla and Safieri, used since they are short, // unlike real UA strings. SetFetchResponse(StrCat(kRoboto, "&UA=Chromezilla"), response_headers, "font_chromezilla"); SetFetchResponse(StrCat(kRoboto, "&UA=Safieri"), response_headers, "font_safieri"); } }; class GoogleFontCssInlineFilterTest : public GoogleFontCssInlineFilterTestBase { protected: virtual void SetUp() { GoogleFontCssInlineFilterTestBase::SetUp(); SetUpForFontFilterTest(RewriteOptions::kInlineGoogleFontCss); } }; TEST_F(GoogleFontCssInlineFilterTest, BasicOperation) { rewrite_driver()->SetUserAgent("Chromezilla"); ValidateExpected("simple", CssLinkHref(kRoboto), "<style>font_chromezilla</style>"); // Different UAs get different cache entries rewrite_driver()->SetUserAgent("Safieri"); ValidateExpected("simple2", CssLinkHref(kRoboto), "<style>font_safieri</style>"); } TEST_F(GoogleFontCssInlineFilterTest, UsageRestrictions) { rewrite_driver()->SetUserAgent("Chromezilla"); options()->ClearSignatureForTesting(); options()->set_modify_caching_headers(false); server_context()->ComputeSignature(options()); ValidateExpected("incompat1", CssLinkHref(kRoboto), StrCat(CssLinkHref(kRoboto), "<!--Cannot inline font loader CSS when " "ModifyCachingHeaders is off-->")); options()->ClearSignatureForTesting(); options()->set_modify_caching_headers(true); options()->set_downstream_cache_purge_location_prefix("foo"); server_context()->ComputeSignature(options()); ValidateExpected("incompat2", CssLinkHref(kRoboto), StrCat(CssLinkHref(kRoboto), "<!--Cannot inline font loader CSS when " "using downstream cache-->")); } TEST_F(GoogleFontCssInlineFilterTest, ProtocolRelative) { rewrite_driver()->SetUserAgent("Chromezilla"); ValidateExpected("proto_rel", CssLinkHref("//fonts.googleapis.com/css?family=Roboto"), "<style>font_chromezilla</style>"); } class GoogleFontCssInlineFilterSizeLimitTest : public GoogleFontCssInlineFilterTestBase { protected: virtual void SetUp() { GoogleFontCssInlineFilterTestBase::SetUp(); // GoogleFontCssInlineFilter uses google_font_css_inline_max_bytes. // Set a threshold at font_safieri, which should prevent longer // font_chromezilla from inlining. options()->set_google_font_css_inline_max_bytes( STATIC_STRLEN("font_safieri")); SetUpForFontFilterTest(RewriteOptions::kInlineGoogleFontCss); } }; TEST_F(GoogleFontCssInlineFilterSizeLimitTest, SizeLimit) { rewrite_driver()->SetUserAgent("Chromezilla"); ValidateExpected( "slightly_long", CssLinkHref(kRoboto), StrCat(CssLinkHref(kRoboto), "<!--CSS not inlined since it&#39;s bigger than 12 bytes-->")); rewrite_driver()->SetUserAgent("Safieri"); ValidateExpected("short", CssLinkHref(kRoboto), "<style>font_safieri</style>"); } class GoogleFontCssInlineFilterAndImportTest : public GoogleFontCssInlineFilterTest { protected: virtual void SetUp() { RewriteTestBase::SetUp(); // skipped base on purpose options()->EnableFilter( RewriteOptions::RewriteOptions::kInlineImportToLink); SetUpForFontFilterTest(RewriteOptions::kInlineGoogleFontCss); } }; TEST_F(GoogleFontCssInlineFilterAndImportTest, ViaInlineImport) { // Tests to make sure that if InlineImportToLink filter is on we // convert a <style>@import'ing </style> this as well. rewrite_driver()->SetUserAgent("Chromezilla"); ValidateExpected("import", StringPrintf("<style>@import \"%s\";</style>", kRoboto), "<style>font_chromezilla</style>"); rewrite_driver()->SetUserAgent("Safieri"); ValidateExpected("import", StringPrintf("<style>@import \"%s\";</style>", kRoboto), "<style>font_safieri</style>"); } class GoogleFontCssInlineFilterAndWidePermissionsTest : public GoogleFontCssInlineFilterTestBase { virtual void SetUp() { GoogleFontCssInlineFilterTestBase::SetUp(); // Check that we don't rely solely on authorization to properly // dispatch the URL to us. options()->WriteableDomainLawyer()->AddDomain("*", message_handler()); options()->EnableFilter(RewriteOptions::kInlineCss); SetUpForFontFilterTest(RewriteOptions::kInlineGoogleFontCss); } }; TEST_F(GoogleFontCssInlineFilterAndWidePermissionsTest, WithWideAuthorization) { rewrite_driver()->SetUserAgent("Chromezilla"); ValidateExpected("with_domain_*", CssLinkHref(kRoboto), "<style>font_chromezilla</style>"); } // Negative test for the above, with font filter off, to make sure // it's not inline_css doing stuff. class NoGoogleFontCssInlineFilterAndWidePermissionsTest : public GoogleFontCssInlineFilterTestBase { virtual void SetUp() { GoogleFontCssInlineFilterTestBase::SetUp(); // Check that we don't rely solely on authorization to properly // dispatch the URL to us. options()->WriteableDomainLawyer()->AddDomain("*", message_handler()); SetUpForFontFilterTest(RewriteOptions::kInlineCss); } }; TEST_F(NoGoogleFontCssInlineFilterAndWidePermissionsTest, WithWideAuthorization) { // Since font inlining isn't on, the regular inliner complains. This isn't // ideal, but doing otherwise requires inline_css to know about // inline_google_font_css, which also seems suboptimal. // TODO(morlovich): Figure out why this is 4xx. rewrite_driver()->SetUserAgent("Chromezilla"); ValidateExpected("with_domain_*_without_font_filter", CssLinkHref(kRoboto), StrCat(CssLinkHref(kRoboto), "<!--4xx status code, preventing rewriting of " "http://fonts.googleapis.com/css?family=Roboto-->")); } } // namespace } // namespace net_instaweb <commit_msg>Make NoGoogleFontCssInlineFilterAndWidePermissionsTest.WideAuthorization actually test what it was supposed to test.<commit_after>/* * Copyright 2013 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ // Author: [email protected] (Maksim Orlovich) // Unit tests for GoogleFontCssInlineFilter #include "net/instaweb/http/public/ua_sensitive_test_fetcher.h" #include "net/instaweb/rewriter/public/domain_lawyer.h" #include "net/instaweb/rewriter/public/rewrite_driver.h" #include "net/instaweb/rewriter/public/rewrite_options.h" #include "net/instaweb/rewriter/public/rewrite_test_base.h" #include "net/instaweb/rewriter/public/server_context.h" #include "pagespeed/kernel/base/gtest.h" #include "pagespeed/kernel/base/mock_message_handler.h" #include "pagespeed/kernel/base/string_util.h" #include "pagespeed/kernel/base/timer.h" #include "pagespeed/kernel/http/content_type.h" #include "pagespeed/kernel/http/response_headers.h" namespace net_instaweb { namespace { const char kRoboto[] = "http://fonts.googleapis.com/css?family=Roboto"; class GoogleFontCssInlineFilterTestBase : public RewriteTestBase { protected: virtual void SetUp() { RewriteTestBase::SetUp(); } void SetUpForFontFilterTest(RewriteOptions::Filter filter_to_enable) { AddFilter(filter_to_enable); // We want to enable debug after AddFilters, since we don't want the // standard debug filter output, just that from the font filter. options()->ClearSignatureForTesting(); options()->EnableFilter(RewriteOptions::kDebug); server_context()->ComputeSignature(options()); rewrite_driver()->SetSessionFetcher( new UserAgentSensitiveTestFetcher(rewrite_driver()->async_fetcher())); // Font loader CSS gets Cache-Control:private, max-age=86400 ResponseHeaders response_headers; SetDefaultLongCacheHeaders(&kContentTypeCss, &response_headers); response_headers.SetDateAndCaching( timer()->NowMs(), 86400 * Timer::kSecondMs, ", private"); // Now upload some UA-specific CSS where UaSensitiveFetcher will find it, // for two fake UAs: Chromezilla and Safieri, used since they are short, // unlike real UA strings. SetFetchResponse(StrCat(kRoboto, "&UA=Chromezilla"), response_headers, "font_chromezilla"); SetFetchResponse(StrCat(kRoboto, "&UA=Safieri"), response_headers, "font_safieri"); // If other filters will try to fetch this, they won't have a UA. SetFetchResponse(StrCat(kRoboto, "&UA=unknown"), response_headers, "font_huh"); } }; class GoogleFontCssInlineFilterTest : public GoogleFontCssInlineFilterTestBase { protected: virtual void SetUp() { GoogleFontCssInlineFilterTestBase::SetUp(); SetUpForFontFilterTest(RewriteOptions::kInlineGoogleFontCss); } }; TEST_F(GoogleFontCssInlineFilterTest, BasicOperation) { rewrite_driver()->SetUserAgent("Chromezilla"); ValidateExpected("simple", CssLinkHref(kRoboto), "<style>font_chromezilla</style>"); // Different UAs get different cache entries rewrite_driver()->SetUserAgent("Safieri"); ValidateExpected("simple2", CssLinkHref(kRoboto), "<style>font_safieri</style>"); } TEST_F(GoogleFontCssInlineFilterTest, UsageRestrictions) { rewrite_driver()->SetUserAgent("Chromezilla"); options()->ClearSignatureForTesting(); options()->set_modify_caching_headers(false); server_context()->ComputeSignature(options()); ValidateExpected("incompat1", CssLinkHref(kRoboto), StrCat(CssLinkHref(kRoboto), "<!--Cannot inline font loader CSS when " "ModifyCachingHeaders is off-->")); options()->ClearSignatureForTesting(); options()->set_modify_caching_headers(true); options()->set_downstream_cache_purge_location_prefix("foo"); server_context()->ComputeSignature(options()); ValidateExpected("incompat2", CssLinkHref(kRoboto), StrCat(CssLinkHref(kRoboto), "<!--Cannot inline font loader CSS when " "using downstream cache-->")); } TEST_F(GoogleFontCssInlineFilterTest, ProtocolRelative) { rewrite_driver()->SetUserAgent("Chromezilla"); ValidateExpected("proto_rel", CssLinkHref("//fonts.googleapis.com/css?family=Roboto"), "<style>font_chromezilla</style>"); } class GoogleFontCssInlineFilterSizeLimitTest : public GoogleFontCssInlineFilterTestBase { protected: virtual void SetUp() { GoogleFontCssInlineFilterTestBase::SetUp(); // GoogleFontCssInlineFilter uses google_font_css_inline_max_bytes. // Set a threshold at font_safieri, which should prevent longer // font_chromezilla from inlining. options()->set_google_font_css_inline_max_bytes( STATIC_STRLEN("font_safieri")); SetUpForFontFilterTest(RewriteOptions::kInlineGoogleFontCss); } }; TEST_F(GoogleFontCssInlineFilterSizeLimitTest, SizeLimit) { rewrite_driver()->SetUserAgent("Chromezilla"); ValidateExpected( "slightly_long", CssLinkHref(kRoboto), StrCat(CssLinkHref(kRoboto), "<!--CSS not inlined since it&#39;s bigger than 12 bytes-->")); rewrite_driver()->SetUserAgent("Safieri"); ValidateExpected("short", CssLinkHref(kRoboto), "<style>font_safieri</style>"); } class GoogleFontCssInlineFilterAndImportTest : public GoogleFontCssInlineFilterTest { protected: virtual void SetUp() { RewriteTestBase::SetUp(); // skipped base on purpose options()->EnableFilter( RewriteOptions::RewriteOptions::kInlineImportToLink); SetUpForFontFilterTest(RewriteOptions::kInlineGoogleFontCss); } }; TEST_F(GoogleFontCssInlineFilterAndImportTest, ViaInlineImport) { // Tests to make sure that if InlineImportToLink filter is on we // convert a <style>@import'ing </style> this as well. rewrite_driver()->SetUserAgent("Chromezilla"); ValidateExpected("import", StringPrintf("<style>@import \"%s\";</style>", kRoboto), "<style>font_chromezilla</style>"); rewrite_driver()->SetUserAgent("Safieri"); ValidateExpected("import", StringPrintf("<style>@import \"%s\";</style>", kRoboto), "<style>font_safieri</style>"); } class GoogleFontCssInlineFilterAndWidePermissionsTest : public GoogleFontCssInlineFilterTestBase { virtual void SetUp() { GoogleFontCssInlineFilterTestBase::SetUp(); // Check that we don't rely solely on authorization to properly // dispatch the URL to us. options()->WriteableDomainLawyer()->AddDomain("*", message_handler()); rewrite_driver()->request_context()->AddSessionAuthorizedFetchOrigin( "http://fonts.googleapis.com"); options()->EnableFilter(RewriteOptions::kInlineCss); SetUpForFontFilterTest(RewriteOptions::kInlineGoogleFontCss); } }; TEST_F(GoogleFontCssInlineFilterAndWidePermissionsTest, WithWideAuthorization) { rewrite_driver()->SetUserAgent("Chromezilla"); ValidateExpected("with_domain_*", CssLinkHref(kRoboto), "<style>font_chromezilla</style>"); } // Negative test for the above, with font filter off, to make sure // it's not inline_css doing stuff. class NoGoogleFontCssInlineFilterAndWidePermissionsTest : public GoogleFontCssInlineFilterTestBase { virtual void SetUp() { GoogleFontCssInlineFilterTestBase::SetUp(); // Check that we don't rely solely on authorization to properly // dispatch the URL to us. Note that we can't only use DomainLawyer here // since UserAgentSensitiveTestFetcher is at http layer so is simply // unaware of it. options()->WriteableDomainLawyer()->AddDomain("*", message_handler()); rewrite_driver()->request_context()->AddSessionAuthorizedFetchOrigin( "http://fonts.googleapis.com"); SetUpForFontFilterTest(RewriteOptions::kInlineCss); } }; TEST_F(NoGoogleFontCssInlineFilterAndWidePermissionsTest, WithWideAuthorization) { // Since font inlining isn't on, the regular inliner complains. This isn't // ideal, but doing otherwise requires inline_css to know about // inline_google_font_css, which also seems suboptimal. rewrite_driver()->SetUserAgent("Chromezilla"); ValidateExpected("with_domain_*_without_font_filter", CssLinkHref(kRoboto), StrCat(CssLinkHref(kRoboto), "<!--Uncacheable content, preventing rewriting of " "http://fonts.googleapis.com/css?family=Roboto-->")); } } // namespace } // namespace net_instaweb <|endoftext|>
<commit_before>/**************************************************************************** ** ** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). ** All rights reserved. ** Contact: Nokia Corporation ([email protected]) ** ** This file is part of the Qt Mobility Components. ** ** $QT_BEGIN_LICENSE:LGPL$ ** No Commercial Usage ** This file contains pre-release code and may not be distributed. ** You may use this file in accordance with the terms and conditions ** contained in the Technology Preview License Agreement accompanying ** this package. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Nokia gives you certain additional ** rights. These rights are described in the Nokia Qt LGPL Exception ** version 1.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 [email protected]. ** ** ** ** ** ** ** ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #include "s60mediaplayercontrol.h" #include "s60mediaplayersession.h" #include <QMediaPlaylistNavigator> #include <QtCore/qdir.h> #include <QtCore/qurl.h> #include <QtCore/qdebug.h> S60MediaPlayerControl::S60MediaPlayerControl(MS60MediaPlayerResolver& mediaPlayerResolver, QObject *parent) : QMediaPlayerControl(parent), m_mediaPlayerResolver(mediaPlayerResolver), m_session(NULL), m_stream(NULL) { } S60MediaPlayerControl::~S60MediaPlayerControl() { } qint64 S60MediaPlayerControl::position() const { if (m_session) return m_session->position(); return 0; } qint64 S60MediaPlayerControl::duration() const { if (m_session) return m_session->duration(); return -1; } QMediaPlayer::State S60MediaPlayerControl::state() const { if (m_session) return m_session->state(); return QMediaPlayer::StoppedState; } QMediaPlayer::MediaStatus S60MediaPlayerControl::mediaStatus() const { if (m_session) return m_session->mediaStatus(); return QMediaPlayer::NoMedia; } int S60MediaPlayerControl::bufferStatus() const { return -1; } int S60MediaPlayerControl::volume() const { if (m_session) return m_session->volume(); return m_mediaSettings.volume(); } bool S60MediaPlayerControl::isMuted() const { if (m_session) return m_session->isMuted(); return m_mediaSettings.isMuted(); } bool S60MediaPlayerControl::isSeekable() const { if (m_session) return m_session->isSeekable(); return true; } QPair<qint64, qint64> S60MediaPlayerControl::seekRange() const { if (m_session) { return q_check_ptr(m_session)->isSeekable() ? qMakePair<qint64, qint64>(0, m_session->duration()) : qMakePair<qint64, qint64>(0, 0); } return QPair<qint64, qint64>(); } qreal S60MediaPlayerControl::playbackRate() const { if (m_session) return m_session->playbackRate(); return m_mediaSettings.playbackRate(); } void S60MediaPlayerControl::setPlaybackRate(qreal rate) { if (m_session) m_session->setPlaybackRate(rate); m_mediaSettings.setPlaybackRate(rate); } void S60MediaPlayerControl::setPosition(qint64 pos) { if (m_session) m_session->setPosition(pos); } void S60MediaPlayerControl::play() { if (m_session) m_session->play(); } void S60MediaPlayerControl::pause() { if (m_session) m_session->pause(); } void S60MediaPlayerControl::stop() { if (m_session) m_session->stop(); } void S60MediaPlayerControl::setVolume(int volume) { if (m_session) m_session->setVolume(volume); m_mediaSettings.setVolume(volume); } void S60MediaPlayerControl::setMuted(bool muted) { if (m_session) m_session->setMuted(muted); else if (m_mediaSettings.isMuted() != muted) emit mutedChanged(muted); m_mediaSettings.setMuted(muted); } QMediaContent S60MediaPlayerControl::media() const { return m_currentResource; } const QIODevice *S60MediaPlayerControl::mediaStream() const { return m_stream; } void S60MediaPlayerControl::setMedia(const QMediaContent &source, QIODevice *stream) { Q_UNUSED(stream) // we don't want to set & load media again when it is already loaded if (m_session && (m_currentResource == source) && m_session->state() == QMediaPlayer::LoadedMedia) { return; } // store to variable as session is created based on the content type. m_currentResource = source; if (m_session) { m_session->stop(); } m_session = currentPlayerSession(); QUrl url; if (m_session && !source.isNull()) { url = source.canonicalUrl(); if (m_session->isUrl() == false) { m_session->load(url); } else { m_session->loadUrl(url); } emit mediaChanged(m_currentResource); } else { emit mediaStatusChanged(QMediaPlayer::InvalidMedia); } } void S60MediaPlayerControl::setVideoOutput(QObject *output) { if (!m_session) m_session = m_mediaPlayerResolver.VideoPlayerSession(); m_session->setVideoRenderer(output); } bool S60MediaPlayerControl::isVideoAvailable() const { if (m_session) return m_session->isVideoAvailable(); return false; } S60MediaPlayerSession* S60MediaPlayerControl::currentPlayerSession() { return m_mediaPlayerResolver.PlayerSession(); } const S60MediaSettings& S60MediaPlayerControl::mediaControlSettings() const { return m_mediaSettings; } <commit_msg>Fixed s60mediaplayercontrol isSeekable default value to false.<commit_after>/**************************************************************************** ** ** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). ** All rights reserved. ** Contact: Nokia Corporation ([email protected]) ** ** This file is part of the Qt Mobility Components. ** ** $QT_BEGIN_LICENSE:LGPL$ ** No Commercial Usage ** This file contains pre-release code and may not be distributed. ** You may use this file in accordance with the terms and conditions ** contained in the Technology Preview License Agreement accompanying ** this package. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Nokia gives you certain additional ** rights. These rights are described in the Nokia Qt LGPL Exception ** version 1.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 [email protected]. ** ** ** ** ** ** ** ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #include "s60mediaplayercontrol.h" #include "s60mediaplayersession.h" #include <QMediaPlaylistNavigator> #include <QtCore/qdir.h> #include <QtCore/qurl.h> #include <QtCore/qdebug.h> S60MediaPlayerControl::S60MediaPlayerControl(MS60MediaPlayerResolver& mediaPlayerResolver, QObject *parent) : QMediaPlayerControl(parent), m_mediaPlayerResolver(mediaPlayerResolver), m_session(NULL), m_stream(NULL) { } S60MediaPlayerControl::~S60MediaPlayerControl() { } qint64 S60MediaPlayerControl::position() const { if (m_session) return m_session->position(); return 0; } qint64 S60MediaPlayerControl::duration() const { if (m_session) return m_session->duration(); return -1; } QMediaPlayer::State S60MediaPlayerControl::state() const { if (m_session) return m_session->state(); return QMediaPlayer::StoppedState; } QMediaPlayer::MediaStatus S60MediaPlayerControl::mediaStatus() const { if (m_session) return m_session->mediaStatus(); return QMediaPlayer::NoMedia; } int S60MediaPlayerControl::bufferStatus() const { return -1; } int S60MediaPlayerControl::volume() const { if (m_session) return m_session->volume(); return m_mediaSettings.volume(); } bool S60MediaPlayerControl::isMuted() const { if (m_session) return m_session->isMuted(); return m_mediaSettings.isMuted(); } bool S60MediaPlayerControl::isSeekable() const { if (m_session) return m_session->isSeekable(); return false; } QPair<qint64, qint64> S60MediaPlayerControl::seekRange() const { if (m_session) { return q_check_ptr(m_session)->isSeekable() ? qMakePair<qint64, qint64>(0, m_session->duration()) : qMakePair<qint64, qint64>(0, 0); } return QPair<qint64, qint64>(); } qreal S60MediaPlayerControl::playbackRate() const { if (m_session) return m_session->playbackRate(); return m_mediaSettings.playbackRate(); } void S60MediaPlayerControl::setPlaybackRate(qreal rate) { if (m_session) m_session->setPlaybackRate(rate); m_mediaSettings.setPlaybackRate(rate); } void S60MediaPlayerControl::setPosition(qint64 pos) { if (m_session) m_session->setPosition(pos); } void S60MediaPlayerControl::play() { if (m_session) m_session->play(); } void S60MediaPlayerControl::pause() { if (m_session) m_session->pause(); } void S60MediaPlayerControl::stop() { if (m_session) m_session->stop(); } void S60MediaPlayerControl::setVolume(int volume) { if (m_session) m_session->setVolume(volume); m_mediaSettings.setVolume(volume); } void S60MediaPlayerControl::setMuted(bool muted) { if (m_session) m_session->setMuted(muted); else if (m_mediaSettings.isMuted() != muted) emit mutedChanged(muted); m_mediaSettings.setMuted(muted); } QMediaContent S60MediaPlayerControl::media() const { return m_currentResource; } const QIODevice *S60MediaPlayerControl::mediaStream() const { return m_stream; } void S60MediaPlayerControl::setMedia(const QMediaContent &source, QIODevice *stream) { Q_UNUSED(stream) // we don't want to set & load media again when it is already loaded if (m_session && (m_currentResource == source) && m_session->state() == QMediaPlayer::LoadedMedia) { return; } // store to variable as session is created based on the content type. m_currentResource = source; if (m_session) { m_session->stop(); } m_session = currentPlayerSession(); QUrl url; if (m_session && !source.isNull()) { url = source.canonicalUrl(); if (m_session->isUrl() == false) { m_session->load(url); } else { m_session->loadUrl(url); } emit mediaChanged(m_currentResource); } else { emit mediaStatusChanged(QMediaPlayer::InvalidMedia); } } void S60MediaPlayerControl::setVideoOutput(QObject *output) { if (!m_session) m_session = m_mediaPlayerResolver.VideoPlayerSession(); m_session->setVideoRenderer(output); } bool S60MediaPlayerControl::isVideoAvailable() const { if (m_session) return m_session->isVideoAvailable(); return false; } S60MediaPlayerSession* S60MediaPlayerControl::currentPlayerSession() { return m_mediaPlayerResolver.PlayerSession(); } const S60MediaSettings& S60MediaPlayerControl::mediaControlSettings() const { return m_mediaSettings; } <|endoftext|>
<commit_before>#ifndef __STDAIR_BOM_BOMCHILDRENHOLDERIMP_HPP #define __STDAIR_BOM_BOMCHILDRENHOLDERIMP_HPP // ////////////////////////////////////////////////////////////////////// // Import section // ////////////////////////////////////////////////////////////////////// // C #include <assert.h> // STL #include <vector> #include <string> #include <map> //STDAIR #include <stdair/bom/BomChildrenHolder.hpp> #include <stdair/bom/BomIterator.hpp> namespace stdair { /** Template class aimed at holding a list and a map of children BOM structure of a dedicated type. */ template <typename BOM_CONTENT_CHILD> class BomChildrenHolderImp : public BomChildrenHolder { friend class FacBomStructure; /** Retrieve associated bom structure type. */ typedef typename BOM_CONTENT_CHILD::BomStructure_T BomStructure_T; public: /** Define lists of children BOM structures. */ typedef std::vector<BomStructure_T*> BomChildrenOrderedList_T; typedef std::map<const std::string, BomStructure_T*> BomChildrenList_T; /** Define the different types of iterators. */ typedef BomConstIterator_T<BOM_CONTENT_CHILD, typename BomChildrenOrderedList_T::const_iterator> ListConstIterator_T; typedef BomConstIterator_T<BOM_CONTENT_CHILD, typename BomChildrenOrderedList_T::const_reverse_iterator> ListConstReverseIterator_T; typedef BomIterator_T<BOM_CONTENT_CHILD, typename BomChildrenOrderedList_T::iterator> ListIterator_T; typedef BomIterator_T<BOM_CONTENT_CHILD, typename BomChildrenOrderedList_T::reverse_iterator> ListReverseIterator_T; typedef BomConstIterator_T<BOM_CONTENT_CHILD, typename BomChildrenList_T::const_iterator> MapConstIterator_T; typedef BomConstIterator_T<BOM_CONTENT_CHILD, typename BomChildrenList_T::const_reverse_iterator> MapConstReverseIterator_T; typedef BomIterator_T<BOM_CONTENT_CHILD, typename BomChildrenList_T::iterator> MapIterator_T; typedef BomIterator_T<BOM_CONTENT_CHILD, typename BomChildrenList_T::reverse_iterator> MapReverseIterator_T; public: // /////////// Display support methods ///////// /** Dump a Business Object into an output stream. @param ostream& the output stream. */ void toStream (std::ostream& ioOut) const { ioOut << toString(); } /** Read a Business Object from an input stream. @param istream& the input stream. */ void fromStream (std::istream& ioIn) { } /** Get the serialised version of the Business Object. */ std::string toString() const { return std::string (""); } /** Get a string describing the whole key (differentiating two objects at any level). */ const std::string describeKey() const { return std::string (""); } /** Get a string describing the short key (differentiating two objects at the same level). */ const std::string describeShortKey() const { return std::string (""); } /** Dump a Business Object into an output stream. @param ostream& the output stream. */ void describeFull (std::ostringstream& ioOut) const { // Initialise the index unsigned short lIdx = 0; for (typename BomChildrenOrderedList_T::const_iterator itChild = _bomChildrenOrderedList.begin(); itChild != _bomChildrenOrderedList.end(); ++itChild, ++lIdx) { const BomStructure_T* lCurrentChild_ptr = *itChild; ioOut << "[" << lIdx << "]: "; lCurrentChild_ptr->describeFull (ioOut); } } // /////////// Iteration methods ////////// /** Initialise the internal const iterators on bom objects: return the iterator at the begining of the list. */ ListConstIterator_T listConstIteratorBegin () const { return _bomChildrenOrderedList.begin(); } /** Initialise the internal const iterators on bom objects: return the iterator past the end of the list. */ ListConstIterator_T listConstIteratorEnd () const { return _bomChildrenOrderedList.end(); } /** Initialise the internal const reverse iterators on bom objects: return the reverse iterator at the rbegining of the list. */ ListConstReverseIterator_T listConstIteratorRBegin () const { return _bomChildrenOrderedList.rbegin(); } /** Initialise the internal const reverse iterators on bom objects: return the reverse iterator past the rend of the list. */ ListConstReverseIterator_T listConstIteratorREnd () const { return _bomChildrenOrderedList.rend(); } /** Initialise the internal iterators on bom objects: return the iterator at the begining of the list. */ ListIterator_T listIteratorBegin () const { typename BomChildrenOrderedList_T::iterator it = _bomChildrenOrderedList.begin(); return it; } /** Initialise the internal iterators on bom objects: return the iterator past the end of the list. */ ListIterator_T listIteratorEnd () const { return ListIterator_T(_bomChildrenOrderedList.end()); } /** Initialise the internal reverse iterators on bom objects: return the reverse iterator at the rbegining of the list. */ ListReverseIterator_T listIteratorRBegin () const { return ListReverseIterator_T(_bomChildrenOrderedList.rbegin()); } /** Initialise the internal reverse iterators on bom objects: return the reverse iterator past the rend of the list. */ ListReverseIterator_T listIteratorREnd () const { return ListReverseIterator_T(_bomChildrenOrderedList.rend()); } /** Initialise the internal const iterators on bom objects: return the iterator at the begining of the map. */ MapConstIterator_T mapConstIteratorBegin () const { return _bomChildrenList.begin(); } /** Initialise the internal const iterators on bom objects: return the iterator past the end of the map. */ MapConstIterator_T mapConstIteratorEnd () const { return _bomChildrenList.end(); } /** Initialise the internal const reverse iterators on bom objects: return the reverse iterator at the rbegining of the map. */ MapConstReverseIterator_T mapConstIteratorRBegin () const { return _bomChildrenList.rbegin(); } /** Initialise the internal const reverse iterators on bom objects: return the reverse iterator past the rend of the map. */ MapConstReverseIterator_T mapConstIteratorREnd () const { return _bomChildrenList.rend(); } /** Initialise the internal iterators on bom objects: return the iterator at the begining of the map. */ MapIterator_T mapIteratorBegin () const { return MapIterator_T(_bomChildrenList.begin()); } /** Initialise the internal iterators on bom objects: return the iterator past the end of the map. */ MapIterator_T mapIteratorEnd () const { return MapIterator_T(_bomChildrenList.end()); } /** Initialise the internal reverse iterators on bom objects: return the reverse iterator at the rbegining of the map. */ MapReverseIterator_T mapIteratorRBegin () const { return MapReverseIterator_T(_bomChildrenList.rbegin()); } /** Initialise the internal reverse iterators on bom objects: return the reverse iterator past the rend of the map. */ MapReverseIterator_T mapIteratorREnd () const { return MapReverseIterator_T(_bomChildrenList.rend()); } private: /** Constructors are private so as to force the usage of the Factory layer. */ /** Default constructors. */ BomChildrenHolderImp () { } BomChildrenHolderImp (const BomChildrenHolderImp&); /** Destructor. */ ~BomChildrenHolderImp() { } private: ///////////// Attributes ////////////// /** List of children BOM structures. */ BomChildrenList_T _bomChildrenList; /** Map of children BOM structures with their key. */ BomChildrenOrderedList_T _bomChildrenOrderedList; }; } #endif // __STDAIR_BOM_BOMCHILDRENHOLDERIMP_HPP <commit_msg>Small change in some functions.<commit_after>#ifndef __STDAIR_BOM_BOMCHILDRENHOLDERIMP_HPP #define __STDAIR_BOM_BOMCHILDRENHOLDERIMP_HPP // ////////////////////////////////////////////////////////////////////// // Import section // ////////////////////////////////////////////////////////////////////// // C #include <assert.h> // STL #include <vector> #include <string> #include <map> //STDAIR #include <stdair/bom/BomChildrenHolder.hpp> #include <stdair/bom/BomIterator.hpp> namespace stdair { /** Template class aimed at holding a list and a map of children BOM structure of a dedicated type. */ template <typename BOM_CONTENT_CHILD> class BomChildrenHolderImp : public BomChildrenHolder { friend class FacBomStructure; /** Retrieve associated bom structure type. */ typedef typename BOM_CONTENT_CHILD::BomStructure_T BomStructure_T; public: /** Define lists of children BOM structures. */ typedef std::vector<BomStructure_T*> BomChildrenOrderedList_T; typedef std::map<const std::string, BomStructure_T*> BomChildrenList_T; /** Define the different types of iterators. */ typedef BomConstIterator_T<BOM_CONTENT_CHILD, typename BomChildrenOrderedList_T::const_iterator> ListConstIterator_T; typedef BomConstIterator_T<BOM_CONTENT_CHILD, typename BomChildrenOrderedList_T::const_reverse_iterator> ListConstReverseIterator_T; typedef BomIterator_T<BOM_CONTENT_CHILD, typename BomChildrenOrderedList_T::iterator> ListIterator_T; typedef BomIterator_T<BOM_CONTENT_CHILD, typename BomChildrenOrderedList_T::reverse_iterator> ListReverseIterator_T; typedef BomConstIterator_T<BOM_CONTENT_CHILD, typename BomChildrenList_T::const_iterator> MapConstIterator_T; typedef BomConstIterator_T<BOM_CONTENT_CHILD, typename BomChildrenList_T::const_reverse_iterator> MapConstReverseIterator_T; typedef BomIterator_T<BOM_CONTENT_CHILD, typename BomChildrenList_T::iterator> MapIterator_T; typedef BomIterator_T<BOM_CONTENT_CHILD, typename BomChildrenList_T::reverse_iterator> MapReverseIterator_T; public: // /////////// Display support methods ///////// /** Dump a Business Object into an output stream. @param ostream& the output stream. */ void toStream (std::ostream& ioOut) const { ioOut << toString(); } /** Read a Business Object from an input stream. @param istream& the input stream. */ void fromStream (std::istream& ioIn) { } /** Get the serialised version of the Business Object. */ std::string toString() const { return std::string (""); } /** Get a string describing the whole key (differentiating two objects at any level). */ const std::string describeKey() const { return std::string (""); } /** Get a string describing the short key (differentiating two objects at the same level). */ const std::string describeShortKey() const { return std::string (""); } /** Dump a Business Object into an output stream. @param ostream& the output stream. */ void describeFull (std::ostringstream& ioOut) const { // Initialise the index unsigned short lIdx = 0; for (typename BomChildrenOrderedList_T::const_iterator itChild = _bomChildrenOrderedList.begin(); itChild != _bomChildrenOrderedList.end(); ++itChild, ++lIdx) { const BomStructure_T* lCurrentChild_ptr = *itChild; ioOut << "[" << lIdx << "]: "; lCurrentChild_ptr->describeFull (ioOut); } } // /////////// Iteration methods ////////// /** Initialise the internal const iterators on bom objects: return the iterator at the begining of the list. */ ListConstIterator_T listConstIteratorBegin () const { return _bomChildrenOrderedList.begin(); } /** Initialise the internal const iterators on bom objects: return the iterator past the end of the list. */ ListConstIterator_T listConstIteratorEnd () const { return _bomChildrenOrderedList.end(); } /** Initialise the internal const reverse iterators on bom objects: return the reverse iterator at the rbegining of the list. */ ListConstReverseIterator_T listConstIteratorRBegin () const { return _bomChildrenOrderedList.rbegin(); } /** Initialise the internal const reverse iterators on bom objects: return the reverse iterator past the rend of the list. */ ListConstReverseIterator_T listConstIteratorREnd () const { return _bomChildrenOrderedList.rend(); } /** Initialise the internal iterators on bom objects: return the iterator at the begining of the list. */ ListIterator_T listIteratorBegin () const { typename BomChildrenOrderedList_T::iterator it = _bomChildrenOrderedList.begin(); return ListIterator_T (it); } /** Initialise the internal iterators on bom objects: return the iterator past the end of the list. */ ListIterator_T listIteratorEnd () const { return ListIterator_T(_bomChildrenOrderedList.end()); } /** Initialise the internal reverse iterators on bom objects: return the reverse iterator at the rbegining of the list. */ ListReverseIterator_T listIteratorRBegin () const { return ListReverseIterator_T(_bomChildrenOrderedList.rbegin()); } /** Initialise the internal reverse iterators on bom objects: return the reverse iterator past the rend of the list. */ ListReverseIterator_T listIteratorREnd () const { return ListReverseIterator_T(_bomChildrenOrderedList.rend()); } /** Initialise the internal const iterators on bom objects: return the iterator at the begining of the map. */ MapConstIterator_T mapConstIteratorBegin () const { return _bomChildrenList.begin(); } /** Initialise the internal const iterators on bom objects: return the iterator past the end of the map. */ MapConstIterator_T mapConstIteratorEnd () const { return _bomChildrenList.end(); } /** Initialise the internal const reverse iterators on bom objects: return the reverse iterator at the rbegining of the map. */ MapConstReverseIterator_T mapConstIteratorRBegin () const { return _bomChildrenList.rbegin(); } /** Initialise the internal const reverse iterators on bom objects: return the reverse iterator past the rend of the map. */ MapConstReverseIterator_T mapConstIteratorREnd () const { return _bomChildrenList.rend(); } /** Initialise the internal iterators on bom objects: return the iterator at the begining of the map. */ MapIterator_T mapIteratorBegin () const { return MapIterator_T(_bomChildrenList.begin()); } /** Initialise the internal iterators on bom objects: return the iterator past the end of the map. */ MapIterator_T mapIteratorEnd () const { return MapIterator_T(_bomChildrenList.end()); } /** Initialise the internal reverse iterators on bom objects: return the reverse iterator at the rbegining of the map. */ MapReverseIterator_T mapIteratorRBegin () const { return MapReverseIterator_T(_bomChildrenList.rbegin()); } /** Initialise the internal reverse iterators on bom objects: return the reverse iterator past the rend of the map. */ MapReverseIterator_T mapIteratorREnd () const { return MapReverseIterator_T(_bomChildrenList.rend()); } private: /** Constructors are private so as to force the usage of the Factory layer. */ /** Default constructors. */ BomChildrenHolderImp () { } BomChildrenHolderImp (const BomChildrenHolderImp&); /** Destructor. */ ~BomChildrenHolderImp() { } private: ///////////// Attributes ////////////// /** List of children BOM structures. */ BomChildrenList_T _bomChildrenList; /** Map of children BOM structures with their key. */ BomChildrenOrderedList_T _bomChildrenOrderedList; }; } #endif // __STDAIR_BOM_BOMCHILDRENHOLDERIMP_HPP <|endoftext|>
<commit_before>/* * kwallet.cpp: KWallet provider for SVN_AUTH_CRED_SIMPLE * * ==================================================================== * Copyright (c) 2008 CollabNet. All rights reserved. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at http://subversion.tigris.org/license-1.html. * If newer versions of this license are posted there, you may use a * newer version instead, at your option. * * This software consists of voluntary contributions made by many * individuals. For exact contribution history, see the revision * history and logs, available at http://subversion.tigris.org/. * ==================================================================== */ /* ==================================================================== */ /*** Includes. ***/ #include <apr_pools.h> #include "svn_auth.h" #include "svn_auth_dso.h" #include "svn_error.h" #include "svn_version.h" #include "private/svn_auth_private.h" #include "svn_private_config.h" #include <QtCore/QString> #include <kapplication.h> #include <kcmdlineargs.h> #include <kwallet.h> /*-----------------------------------------------------------------------*/ /* KWallet simple provider, puts passwords in KWallet */ /*-----------------------------------------------------------------------*/ /* Implementation of svn_auth__password_get_t that retrieves the password from KWallet. */ static svn_boolean_t kwallet_password_get(const char **password, apr_hash_t *creds, const char *realmstring, const char *username, svn_boolean_t non_interactive, apr_pool_t *pool) { if (non_interactive) { return FALSE; } if (! KWallet::Wallet::isEnabled()) { return FALSE; } KCmdLineArgs::init(1, (char *[1]) { "svn" }, "Subversion", "subversion", ki18n("Subversion"), SVN_VER_NUMBER, ki18n("Version control system"), KCmdLineArgs::CmdLineArgKDE); KApplication application; svn_boolean_t ret = FALSE; QString wallet_name = KWallet::Wallet::NetworkWallet(); QString folder = QString::fromUtf8("Subversion"); QString key = QString::fromUtf8(username) + "@" + QString::fromUtf8(realmstring); if (! KWallet::Wallet::keyDoesNotExist(wallet_name, folder, key)) { KWallet::Wallet *wallet = KWallet::Wallet::openWallet(wallet_name, -1, KWallet::Wallet::Synchronous); if (wallet) { if (wallet->hasFolder(folder)) { if (wallet->setFolder(folder)) { QString q_password; if (wallet->readPassword(key, q_password) == 0); { *password = apr_pstrmemdup(pool, q_password.toUtf8().data(), q_password.size()); ret = TRUE; } } } } } // KWallet::Wallet::disconnectApplication(wallet_name, // QString::fromUtf8("Subversion")); return ret; } /* Implementation of svn_auth__password_set_t that stores the password in KWallet. */ static svn_boolean_t kwallet_password_set(apr_hash_t *creds, const char *realmstring, const char *username, const char *password, svn_boolean_t non_interactive, apr_pool_t *pool) { if (non_interactive) { return FALSE; } if (! KWallet::Wallet::isEnabled()) { return FALSE; } KCmdLineArgs::init(1, (char *[1]) { "svn" }, "Subversion", "subversion", ki18n("Subversion"), SVN_VER_NUMBER, ki18n("Version control system"), KCmdLineArgs::CmdLineArgKDE); KApplication application; svn_boolean_t ret = FALSE; QString q_password = QString::fromUtf8(password); QString wallet_name = KWallet::Wallet::NetworkWallet(); QString folder = QString::fromUtf8("Subversion"); KWallet::Wallet *wallet = KWallet::Wallet::openWallet(wallet_name, -1, KWallet::Wallet::Synchronous); if (wallet) { if (! wallet->hasFolder(folder)) { wallet->createFolder(folder); } if (wallet->hasFolder(folder)) { if (wallet->setFolder(folder)) { QString key = QString::fromUtf8(username) + "@" + QString::fromUtf8(realmstring); if (wallet->writePassword(key, q_password) == 0) { ret = TRUE; } } } } // KWallet::Wallet::disconnectApplication(wallet_name, // QString::fromUtf8("Subversion")); return ret; } /* Get cached encrypted credentials from the simple provider's cache. */ static svn_error_t * kwallet_simple_first_creds(void **credentials, void **iter_baton, void *provider_baton, apr_hash_t *parameters, const char *realmstring, apr_pool_t *pool) { return svn_auth__simple_first_creds_helper(credentials, iter_baton, provider_baton, parameters, realmstring, kwallet_password_get, SVN_AUTH__KWALLET_PASSWORD_TYPE, pool); } /* Save encrypted credentials to the simple provider's cache. */ static svn_error_t * kwallet_simple_save_creds(svn_boolean_t *saved, void *credentials, void *provider_baton, apr_hash_t *parameters, const char *realmstring, apr_pool_t *pool) { return svn_auth__simple_save_creds_helper(saved, credentials, provider_baton, parameters, realmstring, kwallet_password_set, SVN_AUTH__KWALLET_PASSWORD_TYPE, pool); } static const svn_auth_provider_t kwallet_simple_provider = { SVN_AUTH_CRED_SIMPLE, kwallet_simple_first_creds, NULL, kwallet_simple_save_creds }; /* Public API */ extern "C" { void svn_auth_get_kwallet_simple_provider(svn_auth_provider_object_t **provider, apr_pool_t *pool) { svn_auth_provider_object_t *po = static_cast<svn_auth_provider_object_t *> (apr_pcalloc(pool, sizeof(*po))); po->vtable = &kwallet_simple_provider; *provider = po; } } <commit_msg>Follow-up to r31427:<commit_after>/* * kwallet.cpp: KWallet provider for SVN_AUTH_CRED_SIMPLE * * ==================================================================== * Copyright (c) 2008 CollabNet. All rights reserved. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at http://subversion.tigris.org/license-1.html. * If newer versions of this license are posted there, you may use a * newer version instead, at your option. * * This software consists of voluntary contributions made by many * individuals. For exact contribution history, see the revision * history and logs, available at http://subversion.tigris.org/. * ==================================================================== */ /* ==================================================================== */ /*** Includes. ***/ #include <apr_pools.h> #include "svn_auth.h" #include "svn_auth_dso.h" #include "svn_error.h" #include "svn_version.h" #include "private/svn_auth_private.h" #include "svn_private_config.h" #include <QtCore/QString> #include <kapplication.h> #include <kcmdlineargs.h> #include <kwallet.h> /*-----------------------------------------------------------------------*/ /* KWallet simple provider, puts passwords in KWallet */ /*-----------------------------------------------------------------------*/ /* Implementation of svn_auth__password_get_t that retrieves the password from KWallet. */ static svn_boolean_t kwallet_password_get(const char **password, apr_hash_t *creds, const char *realmstring, const char *username, svn_boolean_t non_interactive, apr_pool_t *pool) { if (non_interactive) { return FALSE; } if (! KWallet::Wallet::isEnabled()) { return FALSE; } KCmdLineArgs::init(1, (char *[1]) { "svn" }, "Subversion", "subversion", ki18n("Subversion"), SVN_VER_NUMBER, ki18n("Version control system"), KCmdLineArgs::CmdLineArgKDE); KApplication application; svn_boolean_t ret = FALSE; QString wallet_name = KWallet::Wallet::NetworkWallet(); QString folder = QString::fromUtf8("Subversion"); QString key = QString::fromUtf8(username) + "@" + QString::fromUtf8(realmstring); if (! KWallet::Wallet::keyDoesNotExist(wallet_name, folder, key)) { KWallet::Wallet *wallet = KWallet::Wallet::openWallet(wallet_name, -1, KWallet::Wallet::Synchronous); if (wallet) { if (wallet->hasFolder(folder)) { if (wallet->setFolder(folder)) { QString q_password; if (wallet->readPassword(key, q_password) == 0); { *password = apr_pstrmemdup(pool, q_password.toUtf8().data(), q_password.size()); ret = TRUE; } } } } } // This function currently closes the wallet if no other application // is connected to the wallet. We're waiting for this to be fixed // upstream, see https://bugs.kde.org/show_bug.cgi?id=162570 // KWallet::Wallet::disconnectApplication(wallet_name, // QString::fromUtf8("Subversion")); return ret; } /* Implementation of svn_auth__password_set_t that stores the password in KWallet. */ static svn_boolean_t kwallet_password_set(apr_hash_t *creds, const char *realmstring, const char *username, const char *password, svn_boolean_t non_interactive, apr_pool_t *pool) { if (non_interactive) { return FALSE; } if (! KWallet::Wallet::isEnabled()) { return FALSE; } KCmdLineArgs::init(1, (char *[1]) { "svn" }, "Subversion", "subversion", ki18n("Subversion"), SVN_VER_NUMBER, ki18n("Version control system"), KCmdLineArgs::CmdLineArgKDE); KApplication application; svn_boolean_t ret = FALSE; QString q_password = QString::fromUtf8(password); QString wallet_name = KWallet::Wallet::NetworkWallet(); QString folder = QString::fromUtf8("Subversion"); KWallet::Wallet *wallet = KWallet::Wallet::openWallet(wallet_name, -1, KWallet::Wallet::Synchronous); if (wallet) { if (! wallet->hasFolder(folder)) { wallet->createFolder(folder); } if (wallet->hasFolder(folder)) { if (wallet->setFolder(folder)) { QString key = QString::fromUtf8(username) + "@" + QString::fromUtf8(realmstring); if (wallet->writePassword(key, q_password) == 0) { ret = TRUE; } } } } // This function currently closes the wallet if no other application // is connected to the wallet. We're waiting for this to be fixed // upstream, see https://bugs.kde.org/show_bug.cgi?id=162570 // KWallet::Wallet::disconnectApplication(wallet_name, // QString::fromUtf8("Subversion")); return ret; } /* Get cached encrypted credentials from the simple provider's cache. */ static svn_error_t * kwallet_simple_first_creds(void **credentials, void **iter_baton, void *provider_baton, apr_hash_t *parameters, const char *realmstring, apr_pool_t *pool) { return svn_auth__simple_first_creds_helper(credentials, iter_baton, provider_baton, parameters, realmstring, kwallet_password_get, SVN_AUTH__KWALLET_PASSWORD_TYPE, pool); } /* Save encrypted credentials to the simple provider's cache. */ static svn_error_t * kwallet_simple_save_creds(svn_boolean_t *saved, void *credentials, void *provider_baton, apr_hash_t *parameters, const char *realmstring, apr_pool_t *pool) { return svn_auth__simple_save_creds_helper(saved, credentials, provider_baton, parameters, realmstring, kwallet_password_set, SVN_AUTH__KWALLET_PASSWORD_TYPE, pool); } static const svn_auth_provider_t kwallet_simple_provider = { SVN_AUTH_CRED_SIMPLE, kwallet_simple_first_creds, NULL, kwallet_simple_save_creds }; /* Public API */ extern "C" { void svn_auth_get_kwallet_simple_provider(svn_auth_provider_object_t **provider, apr_pool_t *pool) { svn_auth_provider_object_t *po = static_cast<svn_auth_provider_object_t *> (apr_pcalloc(pool, sizeof(*po))); po->vtable = &kwallet_simple_provider; *provider = po; } } <|endoftext|>
<commit_before>/* * Copyright (c) 2011 The WebRTC project authors. All Rights Reserved. * * Use of this source code is governed by a BSD-style license * that can be found in the LICENSE file in the root of the source * tree. An additional intellectual property rights grant can be found * in the file PATENTS. All contributing project authors may * be found in the AUTHORS file in the root of the source tree. */ #include "webrtc/system_wrappers/interface/trace.h" namespace webrtc { void Trace::CreateTrace() { } void Trace::ReturnTrace() { } int32_t Trace::SetLevelFilter(uint32_t filter) { return 0; } int32_t Trace::LevelFilter(uint32_t& filter) { return 0; } int32_t Trace::TraceFile(char file_name[1024]) { return -1; } int32_t Trace::SetTraceFile(const char* file_name, const bool add_file_counter) { return -1; } int32_t Trace::SetTraceCallback(TraceCallback* callback) { return -1; } void Trace::Add(const TraceLevel level, const TraceModule module, const int32_t id, const char* msg, ...) { } } // namespace webrtc <commit_msg>Fixes linker issue with no op trace.<commit_after>/* * Copyright (c) 2011 The WebRTC project authors. All Rights Reserved. * * Use of this source code is governed by a BSD-style license * that can be found in the LICENSE file in the root of the source * tree. An additional intellectual property rights grant can be found * in the file PATENTS. All contributing project authors may * be found in the AUTHORS file in the root of the source tree. */ #include "webrtc/system_wrappers/interface/trace.h" namespace webrtc { const int Trace::kBoilerplateLength = 71; const int Trace::kTimestampPosition = 13; const int Trace::kTimestampLength = 12; void Trace::CreateTrace() { } void Trace::ReturnTrace() { } int32_t Trace::SetLevelFilter(uint32_t filter) { return 0; } int32_t Trace::LevelFilter(uint32_t& filter) { return 0; } int32_t Trace::TraceFile(char file_name[1024]) { return -1; } int32_t Trace::SetTraceFile(const char* file_name, const bool add_file_counter) { return -1; } int32_t Trace::SetTraceCallback(TraceCallback* callback) { return -1; } void Trace::Add(const TraceLevel level, const TraceModule module, const int32_t id, const char* msg, ...) { } } // namespace webrtc <|endoftext|>
<commit_before>#include <iostream> #include "DrakeCollision.h" #include "BulletModel.h" using namespace std; using namespace Eigen; namespace DrakeCollision { BulletElement::BulletElement(const Matrix4d& T_elem_to_link, Shape shape, const vector<double>& params, const string& group_name, bool use_margins) : T_elem_to_link(T_elem_to_link),shape(shape) { setGroupName(group_name); //DEBUG //std::cout << "BulletElement::BulletElement: START" << std::endl; //END_DEBUG btCollisionShape* bt_shape; switch (shape) { case BOX: { //DEBUG //std::cout << "BulletElement::BulletElement: Create BOX ..." << std::endl; //END_DEBUG btBoxShape bt_box( btVector3(params[0]/2,params[1]/2,params[2]/2) ); /* Strange things happen to the collision-normals when we use the * convex interface to the btBoxShape. Instead, we'll explicitly create * a btConvexHullShape. */ bt_shape = new btConvexHullShape(); if (use_margins) bt_shape->setMargin(0.05); else bt_shape->setMargin(0.0); for (int i=0; i<8; ++i){ btVector3 vtx; bt_box.getVertex(i,vtx); dynamic_cast<btConvexHullShape*>(bt_shape)->addPoint(vtx); } //DEBUG //std::cout << "BulletElement::BulletElement: Created BOX" << std::endl; //END_DEBUG } break; case SPHERE: if (true || params[0] != 0) { //DEBUG //std::cout << "BulletElement::BulletElement: Create SPHERE ..." << std::endl; //END_DEBUG bt_shape = new btSphereShape(params[0]) ; //DEBUG //std::cout << "BulletElement::BulletElement: Created SPHERE" << std::endl; //END_DEBUG } else { //DEBUG //std::cout << "BulletElement::BulletElement: THROW" << std::endl; //END_DEBUG throw zeroRadiusSphereException(); } break; case CYLINDER: //DEBUG //std::cout << "BulletElement::BulletElement: Create CYLINDER ..." << std::endl; //END_DEBUG bt_shape = new btCylinderShapeZ( btVector3(params[0],params[0],params[1]/2) ); //DEBUG //std::cout << "BulletElement::BulletElement: Created CYLINDER ..." << std::endl; //END_DEBUG break; case MESH: //DEBUG //std::cout << "BulletElement::BulletElement: Create MESH ..." << std::endl; //END_DEBUG //bt_shape = new btConvexHullShape( (btScalar*) params.data(), //params.size()/3, //(int) 3*sizeof(double) ); bt_shape = new btConvexHullShape(); if (use_margins) bt_shape->setMargin(0.05); else bt_shape->setMargin(0.0); for (int i=0; i<params.size(); i+=3){ //DEBUG //std::cout << "BulletElement::BulletElement: Adding point " << i/3 + 1 << std::endl; //END_DEBUG dynamic_cast<btConvexHullShape*>(bt_shape)->addPoint(btVector3(params[i],params[i+1],params[i+2])); } //DEBUG //std::cout << "BulletElement::BulletElement: Created MESH ..." << std::endl; //END_DEBUG break; case CAPSULE: bt_shape = new btConvexHullShape(); dynamic_cast<btConvexHullShape*>(bt_shape)->addPoint(btVector3(0,0,-params[1]/2)); dynamic_cast<btConvexHullShape*>(bt_shape)->addPoint(btVector3(0,0,params[1]/2)); bt_shape->setMargin(params[0]); break; default: cerr << "Warning: Collision element has an unknown type " << shape << endl; //DEBUG //std::cout << "BulletElement::BulletElement: THROW" << std::endl; //END_DEBUG throw unknownShapeException(shape); break; } //DEBUG //cout << "BulletElement::BulletElement: Creating btCollisionObject" << endl; //END_DEBUG bt_obj = make_shared<btCollisionObject>(); //DEBUG //cout << "BulletElement::BulletElement: Setting bt_shape for bt_ob" << endl; //END_DEBUG bt_obj->setCollisionShape(bt_shape); //DEBUG //cout << "BulletElement::BulletElement: Setting world transform for bt_ob" << endl; //END_DEBUG setWorldTransform(Matrix4d::Identity()); //DEBUG //cout << "BulletElement::BulletElement: END" << std::endl; //END_DEBUG } const Matrix4d& BulletElement::getWorldTransform() const { return T_elem_to_world; } const Matrix4d& BulletElement::getLinkTransform() const { return T_elem_to_link; } const Shape& BulletElement::getShape() const { return shape; } void BulletElement::updateWorldTransform(const Matrix4d& T_link_to_world) { setWorldTransform(T_link_to_world*(this->T_elem_to_link)); } void BulletElement::setWorldTransform(const Matrix4d& T) { this->T_elem_to_world = T_elem_to_world; btMatrix3x3 rot; btVector3 pos; btTransform btT; rot.setValue( T(0,0), T(0,1), T(0,2), T(1,0), T(1,1), T(1,2), T(2,0), T(2,1), T(2,2) ); btT.setBasis(rot); pos.setValue( T(0,3), T(1,3), T(2,3) ); btT.setOrigin(pos); bt_obj->setWorldTransform(btT); } const string& BulletElement::getGroupName() const { return group_name; } void BulletElement::setGroupName(const string& group_name) { this->group_name = group_name; } } <commit_msg>Add 1e-8 m margin to the no-margin model.<commit_after>#include <iostream> #include "DrakeCollision.h" #include "BulletModel.h" using namespace std; using namespace Eigen; namespace DrakeCollision { BulletElement::BulletElement(const Matrix4d& T_elem_to_link, Shape shape, const vector<double>& params, const string& group_name, bool use_margins) : T_elem_to_link(T_elem_to_link),shape(shape) { setGroupName(group_name); //DEBUG //std::cout << "BulletElement::BulletElement: START" << std::endl; //END_DEBUG btCollisionShape* bt_shape; double small_margin = 1e-8; switch (shape) { case BOX: { //DEBUG //std::cout << "BulletElement::BulletElement: Create BOX ..." << std::endl; //END_DEBUG btBoxShape bt_box( btVector3(params[0]/2,params[1]/2,params[2]/2) ); /* Strange things happen to the collision-normals when we use the * convex interface to the btBoxShape. Instead, we'll explicitly create * a btConvexHullShape. */ bt_shape = new btConvexHullShape(); if (use_margins) bt_shape->setMargin(0.05); else bt_shape->setMargin(small_margin); for (int i=0; i<8; ++i){ btVector3 vtx; bt_box.getVertex(i,vtx); dynamic_cast<btConvexHullShape*>(bt_shape)->addPoint(vtx); } //DEBUG //std::cout << "BulletElement::BulletElement: Created BOX" << std::endl; //END_DEBUG } break; case SPHERE: if (true || params[0] != 0) { //DEBUG //std::cout << "BulletElement::BulletElement: Create SPHERE ..." << std::endl; //END_DEBUG bt_shape = new btSphereShape(params[0]) ; //DEBUG //std::cout << "BulletElement::BulletElement: Created SPHERE" << std::endl; //END_DEBUG } else { //DEBUG //std::cout << "BulletElement::BulletElement: THROW" << std::endl; //END_DEBUG throw zeroRadiusSphereException(); } break; case CYLINDER: //DEBUG //std::cout << "BulletElement::BulletElement: Create CYLINDER ..." << std::endl; //END_DEBUG bt_shape = new btCylinderShapeZ( btVector3(params[0],params[0],params[1]/2) ); //DEBUG //std::cout << "BulletElement::BulletElement: Created CYLINDER ..." << std::endl; //END_DEBUG break; case MESH: //DEBUG //std::cout << "BulletElement::BulletElement: Create MESH ..." << std::endl; //END_DEBUG //bt_shape = new btConvexHullShape( (btScalar*) params.data(), //params.size()/3, //(int) 3*sizeof(double) ); bt_shape = new btConvexHullShape(); if (use_margins) bt_shape->setMargin(0.05); else bt_shape->setMargin(small_margin); for (int i=0; i<params.size(); i+=3){ //DEBUG //std::cout << "BulletElement::BulletElement: Adding point " << i/3 + 1 << std::endl; //END_DEBUG dynamic_cast<btConvexHullShape*>(bt_shape)->addPoint(btVector3(params[i],params[i+1],params[i+2])); } //DEBUG //std::cout << "BulletElement::BulletElement: Created MESH ..." << std::endl; //END_DEBUG break; case CAPSULE: bt_shape = new btConvexHullShape(); dynamic_cast<btConvexHullShape*>(bt_shape)->addPoint(btVector3(0,0,-params[1]/2)); dynamic_cast<btConvexHullShape*>(bt_shape)->addPoint(btVector3(0,0,params[1]/2)); bt_shape->setMargin(params[0]); break; default: cerr << "Warning: Collision element has an unknown type " << shape << endl; //DEBUG //std::cout << "BulletElement::BulletElement: THROW" << std::endl; //END_DEBUG throw unknownShapeException(shape); break; } //DEBUG //cout << "BulletElement::BulletElement: Creating btCollisionObject" << endl; //END_DEBUG bt_obj = make_shared<btCollisionObject>(); //DEBUG //cout << "BulletElement::BulletElement: Setting bt_shape for bt_ob" << endl; //END_DEBUG bt_obj->setCollisionShape(bt_shape); //DEBUG //cout << "BulletElement::BulletElement: Setting world transform for bt_ob" << endl; //END_DEBUG setWorldTransform(Matrix4d::Identity()); //DEBUG //cout << "BulletElement::BulletElement: END" << std::endl; //END_DEBUG } const Matrix4d& BulletElement::getWorldTransform() const { return T_elem_to_world; } const Matrix4d& BulletElement::getLinkTransform() const { return T_elem_to_link; } const Shape& BulletElement::getShape() const { return shape; } void BulletElement::updateWorldTransform(const Matrix4d& T_link_to_world) { setWorldTransform(T_link_to_world*(this->T_elem_to_link)); } void BulletElement::setWorldTransform(const Matrix4d& T) { this->T_elem_to_world = T_elem_to_world; btMatrix3x3 rot; btVector3 pos; btTransform btT; rot.setValue( T(0,0), T(0,1), T(0,2), T(1,0), T(1,1), T(1,2), T(2,0), T(2,1), T(2,2) ); btT.setBasis(rot); pos.setValue( T(0,3), T(1,3), T(2,3) ); btT.setOrigin(pos); bt_obj->setWorldTransform(btT); } const string& BulletElement::getGroupName() const { return group_name; } void BulletElement::setGroupName(const string& group_name) { this->group_name = group_name; } } <|endoftext|>
<commit_before> #include "PINTracker.hh" #include "Exception.hh" #include "Config.hh" #include "ProcessState.hh" namespace aegir { /* * PINTracker::PIN */ PINTracker::PIN::PIN(const std::string &_name): c_name(_name) { c_value = PINState::Off; c_newvalue = PINState::Off; } PINTracker::PIN::~PIN() { } PINState PINTracker::PIN::getValue() { return c_value; } float PINTracker::PIN::getCycletime() { return c_cycletime; } float PINTracker::PIN::getOnratio() { return c_onratio; } void PINTracker::PIN::pushback() { #ifdef AEGIR_DEBUG printf("PINTracker::PIN::pushback(%p): %s V:%hhu<-%hhu CT:%.2f<-%.2f OR:%.2f<-%.2f\n", (void*)this, c_name.c_str(), c_value, c_newvalue, c_cycletime, c_newcycletime, c_onratio, c_newonratio); #endif c_value = c_newvalue; c_cycletime = c_newcycletime; c_onratio = c_newonratio; } /* * PINTracker::OutPIN */ PINTracker::OutPIN::OutPIN(const std::string &_name, PINChanges &_pcq): PINTracker::PIN(_name), c_pcq(_pcq) { c_type = PINTracker::PIN::PINType::OUT; } PINTracker::OutPIN::~OutPIN() { } PINState PINTracker::OutPIN::getValue() { return c_value; } /* * if newval!=oldval, then has to be in the queue * if newval==oldval, then hos to be absent from the queue */ void PINTracker::OutPIN::setValue(PINState _v, float _cycletime, float _onratio) { c_newvalue = _v; c_newcycletime = _cycletime; c_newonratio = _onratio; #ifdef AEGIR_DEBUG printf("PINTracker::OutPIN::setValue(%p, %s, %hhu->%hhu, %.2f->%.2f, %.2f->%.2f)\n", (void*)this, c_name.c_str(), c_value, c_newvalue, c_cycletime, c_newcycletime, c_onratio, c_newonratio); #endif auto it = c_pcq.find(this); if ( c_value != c_newvalue || (c_newvalue == PINState::Pulsate && (c_cycletime != c_newcycletime || c_onratio != c_newonratio))) { if ( it == c_pcq.end() ) { c_pcq.insert(this); } return; } // chg == false here if ( it != c_pcq.end() ) { c_pcq.erase(it); } } /* * PINTracker::InPIN */ PINTracker::InPIN::InPIN(const std::string &_name, PINChanges &_inch): PINTracker::PIN(_name), c_inch(_inch) { c_type = PINTracker::PIN::PINType::IN; } PINTracker::InPIN::~InPIN() { } PINState PINTracker::InPIN::getValue() { return c_newvalue; } /* * if newval!=oldval, then has to be in the queue * if newval==oldval, then hos to be absent from the queue */ void PINTracker::InPIN::setValue(PINState _v, float _cycletime, float _onratio) { c_newvalue = _v; c_newcycletime = _cycletime; c_newonratio = _onratio; #ifdef AEGIR_DEBUG printf("PINTracker::InPIN::setValue(%s, %hhu->%hhu, %.2f->%.2f, %.2f->%.2f)\n", c_name.c_str(), c_value, c_newvalue, c_cycletime, c_newcycletime, c_onratio, c_newonratio); #endif auto it = c_inch.find(this); if ( c_value == c_newvalue || ((c_newvalue == PINState::Pulsate) && ( c_cycletime == c_newcycletime && c_onratio == c_newonratio)) ) { if ( it != c_inch.end() ) c_inch.erase(it); return; } if ( it == c_inch.end() ) c_inch.insert(this); } /* * PINTracker */ PINTracker::PINTracker() { } PINTracker::~PINTracker() { c_pinchangequeue.clear(); c_inpinchanges.clear(); c_pins.clear(); } void PINTracker::reconfigure() { if ( ProcessState::getInstance().isActive() ) throw Exception("PINTracker cannot be reconfigured while a process is in progress"); // configure the pins #if 0 printf("PINTracker::reconfigure(): Wiping already configured pins:\n"); for ( auto &it: c_pins ) printf(" - PIN: %s\n", it.first.c_str()); #endif c_pins.clear(); for ( auto &it: g_pinconfig ) { if ( it.second.mode == PinMode::IN ) { auto x = std::make_shared<InPIN>(it.first, c_inpinchanges); c_pins[it.first] = std::dynamic_pointer_cast<PIN>(x); } else if ( it.second.mode == PinMode::OUT ) { auto x = std::make_shared<OutPIN>(it.first, c_pinchangequeue); c_pins[it.first] = std::dynamic_pointer_cast<PIN>(x); } } } void PINTracker::startCycle() { } void PINTracker::endCycle() { if ( c_inpinchanges.size() ) { for ( auto &it: c_inpinchanges ) it->pushback(); c_inpinchanges.clear(); } if ( c_pinchangequeue.size() ) { for ( auto &it: c_pinchangequeue ) { handleOutPIN(*it); it->pushback(); } c_pinchangequeue.clear(); } } std::shared_ptr<PINTracker::PIN> PINTracker::getPIN(const std::string &_name) { auto it = c_pins.find(_name); if ( it == c_pins.end() ) throw Exception("Unknown PIN: %s", _name.c_str()); return it->second; } void PINTracker::setPIN(const std::string &_name, PINState _value, float _cycletime, float _onratio) { #ifdef AEGIR_DEBUG printf("PINTracker::setPIN(%s, %hhu, %.2f %.2f)\n", _name.c_str(), _value, _cycletime, _onratio); #endif auto it = c_pins.find(_name); if ( it != c_pins.end() ) { #ifdef AEGIR_DEBUG printf("PINTracker::setPIN(%s): type: %hhu\n", _name.c_str(), it->second->getType()); #endif if ( it->second->getType() == PIN::PINType::OUT ) { auto sppin = std::static_pointer_cast<OutPIN>(it->second); sppin->setValue(_value, _cycletime, _onratio); } else if ( it->second->getType() == PIN::PINType::IN ) { auto sppin = std::static_pointer_cast<InPIN>(it->second); sppin->setValue(_value); } } else { printf("PINTracker::setPIN(%s): not found\n", _name.c_str()); } } bool PINTracker::hasChanged(const std::string &_name) { auto it = c_pins.find(_name); if ( it == c_pins.end() ) throw Exception("PINTracker::hasChanged(%s): no such PIN", _name.c_str()); return it->second->isChanged(); } bool PINTracker::hasChanged(const std::string &_name, std::shared_ptr<PIN> &_pin) { auto it = c_pins.find(_name); if ( it == c_pins.end() ) throw Exception("PINTracker::hasChanged(%s): no such PIN", _name.c_str()); _pin = it->second; return _pin->isChanged(); } } <commit_msg>[brewd] PINTracker::OutPIN::SetValue now setting the ratio on on/off states as well<commit_after> #include "PINTracker.hh" #include "Exception.hh" #include "Config.hh" #include "ProcessState.hh" namespace aegir { /* * PINTracker::PIN */ PINTracker::PIN::PIN(const std::string &_name): c_name(_name) { c_value = PINState::Off; c_newvalue = PINState::Off; } PINTracker::PIN::~PIN() { } PINState PINTracker::PIN::getValue() { return c_value; } float PINTracker::PIN::getCycletime() { return c_cycletime; } float PINTracker::PIN::getOnratio() { return c_onratio; } void PINTracker::PIN::pushback() { #ifdef AEGIR_DEBUG printf("PINTracker::PIN::pushback(%p): %s V:%hhu<-%hhu CT:%.2f<-%.2f OR:%.2f<-%.2f\n", (void*)this, c_name.c_str(), c_value, c_newvalue, c_cycletime, c_newcycletime, c_onratio, c_newonratio); #endif c_value = c_newvalue; c_cycletime = c_newcycletime; c_onratio = c_newonratio; } /* * PINTracker::OutPIN */ PINTracker::OutPIN::OutPIN(const std::string &_name, PINChanges &_pcq): PINTracker::PIN(_name), c_pcq(_pcq) { c_type = PINTracker::PIN::PINType::OUT; } PINTracker::OutPIN::~OutPIN() { } PINState PINTracker::OutPIN::getValue() { return c_value; } /* * if newval!=oldval, then has to be in the queue * if newval==oldval, then hos to be absent from the queue */ void PINTracker::OutPIN::setValue(PINState _v, float _cycletime, float _onratio) { c_newcycletime = _cycletime; switch (_v) { case PINState::On: c_newonratio = 1; break; case PINState::Off: c_newonratio = 0; break; default: c_newonratio = _onratio; } if ( _v == PINState::Pulsate ) { if ( c_newonratio <= 0 ) c_newvalue = PINState::Off; else if ( c_newonratio >= 1 ) c_newvalue = PINState::On; else c_newvalue = _v; } else { c_newvalue = _v; } #ifdef AEGIR_DEBUG printf("PINTracker::OutPIN::setValue(%p, %s, %hhu->%hhu, %.2f->%.2f, %.2f->%.2f)\n", (void*)this, c_name.c_str(), c_value, c_newvalue, c_cycletime, c_newcycletime, c_onratio, c_newonratio); #endif auto it = c_pcq.find(this); if ( c_value != c_newvalue || (c_newvalue == PINState::Pulsate && (c_cycletime != c_newcycletime || c_onratio != c_newonratio))) { if ( it == c_pcq.end() ) { c_pcq.insert(this); } return; } // chg == false here if ( it != c_pcq.end() ) { c_pcq.erase(it); } } /* * PINTracker::InPIN */ PINTracker::InPIN::InPIN(const std::string &_name, PINChanges &_inch): PINTracker::PIN(_name), c_inch(_inch) { c_type = PINTracker::PIN::PINType::IN; } PINTracker::InPIN::~InPIN() { } PINState PINTracker::InPIN::getValue() { return c_newvalue; } /* * if newval!=oldval, then has to be in the queue * if newval==oldval, then hos to be absent from the queue */ void PINTracker::InPIN::setValue(PINState _v, float _cycletime, float _onratio) { c_newvalue = _v; c_newcycletime = _cycletime; c_newonratio = _onratio; #ifdef AEGIR_DEBUG printf("PINTracker::InPIN::setValue(%s, %hhu->%hhu, %.2f->%.2f, %.2f->%.2f)\n", c_name.c_str(), c_value, c_newvalue, c_cycletime, c_newcycletime, c_onratio, c_newonratio); #endif auto it = c_inch.find(this); if ( c_value == c_newvalue || ((c_newvalue == PINState::Pulsate) && ( c_cycletime == c_newcycletime && c_onratio == c_newonratio)) ) { if ( it != c_inch.end() ) c_inch.erase(it); return; } if ( it == c_inch.end() ) c_inch.insert(this); } /* * PINTracker */ PINTracker::PINTracker() { } PINTracker::~PINTracker() { c_pinchangequeue.clear(); c_inpinchanges.clear(); c_pins.clear(); } void PINTracker::reconfigure() { if ( ProcessState::getInstance().isActive() ) throw Exception("PINTracker cannot be reconfigured while a process is in progress"); // configure the pins #if 0 printf("PINTracker::reconfigure(): Wiping already configured pins:\n"); for ( auto &it: c_pins ) printf(" - PIN: %s\n", it.first.c_str()); #endif c_pins.clear(); for ( auto &it: g_pinconfig ) { if ( it.second.mode == PinMode::IN ) { auto x = std::make_shared<InPIN>(it.first, c_inpinchanges); c_pins[it.first] = std::dynamic_pointer_cast<PIN>(x); } else if ( it.second.mode == PinMode::OUT ) { auto x = std::make_shared<OutPIN>(it.first, c_pinchangequeue); c_pins[it.first] = std::dynamic_pointer_cast<PIN>(x); } } } void PINTracker::startCycle() { } void PINTracker::endCycle() { if ( c_inpinchanges.size() ) { for ( auto &it: c_inpinchanges ) it->pushback(); c_inpinchanges.clear(); } if ( c_pinchangequeue.size() ) { for ( auto &it: c_pinchangequeue ) { handleOutPIN(*it); it->pushback(); } c_pinchangequeue.clear(); } } std::shared_ptr<PINTracker::PIN> PINTracker::getPIN(const std::string &_name) { auto it = c_pins.find(_name); if ( it == c_pins.end() ) throw Exception("Unknown PIN: %s", _name.c_str()); return it->second; } void PINTracker::setPIN(const std::string &_name, PINState _value, float _cycletime, float _onratio) { #ifdef AEGIR_DEBUG printf("PINTracker::setPIN(%s, %hhu, %.2f %.2f)\n", _name.c_str(), _value, _cycletime, _onratio); #endif auto it = c_pins.find(_name); if ( it != c_pins.end() ) { #ifdef AEGIR_DEBUG printf("PINTracker::setPIN(%s): type: %hhu\n", _name.c_str(), it->second->getType()); #endif if ( it->second->getType() == PIN::PINType::OUT ) { auto sppin = std::static_pointer_cast<OutPIN>(it->second); sppin->setValue(_value, _cycletime, _onratio); } else if ( it->second->getType() == PIN::PINType::IN ) { auto sppin = std::static_pointer_cast<InPIN>(it->second); sppin->setValue(_value); } } else { printf("PINTracker::setPIN(%s): not found\n", _name.c_str()); } } bool PINTracker::hasChanged(const std::string &_name) { auto it = c_pins.find(_name); if ( it == c_pins.end() ) throw Exception("PINTracker::hasChanged(%s): no such PIN", _name.c_str()); return it->second->isChanged(); } bool PINTracker::hasChanged(const std::string &_name, std::shared_ptr<PIN> &_pin) { auto it = c_pins.find(_name); if ( it == c_pins.end() ) throw Exception("PINTracker::hasChanged(%s): no such PIN", _name.c_str()); _pin = it->second; return _pin->isChanged(); } } <|endoftext|>
<commit_before>#pragma once #include <type_traits> #include <agency/detail/tuple.hpp> #include <agency/executor_traits.hpp> #include <agency/execution_categories.hpp> #include <agency/nested_executor.hpp> #include <agency/detail/factory.hpp> #include <agency/detail/optional.hpp> #include <agency/detail/project_index_and_invoke.hpp> #include <agency/detail/array.hpp> namespace agency { namespace detail { // XXX we should find a better home for this functionality because grid_executor.hpp replicates this code template<class Container> struct guarded_container : Container { using Container::Container; __AGENCY_ANNOTATION guarded_container() : Container() {} __AGENCY_ANNOTATION guarded_container(Container&& other) : Container(std::move(other)) {} struct reference { Container& self_; template<class OptionalValueAndIndex> __AGENCY_ANNOTATION void operator=(OptionalValueAndIndex&& opt) { if(opt) { auto idx = opt.value().index; self_[idx] = std::forward<OptionalValueAndIndex>(opt).value().value; } } }; template<class Index> __AGENCY_ANNOTATION reference operator[](const Index&) { return reference{*this}; } }; template<class Container> __AGENCY_ANNOTATION guarded_container<typename std::decay<Container>::type> make_guarded_container(Container&& value) { return guarded_container<typename std::decay<Container>::type>(std::forward<Container>(value)); } template<class Factory, class Shape> struct guarded_container_factory { Factory factory_; Shape shape_; using container_type = typename std::result_of<Factory(Shape)>::type; __agency_hd_warning_disable__ template<class Arg> __AGENCY_ANNOTATION guarded_container<container_type> operator()(const Arg&) { return make_guarded_container(factory_(shape_)); } }; template<class ExecutionCategory> struct flattened_execution_tag_impl; template<class OuterCategory, class InnerCategory> struct flattened_execution_tag_impl<nested_execution_tag<OuterCategory,InnerCategory>> { using type = parallel_execution_tag; }; template<class OuterCategory, class InnerCategory, class InnerInnerCategory> struct flattened_execution_tag_impl<nested_execution_tag<OuterCategory, nested_execution_tag<InnerCategory,InnerInnerCategory>>> { // OuterCategory and InnerInnerCategory merge into parallel as the outer category // while InnerInnerCategory is promoted to the inner category using type = nested_execution_tag< parallel_execution_tag, InnerInnerCategory >; }; template<class ExecutionCategory> using flattened_execution_tag = typename flattened_execution_tag_impl<ExecutionCategory>::type; template<class TypeList> struct flattened_shape_type; template<class Shape1, class Shape2, class... Shapes> struct flattened_shape_type<type_list<Shape1,Shape2,Shapes...>> { // XXX we probably want to think carefully about what it means two "merge" two arithmetic tuples together template<class T1, class T2> using merge_shapes_t = typename std::common_type<T1,T2>::type; using tuple_type = shape_tuple< merge_shapes_t<Shape1,Shape2>, Shapes... >; // unwrap single-element tuples using type = typename std::conditional< (std::tuple_size<tuple_type>::value == 1), typename std::tuple_element<0,tuple_type>::type, tuple_type >::type; }; // XXX need to do something similar as execution_category // the two leftmost indices merge into one while the rest of the indices shift one space left template<class ShapeTuple> using flattened_shape_type_t = typename flattened_shape_type<tuple_elements<ShapeTuple>>::type; template<class TypeList> struct flattened_index_type; template<class Index1, class Index2, class... Indices> struct flattened_index_type<type_list<Index1,Index2,Indices...>> { // XXX we probably want to think carefully about what it means two "merge" two arithmetic tuples together template<class T1, class T2> using merge_indices_t = typename std::common_type<T1,T2>::type; using tuple_type = index_tuple< merge_indices_t<Index1,Index2>, Indices... >; // unwrap single-element tuples using type = typename std::conditional< (std::tuple_size<tuple_type>::value == 1), typename std::tuple_element<0,tuple_type>::type, tuple_type >::type; }; template<class IndexTuple> using flattened_index_type_t = flattened_shape_type_t<IndexTuple>; } // end detail template<class Executor> class flattened_executor { // probably shouldn't insist on a nested executor static_assert( detail::is_nested_execution_category<typename executor_traits<Executor>::execution_category>::value, "Execution category of Executor must be nested." ); private: using base_traits = executor_traits<Executor>; using base_execution_category = typename base_traits::execution_category; public: using base_executor_type = Executor; using execution_category = detail::flattened_execution_tag<base_execution_category>; using shape_type = detail::flattened_shape_type_t<typename base_traits::shape_type>; using index_type = detail::flattened_shape_type_t<typename base_traits::index_type>; template<class T> using future = typename base_traits::template future<T>; template<class T> using container = detail::array<T, shape_type, typename base_traits::template allocator<T>>; future<void> make_ready_future() { return executor_traits<base_executor_type>::make_ready_future(base_executor()); } flattened_executor(const base_executor_type& base_executor = base_executor_type()) : min_inner_size_(1000), outer_subscription_(std::max(1u, log2(std::max(1u,std::thread::hardware_concurrency())))), base_executor_(base_executor) {} template<class Function, class Factory1, class Future, class Factory2> future<typename std::result_of<Factory1(shape_type)>::type> then_execute(Function f, Factory1 result_factory, shape_type shape, Future& dependency, Factory2 shared_factory) { auto partitioning = partition(shape); // store results into an intermediate result detail::guarded_container_factory<Factory1,shape_type> intermediate_result_factory{result_factory,shape}; // create a function to execute using base_index_type = typename executor_traits<base_executor_type>::index_type; auto execute_me = detail::make_project_index_and_invoke<base_index_type>(f, partitioning, shape); // execute auto intermediate_fut = executor_traits<base_executor_type>::then_execute(base_executor(), execute_me, intermediate_result_factory, partitioning, dependency, shared_factory, agency::detail::unit_factory()); // cast the intermediate result to the type of result expected by the caller using result_type = typename std::result_of<Factory1(shape_type)>::type; return executor_traits<base_executor_type>::template future_cast<result_type>(base_executor(), intermediate_fut); } const base_executor_type& base_executor() const { return base_executor_; } base_executor_type& base_executor() { return base_executor_; } private: using partition_type = typename executor_traits<base_executor_type>::shape_type; // returns (outer size, inner size) partition_type partition(shape_type shape) const { // avoid division by zero below // XXX implement me! // if(is_empty(shape)) return partition_type{}; using outer_shape_type = typename std::tuple_element<0,partition_type>::type; using inner_shape_type = typename std::tuple_element<1,partition_type>::type; outer_shape_type outer_size = (shape + min_inner_size_ - 1) / min_inner_size_; outer_size = std::min<size_t>(outer_subscription_ * std::thread::hardware_concurrency(), outer_size); inner_shape_type inner_size = (shape + outer_size - 1) / outer_size; return partition_type{outer_size, inner_size}; } inline static unsigned int log2(unsigned int x) { unsigned int result = 0; while(x >>= 1) ++result; return result; } size_t min_inner_size_; size_t outer_subscription_; base_executor_type base_executor_; }; } // end agency <commit_msg>Add a TODO to flattened_executor.hpp<commit_after>#pragma once #include <type_traits> #include <agency/detail/tuple.hpp> #include <agency/executor_traits.hpp> #include <agency/execution_categories.hpp> #include <agency/nested_executor.hpp> #include <agency/detail/factory.hpp> #include <agency/detail/optional.hpp> #include <agency/detail/project_index_and_invoke.hpp> #include <agency/detail/array.hpp> namespace agency { namespace detail { // XXX we should find a better home for this functionality because grid_executor.hpp replicates this code template<class Container> struct guarded_container : Container { using Container::Container; __AGENCY_ANNOTATION guarded_container() : Container() {} __AGENCY_ANNOTATION guarded_container(Container&& other) : Container(std::move(other)) {} struct reference { Container& self_; template<class OptionalValueAndIndex> __AGENCY_ANNOTATION void operator=(OptionalValueAndIndex&& opt) { if(opt) { auto idx = opt.value().index; self_[idx] = std::forward<OptionalValueAndIndex>(opt).value().value; } } }; template<class Index> __AGENCY_ANNOTATION reference operator[](const Index&) { return reference{*this}; } }; template<class Container> __AGENCY_ANNOTATION guarded_container<typename std::decay<Container>::type> make_guarded_container(Container&& value) { return guarded_container<typename std::decay<Container>::type>(std::forward<Container>(value)); } template<class Factory, class Shape> struct guarded_container_factory { Factory factory_; Shape shape_; using container_type = typename std::result_of<Factory(Shape)>::type; __agency_hd_warning_disable__ template<class Arg> __AGENCY_ANNOTATION guarded_container<container_type> operator()(const Arg&) { return make_guarded_container(factory_(shape_)); } }; template<class ExecutionCategory> struct flattened_execution_tag_impl; template<class OuterCategory, class InnerCategory> struct flattened_execution_tag_impl<nested_execution_tag<OuterCategory,InnerCategory>> { using type = parallel_execution_tag; }; template<class OuterCategory, class InnerCategory, class InnerInnerCategory> struct flattened_execution_tag_impl<nested_execution_tag<OuterCategory, nested_execution_tag<InnerCategory,InnerInnerCategory>>> { // OuterCategory and InnerInnerCategory merge into parallel as the outer category // while InnerInnerCategory is promoted to the inner category using type = nested_execution_tag< parallel_execution_tag, InnerInnerCategory >; }; template<class ExecutionCategory> using flattened_execution_tag = typename flattened_execution_tag_impl<ExecutionCategory>::type; template<class TypeList> struct flattened_shape_type; template<class Shape1, class Shape2, class... Shapes> struct flattened_shape_type<type_list<Shape1,Shape2,Shapes...>> { // XXX we probably want to think carefully about what it means two "merge" two arithmetic tuples together template<class T1, class T2> using merge_shapes_t = typename std::common_type<T1,T2>::type; using tuple_type = shape_tuple< merge_shapes_t<Shape1,Shape2>, Shapes... >; // unwrap single-element tuples using type = typename std::conditional< (std::tuple_size<tuple_type>::value == 1), typename std::tuple_element<0,tuple_type>::type, tuple_type >::type; }; // XXX need to do something similar as execution_category // the two leftmost indices merge into one while the rest of the indices shift one space left template<class ShapeTuple> using flattened_shape_type_t = typename flattened_shape_type<tuple_elements<ShapeTuple>>::type; template<class TypeList> struct flattened_index_type; template<class Index1, class Index2, class... Indices> struct flattened_index_type<type_list<Index1,Index2,Indices...>> { // XXX we probably want to think carefully about what it means two "merge" two arithmetic tuples together template<class T1, class T2> using merge_indices_t = typename std::common_type<T1,T2>::type; using tuple_type = index_tuple< merge_indices_t<Index1,Index2>, Indices... >; // unwrap single-element tuples using type = typename std::conditional< (std::tuple_size<tuple_type>::value == 1), typename std::tuple_element<0,tuple_type>::type, tuple_type >::type; }; template<class IndexTuple> using flattened_index_type_t = flattened_shape_type_t<IndexTuple>; } // end detail template<class Executor> class flattened_executor { // probably shouldn't insist on a nested executor static_assert( detail::is_nested_execution_category<typename executor_traits<Executor>::execution_category>::value, "Execution category of Executor must be nested." ); private: using base_traits = executor_traits<Executor>; using base_execution_category = typename base_traits::execution_category; public: using base_executor_type = Executor; using execution_category = detail::flattened_execution_tag<base_execution_category>; using shape_type = detail::flattened_shape_type_t<typename base_traits::shape_type>; using index_type = detail::flattened_shape_type_t<typename base_traits::index_type>; template<class T> using future = typename base_traits::template future<T>; template<class T> using container = detail::array<T, shape_type, typename base_traits::template allocator<T>>; future<void> make_ready_future() { return executor_traits<base_executor_type>::make_ready_future(base_executor()); } flattened_executor(const base_executor_type& base_executor = base_executor_type()) : min_inner_size_(1000), outer_subscription_(std::max(1u, log2(std::max(1u,std::thread::hardware_concurrency())))), base_executor_(base_executor) {} // XXX need to generalize to multiple shared factories template<class Function, class Factory1, class Future, class Factory2> future<typename std::result_of<Factory1(shape_type)>::type> then_execute(Function f, Factory1 result_factory, shape_type shape, Future& dependency, Factory2 shared_factory) { auto partitioning = partition(shape); // store results into an intermediate result detail::guarded_container_factory<Factory1,shape_type> intermediate_result_factory{result_factory,shape}; // create a function to execute using base_index_type = typename executor_traits<base_executor_type>::index_type; auto execute_me = detail::make_project_index_and_invoke<base_index_type>(f, partitioning, shape); // execute auto intermediate_fut = executor_traits<base_executor_type>::then_execute(base_executor(), execute_me, intermediate_result_factory, partitioning, dependency, shared_factory, agency::detail::unit_factory()); // cast the intermediate result to the type of result expected by the caller using result_type = typename std::result_of<Factory1(shape_type)>::type; return executor_traits<base_executor_type>::template future_cast<result_type>(base_executor(), intermediate_fut); } const base_executor_type& base_executor() const { return base_executor_; } base_executor_type& base_executor() { return base_executor_; } private: using partition_type = typename executor_traits<base_executor_type>::shape_type; // returns (outer size, inner size) partition_type partition(shape_type shape) const { // avoid division by zero below // XXX implement me! // if(is_empty(shape)) return partition_type{}; using outer_shape_type = typename std::tuple_element<0,partition_type>::type; using inner_shape_type = typename std::tuple_element<1,partition_type>::type; outer_shape_type outer_size = (shape + min_inner_size_ - 1) / min_inner_size_; outer_size = std::min<size_t>(outer_subscription_ * std::thread::hardware_concurrency(), outer_size); inner_shape_type inner_size = (shape + outer_size - 1) / outer_size; return partition_type{outer_size, inner_size}; } inline static unsigned int log2(unsigned int x) { unsigned int result = 0; while(x >>= 1) ++result; return result; } size_t min_inner_size_; size_t outer_subscription_; base_executor_type base_executor_; }; } // end agency <|endoftext|>
<commit_before>/* * * Copyright 2015, Google Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following disclaimer * in the documentation and/or other materials provided with the * distribution. * * Neither the name of Google Inc. nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * */ #include <list> #include <thread> #include <deque> #include <vector> #include <grpc/support/alloc.h> #include <grpc/support/log.h> #include <grpc/support/host_port.h> #include <grpc++/client_context.h> #include <grpc++/create_channel.h> #include "src/core/support/env.h" #include "test/core/util/port.h" #include "test/core/util/test_config.h" #include "test/cpp/qps/driver.h" #include "test/cpp/qps/histogram.h" #include "test/cpp/qps/qps_worker.h" #include "src/proto/grpc/testing/services.grpc.pb.h" using std::list; using std::thread; using std::unique_ptr; using std::deque; using std::vector; namespace grpc { namespace testing { static deque<string> get_hosts(const string& name) { char* env = gpr_getenv(name.c_str()); if (!env) return deque<string>(); deque<string> out; char* p = env; for (;;) { char* comma = strchr(p, ','); if (comma) { out.emplace_back(p, comma); p = comma + 1; } else { out.emplace_back(p); gpr_free(env); return out; } } } // Namespace for classes and functions used only in RunScenario // Using this rather than local definitions to workaround gcc-4.4 limitations // regarding using templates without linkage namespace runsc { // ClientContext allocator template <class T> static ClientContext* AllocContext(list<ClientContext>* contexts, T deadline) { contexts->emplace_back(); auto context = &contexts->back(); context->set_deadline(deadline); return context; } struct ServerData { unique_ptr<WorkerService::Stub> stub; unique_ptr<ClientReaderWriter<ServerArgs, ServerStatus>> stream; }; struct ClientData { unique_ptr<WorkerService::Stub> stub; unique_ptr<ClientReaderWriter<ClientArgs, ClientStatus>> stream; }; } // namespace runsc std::unique_ptr<ScenarioResult> RunScenario( const ClientConfig& initial_client_config, size_t num_clients, const ServerConfig& server_config, size_t num_servers, int warmup_seconds, int benchmark_seconds, int spawn_local_worker_count) { // ClientContext allocations (all are destroyed at scope exit) list<ClientContext> contexts; // To be added to the result, containing the final configuration used for // client and config (including host, etc.) ClientConfig result_client_config; ServerConfig result_server_config; // Get client, server lists auto workers = get_hosts("QPS_WORKERS"); ClientConfig client_config = initial_client_config; // Spawn some local workers if desired vector<unique_ptr<QpsWorker>> local_workers; for (int i = 0; i < abs(spawn_local_worker_count); i++) { // act as if we're a new test -- gets a good rng seed static bool called_init = false; if (!called_init) { char args_buf[100]; strcpy(args_buf, "some-benchmark"); char* args[] = {args_buf}; grpc_test_init(1, args); called_init = true; } int driver_port = grpc_pick_unused_port_or_die(); local_workers.emplace_back(new QpsWorker(driver_port)); char addr[256]; sprintf(addr, "localhost:%d", driver_port); if (spawn_local_worker_count < 0) { workers.push_front(addr); } else { workers.push_back(addr); } } // TODO(ctiller): support running multiple configurations, and binpack // client/server pairs // to available workers GPR_ASSERT(workers.size() >= num_clients + num_servers); // Trim to just what we need workers.resize(num_clients + num_servers); gpr_timespec deadline = gpr_time_add(gpr_now(GPR_CLOCK_REALTIME), gpr_time_from_seconds( warmup_seconds + benchmark_seconds + 20, GPR_TIMESPAN)); // Start servers using runsc::ServerData; // servers is array rather than std::vector to avoid gcc-4.4 issues // where class contained in std::vector must have a copy constructor auto* servers = new ServerData[num_servers]; for (size_t i = 0; i < num_servers; i++) { gpr_log(GPR_INFO, "Starting server on %s (worker #%d)", workers[i].c_str(), i); servers[i].stub = WorkerService::NewStub( CreateChannel(workers[i], InsecureChannelCredentials())); ServerArgs args; result_server_config = server_config; *args.mutable_setup() = server_config; servers[i].stream = servers[i].stub->RunServer(runsc::AllocContext(&contexts, deadline)); GPR_ASSERT(servers[i].stream->Write(args)); ServerStatus init_status; GPR_ASSERT(servers[i].stream->Read(&init_status)); char* host; char* driver_port; char* cli_target; gpr_split_host_port(workers[i].c_str(), &host, &driver_port); gpr_join_host_port(&cli_target, host, init_status.port()); client_config.add_server_targets(cli_target); gpr_free(host); gpr_free(driver_port); gpr_free(cli_target); } // Start clients using runsc::ClientData; // clients is array rather than std::vector to avoid gcc-4.4 issues // where class contained in std::vector must have a copy constructor auto* clients = new ClientData[num_clients]; for (size_t i = 0; i < num_clients; i++) { gpr_log(GPR_INFO, "Starting client on %s (worker #%d)", workers[i].c_str(), i); clients[i].stub = WorkerService::NewStub( CreateChannel(workers[i + num_servers], InsecureChannelCredentials())); ClientArgs args; result_client_config = client_config; *args.mutable_setup() = client_config; clients[i].stream = clients[i].stub->RunClient(runsc::AllocContext(&contexts, deadline)); GPR_ASSERT(clients[i].stream->Write(args)); ClientStatus init_status; GPR_ASSERT(clients[i].stream->Read(&init_status)); } // Let everything warmup gpr_log(GPR_INFO, "Warming up"); gpr_timespec start = gpr_now(GPR_CLOCK_REALTIME); gpr_sleep_until( gpr_time_add(start, gpr_time_from_seconds(warmup_seconds, GPR_TIMESPAN))); // Start a run gpr_log(GPR_INFO, "Starting"); ServerArgs server_mark; server_mark.mutable_mark()->set_reset(true); ClientArgs client_mark; client_mark.mutable_mark()->set_reset(true); for (auto server = &servers[0]; server != &servers[num_servers]; server++) { GPR_ASSERT(server->stream->Write(server_mark)); } for (auto client = &clients[0]; client != &clients[num_clients]; client++) { GPR_ASSERT(client->stream->Write(client_mark)); } ServerStatus server_status; ClientStatus client_status; for (auto server = &servers[0]; server != &servers[num_servers]; server++) { GPR_ASSERT(server->stream->Read(&server_status)); } for (auto client = &clients[0]; client != &clients[num_clients]; client++) { GPR_ASSERT(client->stream->Read(&client_status)); } // Wait some time gpr_log(GPR_INFO, "Running"); // Use gpr_sleep_until rather than this_thread::sleep_until to support // compilers that don't work with this_thread gpr_sleep_until(gpr_time_add( start, gpr_time_from_seconds(benchmark_seconds, GPR_TIMESPAN))); // Finish a run std::unique_ptr<ScenarioResult> result(new ScenarioResult); result->client_config = result_client_config; result->server_config = result_server_config; gpr_log(GPR_INFO, "Finishing"); for (auto server = &servers[0]; server != &servers[num_servers]; server++) { GPR_ASSERT(server->stream->Write(server_mark)); } for (auto client = &clients[0]; client != &clients[num_clients]; client++) { GPR_ASSERT(client->stream->Write(client_mark)); } for (auto server = &servers[0]; server != &servers[num_servers]; server++) { GPR_ASSERT(server->stream->Read(&server_status)); const auto& stats = server_status.stats(); result->server_resources.emplace_back( stats.time_elapsed(), stats.time_user(), stats.time_system(), server_status.cores()); } for (auto client = &clients[0]; client != &clients[num_clients]; client++) { GPR_ASSERT(client->stream->Read(&client_status)); const auto& stats = client_status.stats(); result->latencies.MergeProto(stats.latencies()); result->client_resources.emplace_back( stats.time_elapsed(), stats.time_user(), stats.time_system(), -1); } for (auto client = &clients[0]; client != &clients[num_clients]; client++) { GPR_ASSERT(client->stream->WritesDone()); GPR_ASSERT(client->stream->Finish().ok()); } for (auto server = &servers[0]; server != &servers[num_servers]; server++) { GPR_ASSERT(server->stream->WritesDone()); GPR_ASSERT(server->stream->Finish().ok()); } delete[] clients; delete[] servers; return result; } } // namespace testing } // namespace grpc <commit_msg>Properly state client name<commit_after>/* * * Copyright 2015, Google Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following disclaimer * in the documentation and/or other materials provided with the * distribution. * * Neither the name of Google Inc. nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * */ #include <list> #include <thread> #include <deque> #include <vector> #include <grpc/support/alloc.h> #include <grpc/support/log.h> #include <grpc/support/host_port.h> #include <grpc++/client_context.h> #include <grpc++/create_channel.h> #include "src/core/support/env.h" #include "test/core/util/port.h" #include "test/core/util/test_config.h" #include "test/cpp/qps/driver.h" #include "test/cpp/qps/histogram.h" #include "test/cpp/qps/qps_worker.h" #include "src/proto/grpc/testing/services.grpc.pb.h" using std::list; using std::thread; using std::unique_ptr; using std::deque; using std::vector; namespace grpc { namespace testing { static deque<string> get_hosts(const string& name) { char* env = gpr_getenv(name.c_str()); if (!env) return deque<string>(); deque<string> out; char* p = env; for (;;) { char* comma = strchr(p, ','); if (comma) { out.emplace_back(p, comma); p = comma + 1; } else { out.emplace_back(p); gpr_free(env); return out; } } } // Namespace for classes and functions used only in RunScenario // Using this rather than local definitions to workaround gcc-4.4 limitations // regarding using templates without linkage namespace runsc { // ClientContext allocator template <class T> static ClientContext* AllocContext(list<ClientContext>* contexts, T deadline) { contexts->emplace_back(); auto context = &contexts->back(); context->set_deadline(deadline); return context; } struct ServerData { unique_ptr<WorkerService::Stub> stub; unique_ptr<ClientReaderWriter<ServerArgs, ServerStatus>> stream; }; struct ClientData { unique_ptr<WorkerService::Stub> stub; unique_ptr<ClientReaderWriter<ClientArgs, ClientStatus>> stream; }; } // namespace runsc std::unique_ptr<ScenarioResult> RunScenario( const ClientConfig& initial_client_config, size_t num_clients, const ServerConfig& server_config, size_t num_servers, int warmup_seconds, int benchmark_seconds, int spawn_local_worker_count) { // ClientContext allocations (all are destroyed at scope exit) list<ClientContext> contexts; // To be added to the result, containing the final configuration used for // client and config (including host, etc.) ClientConfig result_client_config; ServerConfig result_server_config; // Get client, server lists auto workers = get_hosts("QPS_WORKERS"); ClientConfig client_config = initial_client_config; // Spawn some local workers if desired vector<unique_ptr<QpsWorker>> local_workers; for (int i = 0; i < abs(spawn_local_worker_count); i++) { // act as if we're a new test -- gets a good rng seed static bool called_init = false; if (!called_init) { char args_buf[100]; strcpy(args_buf, "some-benchmark"); char* args[] = {args_buf}; grpc_test_init(1, args); called_init = true; } int driver_port = grpc_pick_unused_port_or_die(); local_workers.emplace_back(new QpsWorker(driver_port)); char addr[256]; sprintf(addr, "localhost:%d", driver_port); if (spawn_local_worker_count < 0) { workers.push_front(addr); } else { workers.push_back(addr); } } // TODO(ctiller): support running multiple configurations, and binpack // client/server pairs // to available workers GPR_ASSERT(workers.size() >= num_clients + num_servers); // Trim to just what we need workers.resize(num_clients + num_servers); gpr_timespec deadline = gpr_time_add(gpr_now(GPR_CLOCK_REALTIME), gpr_time_from_seconds( warmup_seconds + benchmark_seconds + 20, GPR_TIMESPAN)); // Start servers using runsc::ServerData; // servers is array rather than std::vector to avoid gcc-4.4 issues // where class contained in std::vector must have a copy constructor auto* servers = new ServerData[num_servers]; for (size_t i = 0; i < num_servers; i++) { gpr_log(GPR_INFO, "Starting server on %s (worker #%d)", workers[i].c_str(), i); servers[i].stub = WorkerService::NewStub( CreateChannel(workers[i], InsecureChannelCredentials())); ServerArgs args; result_server_config = server_config; *args.mutable_setup() = server_config; servers[i].stream = servers[i].stub->RunServer(runsc::AllocContext(&contexts, deadline)); GPR_ASSERT(servers[i].stream->Write(args)); ServerStatus init_status; GPR_ASSERT(servers[i].stream->Read(&init_status)); char* host; char* driver_port; char* cli_target; gpr_split_host_port(workers[i].c_str(), &host, &driver_port); gpr_join_host_port(&cli_target, host, init_status.port()); client_config.add_server_targets(cli_target); gpr_free(host); gpr_free(driver_port); gpr_free(cli_target); } // Start clients using runsc::ClientData; // clients is array rather than std::vector to avoid gcc-4.4 issues // where class contained in std::vector must have a copy constructor auto* clients = new ClientData[num_clients]; for (size_t i = 0; i < num_clients; i++) { gpr_log(GPR_INFO, "Starting client on %s (worker #%d)", workers[i + num_servers].c_str(), i + num_servers); clients[i].stub = WorkerService::NewStub( CreateChannel(workers[i + num_servers], InsecureChannelCredentials())); ClientArgs args; result_client_config = client_config; *args.mutable_setup() = client_config; clients[i].stream = clients[i].stub->RunClient(runsc::AllocContext(&contexts, deadline)); GPR_ASSERT(clients[i].stream->Write(args)); ClientStatus init_status; GPR_ASSERT(clients[i].stream->Read(&init_status)); } // Let everything warmup gpr_log(GPR_INFO, "Warming up"); gpr_timespec start = gpr_now(GPR_CLOCK_REALTIME); gpr_sleep_until( gpr_time_add(start, gpr_time_from_seconds(warmup_seconds, GPR_TIMESPAN))); // Start a run gpr_log(GPR_INFO, "Starting"); ServerArgs server_mark; server_mark.mutable_mark()->set_reset(true); ClientArgs client_mark; client_mark.mutable_mark()->set_reset(true); for (auto server = &servers[0]; server != &servers[num_servers]; server++) { GPR_ASSERT(server->stream->Write(server_mark)); } for (auto client = &clients[0]; client != &clients[num_clients]; client++) { GPR_ASSERT(client->stream->Write(client_mark)); } ServerStatus server_status; ClientStatus client_status; for (auto server = &servers[0]; server != &servers[num_servers]; server++) { GPR_ASSERT(server->stream->Read(&server_status)); } for (auto client = &clients[0]; client != &clients[num_clients]; client++) { GPR_ASSERT(client->stream->Read(&client_status)); } // Wait some time gpr_log(GPR_INFO, "Running"); // Use gpr_sleep_until rather than this_thread::sleep_until to support // compilers that don't work with this_thread gpr_sleep_until(gpr_time_add( start, gpr_time_from_seconds(benchmark_seconds, GPR_TIMESPAN))); // Finish a run std::unique_ptr<ScenarioResult> result(new ScenarioResult); result->client_config = result_client_config; result->server_config = result_server_config; gpr_log(GPR_INFO, "Finishing"); for (auto server = &servers[0]; server != &servers[num_servers]; server++) { GPR_ASSERT(server->stream->Write(server_mark)); } for (auto client = &clients[0]; client != &clients[num_clients]; client++) { GPR_ASSERT(client->stream->Write(client_mark)); } for (auto server = &servers[0]; server != &servers[num_servers]; server++) { GPR_ASSERT(server->stream->Read(&server_status)); const auto& stats = server_status.stats(); result->server_resources.emplace_back( stats.time_elapsed(), stats.time_user(), stats.time_system(), server_status.cores()); } for (auto client = &clients[0]; client != &clients[num_clients]; client++) { GPR_ASSERT(client->stream->Read(&client_status)); const auto& stats = client_status.stats(); result->latencies.MergeProto(stats.latencies()); result->client_resources.emplace_back( stats.time_elapsed(), stats.time_user(), stats.time_system(), -1); } for (auto client = &clients[0]; client != &clients[num_clients]; client++) { GPR_ASSERT(client->stream->WritesDone()); GPR_ASSERT(client->stream->Finish().ok()); } for (auto server = &servers[0]; server != &servers[num_servers]; server++) { GPR_ASSERT(server->stream->WritesDone()); GPR_ASSERT(server->stream->Finish().ok()); } delete[] clients; delete[] servers; return result; } } // namespace testing } // namespace grpc <|endoftext|>
<commit_before> #ifndef DUNE_DETAILED_DISCRETIZATIONS_DISCRETEFUNCTION_MULTISCALE_HH #define DUNE_DETAILED_DISCRETIZATIONS_DISCRETEFUNCTION_MULTISCALE_HH // system #include <sstream> #include <vector> // dune-common #include <dune/common/exceptions.hh> #include <dune/common/shared_ptr.hh> // dune-grid #include <dune/grid/io/file/vtk/function.hh> // dune-grid-multiscale #include <dune/grid/multiscale/default.hh> // dune-detailed-discretizations #include <dune/detailed/discretizations/discretefunction/default.hh> namespace Dune { namespace Detailed { namespace Discretizations { namespace DiscreteFunction { template <class MsGridImp, class LocalDiscreteFunctionImp> class Multiscale; template <class GridImp, class LocalDiscreteFunctionSpaceImp, class LocalVectorBackendImp> class Multiscale<Dune::grid::Multiscale::Default<GridImp>, Dune::Detailed::Discretizations::DiscreteFunction::Default<LocalDiscreteFunctionSpaceImp, LocalVectorBackendImp>> : public Dune::VTKFunction<typename Dune::grid::Multiscale::Default<GridImp>::GlobalGridViewType> { public: typedef Multiscale<Dune::grid::Multiscale::Default<GridImp>, Dune::Detailed::Discretizations::DiscreteFunction::Default<LocalDiscreteFunctionSpaceImp, LocalVectorBackendImp>> ThisType; typedef Dune::grid::Multiscale::Default<GridImp> MsGridType; typedef typename MsGridType::GlobalGridViewType GlobalGridViewType; typedef Dune::Detailed::Discretizations::DiscreteFunction::Default<LocalDiscreteFunctionSpaceImp, LocalVectorBackendImp> LocalDiscreteFunctionType; typedef typename Dune::VTKFunction<GlobalGridViewType> BaseType; typedef typename GlobalGridViewType::template Codim<0>::Iterator::Entity EntityType; typedef typename LocalDiscreteFunctionType::DiscreteFunctionSpaceType::FunctionSpaceType FunctionSpaceType; typedef typename FunctionSpaceType::DomainFieldType DomainFieldType; typedef typename FunctionSpaceType::DomainType DomainType; typedef typename FunctionSpaceType::RangeFieldType RangeFieldType; typedef typename FunctionSpaceType::RangeType RangeType; typedef typename FunctionSpaceType::JacobianRangeType JacobianRangeType; static const int dimDomain = LocalDiscreteFunctionType::dimDomain; static const int dimRange = LocalDiscreteFunctionType::dimRange; static const std::string id; private: typedef typename MsGridType::EntityToSubdomainMapType EntityToSubdomainMapType; public: Multiscale(const MsGridType& msGrid, const std::vector<Dune::shared_ptr<LocalDiscreteFunctionType>>& localDiscreteFunctions, const std::string name = id) : msGrid_(msGrid) , entityToSubdomainMap_(msGrid_.entityToSubdomainMap()) , localDiscreteFunctions_(localDiscreteFunctions) , name_(name) { assert(localDiscreteFunctions_.size() == msGrid_.size()); } Dune::shared_ptr<const LocalDiscreteFunctionType> localDiscreteFunction(const unsigned int subdomain) const { assert(subdomain < msGrid_.size()); return localDiscreteFunctions_[subdomain]; } Dune::shared_ptr<LocalDiscreteFunctionType> localDiscreteFunction(const unsigned int subdomain) { assert(subdomain < msGrid_.size()); return localDiscreteFunctions_[subdomain]; } virtual std::string name() const { return name_; } void setName(const std::string& newName = "") { name_ = newName; } /** @name Methods to comply with the Dune::VTKFunction interface @{ **/ virtual int ncomps() const { return dimRange; } virtual RangeFieldType evaluate(const int component, const EntityType& entity, const DomainType& x) const { // get the subdomain of this entity const unsigned int globalIndex = msGrid_.globalGridView()->indexSet().index(entity); const typename EntityToSubdomainMapType::const_iterator result = entityToSubdomainMap_->find(globalIndex); if (result == entityToSubdomainMap_->end()) { std::stringstream msg; msg << "Error in " << id << ": Entity " << globalIndex << " not found in the multiscale grid!"; DUNE_THROW(Dune::InvalidStateException, msg.str()); } const unsigned int subdomain = result->second; assert(subdomain < msGrid_.size()); // get and call the local discrete function of the entity's subdomain const LocalDiscreteFunctionType& localDiscreteFunction = *(localDiscreteFunctions_[subdomain]); return localDiscreteFunction.evaluate(component, entity, x); } // virtual RangeFieldType evaluate(const int component, const EntityType& entity, const DomainType& x) const /** @} **/ private: const MsGridType& msGrid_; const Dune::shared_ptr<const EntityToSubdomainMapType> entityToSubdomainMap_; std::vector<Dune::shared_ptr<LocalDiscreteFunctionType>> localDiscreteFunctions_; std::string name_; }; // class Multiscale template <class GridType, class LocalDiscreteFunctionSpaceType, class LocalVectorBackendType> const std::string Multiscale<Dune::grid::Multiscale::Default<GridType>, Dune::Detailed::Discretizations::DiscreteFunction::Default<LocalDiscreteFunctionSpaceType, LocalVectorBackendType>>::id = "detailed.discretizations.discretefunction.multiscale"; } // namespace DiscreteFunction } // namespace Discretizations } // namespace Detailed } // namespace Dune #endif // DUNE_DETAILED_DISCRETIZATIONS_DISCRETEFUNCTION_MULTISCALE_HH <commit_msg>[discretefunction.multiscale] added localFuntion()<commit_after> #ifndef DUNE_DETAILED_DISCRETIZATIONS_DISCRETEFUNCTION_MULTISCALE_HH #define DUNE_DETAILED_DISCRETIZATIONS_DISCRETEFUNCTION_MULTISCALE_HH // system #include <sstream> #include <vector> // dune-common #include <dune/common/exceptions.hh> #include <dune/common/shared_ptr.hh> // dune-grid #include <dune/grid/io/file/vtk/function.hh> // dune-grid-multiscale #include <dune/grid/multiscale/default.hh> // dune-detailed-discretizations #include <dune/detailed/discretizations/discretefunction/default.hh> namespace Dune { namespace Detailed { namespace Discretizations { namespace DiscreteFunction { template <class MsGridImp, class LocalDiscreteFunctionImp> class Multiscale; template <class GridImp, class LocalDiscreteFunctionSpaceImp, class LocalVectorBackendImp> class Multiscale<Dune::grid::Multiscale::Default<GridImp>, Dune::Detailed::Discretizations::DiscreteFunction::Default<LocalDiscreteFunctionSpaceImp, LocalVectorBackendImp>> : public Dune::VTKFunction<typename Dune::grid::Multiscale::Default<GridImp>::GlobalGridViewType> { public: typedef Multiscale<Dune::grid::Multiscale::Default<GridImp>, Dune::Detailed::Discretizations::DiscreteFunction::Default<LocalDiscreteFunctionSpaceImp, LocalVectorBackendImp>> ThisType; typedef Dune::grid::Multiscale::Default<GridImp> MsGridType; typedef typename MsGridType::GlobalGridViewType GlobalGridViewType; typedef Dune::Detailed::Discretizations::DiscreteFunction::Default<LocalDiscreteFunctionSpaceImp, LocalVectorBackendImp> LocalDiscreteFunctionType; typedef typename LocalDiscreteFunctionType::LocalFunctionType LocalFunctionType; typedef typename LocalDiscreteFunctionType::ConstLocalFunctionType ConstLocalFunctionType; typedef typename Dune::VTKFunction<GlobalGridViewType> BaseType; typedef typename GlobalGridViewType::template Codim<0>::Iterator::Entity EntityType; typedef typename LocalDiscreteFunctionType::DiscreteFunctionSpaceType::FunctionSpaceType FunctionSpaceType; typedef typename FunctionSpaceType::DomainFieldType DomainFieldType; typedef typename FunctionSpaceType::DomainType DomainType; typedef typename FunctionSpaceType::RangeFieldType RangeFieldType; typedef typename FunctionSpaceType::RangeType RangeType; typedef typename FunctionSpaceType::JacobianRangeType JacobianRangeType; static const int dimDomain = LocalDiscreteFunctionType::dimDomain; static const int dimRange = LocalDiscreteFunctionType::dimRange; static const std::string id; private: typedef typename MsGridType::EntityToSubdomainMapType EntityToSubdomainMapType; public: Multiscale(const MsGridType& msGrid, const std::vector<Dune::shared_ptr<LocalDiscreteFunctionType>>& localDiscreteFunctions, const std::string name = id) : msGrid_(msGrid) , entityToSubdomainMap_(msGrid_.entityToSubdomainMap()) , localDiscreteFunctions_(localDiscreteFunctions) , name_(name) { assert(localDiscreteFunctions_.size() == msGrid_.size()); } const MsGridType& msGrid() const { return msGrid_; } unsigned int size() const { return msGrid_.size(); } Dune::shared_ptr<const LocalDiscreteFunctionType> localDiscreteFunction(const unsigned int subdomain) const { assert(subdomain < msGrid_.size()); return localDiscreteFunctions_[subdomain]; } Dune::shared_ptr<LocalDiscreteFunctionType> localDiscreteFunction(const unsigned int subdomain) { assert(subdomain < msGrid_.size()); return localDiscreteFunctions_[subdomain]; } LocalFunctionType localFunction(const EntityType& entity) { // get the subdomain of this entity const unsigned int globalIndex = msGrid_.globalGridView()->indexSet().index(entity); const typename EntityToSubdomainMapType::const_iterator result = entityToSubdomainMap_->find(globalIndex); if (result == entityToSubdomainMap_->end()) { std::stringstream msg; msg << "Error in " << id << ": Entity " << globalIndex << " not found in the multiscale grid!"; DUNE_THROW(Dune::InvalidStateException, msg.str()); } const unsigned int subdomain = result->second; assert(subdomain < msGrid_.size()); // get the corresponding local discrete function const LocalDiscreteFunctionType& localDiscreteFunction = *(localDiscreteFunctions_[subdomain]); // and return its local function return localDiscreteFunction.localFunction(entity); } ConstLocalFunctionType localFunction(const EntityType& entity) const { // get the subdomain of this entity const unsigned int globalIndex = msGrid_.globalGridView()->indexSet().index(entity); const typename EntityToSubdomainMapType::const_iterator result = entityToSubdomainMap_->find(globalIndex); if (result == entityToSubdomainMap_->end()) { std::stringstream msg; msg << "Error in " << id << ": Entity " << globalIndex << " not found in the multiscale grid!"; DUNE_THROW(Dune::InvalidStateException, msg.str()); } const unsigned int subdomain = result->second; assert(subdomain < msGrid_.size()); // get the corresponding local discrete function const LocalDiscreteFunctionType& localDiscreteFunction = *(localDiscreteFunctions_[subdomain]); // and return its local function return localDiscreteFunction.localFunction(entity); } virtual std::string name() const { return name_; } void setName(const std::string& newName = "") { name_ = newName; } /** @name Methods needed, to comply with the Dune::VTKFunction interface @{ */ virtual int ncomps() const { return dimRange; } virtual RangeFieldType evaluate(const int component, const EntityType& entity, const DomainType& x) const { // get the subdomain of this entity const unsigned int globalIndex = msGrid_.globalGridView()->indexSet().index(entity); const typename EntityToSubdomainMapType::const_iterator result = entityToSubdomainMap_->find(globalIndex); if (result == entityToSubdomainMap_->end()) { std::stringstream msg; msg << "Error in " << id << ": Entity " << globalIndex << " not found in the multiscale grid!"; DUNE_THROW(Dune::InvalidStateException, msg.str()); } const unsigned int subdomain = result->second; assert(subdomain < msGrid_.size()); // get and call the local discrete function of the entity's subdomain const LocalDiscreteFunctionType& localDiscreteFunction = *(localDiscreteFunctions_[subdomain]); return localDiscreteFunction.evaluate(component, entity, x); } // virtual RangeFieldType evaluate(const int component, const EntityType& entity, const DomainType& x) const /** @} */ private: const MsGridType& msGrid_; const Dune::shared_ptr<const EntityToSubdomainMapType> entityToSubdomainMap_; std::vector<Dune::shared_ptr<LocalDiscreteFunctionType>> localDiscreteFunctions_; std::string name_; }; // class Multiscale template <class GridType, class LocalDiscreteFunctionSpaceType, class LocalVectorBackendType> const std::string Multiscale<Dune::grid::Multiscale::Default<GridType>, Dune::Detailed::Discretizations::DiscreteFunction::Default<LocalDiscreteFunctionSpaceType, LocalVectorBackendType>>::id = "detailed.discretizations.discretefunction.multiscale"; } // namespace DiscreteFunction } // namespace Discretizations } // namespace Detailed } // namespace Dune #endif // DUNE_DETAILED_DISCRETIZATIONS_DISCRETEFUNCTION_MULTISCALE_HH <|endoftext|>
<commit_before>#include <QtCore/QEventLoop> #include <QtTest/QtTest> #include <TelepathyQt4/Debug> #include <TelepathyQt4/Types> #include <TelepathyQt4/Account> #include <TelepathyQt4/AccountManager> #include <TelepathyQt4/AccountSet> #include <TelepathyQt4/ConnectionManager> #include <TelepathyQt4/PendingAccount> #include <TelepathyQt4/PendingOperation> #include <TelepathyQt4/PendingReady> #include <tests/lib/test.h> using namespace Tp; class TestAccountBasics : public Test { Q_OBJECT public: TestAccountBasics(QObject *parent = 0) : Test(parent), mServiceNameChanged(false), mAccountsCount(0), mGotAvatarChanged(false) { } protected Q_SLOTS: void onNewAccount(const Tp::AccountPtr &); void onAccountServiceNameChanged(const QString &); void onAvatarChanged(const Tp::Avatar &); private Q_SLOTS: void initTestCase(); void init(); void testBasics(); void cleanup(); void cleanupTestCase(); private: QStringList pathsForAccountList(const QList<Tp::AccountPtr> &list); QStringList pathsForAccountSet(const Tp::AccountSetPtr &set); Tp::AccountManagerPtr mAM; bool mServiceNameChanged; QString mServiceName; int mAccountsCount; bool mGotAvatarChanged; }; void TestAccountBasics::onNewAccount(const Tp::AccountPtr &acc) { Q_UNUSED(acc); mAccountsCount++; mLoop->exit(0); } void TestAccountBasics::onAccountServiceNameChanged(const QString &serviceName) { mServiceNameChanged = true; mServiceName = serviceName; mLoop->exit(0); } void TestAccountBasics::onAvatarChanged(const Tp::Avatar &avatar) { qDebug() << "on avatar changed"; mGotAvatarChanged = true; QCOMPARE(avatar.avatarData, QByteArray("asdfg")); QCOMPARE(avatar.MIMEType, QString(QLatin1String("image/jpeg"))); mLoop->exit(0); } QStringList TestAccountBasics::pathsForAccountList(const QList<Tp::AccountPtr> &list) { QStringList ret; Q_FOREACH (const AccountPtr &account, list) { ret << account->objectPath(); } return ret; } QStringList TestAccountBasics::pathsForAccountSet(const Tp::AccountSetPtr &set) { QStringList ret; Q_FOREACH (const AccountPtr &account, set->accounts()) { ret << account->objectPath(); } return ret; } void TestAccountBasics::initTestCase() { initTestCaseImpl(); mAM = AccountManager::create(); QCOMPARE(mAM->isReady(), false); } void TestAccountBasics::init() { mGotAvatarChanged = false; initImpl(); } void TestAccountBasics::testBasics() { QVERIFY(connect(mAM->becomeReady(), SIGNAL(finished(Tp::PendingOperation *)), SLOT(expectSuccessfulCall(Tp::PendingOperation *)))); QCOMPARE(mLoop->exec(), 0); QCOMPARE(mAM->isReady(), true); QVERIFY(connect(mAM.data(), SIGNAL(newAccount(const Tp::AccountPtr &)), SLOT(onNewAccount(const Tp::AccountPtr &)))); QVariantMap parameters; parameters[QLatin1String("account")] = QLatin1String("foobar"); PendingAccount *pacc = mAM->createAccount(QLatin1String("foo"), QLatin1String("bar"), QLatin1String("foobar"), parameters); QVERIFY(connect(pacc, SIGNAL(finished(Tp::PendingOperation *)), SLOT(expectSuccessfulCall(Tp::PendingOperation *)))); QCOMPARE(mLoop->exec(), 0); QVERIFY(pacc->account()); while (mAccountsCount != 1) { QCOMPARE(mLoop->exec(), 0); } QCOMPARE(mAM->interfaces(), QStringList()); QStringList paths; QCOMPARE(pathsForAccountSet(mAM->validAccountsSet()), QStringList() << QLatin1String("/org/freedesktop/Telepathy/Account/foo/bar/Account0")); QCOMPARE(pathsForAccountSet(mAM->invalidAccountsSet()), QStringList()); QCOMPARE(pathsForAccountList(mAM->allAccounts()), QStringList() << QLatin1String("/org/freedesktop/Telepathy/Account/foo/bar/Account0")); AccountPtr acc = Account::create(mAM->dbusConnection(), mAM->busName(), QLatin1String("/org/freedesktop/Telepathy/Account/foo/bar/Account0")); QVERIFY(connect(acc->becomeReady(), SIGNAL(finished(Tp::PendingOperation *)), SLOT(expectSuccessfulCall(Tp::PendingOperation *)))); QCOMPARE(mLoop->exec(), 0); QCOMPARE(acc->displayName(), QString(QLatin1String("foobar (account 0)"))); qDebug() << "making Account::FeatureAvatar ready"; QVERIFY(connect(acc->becomeReady(Account::FeatureAvatar), SIGNAL(finished(Tp::PendingOperation *)), SLOT(expectSuccessfulCall(Tp::PendingOperation *)))); QCOMPARE(mLoop->exec(), 0); QCOMPARE(acc->isReady(Account::FeatureAvatar), true); QCOMPARE(acc->avatar().MIMEType, QString(QLatin1String("image/png"))); qDebug() << "connecting to avatarChanged()"; QVERIFY(connect(acc.data(), SIGNAL(avatarChanged(const Tp::Avatar &)), SLOT(onAvatarChanged(const Tp::Avatar &)))); qDebug() << "setting the avatar"; Tp::Avatar avatar = { QByteArray("asdfg"), QLatin1String("image/jpeg") }; QVERIFY(connect(acc->setAvatar(avatar), SIGNAL(finished(Tp::PendingOperation *)), SLOT(expectSuccessfulCall(Tp::PendingOperation *)))); QCOMPARE(mLoop->exec(), 0); qDebug() << "making Account::FeatureAvatar ready again (redundantly)"; QVERIFY(connect(acc->becomeReady(Account::FeatureAvatar), SIGNAL(finished(Tp::PendingOperation *)), SLOT(expectSuccessfulCall(Tp::PendingOperation *)))); QCOMPARE(mLoop->exec(), 0); QCOMPARE(acc->isReady(Account::FeatureAvatar), true); // We might have got it already in the earlier mainloop runs if (!mGotAvatarChanged) { qDebug() << "waiting for the avatarChanged signal"; QCOMPARE(mLoop->exec(), 0); } else { qDebug() << "not waiting for avatarChanged because we already got it"; } qDebug() << "creating another account"; pacc = mAM->createAccount(QLatin1String("spurious"), QLatin1String("normal"), QLatin1String("foobar"), parameters); QVERIFY(connect(pacc, SIGNAL(finished(Tp::PendingOperation *)), SLOT(expectSuccessfulCall(Tp::PendingOperation *)))); QCOMPARE(mLoop->exec(), 0); while (mAccountsCount != 2) { QCOMPARE(mLoop->exec(), 0); } acc = Account::create(mAM->dbusConnection(), mAM->busName(), QLatin1String("/org/freedesktop/Telepathy/Account/spurious/normal/Account0")); QVERIFY(connect(acc->becomeReady(), SIGNAL(finished(Tp::PendingOperation *)), SLOT(expectSuccessfulCall(Tp::PendingOperation *)))); QCOMPARE(mLoop->exec(), 0); acc = Account::create(mAM->dbusConnection(), mAM->busName(), QLatin1String("/org/freedesktop/Telepathy/Account/spurious/normal/Account0")); QVERIFY(connect(acc->becomeReady(), SIGNAL(finished(Tp::PendingOperation *)), SLOT(expectSuccessfulCall(Tp::PendingOperation *)))); QCOMPARE(mLoop->exec(), 0); // At this point, there's a set icon QCOMPARE(acc->iconName(), QLatin1String("bob.png")); // ?!?? // Unset that QVERIFY(connect(acc->setIconName(QString()), SIGNAL(finished(Tp::PendingOperation *)), SLOT(expectSuccessfulCall(Tp::PendingOperation *)))); QCOMPARE(mLoop->exec(), 0); // Now that it's unset, an icon name is formed from the protocol name QCOMPARE(acc->iconName(), QLatin1String("im-normal")); QVERIFY(connect(acc->becomeReady(Account::FeatureProtocolInfo), SIGNAL(finished(Tp::PendingOperation *)), SLOT(expectSuccessfulCall(Tp::PendingOperation *)))); QCOMPARE(mLoop->exec(), 0); QCOMPARE(acc->isReady(Account::FeatureProtocolInfo), true); // This time it's fetched from the protocol object (although it probably internally just // infers it from the protocol name too) QCOMPARE(acc->iconName(), QLatin1String("im-normal")); QVERIFY(acc->serviceName() != acc->protocolName()); QCOMPARE(acc->serviceName(), QString(QLatin1String("bob_service"))); connect(acc.data(), SIGNAL(serviceNameChanged(const QString &)), SLOT(onAccountServiceNameChanged(const QString &))); connect(acc->setServiceName(acc->protocolName()), SIGNAL(finished(Tp::PendingOperation *)), SLOT(expectSuccessfulCall(Tp::PendingOperation *))); // wait for setServiceName finish QCOMPARE(mLoop->exec(), 0); // wait for serviceNameChanged QCOMPARE(mLoop->exec(), 0); QCOMPARE(acc->serviceName(), acc->protocolName()); QCOMPARE(mServiceName, acc->serviceName()); ProtocolInfo *protocolInfo = acc->protocolInfo(); QCOMPARE((bool) protocolInfo, !((ProtocolInfo *) 0)); QCOMPARE(protocolInfo->hasParameter(QLatin1String("account")), true); QCOMPARE(protocolInfo->hasParameter(QLatin1String("password")), true); QCOMPARE(protocolInfo->hasParameter(QLatin1String("register")), true); QVERIFY(connect(acc->becomeReady(Account::FeatureAvatar), SIGNAL(finished(Tp::PendingOperation *)), SLOT(expectSuccessfulCall(Tp::PendingOperation *)))); QCOMPARE(mLoop->exec(), 0); QCOMPARE(acc->isReady(Account::FeatureAvatar), true); QCOMPARE(acc->avatar().MIMEType, QString(QLatin1String("image/png"))); QVERIFY(connect(acc->becomeReady(Account::FeatureAvatar | Account::FeatureProtocolInfo), SIGNAL(finished(Tp::PendingOperation *)), SLOT(expectSuccessfulCall(Tp::PendingOperation *)))); QCOMPARE(mLoop->exec(), 0); QCOMPARE(acc->isReady(Account::FeatureAvatar | Account::FeatureProtocolInfo), true); QCOMPARE(acc->avatar().MIMEType, QString(QLatin1String("image/png"))); protocolInfo = acc->protocolInfo(); QCOMPARE((bool) protocolInfo, !((ProtocolInfo *) 0)); QList<AccountPtr> allAccounts = mAM->allAccounts(); QVariantMap filter; Tp::AccountSetPtr filteredAccountSet; filter.insert(QLatin1String("protocolName"), QLatin1String("foo")); filteredAccountSet = AccountSetPtr(new AccountSet(mAM, filter)); QCOMPARE(filteredAccountSet->isFilterValid(), true); filter.clear(); filter.insert(QLatin1String("protocolFoo"), acc->protocolName()); filteredAccountSet = AccountSetPtr(new AccountSet(mAM, filter)); QCOMPARE(filteredAccountSet->isFilterValid(), false); filter.clear(); filter.insert(QLatin1String("protocolName"), allAccounts.first()->protocolName()); filteredAccountSet = mAM->filterAccounts(filter); QCOMPARE(filteredAccountSet->isFilterValid(), true); QVERIFY(filteredAccountSet->accounts().contains(allAccounts.first())); filteredAccountSet = mAM->accountsByProtocol(allAccounts.first()->protocolName()); QCOMPARE(filteredAccountSet->isFilterValid(), true); QVERIFY(filteredAccountSet->accounts().contains(allAccounts.first())); filter.clear(); filter.insert(QLatin1String("protocolFoo"), acc->protocolName()); filteredAccountSet = mAM->filterAccounts(filter); QCOMPARE(filteredAccountSet->isFilterValid(), false); QVERIFY(filteredAccountSet->accounts().isEmpty()); QCOMPARE(mAM->validAccountsSet()->isFilterValid(), true); QCOMPARE(mAM->validAccountsSet()->accounts().isEmpty(), false); QCOMPARE(mAM->invalidAccountsSet()->isFilterValid(), true); QCOMPARE(mAM->invalidAccountsSet()->accounts().isEmpty(), true); QCOMPARE(mAM->enabledAccountsSet()->isFilterValid(), true); QCOMPARE(mAM->enabledAccountsSet()->accounts().isEmpty(), false); QCOMPARE(mAM->disabledAccountsSet()->isFilterValid(), true); QCOMPARE(mAM->disabledAccountsSet()->accounts().isEmpty(), true); } void TestAccountBasics::cleanup() { cleanupImpl(); } void TestAccountBasics::cleanupTestCase() { cleanupTestCaseImpl(); } QTEST_MAIN(TestAccountBasics) #include "_gen/account-basics.cpp.moc.hpp" <commit_msg>account-basics test: Added tests for filter accounts by RCC support.<commit_after>#include <QtCore/QEventLoop> #include <QtTest/QtTest> #include <TelepathyQt4/Debug> #include <TelepathyQt4/Types> #include <TelepathyQt4/Account> #include <TelepathyQt4/AccountManager> #include <TelepathyQt4/AccountSet> #include <TelepathyQt4/ConnectionManager> #include <TelepathyQt4/PendingAccount> #include <TelepathyQt4/PendingOperation> #include <TelepathyQt4/PendingReady> #include <tests/lib/test.h> using namespace Tp; class TestAccountBasics : public Test { Q_OBJECT public: TestAccountBasics(QObject *parent = 0) : Test(parent), mServiceNameChanged(false), mAccountsCount(0), mGotAvatarChanged(false) { } protected Q_SLOTS: void onNewAccount(const Tp::AccountPtr &); void onAccountServiceNameChanged(const QString &); void onAvatarChanged(const Tp::Avatar &); private Q_SLOTS: void initTestCase(); void init(); void testBasics(); void cleanup(); void cleanupTestCase(); private: QStringList pathsForAccountList(const QList<Tp::AccountPtr> &list); QStringList pathsForAccountSet(const Tp::AccountSetPtr &set); Tp::AccountManagerPtr mAM; bool mServiceNameChanged; QString mServiceName; int mAccountsCount; bool mGotAvatarChanged; }; void TestAccountBasics::onNewAccount(const Tp::AccountPtr &acc) { Q_UNUSED(acc); mAccountsCount++; mLoop->exit(0); } void TestAccountBasics::onAccountServiceNameChanged(const QString &serviceName) { mServiceNameChanged = true; mServiceName = serviceName; mLoop->exit(0); } void TestAccountBasics::onAvatarChanged(const Tp::Avatar &avatar) { qDebug() << "on avatar changed"; mGotAvatarChanged = true; QCOMPARE(avatar.avatarData, QByteArray("asdfg")); QCOMPARE(avatar.MIMEType, QString(QLatin1String("image/jpeg"))); mLoop->exit(0); } QStringList TestAccountBasics::pathsForAccountList(const QList<Tp::AccountPtr> &list) { QStringList ret; Q_FOREACH (const AccountPtr &account, list) { ret << account->objectPath(); } return ret; } QStringList TestAccountBasics::pathsForAccountSet(const Tp::AccountSetPtr &set) { QStringList ret; Q_FOREACH (const AccountPtr &account, set->accounts()) { ret << account->objectPath(); } return ret; } void TestAccountBasics::initTestCase() { initTestCaseImpl(); mAM = AccountManager::create(); QCOMPARE(mAM->isReady(), false); } void TestAccountBasics::init() { mGotAvatarChanged = false; initImpl(); } void TestAccountBasics::testBasics() { QVERIFY(connect(mAM->becomeReady(), SIGNAL(finished(Tp::PendingOperation *)), SLOT(expectSuccessfulCall(Tp::PendingOperation *)))); QCOMPARE(mLoop->exec(), 0); QCOMPARE(mAM->isReady(), true); QVERIFY(connect(mAM.data(), SIGNAL(newAccount(const Tp::AccountPtr &)), SLOT(onNewAccount(const Tp::AccountPtr &)))); QVariantMap parameters; parameters[QLatin1String("account")] = QLatin1String("foobar"); PendingAccount *pacc = mAM->createAccount(QLatin1String("foo"), QLatin1String("bar"), QLatin1String("foobar"), parameters); QVERIFY(connect(pacc, SIGNAL(finished(Tp::PendingOperation *)), SLOT(expectSuccessfulCall(Tp::PendingOperation *)))); QCOMPARE(mLoop->exec(), 0); QVERIFY(pacc->account()); while (mAccountsCount != 1) { QCOMPARE(mLoop->exec(), 0); } QCOMPARE(mAM->interfaces(), QStringList()); QStringList paths; QCOMPARE(pathsForAccountSet(mAM->validAccountsSet()), QStringList() << QLatin1String("/org/freedesktop/Telepathy/Account/foo/bar/Account0")); QCOMPARE(pathsForAccountSet(mAM->invalidAccountsSet()), QStringList()); QCOMPARE(pathsForAccountList(mAM->allAccounts()), QStringList() << QLatin1String("/org/freedesktop/Telepathy/Account/foo/bar/Account0")); AccountPtr acc = Account::create(mAM->dbusConnection(), mAM->busName(), QLatin1String("/org/freedesktop/Telepathy/Account/foo/bar/Account0")); QVERIFY(connect(acc->becomeReady(), SIGNAL(finished(Tp::PendingOperation *)), SLOT(expectSuccessfulCall(Tp::PendingOperation *)))); QCOMPARE(mLoop->exec(), 0); QCOMPARE(acc->displayName(), QString(QLatin1String("foobar (account 0)"))); qDebug() << "making Account::FeatureAvatar ready"; QVERIFY(connect(acc->becomeReady(Account::FeatureAvatar), SIGNAL(finished(Tp::PendingOperation *)), SLOT(expectSuccessfulCall(Tp::PendingOperation *)))); QCOMPARE(mLoop->exec(), 0); QCOMPARE(acc->isReady(Account::FeatureAvatar), true); QCOMPARE(acc->avatar().MIMEType, QString(QLatin1String("image/png"))); qDebug() << "connecting to avatarChanged()"; QVERIFY(connect(acc.data(), SIGNAL(avatarChanged(const Tp::Avatar &)), SLOT(onAvatarChanged(const Tp::Avatar &)))); qDebug() << "setting the avatar"; Tp::Avatar avatar = { QByteArray("asdfg"), QLatin1String("image/jpeg") }; QVERIFY(connect(acc->setAvatar(avatar), SIGNAL(finished(Tp::PendingOperation *)), SLOT(expectSuccessfulCall(Tp::PendingOperation *)))); QCOMPARE(mLoop->exec(), 0); qDebug() << "making Account::FeatureAvatar ready again (redundantly)"; QVERIFY(connect(acc->becomeReady(Account::FeatureAvatar), SIGNAL(finished(Tp::PendingOperation *)), SLOT(expectSuccessfulCall(Tp::PendingOperation *)))); QCOMPARE(mLoop->exec(), 0); QCOMPARE(acc->isReady(Account::FeatureAvatar), true); // We might have got it already in the earlier mainloop runs if (!mGotAvatarChanged) { qDebug() << "waiting for the avatarChanged signal"; QCOMPARE(mLoop->exec(), 0); } else { qDebug() << "not waiting for avatarChanged because we already got it"; } qDebug() << "creating another account"; pacc = mAM->createAccount(QLatin1String("spurious"), QLatin1String("normal"), QLatin1String("foobar"), parameters); QVERIFY(connect(pacc, SIGNAL(finished(Tp::PendingOperation *)), SLOT(expectSuccessfulCall(Tp::PendingOperation *)))); QCOMPARE(mLoop->exec(), 0); while (mAccountsCount != 2) { QCOMPARE(mLoop->exec(), 0); } acc = Account::create(mAM->dbusConnection(), mAM->busName(), QLatin1String("/org/freedesktop/Telepathy/Account/spurious/normal/Account0")); QVERIFY(connect(acc->becomeReady(), SIGNAL(finished(Tp::PendingOperation *)), SLOT(expectSuccessfulCall(Tp::PendingOperation *)))); QCOMPARE(mLoop->exec(), 0); acc = Account::create(mAM->dbusConnection(), mAM->busName(), QLatin1String("/org/freedesktop/Telepathy/Account/spurious/normal/Account0")); QVERIFY(connect(acc->becomeReady(), SIGNAL(finished(Tp::PendingOperation *)), SLOT(expectSuccessfulCall(Tp::PendingOperation *)))); QCOMPARE(mLoop->exec(), 0); // At this point, there's a set icon QCOMPARE(acc->iconName(), QLatin1String("bob.png")); // ?!?? // Unset that QVERIFY(connect(acc->setIconName(QString()), SIGNAL(finished(Tp::PendingOperation *)), SLOT(expectSuccessfulCall(Tp::PendingOperation *)))); QCOMPARE(mLoop->exec(), 0); // Now that it's unset, an icon name is formed from the protocol name QCOMPARE(acc->iconName(), QLatin1String("im-normal")); QVERIFY(connect(acc->becomeReady(Account::FeatureProtocolInfo), SIGNAL(finished(Tp::PendingOperation *)), SLOT(expectSuccessfulCall(Tp::PendingOperation *)))); QCOMPARE(mLoop->exec(), 0); QCOMPARE(acc->isReady(Account::FeatureProtocolInfo), true); // This time it's fetched from the protocol object (although it probably internally just // infers it from the protocol name too) QCOMPARE(acc->iconName(), QLatin1String("im-normal")); QVERIFY(acc->serviceName() != acc->protocolName()); QCOMPARE(acc->serviceName(), QString(QLatin1String("bob_service"))); connect(acc.data(), SIGNAL(serviceNameChanged(const QString &)), SLOT(onAccountServiceNameChanged(const QString &))); connect(acc->setServiceName(acc->protocolName()), SIGNAL(finished(Tp::PendingOperation *)), SLOT(expectSuccessfulCall(Tp::PendingOperation *))); // wait for setServiceName finish QCOMPARE(mLoop->exec(), 0); // wait for serviceNameChanged QCOMPARE(mLoop->exec(), 0); QCOMPARE(acc->serviceName(), acc->protocolName()); QCOMPARE(mServiceName, acc->serviceName()); ProtocolInfo *protocolInfo = acc->protocolInfo(); QCOMPARE((bool) protocolInfo, !((ProtocolInfo *) 0)); QCOMPARE(protocolInfo->hasParameter(QLatin1String("account")), true); QCOMPARE(protocolInfo->hasParameter(QLatin1String("password")), true); QCOMPARE(protocolInfo->hasParameter(QLatin1String("register")), true); QVERIFY(connect(acc->becomeReady(Account::FeatureAvatar), SIGNAL(finished(Tp::PendingOperation *)), SLOT(expectSuccessfulCall(Tp::PendingOperation *)))); QCOMPARE(mLoop->exec(), 0); QCOMPARE(acc->isReady(Account::FeatureAvatar), true); QCOMPARE(acc->avatar().MIMEType, QString(QLatin1String("image/png"))); QVERIFY(connect(acc->becomeReady(Account::FeatureAvatar | Account::FeatureProtocolInfo), SIGNAL(finished(Tp::PendingOperation *)), SLOT(expectSuccessfulCall(Tp::PendingOperation *)))); QCOMPARE(mLoop->exec(), 0); QCOMPARE(acc->isReady(Account::FeatureAvatar | Account::FeatureProtocolInfo), true); QCOMPARE(acc->avatar().MIMEType, QString(QLatin1String("image/png"))); protocolInfo = acc->protocolInfo(); QCOMPARE((bool) protocolInfo, !((ProtocolInfo *) 0)); QList<AccountPtr> allAccounts = mAM->allAccounts(); QVariantMap filter; Tp::AccountSetPtr filteredAccountSet; filter.insert(QLatin1String("protocolName"), QLatin1String("foo")); filteredAccountSet = AccountSetPtr(new AccountSet(mAM, filter)); QCOMPARE(filteredAccountSet->isFilterValid(), true); filter.clear(); filter.insert(QLatin1String("protocolFoo"), acc->protocolName()); filteredAccountSet = AccountSetPtr(new AccountSet(mAM, filter)); QCOMPARE(filteredAccountSet->isFilterValid(), false); filter.clear(); filter.insert(QLatin1String("protocolName"), allAccounts.first()->protocolName()); filteredAccountSet = mAM->filterAccounts(filter); QCOMPARE(filteredAccountSet->isFilterValid(), true); QVERIFY(filteredAccountSet->accounts().contains(allAccounts.first())); filteredAccountSet = mAM->accountsByProtocol(allAccounts.first()->protocolName()); QCOMPARE(filteredAccountSet->isFilterValid(), true); QVERIFY(filteredAccountSet->accounts().contains(allAccounts.first())); filter.clear(); filter.insert(QLatin1String("protocolFoo"), acc->protocolName()); filteredAccountSet = mAM->filterAccounts(filter); QCOMPARE(filteredAccountSet->isFilterValid(), false); QVERIFY(filteredAccountSet->accounts().isEmpty()); QCOMPARE(mAM->validAccountsSet()->isFilterValid(), true); QCOMPARE(mAM->validAccountsSet()->accounts().isEmpty(), false); QCOMPARE(mAM->invalidAccountsSet()->isFilterValid(), true); QCOMPARE(mAM->invalidAccountsSet()->accounts().isEmpty(), true); QCOMPARE(mAM->enabledAccountsSet()->isFilterValid(), true); QCOMPARE(mAM->enabledAccountsSet()->accounts().isEmpty(), false); QCOMPARE(mAM->disabledAccountsSet()->isFilterValid(), true); QCOMPARE(mAM->disabledAccountsSet()->accounts().isEmpty(), true); filter.clear(); filter.insert(QLatin1String("cmName"), QLatin1String("spurious")); AccountSetPtr spuriousAccountSet = AccountSetPtr(new AccountSet(mAM, filter)); QCOMPARE(spuriousAccountSet->isFilterValid(), true); /* match fixedProperties is complete and allowedProperties is a subset of * the allowed properties */ filter.clear(); RequestableChannelClassList rccs; RequestableChannelClass rcc; rcc.fixedProperties.insert( QLatin1String(TELEPATHY_INTERFACE_CHANNEL ".ChannelType"), QLatin1String(TELEPATHY_INTERFACE_CHANNEL_TYPE_TEXT)); rcc.fixedProperties.insert( QLatin1String(TELEPATHY_INTERFACE_CHANNEL ".TargetHandleType"), (uint) HandleTypeContact); rcc.allowedProperties.append( QLatin1String(TELEPATHY_INTERFACE_CHANNEL ".TargetHandle")); rccs.append(rcc); filter.insert(QLatin1String("rccSubset"), qVariantFromValue(rccs)); filter.insert(QLatin1String("cmName"), QLatin1String("spurious")); filteredAccountSet = AccountSetPtr(new AccountSet(mAM, filter)); QCOMPARE(filteredAccountSet->isFilterValid(), true); QCOMPARE(filteredAccountSet->accounts(), spuriousAccountSet->accounts()); /* match fixedProperties and allowedProperties is complete */ filter.clear(); rccs.clear(); rcc.fixedProperties.clear(); rcc.allowedProperties.clear(); rcc.fixedProperties.insert( QLatin1String(TELEPATHY_INTERFACE_CHANNEL ".ChannelType"), QLatin1String(TELEPATHY_INTERFACE_CHANNEL_TYPE_TEXT)); rcc.fixedProperties.insert( QLatin1String(TELEPATHY_INTERFACE_CHANNEL ".TargetHandleType"), (uint) HandleTypeContact); rcc.allowedProperties.append( QLatin1String(TELEPATHY_INTERFACE_CHANNEL ".TargetHandle")); rcc.allowedProperties.append( QLatin1String(TELEPATHY_INTERFACE_CHANNEL ".TargetID")); rccs.append(rcc); filter.insert(QLatin1String("rccSubset"), qVariantFromValue(rccs)); filter.insert(QLatin1String("cmName"), QLatin1String("spurious")); filteredAccountSet = AccountSetPtr(new AccountSet(mAM, filter)); QCOMPARE(filteredAccountSet->isFilterValid(), true); QCOMPARE(filteredAccountSet->accounts(), spuriousAccountSet->accounts()); /* should not match as fixedProperties lack TargetHandleType */ filter.clear(); rccs.clear(); rcc.fixedProperties.clear(); rcc.allowedProperties.clear(); rcc.fixedProperties.insert( QLatin1String(TELEPATHY_INTERFACE_CHANNEL ".ChannelType"), QLatin1String(TELEPATHY_INTERFACE_CHANNEL_TYPE_TEXT)); rcc.allowedProperties.append( QLatin1String(TELEPATHY_INTERFACE_CHANNEL ".TargetHandle")); rccs.append(rcc); filter.insert(QLatin1String("rccSubset"), qVariantFromValue(rccs)); filter.insert(QLatin1String("cmName"), QLatin1String("spurious")); filteredAccountSet = AccountSetPtr(new AccountSet(mAM, filter)); QCOMPARE(filteredAccountSet->isFilterValid(), true); QCOMPARE(filteredAccountSet->accounts().isEmpty(), true); /* should not match as fixedProperties has more than expected */ filter.clear(); rccs.clear(); rcc.fixedProperties.clear(); rcc.allowedProperties.clear(); rcc.fixedProperties.insert( QLatin1String(TELEPATHY_INTERFACE_CHANNEL ".ChannelType"), QLatin1String(TELEPATHY_INTERFACE_CHANNEL_TYPE_TEXT)); rcc.fixedProperties.insert( QLatin1String(TELEPATHY_INTERFACE_CHANNEL ".TargetHandleType"), (uint) HandleTypeContact); rcc.fixedProperties.insert( QLatin1String(TELEPATHY_INTERFACE_CHANNEL ".TargetID"), (uint) HandleTypeContact); rcc.allowedProperties.append( QLatin1String(TELEPATHY_INTERFACE_CHANNEL ".TargetHandle")); rccs.append(rcc); filter.insert(QLatin1String("rccSubset"), qVariantFromValue(rccs)); filter.insert(QLatin1String("cmName"), QLatin1String("spurious")); filteredAccountSet = AccountSetPtr(new AccountSet(mAM, filter)); QCOMPARE(filteredAccountSet->isFilterValid(), true); QCOMPARE(filteredAccountSet->accounts().isEmpty(), true); /* should not match as allowedProperties has TargetFoo that is not allowed */ filter.clear(); rccs.clear(); rcc.fixedProperties.clear(); rcc.allowedProperties.clear(); rcc.fixedProperties.insert( QLatin1String(TELEPATHY_INTERFACE_CHANNEL ".ChannelType"), QLatin1String(TELEPATHY_INTERFACE_CHANNEL_TYPE_TEXT)); rcc.fixedProperties.insert( QLatin1String(TELEPATHY_INTERFACE_CHANNEL ".TargetHandleType"), (uint) HandleTypeContact); rcc.allowedProperties.append( QLatin1String(TELEPATHY_INTERFACE_CHANNEL ".TargetHandle")); rcc.allowedProperties.append( QLatin1String(TELEPATHY_INTERFACE_CHANNEL ".TargetFoo")); rccs.append(rcc); filter.insert(QLatin1String("rccSubset"), qVariantFromValue(rccs)); filter.insert(QLatin1String("cmName"), QLatin1String("spurious")); filteredAccountSet = AccountSetPtr(new AccountSet(mAM, filter)); QCOMPARE(filteredAccountSet->isFilterValid(), true); QCOMPARE(filteredAccountSet->accounts().isEmpty(), true); } void TestAccountBasics::cleanup() { cleanupImpl(); } void TestAccountBasics::cleanupTestCase() { cleanupTestCaseImpl(); } QTEST_MAIN(TestAccountBasics) #include "_gen/account-basics.cpp.moc.hpp" <|endoftext|>
<commit_before>// @(#)root/rint:$Name$:$Id$ // Author: Rene Brun 17/02/95 /************************************************************************* * Copyright (C) 1995-2000, Rene Brun and Fons Rademakers. * * All rights reserved. * * * * For the licensing terms see $ROOTSYS/LICENSE. * * For the list of contributors see $ROOTSYS/README/CREDITS. * *************************************************************************/ ////////////////////////////////////////////////////////////////////////// // // // Rint // // // // Rint is the ROOT Interactive Interface. It allows interactive access // // to the ROOT system via the CINT C/C++ interpreter. // // // ////////////////////////////////////////////////////////////////////////// #include "TROOT.h" #include "TClass.h" #include "TVirtualX.h" #include "Getline.h" #include "TStyle.h" #include "TObjectTable.h" #include "TClassTable.h" #include "TStopwatch.h" #include "TCanvas.h" #include "TBenchmark.h" #include "TRint.h" #include "TSystem.h" #include "TEnv.h" #include "TSysEvtHandler.h" #include "TError.h" #include "TException.h" #include "TInterpreter.h" #include "TObjArray.h" #include "TObjString.h" #include "TFile.h" #include "TMapFile.h" #include "TTabCom.h" #ifdef R__UNIX #include <signal.h> extern "C" { extern int G__get_security_error(); extern int G__genericerror(char* msg); } #endif //----- Interrupt signal handler ----------------------------------------------- //______________________________________________________________________________ class TInterruptHandler : public TSignalHandler { public: TInterruptHandler() : TSignalHandler(kSigInterrupt, kFALSE) { } Bool_t Notify(); }; //______________________________________________________________________________ Bool_t TInterruptHandler::Notify() { // TRint interrupt handler. if (fDelay) { fDelay++; return kTRUE; } // make sure we use the sbrk heap (in case of mapped files) gMmallocDesc = 0; // go via the interpreter??? // if (gProof) gProof->Interrupt(TProof::kHardInterrupt); if (!G__get_security_error()) G__genericerror("\n *** Break *** keyboard interrupt"); else { Printf("\n *** Break *** keyboard interrupt"); if (TROOT::Initialized()) { Getlinem(kInit, "Root > "); gInterpreter->RewindDictionary(); Throw(GetSignal()); } } return kTRUE; } //----- Terminal Input file handler -------------------------------------------- //______________________________________________________________________________ class TTermInputHandler : public TFileHandler { public: TTermInputHandler(int fd) : TFileHandler(fd, 1) { } Bool_t Notify(); Bool_t ReadNotify() { return Notify(); } }; //______________________________________________________________________________ Bool_t TTermInputHandler::Notify() { gApplication->HandleTermInput(); return kTRUE; } ClassImp(TRint) //______________________________________________________________________________ TRint::TRint(const char *appClassName, int *argc, char **argv, void *options, int numOptions, Bool_t noLogo) : TApplication(appClassName, argc, argv, options, numOptions) { // Create an application environment. The TRint environment provides an // interface to the WM manager functionality and eventloop via inheritance // of TApplication and in addition provides interactive access to // the CINT C++ interpreter via the command line. fNcmd = 0; fDefaultPrompt = "root [%d] "; fInterrupt = kFALSE; gBenchmark = new TBenchmark(); if (!noLogo) PrintLogo(); // Everybody expects iostream to be available, so load it... #ifndef WIN32 ProcessLine("#include <iostream>"); #endif // The following libs are also useful to have, // make sure they are loaded... gROOT->LoadClass("TGeometry", "Graf3d"); gROOT->LoadClass("TTree", "Tree"); gROOT->LoadClass("TMatrix", "Matrix"); gROOT->LoadClass("TMinuit", "Minuit"); gROOT->LoadClass("TPostScript", "Postscript"); gROOT->LoadClass("TCanvas", "Gpad"); gROOT->LoadClass("THtml", "Html"); // Load user functions const char *logon; logon = gEnv->GetValue("Rint.Load", (char*)0); if (logon) { char *mac = gSystem->Which(TROOT::GetMacroPath(), logon, kReadPermission); if (mac) ProcessLine(Form(".L %s",logon)); delete [] mac; } // Execute logon macro logon = gEnv->GetValue("Rint.Logon", (char*)0); if (logon && !NoLogOpt()) { char *mac = gSystem->Which(TROOT::GetMacroPath(), logon, kReadPermission); if (mac) ProcessFile(logon); delete [] mac; } gInterpreter->SaveContext(); gInterpreter->SaveGlobalsContext(); // Install interrupt and terminal input handlers TInterruptHandler *ih = new TInterruptHandler(); gSystem->AddSignalHandler(ih); SetSignalHandler(ih); TTermInputHandler *th = new TTermInputHandler(0); gSystem->AddFileHandler(th); // Goto into raw terminal input mode char defhist[128]; #ifndef R__VMS sprintf(defhist, "%s/.root_hist", gSystem->Getenv("HOME")); #else sprintf(defhist, "%s.root_hist", gSystem->Getenv("HOME")); #endif logon = gEnv->GetValue("Rint.History", defhist); Gl_histinit((char *)logon); Gl_windowchanged(); // Setup for tab completion gTabCom = new TTabCom; } //______________________________________________________________________________ TRint::~TRint() { } //______________________________________________________________________________ void TRint::Run(Bool_t retrn) { // Main application eventloop. First process files given on the command // line and then go into the main application event loop. Getlinem(kInit, GetPrompt()); // Process shell command line input files if (InputFiles()) { TObjString *file; TIter next(InputFiles()); RETRY { while ((file = (TObjString *)next())) { char cmd[256]; if (file->String().EndsWith(".root")) { const char *rfile = (const char*)file->String(); Printf("\nAttaching file %s...", rfile); char *base = StrDup(gSystem->BaseName(rfile)); char *s = strchr(base, '.'); *s = 0; sprintf(cmd, "TFile *%s = TFile::Open(\"%s\")", base, rfile); delete [] base; } else { Printf("\nProcessing %s...", (const char*)file->String()); sprintf(cmd, ".x %s", (const char*)file->String()); } Getlinem(kCleanUp, 0); Gl_histadd(cmd); fNcmd++; ProcessLine(cmd); } } ENDTRY; if (QuitOpt()) Terminate(0); ClearInputFiles(); Getlinem(kInit, GetPrompt()); } TApplication::Run(retrn); Getlinem(kCleanUp, 0); } //______________________________________________________________________________ void TRint::PrintLogo() { // Print the ROOT logo on standard output. Int_t iday,imonth,iyear; static const char *months[] = {"January","February","March","April","May", "June","July","August","September","October", "November","December"}; const char *root_version = gROOT->GetVersion(); Int_t idatqq = gROOT->GetVersionDate(); iday = idatqq%100; imonth = (idatqq/100)%100; iyear = (idatqq/10000); char *root_date = Form("%d %s %4d",iday,months[imonth-1],iyear); Printf(" *******************************************"); Printf(" * *"); Printf(" * W E L C O M E to R O O T *"); Printf(" * *"); Printf(" * Version%10s %17s *",root_version,root_date); // Printf(" * Development version *"); Printf(" * *"); Printf(" * You are welcome to visit our Web site *"); Printf(" * http://root.cern.ch *"); Printf(" * *"); Printf(" *******************************************"); #ifdef R__UNIX if (!strcmp(gVirtualX->GetName(), "X11TTF")) Printf("\nFreeType Engine v1.1 used to render TrueType fonts."); #endif #ifdef _REENTRANT #ifdef R__UNIX else #endif printf("\n"); Printf("Compiled with thread support."); #endif gInterpreter->PrintIntro(); #ifdef R__UNIX // Popdown X logo, only if started with -splash option for (int i = 0; i < Argc(); i++) if (!strcmp(Argv(i), "-splash")) kill(getppid(), SIGUSR1); #endif } //______________________________________________________________________________ char *TRint::GetPrompt() { // Get prompt from interpreter. Either "root [n]" or "end with '}'". char *s = gInterpreter->GetPrompt(); if (s[0]) strcpy(fPrompt, s); else sprintf(fPrompt, fDefaultPrompt, fNcmd); return fPrompt; } //______________________________________________________________________________ const char *TRint::SetPrompt(const char *newPrompt) { // Set a new default prompt. It returns the previous prompt. // The prompt may contain a %d which will be replaced by the commend // number. The default prompt is "root [%d] ". The maximum length of // the prompt is 55 characters. To set the prompt in an interactive // session do: // root [0] ((TRint*)gROOT->GetApplication())->SetPrompt("aap> ") // aap> const char *op = fDefaultPrompt; if (strlen(newPrompt) <= 55) fDefaultPrompt = newPrompt; else Error("SetPrompt", "newPrompt too long (> 55 characters)"); return op; } //______________________________________________________________________________ void TRint::HandleTermInput() { // Handle input coming from terminal. static TStopwatch timer; char *line; if ((line = Getlinem(kOneChar, 0))) { if (gROOT->Timer()) timer.Start(); Gl_histadd(line); char *s = line; while (s && *s == ' ') s++; // strip-off leading blanks s[strlen(s)-1] = '\0'; // strip also '\n' off fInterrupt = kFALSE; if (!gInterpreter->GetMore() && strlen(s) != 0) fNcmd++; ProcessLine(s); if (strstr(s,".reset") != s) gInterpreter->EndOfLineAction(); if (gROOT->Timer()) timer.Print(); gTabCom->ClearAll(); Getlinem(kInit, GetPrompt()); } } //______________________________________________________________________________ void TRint::Terminate(int status) { // Terminate the application. Reset the terminal to sane mode and call // the logoff macro defined via Rint.Logoff environment variable. Getlinem(kCleanUp, 0); if (ReturnFromRun()) { gSystem->ExitLoop(); } else { //Execute logoff macro const char *logoff; logoff = gEnv->GetValue("Rint.Logoff", (char*)0); if (logoff && !NoLogOpt()) { char *mac = gSystem->Which(TROOT::GetMacroPath(), logoff, kReadPermission); if (mac) ProcessFile(logoff); delete [] mac; } gSystem->Exit(status); } } <commit_msg>when getting an empty line check for Gl_eof(). If an eof found terminate. This is the case when there is no more input while reading from a pipe of from a file via stdin<commit_after>// @(#)root/rint:$Name: $:$Id: TRint.cxx,v 1.1.1.1 2000/05/16 17:00:46 rdm Exp $ // Author: Rene Brun 17/02/95 /************************************************************************* * Copyright (C) 1995-2000, Rene Brun and Fons Rademakers. * * All rights reserved. * * * * For the licensing terms see $ROOTSYS/LICENSE. * * For the list of contributors see $ROOTSYS/README/CREDITS. * *************************************************************************/ ////////////////////////////////////////////////////////////////////////// // // // Rint // // // // Rint is the ROOT Interactive Interface. It allows interactive access // // to the ROOT system via the CINT C/C++ interpreter. // // // ////////////////////////////////////////////////////////////////////////// #include "TROOT.h" #include "TClass.h" #include "TVirtualX.h" #include "Getline.h" #include "TStyle.h" #include "TObjectTable.h" #include "TClassTable.h" #include "TStopwatch.h" #include "TCanvas.h" #include "TBenchmark.h" #include "TRint.h" #include "TSystem.h" #include "TEnv.h" #include "TSysEvtHandler.h" #include "TError.h" #include "TException.h" #include "TInterpreter.h" #include "TObjArray.h" #include "TObjString.h" #include "TFile.h" #include "TMapFile.h" #include "TTabCom.h" #ifdef R__UNIX #include <signal.h> extern "C" { extern int G__get_security_error(); extern int G__genericerror(char* msg); } #endif //----- Interrupt signal handler ----------------------------------------------- //______________________________________________________________________________ class TInterruptHandler : public TSignalHandler { public: TInterruptHandler() : TSignalHandler(kSigInterrupt, kFALSE) { } Bool_t Notify(); }; //______________________________________________________________________________ Bool_t TInterruptHandler::Notify() { // TRint interrupt handler. if (fDelay) { fDelay++; return kTRUE; } // make sure we use the sbrk heap (in case of mapped files) gMmallocDesc = 0; // go via the interpreter??? // if (gProof) gProof->Interrupt(TProof::kHardInterrupt); if (!G__get_security_error()) G__genericerror("\n *** Break *** keyboard interrupt"); else { Printf("\n *** Break *** keyboard interrupt"); if (TROOT::Initialized()) { Getlinem(kInit, "Root > "); gInterpreter->RewindDictionary(); Throw(GetSignal()); } } return kTRUE; } //----- Terminal Input file handler -------------------------------------------- //______________________________________________________________________________ class TTermInputHandler : public TFileHandler { public: TTermInputHandler(int fd) : TFileHandler(fd, 1) { } Bool_t Notify(); Bool_t ReadNotify() { return Notify(); } }; //______________________________________________________________________________ Bool_t TTermInputHandler::Notify() { gApplication->HandleTermInput(); return kTRUE; } ClassImp(TRint) //______________________________________________________________________________ TRint::TRint(const char *appClassName, int *argc, char **argv, void *options, int numOptions, Bool_t noLogo) : TApplication(appClassName, argc, argv, options, numOptions) { // Create an application environment. The TRint environment provides an // interface to the WM manager functionality and eventloop via inheritance // of TApplication and in addition provides interactive access to // the CINT C++ interpreter via the command line. fNcmd = 0; fDefaultPrompt = "root [%d] "; fInterrupt = kFALSE; gBenchmark = new TBenchmark(); if (!noLogo) PrintLogo(); // Everybody expects iostream to be available, so load it... #ifndef WIN32 ProcessLine("#include <iostream>"); #endif // The following libs are also useful to have, // make sure they are loaded... gROOT->LoadClass("TGeometry", "Graf3d"); gROOT->LoadClass("TTree", "Tree"); gROOT->LoadClass("TMatrix", "Matrix"); gROOT->LoadClass("TMinuit", "Minuit"); gROOT->LoadClass("TPostScript", "Postscript"); gROOT->LoadClass("TCanvas", "Gpad"); gROOT->LoadClass("THtml", "Html"); // Load user functions const char *logon; logon = gEnv->GetValue("Rint.Load", (char*)0); if (logon) { char *mac = gSystem->Which(TROOT::GetMacroPath(), logon, kReadPermission); if (mac) ProcessLine(Form(".L %s",logon)); delete [] mac; } // Execute logon macro logon = gEnv->GetValue("Rint.Logon", (char*)0); if (logon && !NoLogOpt()) { char *mac = gSystem->Which(TROOT::GetMacroPath(), logon, kReadPermission); if (mac) ProcessFile(logon); delete [] mac; } gInterpreter->SaveContext(); gInterpreter->SaveGlobalsContext(); // Install interrupt and terminal input handlers TInterruptHandler *ih = new TInterruptHandler(); gSystem->AddSignalHandler(ih); SetSignalHandler(ih); TTermInputHandler *th = new TTermInputHandler(0); gSystem->AddFileHandler(th); // Goto into raw terminal input mode char defhist[128]; #ifndef R__VMS sprintf(defhist, "%s/.root_hist", gSystem->Getenv("HOME")); #else sprintf(defhist, "%s.root_hist", gSystem->Getenv("HOME")); #endif logon = gEnv->GetValue("Rint.History", defhist); Gl_histinit((char *)logon); Gl_windowchanged(); // Setup for tab completion gTabCom = new TTabCom; } //______________________________________________________________________________ TRint::~TRint() { } //______________________________________________________________________________ void TRint::Run(Bool_t retrn) { // Main application eventloop. First process files given on the command // line and then go into the main application event loop. Getlinem(kInit, GetPrompt()); // Process shell command line input files if (InputFiles()) { TObjString *file; TIter next(InputFiles()); RETRY { while ((file = (TObjString *)next())) { char cmd[256]; if (file->String().EndsWith(".root")) { const char *rfile = (const char*)file->String(); Printf("\nAttaching file %s...", rfile); char *base = StrDup(gSystem->BaseName(rfile)); char *s = strchr(base, '.'); *s = 0; sprintf(cmd, "TFile *%s = TFile::Open(\"%s\")", base, rfile); delete [] base; } else { Printf("\nProcessing %s...", (const char*)file->String()); sprintf(cmd, ".x %s", (const char*)file->String()); } Getlinem(kCleanUp, 0); Gl_histadd(cmd); fNcmd++; ProcessLine(cmd); } } ENDTRY; if (QuitOpt()) Terminate(0); ClearInputFiles(); Getlinem(kInit, GetPrompt()); } TApplication::Run(retrn); Getlinem(kCleanUp, 0); } //______________________________________________________________________________ void TRint::PrintLogo() { // Print the ROOT logo on standard output. Int_t iday,imonth,iyear; static const char *months[] = {"January","February","March","April","May", "June","July","August","September","October", "November","December"}; const char *root_version = gROOT->GetVersion(); Int_t idatqq = gROOT->GetVersionDate(); iday = idatqq%100; imonth = (idatqq/100)%100; iyear = (idatqq/10000); char *root_date = Form("%d %s %4d",iday,months[imonth-1],iyear); Printf(" *******************************************"); Printf(" * *"); Printf(" * W E L C O M E to R O O T *"); Printf(" * *"); Printf(" * Version%10s %17s *",root_version,root_date); // Printf(" * Development version *"); Printf(" * *"); Printf(" * You are welcome to visit our Web site *"); Printf(" * http://root.cern.ch *"); Printf(" * *"); Printf(" *******************************************"); #ifdef R__UNIX if (!strcmp(gVirtualX->GetName(), "X11TTF")) Printf("\nFreeType Engine v1.1 used to render TrueType fonts."); #endif #ifdef _REENTRANT #ifdef R__UNIX else #endif printf("\n"); Printf("Compiled with thread support."); #endif gInterpreter->PrintIntro(); #ifdef R__UNIX // Popdown X logo, only if started with -splash option for (int i = 0; i < Argc(); i++) if (!strcmp(Argv(i), "-splash")) kill(getppid(), SIGUSR1); #endif } //______________________________________________________________________________ char *TRint::GetPrompt() { // Get prompt from interpreter. Either "root [n]" or "end with '}'". char *s = gInterpreter->GetPrompt(); if (s[0]) strcpy(fPrompt, s); else sprintf(fPrompt, fDefaultPrompt, fNcmd); return fPrompt; } //______________________________________________________________________________ const char *TRint::SetPrompt(const char *newPrompt) { // Set a new default prompt. It returns the previous prompt. // The prompt may contain a %d which will be replaced by the commend // number. The default prompt is "root [%d] ". The maximum length of // the prompt is 55 characters. To set the prompt in an interactive // session do: // root [0] ((TRint*)gROOT->GetApplication())->SetPrompt("aap> ") // aap> const char *op = fDefaultPrompt; if (strlen(newPrompt) <= 55) fDefaultPrompt = newPrompt; else Error("SetPrompt", "newPrompt too long (> 55 characters)"); return op; } //______________________________________________________________________________ void TRint::HandleTermInput() { // Handle input coming from terminal. static TStopwatch timer; char *line; if ((line = Getlinem(kOneChar, 0))) { if (line[0] == 0 && Gl_eof()) Terminate(0); if (gROOT->Timer()) timer.Start(); Gl_histadd(line); char *s = line; while (s && *s == ' ') s++; // strip-off leading blanks s[strlen(s)-1] = '\0'; // strip also '\n' off fInterrupt = kFALSE; if (!gInterpreter->GetMore() && strlen(s) != 0) fNcmd++; ProcessLine(s); if (strstr(s,".reset") != s) gInterpreter->EndOfLineAction(); if (gROOT->Timer()) timer.Print(); gTabCom->ClearAll(); Getlinem(kInit, GetPrompt()); } } //______________________________________________________________________________ void TRint::Terminate(int status) { // Terminate the application. Reset the terminal to sane mode and call // the logoff macro defined via Rint.Logoff environment variable. Getlinem(kCleanUp, 0); if (ReturnFromRun()) { gSystem->ExitLoop(); } else { //Execute logoff macro const char *logoff; logoff = gEnv->GetValue("Rint.Logoff", (char*)0); if (logoff && !NoLogOpt()) { char *mac = gSystem->Which(TROOT::GetMacroPath(), logoff, kReadPermission); if (mac) ProcessFile(logoff); delete [] mac; } gSystem->Exit(status); } } <|endoftext|>
<commit_before>/* This file is part of the kolab resource - the implementation of the Kolab storage format. See www.kolab.org for documentation on this. Copyright (c) 2004 Bo Thorsen <[email protected]> This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 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 Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; see the file COPYING.LIB. If not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. In addition, as a special exception, the copyright holders give permission to link the code of this program with any edition of the Qt library by Trolltech AS, Norway (or with modified versions of Qt that use the same license as Qt), and distribute linked combinations including the two. You must obey the GNU General Public License in all respects for all of the code used other than Qt. If you modify this file, you may extend this exception to your version of the file, but you are not obligated to do so. If you do not wish to do so, delete this exception statement from your version. */ #include "incidence.h" #include <libkcal/journal.h> #include <libkdepim/email.h> #include <kdebug.h> using namespace Kolab; Incidence::Incidence( KCal::Incidence* incidence ) { if ( incidence ) setFields( incidence ); } Incidence::~Incidence() { } void Incidence::setSummary( const QString& summary ) { mSummary = summary; } QString Incidence::summary() const { return mSummary; } void Incidence::setLocation( const QString& location ) { mLocation = location; } QString Incidence::location() const { return mLocation; } void Incidence::setOrganizer( const Email& organizer ) { mOrganizer = organizer; } KolabBase::Email Incidence::organizer() const { return mOrganizer; } void Incidence::setStartDate( const QDateTime& startDate ) { mStartDate = startDate; } QDateTime Incidence::startDate() const { return mStartDate; } void Incidence::setAlarm( int alarm ) { mAlarm = alarm; } int Incidence::alarm() const { return mAlarm; } void Incidence::setRecurrence( const Recurrence& recurrence ) { mRecurrence = recurrence; } Incidence::Recurrence Incidence::recurrence() const { return mRecurrence; } void Incidence::addAttendee( const Attendee& attendee ) { mAttendees.append( attendee ); } QValueList<Incidence::Attendee>& Incidence::attendees() { return mAttendees; } const QValueList<Incidence::Attendee>& Incidence::attendees() const { return mAttendees; } bool Incidence::loadAttendeeAttribute( QDomElement& element, Attendee& attendee ) { for ( QDomNode n = element.firstChild(); !n.isNull(); n = n.nextSibling() ) { if ( n.isComment() ) continue; if ( n.isElement() ) { QDomElement e = n.toElement(); QString tagName = e.tagName(); if ( tagName == "display-name" ) attendee.displayName = e.text(); else if ( tagName == "smtp-address" ) attendee.smtpAddress = e.text(); else if ( tagName == "status" ) attendee.status = e.text(); else if ( tagName == "request-response" ) // This sets reqResp to false, if the text is "false". Otherwise it // sets it to true. This means the default setting is true. attendee.requestResponse = ( e.text().lower() != "false" ); else if ( tagName == "invitationSent" ) // Like above, only this defaults to false attendee.invitationSent = ( e.text().lower() != "true" ); else if ( tagName == "role" ) attendee.role = e.text(); else // TODO: Unhandled tag - save for later storage kdDebug() << "Warning: Unhandled tag " << e.tagName() << endl; } else kdDebug() << "Node is not a comment or an element???" << endl; } return true; } void Incidence::saveAttendeeAttribute( QDomElement& element, const Attendee& attendee ) const { writeString( element, "display-name", attendee.displayName ); writeString( element, "smtp-address", attendee.smtpAddress ); writeString( element, "status", attendee.status ); writeString( element, "request-response", ( attendee.requestResponse ? "true" : "false" ) ); writeString( element, "invitationSent", ( attendee.invitationSent ? "true" : "false" ) ); writeString( element, "role", attendee.role ); } void Incidence::saveAttendees( QDomElement& element ) const { QValueList<Attendee>::ConstIterator it = mAttendees.begin(); for ( ; it != mAttendees.end(); ++it ) saveAttendeeAttribute( element, *it ); } bool Incidence::loadAttribute( QDomElement& element ) { QString tagName = element.tagName(); if ( tagName == "summary" ) setSummary( element.text() ); else if ( tagName == "location" ) setLocation( element.text() ); else if ( tagName == "organizer" ) { Email email; if ( loadEmailAttribute( element, email ) ) { setOrganizer( email ); return true; } else return false; } else if ( tagName == "start-date" ) setStartDate( stringToDateTime( element.text() ) ); else if ( tagName == "recurrence" ) // TODO ; else if ( tagName == "attendee" ) { Attendee attendee; if ( loadAttendeeAttribute( element, attendee ) ) { addAttendee( attendee ); return true; } else return false; } else return KolabBase::loadAttribute( element ); // We handled this return true; } bool Incidence::saveAttributes( QDomElement& element ) const { // Save the base class elements KolabBase::saveAttributes( element ); writeString( element, "summary", summary() ); writeString( element, "location", location() ); saveEmailAttribute( element, organizer(), "organizer" ); writeString( element, "start-date", dateTimeToString( startDate() ) ); // saveRecurrenceAttribute(); saveAttendees( element ); return true; } static KCal::Attendee::PartStat attendeeStringToStatus( const QString& s ) { if ( s == "none" ) return KCal::Attendee::NeedsAction; if ( s == "tentative" ) return KCal::Attendee::Tentative; if ( s == "declined" ) return KCal::Attendee::Declined; // Default: return KCal::Attendee::Accepted; } static QString attendeeStatusToString( KCal::Attendee::PartStat status ) { switch( status ) { case KCal::Attendee::NeedsAction: return "none"; case KCal::Attendee::Accepted: return "accepted"; case KCal::Attendee::Declined: return "declined"; case KCal::Attendee::Tentative: return "tentative"; case KCal::Attendee::Delegated: case KCal::Attendee::Completed: case KCal::Attendee::InProcess: // These don't have any meaning in the Kolab format, so just use: return "accepted"; } // Default for the case that there are more added later: return "accepted"; } static KCal::Attendee::Role attendeeStringToRole( const QString& s ) { if ( s == "optional" ) return KCal::Attendee::OptParticipant; if ( s == "resource" ) return KCal::Attendee::NonParticipant; return KCal::Attendee::ReqParticipant; } static QString attendeeRoleToString( KCal::Attendee::Role role ) { switch( role ) { case KCal::Attendee::ReqParticipant: return "required"; case KCal::Attendee::OptParticipant: return "optional"; case KCal::Attendee::Chair: // We don't have the notion of chair, so use return "required"; case KCal::Attendee::NonParticipant: // In Kolab, a non-participant is a resource return "resource"; } // Default for the case that there are more added later: return "required"; } void Incidence::setFields( const KCal::Incidence* incidence ) { KolabBase::setFields( incidence ); // TODO: Alarm and recurrence setStartDate( incidence->dtStart() ); setSummary( incidence->summary() ); setLocation( incidence->location() ); Email org; KPIM::getNameAndMail( incidence->organizer(), org.displayName, org.smtpAddress ); setOrganizer( org ); // Attendees: KCal::Attendee::List attendees = incidence->attendees(); KCal::Attendee::List::ConstIterator it; for ( it = attendees.begin(); it != attendees.end(); ++it ) { KCal::Attendee* kcalAttendee = *it; Attendee attendee; attendee.displayName = kcalAttendee->name(); attendee.smtpAddress = kcalAttendee->email(); attendee.status = attendeeStatusToString( kcalAttendee->status() ); attendee.requestResponse = kcalAttendee->RSVP(); // TODO: KCal::Attendee::mFlag is not accessible // attendee.invitationSent = kcalAttendee->mFlag; attendee.role = attendeeRoleToString( kcalAttendee->role() ); addAttendee( attendee ); } } void Incidence::saveTo( KCal::Incidence* incidence ) { KolabBase::saveTo( incidence ); // TODO: Alarm and recurrence incidence->setDtStart( startDate() ); incidence->setSummary( summary() ); incidence->setLocation( location() ); incidence->setOrganizer( organizer().displayName + "<" + organizer().smtpAddress + ">" ); incidence->clearAttendees(); QValueList<Attendee>::ConstIterator it; for ( it = mAttendees.begin(); it != mAttendees.end(); ++it ) { KCal::Attendee::PartStat status = attendeeStringToStatus( (*it).status ); KCal::Attendee::Role role = attendeeStringToRole( (*it).role ); incidence->addAttendee( new KCal::Attendee( (*it).displayName, (*it).smtpAddress, (*it).requestResponse, status, role ) ); } } // Unhandled KCal::Incidence fields: // revision, status (unused), priority (done in tasks), attendee.uid, // mComments, mReadOnly <commit_msg>Don't treat all incidences as "floating" (i.e. no time associated to them)<commit_after>/* This file is part of the kolab resource - the implementation of the Kolab storage format. See www.kolab.org for documentation on this. Copyright (c) 2004 Bo Thorsen <[email protected]> This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 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 Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; see the file COPYING.LIB. If not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. In addition, as a special exception, the copyright holders give permission to link the code of this program with any edition of the Qt library by Trolltech AS, Norway (or with modified versions of Qt that use the same license as Qt), and distribute linked combinations including the two. You must obey the GNU General Public License in all respects for all of the code used other than Qt. If you modify this file, you may extend this exception to your version of the file, but you are not obligated to do so. If you do not wish to do so, delete this exception statement from your version. */ #include "incidence.h" #include <libkcal/journal.h> #include <libkdepim/email.h> #include <kdebug.h> using namespace Kolab; Incidence::Incidence( KCal::Incidence* incidence ) { if ( incidence ) setFields( incidence ); } Incidence::~Incidence() { } void Incidence::setSummary( const QString& summary ) { mSummary = summary; } QString Incidence::summary() const { return mSummary; } void Incidence::setLocation( const QString& location ) { mLocation = location; } QString Incidence::location() const { return mLocation; } void Incidence::setOrganizer( const Email& organizer ) { mOrganizer = organizer; } KolabBase::Email Incidence::organizer() const { return mOrganizer; } void Incidence::setStartDate( const QDateTime& startDate ) { mStartDate = startDate; } QDateTime Incidence::startDate() const { return mStartDate; } void Incidence::setAlarm( int alarm ) { mAlarm = alarm; } int Incidence::alarm() const { return mAlarm; } void Incidence::setRecurrence( const Recurrence& recurrence ) { mRecurrence = recurrence; } Incidence::Recurrence Incidence::recurrence() const { return mRecurrence; } void Incidence::addAttendee( const Attendee& attendee ) { mAttendees.append( attendee ); } QValueList<Incidence::Attendee>& Incidence::attendees() { return mAttendees; } const QValueList<Incidence::Attendee>& Incidence::attendees() const { return mAttendees; } bool Incidence::loadAttendeeAttribute( QDomElement& element, Attendee& attendee ) { for ( QDomNode n = element.firstChild(); !n.isNull(); n = n.nextSibling() ) { if ( n.isComment() ) continue; if ( n.isElement() ) { QDomElement e = n.toElement(); QString tagName = e.tagName(); if ( tagName == "display-name" ) attendee.displayName = e.text(); else if ( tagName == "smtp-address" ) attendee.smtpAddress = e.text(); else if ( tagName == "status" ) attendee.status = e.text(); else if ( tagName == "request-response" ) // This sets reqResp to false, if the text is "false". Otherwise it // sets it to true. This means the default setting is true. attendee.requestResponse = ( e.text().lower() != "false" ); else if ( tagName == "invitationSent" ) // Like above, only this defaults to false attendee.invitationSent = ( e.text().lower() != "true" ); else if ( tagName == "role" ) attendee.role = e.text(); else // TODO: Unhandled tag - save for later storage kdDebug() << "Warning: Unhandled tag " << e.tagName() << endl; } else kdDebug() << "Node is not a comment or an element???" << endl; } return true; } void Incidence::saveAttendeeAttribute( QDomElement& element, const Attendee& attendee ) const { writeString( element, "display-name", attendee.displayName ); writeString( element, "smtp-address", attendee.smtpAddress ); writeString( element, "status", attendee.status ); writeString( element, "request-response", ( attendee.requestResponse ? "true" : "false" ) ); writeString( element, "invitationSent", ( attendee.invitationSent ? "true" : "false" ) ); writeString( element, "role", attendee.role ); } void Incidence::saveAttendees( QDomElement& element ) const { QValueList<Attendee>::ConstIterator it = mAttendees.begin(); for ( ; it != mAttendees.end(); ++it ) saveAttendeeAttribute( element, *it ); } bool Incidence::loadAttribute( QDomElement& element ) { QString tagName = element.tagName(); if ( tagName == "summary" ) setSummary( element.text() ); else if ( tagName == "location" ) setLocation( element.text() ); else if ( tagName == "organizer" ) { Email email; if ( loadEmailAttribute( element, email ) ) { setOrganizer( email ); return true; } else return false; } else if ( tagName == "start-date" ) setStartDate( stringToDateTime( element.text() ) ); else if ( tagName == "recurrence" ) // TODO ; else if ( tagName == "attendee" ) { Attendee attendee; if ( loadAttendeeAttribute( element, attendee ) ) { addAttendee( attendee ); return true; } else return false; } else return KolabBase::loadAttribute( element ); // We handled this return true; } bool Incidence::saveAttributes( QDomElement& element ) const { // Save the base class elements KolabBase::saveAttributes( element ); writeString( element, "summary", summary() ); writeString( element, "location", location() ); saveEmailAttribute( element, organizer(), "organizer" ); writeString( element, "start-date", dateTimeToString( startDate() ) ); // saveRecurrenceAttribute(); saveAttendees( element ); return true; } static KCal::Attendee::PartStat attendeeStringToStatus( const QString& s ) { if ( s == "none" ) return KCal::Attendee::NeedsAction; if ( s == "tentative" ) return KCal::Attendee::Tentative; if ( s == "declined" ) return KCal::Attendee::Declined; // Default: return KCal::Attendee::Accepted; } static QString attendeeStatusToString( KCal::Attendee::PartStat status ) { switch( status ) { case KCal::Attendee::NeedsAction: return "none"; case KCal::Attendee::Accepted: return "accepted"; case KCal::Attendee::Declined: return "declined"; case KCal::Attendee::Tentative: return "tentative"; case KCal::Attendee::Delegated: case KCal::Attendee::Completed: case KCal::Attendee::InProcess: // These don't have any meaning in the Kolab format, so just use: return "accepted"; } // Default for the case that there are more added later: return "accepted"; } static KCal::Attendee::Role attendeeStringToRole( const QString& s ) { if ( s == "optional" ) return KCal::Attendee::OptParticipant; if ( s == "resource" ) return KCal::Attendee::NonParticipant; return KCal::Attendee::ReqParticipant; } static QString attendeeRoleToString( KCal::Attendee::Role role ) { switch( role ) { case KCal::Attendee::ReqParticipant: return "required"; case KCal::Attendee::OptParticipant: return "optional"; case KCal::Attendee::Chair: // We don't have the notion of chair, so use return "required"; case KCal::Attendee::NonParticipant: // In Kolab, a non-participant is a resource return "resource"; } // Default for the case that there are more added later: return "required"; } void Incidence::setFields( const KCal::Incidence* incidence ) { KolabBase::setFields( incidence ); // TODO: Alarm and recurrence setStartDate( incidence->dtStart() ); setSummary( incidence->summary() ); setLocation( incidence->location() ); Email org; KPIM::getNameAndMail( incidence->organizer(), org.displayName, org.smtpAddress ); setOrganizer( org ); // Attendees: KCal::Attendee::List attendees = incidence->attendees(); KCal::Attendee::List::ConstIterator it; for ( it = attendees.begin(); it != attendees.end(); ++it ) { KCal::Attendee* kcalAttendee = *it; Attendee attendee; attendee.displayName = kcalAttendee->name(); attendee.smtpAddress = kcalAttendee->email(); attendee.status = attendeeStatusToString( kcalAttendee->status() ); attendee.requestResponse = kcalAttendee->RSVP(); // TODO: KCal::Attendee::mFlag is not accessible // attendee.invitationSent = kcalAttendee->mFlag; attendee.role = attendeeRoleToString( kcalAttendee->role() ); addAttendee( attendee ); } } void Incidence::saveTo( KCal::Incidence* incidence ) { KolabBase::saveTo( incidence ); // TODO: Alarm and recurrence QDateTime start = startDate(); incidence->setDtStart( start ); incidence->setFloats( start.time().isNull() ); incidence->setSummary( summary() ); incidence->setLocation( location() ); incidence->setOrganizer( organizer().displayName + "<" + organizer().smtpAddress + ">" ); incidence->clearAttendees(); QValueList<Attendee>::ConstIterator it; for ( it = mAttendees.begin(); it != mAttendees.end(); ++it ) { KCal::Attendee::PartStat status = attendeeStringToStatus( (*it).status ); KCal::Attendee::Role role = attendeeStringToRole( (*it).role ); incidence->addAttendee( new KCal::Attendee( (*it).displayName, (*it).smtpAddress, (*it).requestResponse, status, role ) ); } } // Unhandled KCal::Incidence fields: // revision, status (unused), priority (done in tasks), attendee.uid, // mComments, mReadOnly <|endoftext|>
<commit_before>#include <QtCore/QObject> class MyObject; MyObject* somefunc() { return nullptr; } static MyObject * s_obj; class MyObject : public QObject { public: MyObject(); void pub(); MyObject* memberFunc() const; MyObject *another; private: void priv(); public slots: void pubSlot(); signals: void sig(); private Q_SLOTS: void privSlot(); protected: void prot(); Q_SIGNAL void singularSig(); Q_SLOT void singularSlot(); }; void MyObject::pub() { emit prot(); // Warning: emit on non slot. sig(); // Warning: missing emit prot(); // OK pub(); // OK priv(); // OK privSlot(); // OK Q_EMIT privSlot(); // Warning Q_EMIT somefunc()->sig(); // OK somefunc()->sig(); // Warning Q_EMIT memberFunc()->sig(); // OK memberFunc()->sig(); // Warning emit another->sig(); // OK emit s_obj->sig(); // OK } MyObject::MyObject() { emit sig(); // Warning emit another->sig(); // OK; emit memberFunc()->sig(); // OK; [this]{ emit sig(); }; // OK emit singularSig(); // Warning singularSlot(); // OK } void MyObject::singularSlot() { singularSig(); // Warning } struct NotQObject { QObject *o; void test1() {} void test() { test1(); // OK emit test1(); // Warning emit o->destroyed(); // OK } }; <commit_msg>incorrect-emit: Add unit-test for a bug that should be fixed<commit_after>#include <QtCore/QObject> class MyObject; MyObject* somefunc() { return nullptr; } static MyObject * s_obj; class MyObject : public QObject { public: MyObject(); void pub(); MyObject* memberFunc() const; MyObject *another; private: void priv(); public slots: void pubSlot(); signals: void sig(); private Q_SLOTS: void privSlot(); protected: void prot(); Q_SIGNAL void singularSig(); Q_SLOT void singularSlot(); }; void MyObject::pub() { emit prot(); // Warning: emit on non slot. sig(); // Warning: missing emit prot(); // OK pub(); // OK priv(); // OK privSlot(); // OK Q_EMIT privSlot(); // Warning Q_EMIT somefunc()->sig(); // OK somefunc()->sig(); // Warning Q_EMIT memberFunc()->sig(); // OK memberFunc()->sig(); // Warning emit another->sig(); // OK emit s_obj->sig(); // OK } MyObject::MyObject() { emit sig(); // Warning emit another->sig(); // OK; emit memberFunc()->sig(); // OK; [this]{ emit sig(); }; // OK emit singularSig(); // Warning singularSlot(); // OK } void MyObject::singularSlot() { singularSig(); // Warning } struct NotQObject { QObject *o; void test1() {} void test() { test1(); // OK emit test1(); // Warning emit o->destroyed(); // OK } }; class TestBug373947 : public QObject { int method() { return otherMethod(); // OK } Q_SIGNALS: void someSignal(); public: int otherMethod(); }; <|endoftext|>
<commit_before><commit_msg>Planning: fix a bug with pull-over.<commit_after><|endoftext|>
<commit_before>// @(#)root/rint:$Name: $:$Id: TRint.cxx,v 1.3 2000/06/13 18:49:00 rdm Exp $ // Author: Rene Brun 17/02/95 /************************************************************************* * Copyright (C) 1995-2000, Rene Brun and Fons Rademakers. * * All rights reserved. * * * * For the licensing terms see $ROOTSYS/LICENSE. * * For the list of contributors see $ROOTSYS/README/CREDITS. * *************************************************************************/ ////////////////////////////////////////////////////////////////////////// // // // Rint // // // // Rint is the ROOT Interactive Interface. It allows interactive access // // to the ROOT system via the CINT C/C++ interpreter. // // // ////////////////////////////////////////////////////////////////////////// #include "TROOT.h" #include "TClass.h" #include "TVirtualX.h" #include "Getline.h" #include "TStyle.h" #include "TObjectTable.h" #include "TClassTable.h" #include "TStopwatch.h" #include "TCanvas.h" #include "TBenchmark.h" #include "TRint.h" #include "TSystem.h" #include "TEnv.h" #include "TSysEvtHandler.h" #include "TError.h" #include "TException.h" #include "TInterpreter.h" #include "TObjArray.h" #include "TObjString.h" #include "TFile.h" #include "TMapFile.h" #include "TTabCom.h" #ifdef R__UNIX #include <signal.h> extern "C" { extern int G__get_security_error(); extern int G__genericerror(char* msg); } #endif //----- Interrupt signal handler ----------------------------------------------- //______________________________________________________________________________ class TInterruptHandler : public TSignalHandler { public: TInterruptHandler() : TSignalHandler(kSigInterrupt, kFALSE) { } Bool_t Notify(); }; //______________________________________________________________________________ Bool_t TInterruptHandler::Notify() { // TRint interrupt handler. if (fDelay) { fDelay++; return kTRUE; } // make sure we use the sbrk heap (in case of mapped files) gMmallocDesc = 0; // go via the interpreter??? // if (gProof) gProof->Interrupt(TProof::kHardInterrupt); if (!G__get_security_error()) G__genericerror("\n *** Break *** keyboard interrupt"); else { Printf("\n *** Break *** keyboard interrupt"); if (TROOT::Initialized()) { Getlinem(kInit, "Root > "); gInterpreter->RewindDictionary(); Throw(GetSignal()); } } return kTRUE; } //----- Terminal Input file handler -------------------------------------------- //______________________________________________________________________________ class TTermInputHandler : public TFileHandler { public: TTermInputHandler(int fd) : TFileHandler(fd, 1) { } Bool_t Notify(); Bool_t ReadNotify() { return Notify(); } }; //______________________________________________________________________________ Bool_t TTermInputHandler::Notify() { gApplication->HandleTermInput(); return kTRUE; } ClassImp(TRint) //______________________________________________________________________________ TRint::TRint(const char *appClassName, int *argc, char **argv, void *options, int numOptions, Bool_t noLogo) : TApplication(appClassName, argc, argv, options, numOptions) { // Create an application environment. The TRint environment provides an // interface to the WM manager functionality and eventloop via inheritance // of TApplication and in addition provides interactive access to // the CINT C++ interpreter via the command line. fNcmd = 0; fDefaultPrompt = "root [%d] "; fInterrupt = kFALSE; gBenchmark = new TBenchmark(); if (!noLogo) PrintLogo(); // Everybody expects iostream to be available, so load it... #ifndef WIN32 ProcessLine("#include <iostream>"); #endif // The following libs are also useful to have, // make sure they are loaded... gROOT->LoadClass("TGeometry", "Graf3d"); gROOT->LoadClass("TTree", "Tree"); gROOT->LoadClass("TMatrix", "Matrix"); gROOT->LoadClass("TMinuit", "Minuit"); gROOT->LoadClass("TPostScript", "Postscript"); gROOT->LoadClass("TCanvas", "Gpad"); gROOT->LoadClass("THtml", "Html"); // Load user functions const char *logon; logon = gEnv->GetValue("Rint.Load", (char*)0); if (logon) { char *mac = gSystem->Which(TROOT::GetMacroPath(), logon, kReadPermission); if (mac) ProcessLine(Form(".L %s",logon)); delete [] mac; } // Execute logon macro logon = gEnv->GetValue("Rint.Logon", (char*)0); if (logon && !NoLogOpt()) { char *mac = gSystem->Which(TROOT::GetMacroPath(), logon, kReadPermission); if (mac) ProcessFile(logon); delete [] mac; } gInterpreter->SaveContext(); gInterpreter->SaveGlobalsContext(); // Install interrupt and terminal input handlers TInterruptHandler *ih = new TInterruptHandler(); gSystem->AddSignalHandler(ih); SetSignalHandler(ih); TTermInputHandler *th = new TTermInputHandler(0); gSystem->AddFileHandler(th); // Goto into raw terminal input mode char defhist[128]; #ifndef R__VMS sprintf(defhist, "%s/.root_hist", gSystem->Getenv("HOME")); #else sprintf(defhist, "%s.root_hist", gSystem->Getenv("HOME")); #endif logon = gEnv->GetValue("Rint.History", defhist); Gl_histinit((char *)logon); Gl_windowchanged(); // Setup for tab completion gTabCom = new TTabCom; } //______________________________________________________________________________ TRint::~TRint() { } //______________________________________________________________________________ void TRint::Run(Bool_t retrn) { // Main application eventloop. First process files given on the command // line and then go into the main application event loop. Getlinem(kInit, GetPrompt()); // Process shell command line input files if (InputFiles()) { TObjString *file; TIter next(InputFiles()); RETRY { while ((file = (TObjString *)next())) { char cmd[256]; if (file->String().EndsWith(".root")) { const char *rfile = (const char*)file->String(); Printf("\nAttaching file %s...", rfile); char *base = StrDup(gSystem->BaseName(rfile)); char *s = strchr(base, '.'); *s = 0; sprintf(cmd, "TFile *%s = TFile::Open(\"%s\")", base, rfile); delete [] base; } else { Printf("\nProcessing %s...", (const char*)file->String()); sprintf(cmd, ".x %s", (const char*)file->String()); } Getlinem(kCleanUp, 0); Gl_histadd(cmd); fNcmd++; ProcessLine(cmd); } } ENDTRY; if (QuitOpt()) Terminate(0); ClearInputFiles(); Getlinem(kInit, GetPrompt()); } TApplication::Run(retrn); Getlinem(kCleanUp, 0); } //______________________________________________________________________________ void TRint::PrintLogo() { // Print the ROOT logo on standard output. Int_t iday,imonth,iyear; static const char *months[] = {"January","February","March","April","May", "June","July","August","September","October", "November","December"}; const char *root_version = gROOT->GetVersion(); Int_t idatqq = gROOT->GetVersionDate(); iday = idatqq%100; imonth = (idatqq/100)%100; iyear = (idatqq/10000); char *root_date = Form("%d %s %4d",iday,months[imonth-1],iyear); Printf(" *******************************************"); Printf(" * *"); Printf(" * W E L C O M E to R O O T *"); Printf(" * *"); Printf(" * Version%10s %17s *",root_version,root_date); // Printf(" * Development version *"); Printf(" * *"); Printf(" * You are welcome to visit our Web site *"); Printf(" * http://root.cern.ch *"); Printf(" * *"); Printf(" *******************************************"); #ifdef R__UNIX if (!strcmp(gVirtualX->GetName(), "X11TTF")) Printf("\nFreeType Engine v1.x used to render TrueType fonts."); #endif #ifdef _REENTRANT #ifdef R__UNIX else #endif printf("\n"); Printf("Compiled with thread support."); #endif gInterpreter->PrintIntro(); #ifdef R__UNIX // Popdown X logo, only if started with -splash option for (int i = 0; i < Argc(); i++) if (!strcmp(Argv(i), "-splash")) kill(getppid(), SIGUSR1); #endif } //______________________________________________________________________________ char *TRint::GetPrompt() { // Get prompt from interpreter. Either "root [n]" or "end with '}'". char *s = gInterpreter->GetPrompt(); if (s[0]) strcpy(fPrompt, s); else sprintf(fPrompt, fDefaultPrompt.Data(), fNcmd); return fPrompt; } //______________________________________________________________________________ const char *TRint::SetPrompt(const char *newPrompt) { // Set a new default prompt. It returns the previous prompt. // The prompt may contain a %d which will be replaced by the commend // number. The default prompt is "root [%d] ". The maximum length of // the prompt is 55 characters. To set the prompt in an interactive // session do: // root [0] ((TRint*)gROOT->GetApplication())->SetPrompt("aap> ") // aap> static TString op = fDefaultPrompt; if (newPrompt && strlen(newPrompt) <= 55) fDefaultPrompt = newPrompt; else Error("SetPrompt", "newPrompt too long (> 55 characters)"); return op.Data(); } //______________________________________________________________________________ void TRint::HandleTermInput() { // Handle input coming from terminal. static TStopwatch timer; char *line; if ((line = Getlinem(kOneChar, 0))) { if (line[0] == 0 && Gl_eof()) Terminate(0); if (gROOT->Timer()) timer.Start(); Gl_histadd(line); char *s = line; while (s && *s == ' ') s++; // strip-off leading blanks s[strlen(s)-1] = '\0'; // strip also '\n' off fInterrupt = kFALSE; if (!gInterpreter->GetMore() && strlen(s) != 0) fNcmd++; ProcessLine(s); if (strstr(s,".reset") != s) gInterpreter->EndOfLineAction(); if (gROOT->Timer()) timer.Print(); gTabCom->ClearAll(); Getlinem(kInit, GetPrompt()); } } //______________________________________________________________________________ void TRint::Terminate(int status) { // Terminate the application. Reset the terminal to sane mode and call // the logoff macro defined via Rint.Logoff environment variable. Getlinem(kCleanUp, 0); if (ReturnFromRun()) { gSystem->ExitLoop(); } else { //Execute logoff macro const char *logoff; logoff = gEnv->GetValue("Rint.Logoff", (char*)0); if (logoff && !NoLogOpt()) { char *mac = gSystem->Which(TROOT::GetMacroPath(), logoff, kReadPermission); if (mac) ProcessFile(logoff); delete [] mac; } gSystem->Exit(status); } } <commit_msg>move PROOF interrupt handler to TProof.cxx in its own handler instead of handling it via the global TRint interrupt handler.<commit_after>// @(#)root/rint:$Name: $:$Id: TRint.cxx,v 1.4 2001/02/22 13:32:00 rdm Exp $ // Author: Rene Brun 17/02/95 /************************************************************************* * Copyright (C) 1995-2000, Rene Brun and Fons Rademakers. * * All rights reserved. * * * * For the licensing terms see $ROOTSYS/LICENSE. * * For the list of contributors see $ROOTSYS/README/CREDITS. * *************************************************************************/ ////////////////////////////////////////////////////////////////////////// // // // Rint // // // // Rint is the ROOT Interactive Interface. It allows interactive access // // to the ROOT system via the CINT C/C++ interpreter. // // // ////////////////////////////////////////////////////////////////////////// #include "TROOT.h" #include "TClass.h" #include "TVirtualX.h" #include "Getline.h" #include "TStyle.h" #include "TObjectTable.h" #include "TClassTable.h" #include "TStopwatch.h" #include "TCanvas.h" #include "TBenchmark.h" #include "TRint.h" #include "TSystem.h" #include "TEnv.h" #include "TSysEvtHandler.h" #include "TError.h" #include "TException.h" #include "TInterpreter.h" #include "TObjArray.h" #include "TObjString.h" #include "TFile.h" #include "TMapFile.h" #include "TTabCom.h" #ifdef R__UNIX #include <signal.h> extern "C" { extern int G__get_security_error(); extern int G__genericerror(char* msg); } #endif //----- Interrupt signal handler ----------------------------------------------- //______________________________________________________________________________ class TInterruptHandler : public TSignalHandler { public: TInterruptHandler() : TSignalHandler(kSigInterrupt, kFALSE) { } Bool_t Notify(); }; //______________________________________________________________________________ Bool_t TInterruptHandler::Notify() { // TRint interrupt handler. if (fDelay) { fDelay++; return kTRUE; } // make sure we use the sbrk heap (in case of mapped files) gMmallocDesc = 0; if (!G__get_security_error()) G__genericerror("\n *** Break *** keyboard interrupt"); else { Printf("\n *** Break *** keyboard interrupt"); if (TROOT::Initialized()) { Getlinem(kInit, "Root > "); gInterpreter->RewindDictionary(); Throw(GetSignal()); } } return kTRUE; } //----- Terminal Input file handler -------------------------------------------- //______________________________________________________________________________ class TTermInputHandler : public TFileHandler { public: TTermInputHandler(int fd) : TFileHandler(fd, 1) { } Bool_t Notify(); Bool_t ReadNotify() { return Notify(); } }; //______________________________________________________________________________ Bool_t TTermInputHandler::Notify() { gApplication->HandleTermInput(); return kTRUE; } ClassImp(TRint) //______________________________________________________________________________ TRint::TRint(const char *appClassName, int *argc, char **argv, void *options, int numOptions, Bool_t noLogo) : TApplication(appClassName, argc, argv, options, numOptions) { // Create an application environment. The TRint environment provides an // interface to the WM manager functionality and eventloop via inheritance // of TApplication and in addition provides interactive access to // the CINT C++ interpreter via the command line. fNcmd = 0; fDefaultPrompt = "root [%d] "; fInterrupt = kFALSE; gBenchmark = new TBenchmark(); if (!noLogo) PrintLogo(); // Everybody expects iostream to be available, so load it... #ifndef WIN32 ProcessLine("#include <iostream>"); #endif // The following libs are also useful to have, // make sure they are loaded... gROOT->LoadClass("TGeometry", "Graf3d"); gROOT->LoadClass("TTree", "Tree"); gROOT->LoadClass("TMatrix", "Matrix"); gROOT->LoadClass("TMinuit", "Minuit"); gROOT->LoadClass("TPostScript", "Postscript"); gROOT->LoadClass("TCanvas", "Gpad"); gROOT->LoadClass("THtml", "Html"); // Load user functions const char *logon; logon = gEnv->GetValue("Rint.Load", (char*)0); if (logon) { char *mac = gSystem->Which(TROOT::GetMacroPath(), logon, kReadPermission); if (mac) ProcessLine(Form(".L %s",logon)); delete [] mac; } // Execute logon macro logon = gEnv->GetValue("Rint.Logon", (char*)0); if (logon && !NoLogOpt()) { char *mac = gSystem->Which(TROOT::GetMacroPath(), logon, kReadPermission); if (mac) ProcessFile(logon); delete [] mac; } gInterpreter->SaveContext(); gInterpreter->SaveGlobalsContext(); // Install interrupt and terminal input handlers TInterruptHandler *ih = new TInterruptHandler(); ih->Add(); SetSignalHandler(ih); TTermInputHandler *th = new TTermInputHandler(0); th->Add(); // Goto into raw terminal input mode char defhist[128]; #ifndef R__VMS sprintf(defhist, "%s/.root_hist", gSystem->Getenv("HOME")); #else sprintf(defhist, "%s.root_hist", gSystem->Getenv("HOME")); #endif logon = gEnv->GetValue("Rint.History", defhist); Gl_histinit((char *)logon); Gl_windowchanged(); // Setup for tab completion gTabCom = new TTabCom; } //______________________________________________________________________________ TRint::~TRint() { } //______________________________________________________________________________ void TRint::Run(Bool_t retrn) { // Main application eventloop. First process files given on the command // line and then go into the main application event loop. Getlinem(kInit, GetPrompt()); // Process shell command line input files if (InputFiles()) { TObjString *file; TIter next(InputFiles()); RETRY { while ((file = (TObjString *)next())) { char cmd[256]; if (file->String().EndsWith(".root")) { const char *rfile = (const char*)file->String(); Printf("\nAttaching file %s...", rfile); char *base = StrDup(gSystem->BaseName(rfile)); char *s = strchr(base, '.'); *s = 0; sprintf(cmd, "TFile *%s = TFile::Open(\"%s\")", base, rfile); delete [] base; } else { Printf("\nProcessing %s...", (const char*)file->String()); sprintf(cmd, ".x %s", (const char*)file->String()); } Getlinem(kCleanUp, 0); Gl_histadd(cmd); fNcmd++; ProcessLine(cmd); } } ENDTRY; if (QuitOpt()) Terminate(0); ClearInputFiles(); Getlinem(kInit, GetPrompt()); } TApplication::Run(retrn); Getlinem(kCleanUp, 0); } //______________________________________________________________________________ void TRint::PrintLogo() { // Print the ROOT logo on standard output. Int_t iday,imonth,iyear; static const char *months[] = {"January","February","March","April","May", "June","July","August","September","October", "November","December"}; const char *root_version = gROOT->GetVersion(); Int_t idatqq = gROOT->GetVersionDate(); iday = idatqq%100; imonth = (idatqq/100)%100; iyear = (idatqq/10000); char *root_date = Form("%d %s %4d",iday,months[imonth-1],iyear); Printf(" *******************************************"); Printf(" * *"); Printf(" * W E L C O M E to R O O T *"); Printf(" * *"); Printf(" * Version%10s %17s *",root_version,root_date); // Printf(" * Development version *"); Printf(" * *"); Printf(" * You are welcome to visit our Web site *"); Printf(" * http://root.cern.ch *"); Printf(" * *"); Printf(" *******************************************"); #ifdef R__UNIX if (!strcmp(gVirtualX->GetName(), "X11TTF")) Printf("\nFreeType Engine v1.x used to render TrueType fonts."); #endif #ifdef _REENTRANT #ifdef R__UNIX else #endif printf("\n"); Printf("Compiled with thread support."); #endif gInterpreter->PrintIntro(); #ifdef R__UNIX // Popdown X logo, only if started with -splash option for (int i = 0; i < Argc(); i++) if (!strcmp(Argv(i), "-splash")) kill(getppid(), SIGUSR1); #endif } //______________________________________________________________________________ char *TRint::GetPrompt() { // Get prompt from interpreter. Either "root [n]" or "end with '}'". char *s = gInterpreter->GetPrompt(); if (s[0]) strcpy(fPrompt, s); else sprintf(fPrompt, fDefaultPrompt.Data(), fNcmd); return fPrompt; } //______________________________________________________________________________ const char *TRint::SetPrompt(const char *newPrompt) { // Set a new default prompt. It returns the previous prompt. // The prompt may contain a %d which will be replaced by the commend // number. The default prompt is "root [%d] ". The maximum length of // the prompt is 55 characters. To set the prompt in an interactive // session do: // root [0] ((TRint*)gROOT->GetApplication())->SetPrompt("aap> ") // aap> static TString op = fDefaultPrompt; if (newPrompt && strlen(newPrompt) <= 55) fDefaultPrompt = newPrompt; else Error("SetPrompt", "newPrompt too long (> 55 characters)"); return op.Data(); } //______________________________________________________________________________ void TRint::HandleTermInput() { // Handle input coming from terminal. static TStopwatch timer; char *line; if ((line = Getlinem(kOneChar, 0))) { if (line[0] == 0 && Gl_eof()) Terminate(0); if (gROOT->Timer()) timer.Start(); Gl_histadd(line); char *s = line; while (s && *s == ' ') s++; // strip-off leading blanks s[strlen(s)-1] = '\0'; // strip also '\n' off fInterrupt = kFALSE; if (!gInterpreter->GetMore() && strlen(s) != 0) fNcmd++; ProcessLine(s); if (strstr(s,".reset") != s) gInterpreter->EndOfLineAction(); if (gROOT->Timer()) timer.Print(); gTabCom->ClearAll(); Getlinem(kInit, GetPrompt()); } } //______________________________________________________________________________ void TRint::Terminate(int status) { // Terminate the application. Reset the terminal to sane mode and call // the logoff macro defined via Rint.Logoff environment variable. Getlinem(kCleanUp, 0); if (ReturnFromRun()) { gSystem->ExitLoop(); } else { //Execute logoff macro const char *logoff; logoff = gEnv->GetValue("Rint.Logoff", (char*)0); if (logoff && !NoLogOpt()) { char *mac = gSystem->Which(TROOT::GetMacroPath(), logoff, kReadPermission); if (mac) ProcessFile(logoff); delete [] mac; } gSystem->Exit(status); } } <|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/debugger/devtools_http_protocol_handler.h" #include "base/compiler_specific.h" #include "base/logging.h" #include "base/message_loop_proxy.h" #include "base/string_util.h" #include "base/thread.h" #include "chrome/browser/browser.h" #include "chrome/browser/browser_list.h" #include "chrome/browser/chrome_thread.h" #include "chrome/browser/debugger/devtools_client_host.h" #include "chrome/browser/debugger/devtools_manager.h" #include "chrome/browser/profile.h" #include "chrome/browser/tab_contents/tab_contents.h" #include "chrome/common/devtools_messages.h" #include "chrome/common/net/url_request_context_getter.h" #include "googleurl/src/gurl.h" #include "net/base/io_buffer.h" #include "net/base/listen_socket.h" #include "net/server/http_server_request_info.h" #include "net/url_request/url_request_context.h" const int kBufferSize = 16 * 1024; namespace { // An internal implementation of DevToolsClientHost that delegates // messages sent for DevToolsClient to a DebuggerShell instance. class DevToolsClientHostImpl : public DevToolsClientHost { public: explicit DevToolsClientHostImpl(HttpListenSocket* socket) : socket_(socket) {} ~DevToolsClientHostImpl() {} // DevToolsClientHost interface virtual void InspectedTabClosing() { ChromeThread::PostTask( ChromeThread::IO, FROM_HERE, NewRunnableMethod(socket_, &HttpListenSocket::Close)); } virtual void SendMessageToClient(const IPC::Message& msg) { IPC_BEGIN_MESSAGE_MAP(DevToolsClientHostImpl, msg) IPC_MESSAGE_HANDLER(DevToolsClientMsg_RpcMessage, OnRpcMessage); IPC_MESSAGE_UNHANDLED_ERROR() IPC_END_MESSAGE_MAP() } void NotifyCloseListener() { DevToolsClientHost::NotifyCloseListener(); } private: // Message handling routines void OnRpcMessage(const DevToolsMessageData& data) { std::string message; message += "devtools$$dispatch(\"" + data.class_name + "\", \"" + data.method_name + "\""; for (std::vector<std::string>::const_iterator it = data.arguments.begin(); it != data.arguments.end(); ++it) { std::string param = *it; if (!param.empty()) message += ", " + param; } message += ")"; socket_->SendOverWebSocket(message); } HttpListenSocket* socket_; }; } DevToolsHttpProtocolHandler::~DevToolsHttpProtocolHandler() { // Stop() must be called prior to this being called DCHECK(server_.get() == NULL); } void DevToolsHttpProtocolHandler::Start() { ChromeThread::PostTask( ChromeThread::IO, FROM_HERE, NewRunnableMethod(this, &DevToolsHttpProtocolHandler::Init)); } void DevToolsHttpProtocolHandler::Stop() { ChromeThread::PostTask( ChromeThread::IO, FROM_HERE, NewRunnableMethod(this, &DevToolsHttpProtocolHandler::Teardown)); } void DevToolsHttpProtocolHandler::OnHttpRequest( HttpListenSocket* socket, const HttpServerRequestInfo& info) { if (info.path == "" || info.path == "/") { // Pages discovery request. ChromeThread::PostTask( ChromeThread::UI, FROM_HERE, NewRunnableMethod(this, &DevToolsHttpProtocolHandler::OnHttpRequestUI, socket, info)); return; } size_t pos = info.path.find("/devtools/"); if (pos != 0) { socket->Send404(); return; } // Proxy static files from chrome://devtools/*. URLRequest* request = new URLRequest(GURL("chrome:/" + info.path), this); Bind(request, socket); request->set_context( Profile::GetDefaultRequestContext()->GetURLRequestContext()); request->Start(); } void DevToolsHttpProtocolHandler::OnWebSocketRequest( HttpListenSocket* socket, const HttpServerRequestInfo& request) { ChromeThread::PostTask( ChromeThread::UI, FROM_HERE, NewRunnableMethod( this, &DevToolsHttpProtocolHandler::OnWebSocketRequestUI, socket, request)); } void DevToolsHttpProtocolHandler::OnWebSocketMessage(HttpListenSocket* socket, const std::string& data) { ChromeThread::PostTask( ChromeThread::UI, FROM_HERE, NewRunnableMethod( this, &DevToolsHttpProtocolHandler::OnWebSocketMessageUI, socket, data)); } void DevToolsHttpProtocolHandler::OnClose(HttpListenSocket* socket) { SocketToRequestsMap::iterator it = socket_to_requests_io_.find(socket); if (it != socket_to_requests_io_.end()) { // Dispose delegating socket. for (std::set<URLRequest*>::iterator it2 = it->second.begin(); it2 != it->second.end(); ++it2) { URLRequest* request = *it2; request->Cancel(); request_to_socket_io_.erase(request); request_to_buffer_io_.erase(request); delete request; } socket_to_requests_io_.erase(socket); } ChromeThread::PostTask( ChromeThread::UI, FROM_HERE, NewRunnableMethod( this, &DevToolsHttpProtocolHandler::OnCloseUI, socket)); } void DevToolsHttpProtocolHandler::OnHttpRequestUI( HttpListenSocket* socket, const HttpServerRequestInfo& info) { std::string response = "<html><body>"; for (BrowserList::const_iterator it = BrowserList::begin(), end = BrowserList::end(); it != end; ++it) { TabStripModel* model = (*it)->tabstrip_model(); for (int i = 0, size = model->count(); i < size; ++i) { TabContents* tab_contents = model->GetTabContentsAt(i); NavigationController& controller = tab_contents->controller(); NavigationEntry* entry = controller.GetActiveEntry(); if (entry == NULL) continue; if (!entry->url().is_valid()) continue; DevToolsClientHost* client_host = DevToolsManager::GetInstance()-> GetDevToolsClientHostFor(tab_contents->render_view_host()); if (!client_host) { response += StringPrintf( "<a href='/devtools/devtools.html?page=%d'>%s (%s)</a><br>", controller.session_id().id(), UTF16ToUTF8(entry->title()).c_str(), entry->url().spec().c_str()); } else { response += StringPrintf( "%s (%s)<br>", UTF16ToUTF8(entry->title()).c_str(), entry->url().spec().c_str()); } } } response += "</body></html>"; Send200(socket, response, "text/html"); } void DevToolsHttpProtocolHandler::OnWebSocketRequestUI( HttpListenSocket* socket, const HttpServerRequestInfo& request) { std::string prefix = "/devtools/page/"; size_t pos = request.path.find(prefix); if (pos != 0) { Send404(socket); return; } std::string page_id = request.path.substr(prefix.length()); int id = 0; if (!StringToInt(page_id, &id)) { Send500(socket, "Invalid page id: " + page_id); return; } TabContents* tab_contents = GetTabContents(id); if (tab_contents == NULL) { Send500(socket, "No such page id: " + page_id); return; } DevToolsManager* manager = DevToolsManager::GetInstance(); if (manager->GetDevToolsClientHostFor(tab_contents->render_view_host())) { Send500(socket, "Page with given id is being inspected: " + page_id); return; } DevToolsClientHostImpl* client_host = new DevToolsClientHostImpl(socket); socket_to_client_host_ui_[socket] = client_host; manager->RegisterDevToolsClientHostFor( tab_contents->render_view_host(), client_host); AcceptWebSocket(socket, request); } void DevToolsHttpProtocolHandler::OnWebSocketMessageUI( HttpListenSocket* socket, const std::string& d) { SocketToClientHostMap::iterator it = socket_to_client_host_ui_.find(socket); if (it == socket_to_client_host_ui_.end()) return; std::string data = d; // TODO(pfeldman): Replace with proper parsing / dispatching. DevToolsMessageData message_data; message_data.class_name = "ToolsAgent"; message_data.method_name = "dispatchOnInspectorController"; size_t pos = data.find(" "); message_data.arguments.push_back(data.substr(0, pos)); data = data.substr(pos + 1); message_data.arguments.push_back(data); DevToolsManager* manager = DevToolsManager::GetInstance(); manager->ForwardToDevToolsAgent(it->second, DevToolsAgentMsg_RpcMessage(DevToolsMessageData(message_data))); } void DevToolsHttpProtocolHandler::OnCloseUI(HttpListenSocket* socket) { SocketToClientHostMap::iterator it = socket_to_client_host_ui_.find(socket); if (it == socket_to_client_host_ui_.end()) return; DevToolsClientHostImpl* client_host = static_cast<DevToolsClientHostImpl*>(it->second); client_host->NotifyCloseListener(); delete client_host; socket_to_client_host_ui_.erase(socket); } void DevToolsHttpProtocolHandler::OnResponseStarted(URLRequest* request) { RequestToSocketMap::iterator it = request_to_socket_io_.find(request); if (it == request_to_socket_io_.end()) return; HttpListenSocket* socket = it->second; int expected_size = static_cast<int>(request->GetExpectedContentSize()); std::string content_type; request->GetMimeType(&content_type); if (request->status().is_success()) { socket->Send(StringPrintf("HTTP/1.1 200 OK\r\n" "Content-Type:%s\r\n" "Content-Length:%d\r\n" "\r\n", content_type.c_str(), expected_size)); } else { socket->Send404(); } int bytes_read = 0; // Some servers may treat HEAD requests as GET requests. To free up the // network connection as soon as possible, signal that the request has // completed immediately, without trying to read any data back (all we care // about is the response code and headers, which we already have). net::IOBuffer* buffer = request_to_buffer_io_[request].get(); if (request->status().is_success()) request->Read(buffer, kBufferSize, &bytes_read); OnReadCompleted(request, bytes_read); } void DevToolsHttpProtocolHandler::OnReadCompleted(URLRequest* request, int bytes_read) { RequestToSocketMap::iterator it = request_to_socket_io_.find(request); if (it == request_to_socket_io_.end()) return; HttpListenSocket* socket = it->second; net::IOBuffer* buffer = request_to_buffer_io_[request].get(); do { if (!request->status().is_success() || bytes_read <= 0) break; socket->Send(buffer->data(), bytes_read); } while (request->Read(buffer, kBufferSize, &bytes_read)); // See comments re: HEAD requests in OnResponseStarted(). if (!request->status().is_io_pending()) RequestCompleted(request); } DevToolsHttpProtocolHandler::DevToolsHttpProtocolHandler(int port) : port_(port), server_(NULL) { } void DevToolsHttpProtocolHandler::Init() { server_ = HttpListenSocket::Listen("127.0.0.1", port_, this); } // Run on I/O thread void DevToolsHttpProtocolHandler::Teardown() { server_ = NULL; } void DevToolsHttpProtocolHandler::Bind(URLRequest* request, HttpListenSocket* socket) { request_to_socket_io_[request] = socket; SocketToRequestsMap::iterator it = socket_to_requests_io_.find(socket); if (it == socket_to_requests_io_.end()) { std::pair<HttpListenSocket*, std::set<URLRequest*> > value( socket, std::set<URLRequest*>()); it = socket_to_requests_io_.insert(value).first; } it->second.insert(request); request_to_buffer_io_[request] = new net::IOBuffer(kBufferSize); } void DevToolsHttpProtocolHandler::RequestCompleted(URLRequest* request) { RequestToSocketMap::iterator it = request_to_socket_io_.find(request); if (it == request_to_socket_io_.end()) return; HttpListenSocket* socket = it->second; request_to_socket_io_.erase(request); SocketToRequestsMap::iterator it2 = socket_to_requests_io_.find(socket); it2->second.erase(request); request_to_buffer_io_.erase(request); delete request; } void DevToolsHttpProtocolHandler::Send200(HttpListenSocket* socket, const std::string& data, const std::string& mime_type) { ChromeThread::PostTask( ChromeThread::IO, FROM_HERE, NewRunnableMethod(socket, &HttpListenSocket::Send200, data, mime_type)); } void DevToolsHttpProtocolHandler::Send404(HttpListenSocket* socket) { ChromeThread::PostTask( ChromeThread::IO, FROM_HERE, NewRunnableMethod(socket, &HttpListenSocket::Send404)); } void DevToolsHttpProtocolHandler::Send500(HttpListenSocket* socket, const std::string& message) { ChromeThread::PostTask( ChromeThread::IO, FROM_HERE, NewRunnableMethod(socket, &HttpListenSocket::Send500, message)); } void DevToolsHttpProtocolHandler::AcceptWebSocket( HttpListenSocket* socket, const HttpServerRequestInfo& request) { ChromeThread::PostTask( ChromeThread::IO, FROM_HERE, NewRunnableMethod(socket, &HttpListenSocket::AcceptWebSocket, request)); } TabContents* DevToolsHttpProtocolHandler::GetTabContents(int session_id) { for (BrowserList::const_iterator it = BrowserList::begin(), end = BrowserList::end(); it != end; ++it) { TabStripModel* model = (*it)->tabstrip_model(); for (int i = 0, size = model->count(); i < size; ++i) { NavigationController& controller = model->GetTabContentsAt(i)->controller(); if (controller.session_id().id() == session_id) return controller.tab_contents(); } } return NULL; } <commit_msg>DevTools: restore remote rebugging after upstream breakage.<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/debugger/devtools_http_protocol_handler.h" #include "base/compiler_specific.h" #include "base/logging.h" #include "base/message_loop_proxy.h" #include "base/string_util.h" #include "base/thread.h" #include "chrome/browser/browser.h" #include "chrome/browser/browser_list.h" #include "chrome/browser/chrome_thread.h" #include "chrome/browser/debugger/devtools_client_host.h" #include "chrome/browser/debugger/devtools_manager.h" #include "chrome/browser/profile.h" #include "chrome/browser/tab_contents/tab_contents.h" #include "chrome/common/devtools_messages.h" #include "chrome/common/net/url_request_context_getter.h" #include "googleurl/src/gurl.h" #include "net/base/io_buffer.h" #include "net/base/listen_socket.h" #include "net/server/http_server_request_info.h" #include "net/url_request/url_request_context.h" const int kBufferSize = 16 * 1024; namespace { // An internal implementation of DevToolsClientHost that delegates // messages sent for DevToolsClient to a DebuggerShell instance. class DevToolsClientHostImpl : public DevToolsClientHost { public: explicit DevToolsClientHostImpl(HttpListenSocket* socket) : socket_(socket) {} ~DevToolsClientHostImpl() {} // DevToolsClientHost interface virtual void InspectedTabClosing() { ChromeThread::PostTask( ChromeThread::IO, FROM_HERE, NewRunnableMethod(socket_, &HttpListenSocket::Close)); } virtual void SendMessageToClient(const IPC::Message& msg) { IPC_BEGIN_MESSAGE_MAP(DevToolsClientHostImpl, msg) IPC_MESSAGE_HANDLER(DevToolsClientMsg_RpcMessage, OnRpcMessage); IPC_MESSAGE_UNHANDLED_ERROR() IPC_END_MESSAGE_MAP() } void NotifyCloseListener() { DevToolsClientHost::NotifyCloseListener(); } private: // Message handling routines void OnRpcMessage(const DevToolsMessageData& data) { std::string message; message += "devtools$$dispatch(\"" + data.class_name + "\", \"" + data.method_name + "\""; for (std::vector<std::string>::const_iterator it = data.arguments.begin(); it != data.arguments.end(); ++it) { std::string param = *it; if (!param.empty()) message += ", " + param; } message += ")"; socket_->SendOverWebSocket(message); } HttpListenSocket* socket_; }; } DevToolsHttpProtocolHandler::~DevToolsHttpProtocolHandler() { // Stop() must be called prior to this being called DCHECK(server_.get() == NULL); } void DevToolsHttpProtocolHandler::Start() { ChromeThread::PostTask( ChromeThread::IO, FROM_HERE, NewRunnableMethod(this, &DevToolsHttpProtocolHandler::Init)); } void DevToolsHttpProtocolHandler::Stop() { ChromeThread::PostTask( ChromeThread::IO, FROM_HERE, NewRunnableMethod(this, &DevToolsHttpProtocolHandler::Teardown)); } void DevToolsHttpProtocolHandler::OnHttpRequest( HttpListenSocket* socket, const HttpServerRequestInfo& info) { if (info.path == "" || info.path == "/") { // Pages discovery request. ChromeThread::PostTask( ChromeThread::UI, FROM_HERE, NewRunnableMethod(this, &DevToolsHttpProtocolHandler::OnHttpRequestUI, socket, info)); return; } size_t pos = info.path.find("/devtools/"); if (pos != 0) { socket->Send404(); return; } // Proxy static files from chrome://devtools/*. URLRequest* request = new URLRequest(GURL("chrome:/" + info.path), this); Bind(request, socket); request->set_context( Profile::GetDefaultRequestContext()->GetURLRequestContext()); request->Start(); } void DevToolsHttpProtocolHandler::OnWebSocketRequest( HttpListenSocket* socket, const HttpServerRequestInfo& request) { ChromeThread::PostTask( ChromeThread::UI, FROM_HERE, NewRunnableMethod( this, &DevToolsHttpProtocolHandler::OnWebSocketRequestUI, socket, request)); } void DevToolsHttpProtocolHandler::OnWebSocketMessage(HttpListenSocket* socket, const std::string& data) { ChromeThread::PostTask( ChromeThread::UI, FROM_HERE, NewRunnableMethod( this, &DevToolsHttpProtocolHandler::OnWebSocketMessageUI, socket, data)); } void DevToolsHttpProtocolHandler::OnClose(HttpListenSocket* socket) { SocketToRequestsMap::iterator it = socket_to_requests_io_.find(socket); if (it != socket_to_requests_io_.end()) { // Dispose delegating socket. for (std::set<URLRequest*>::iterator it2 = it->second.begin(); it2 != it->second.end(); ++it2) { URLRequest* request = *it2; request->Cancel(); request_to_socket_io_.erase(request); request_to_buffer_io_.erase(request); delete request; } socket_to_requests_io_.erase(socket); } ChromeThread::PostTask( ChromeThread::UI, FROM_HERE, NewRunnableMethod( this, &DevToolsHttpProtocolHandler::OnCloseUI, socket)); } void DevToolsHttpProtocolHandler::OnHttpRequestUI( HttpListenSocket* socket, const HttpServerRequestInfo& info) { std::string response = "<html><body>"; for (BrowserList::const_iterator it = BrowserList::begin(), end = BrowserList::end(); it != end; ++it) { TabStripModel* model = (*it)->tabstrip_model(); for (int i = 0, size = model->count(); i < size; ++i) { TabContents* tab_contents = model->GetTabContentsAt(i); NavigationController& controller = tab_contents->controller(); NavigationEntry* entry = controller.GetActiveEntry(); if (entry == NULL) continue; if (!entry->url().is_valid()) continue; DevToolsClientHost* client_host = DevToolsManager::GetInstance()-> GetDevToolsClientHostFor(tab_contents->render_view_host()); if (!client_host) { response += StringPrintf( "<a href='/devtools/devtools.html?page=%d'>%s (%s)</a><br>", controller.session_id().id(), UTF16ToUTF8(entry->title()).c_str(), entry->url().spec().c_str()); } else { response += StringPrintf( "%s (%s)<br>", UTF16ToUTF8(entry->title()).c_str(), entry->url().spec().c_str()); } } } response += "</body></html>"; Send200(socket, response, "text/html"); } void DevToolsHttpProtocolHandler::OnWebSocketRequestUI( HttpListenSocket* socket, const HttpServerRequestInfo& request) { std::string prefix = "/devtools/page/"; size_t pos = request.path.find(prefix); if (pos != 0) { Send404(socket); return; } std::string page_id = request.path.substr(prefix.length()); int id = 0; if (!StringToInt(page_id, &id)) { Send500(socket, "Invalid page id: " + page_id); return; } TabContents* tab_contents = GetTabContents(id); if (tab_contents == NULL) { Send500(socket, "No such page id: " + page_id); return; } DevToolsManager* manager = DevToolsManager::GetInstance(); if (manager->GetDevToolsClientHostFor(tab_contents->render_view_host())) { Send500(socket, "Page with given id is being inspected: " + page_id); return; } DevToolsClientHostImpl* client_host = new DevToolsClientHostImpl(socket); socket_to_client_host_ui_[socket] = client_host; manager->RegisterDevToolsClientHostFor( tab_contents->render_view_host(), client_host); AcceptWebSocket(socket, request); } void DevToolsHttpProtocolHandler::OnWebSocketMessageUI( HttpListenSocket* socket, const std::string& data) { SocketToClientHostMap::iterator it = socket_to_client_host_ui_.find(socket); if (it == socket_to_client_host_ui_.end()) return; // TODO(pfeldman): Replace with proper parsing / dispatching. DevToolsMessageData message_data; message_data.class_name = "ToolsAgent"; message_data.method_name = "dispatchOnInspectorController"; message_data.arguments.push_back(data); DevToolsManager* manager = DevToolsManager::GetInstance(); manager->ForwardToDevToolsAgent(it->second, DevToolsAgentMsg_RpcMessage(DevToolsMessageData(message_data))); } void DevToolsHttpProtocolHandler::OnCloseUI(HttpListenSocket* socket) { SocketToClientHostMap::iterator it = socket_to_client_host_ui_.find(socket); if (it == socket_to_client_host_ui_.end()) return; DevToolsClientHostImpl* client_host = static_cast<DevToolsClientHostImpl*>(it->second); client_host->NotifyCloseListener(); delete client_host; socket_to_client_host_ui_.erase(socket); } void DevToolsHttpProtocolHandler::OnResponseStarted(URLRequest* request) { RequestToSocketMap::iterator it = request_to_socket_io_.find(request); if (it == request_to_socket_io_.end()) return; HttpListenSocket* socket = it->second; int expected_size = static_cast<int>(request->GetExpectedContentSize()); std::string content_type; request->GetMimeType(&content_type); if (request->status().is_success()) { socket->Send(StringPrintf("HTTP/1.1 200 OK\r\n" "Content-Type:%s\r\n" "Content-Length:%d\r\n" "\r\n", content_type.c_str(), expected_size)); } else { socket->Send404(); } int bytes_read = 0; // Some servers may treat HEAD requests as GET requests. To free up the // network connection as soon as possible, signal that the request has // completed immediately, without trying to read any data back (all we care // about is the response code and headers, which we already have). net::IOBuffer* buffer = request_to_buffer_io_[request].get(); if (request->status().is_success()) request->Read(buffer, kBufferSize, &bytes_read); OnReadCompleted(request, bytes_read); } void DevToolsHttpProtocolHandler::OnReadCompleted(URLRequest* request, int bytes_read) { RequestToSocketMap::iterator it = request_to_socket_io_.find(request); if (it == request_to_socket_io_.end()) return; HttpListenSocket* socket = it->second; net::IOBuffer* buffer = request_to_buffer_io_[request].get(); do { if (!request->status().is_success() || bytes_read <= 0) break; socket->Send(buffer->data(), bytes_read); } while (request->Read(buffer, kBufferSize, &bytes_read)); // See comments re: HEAD requests in OnResponseStarted(). if (!request->status().is_io_pending()) RequestCompleted(request); } DevToolsHttpProtocolHandler::DevToolsHttpProtocolHandler(int port) : port_(port), server_(NULL) { } void DevToolsHttpProtocolHandler::Init() { server_ = HttpListenSocket::Listen("127.0.0.1", port_, this); } // Run on I/O thread void DevToolsHttpProtocolHandler::Teardown() { server_ = NULL; } void DevToolsHttpProtocolHandler::Bind(URLRequest* request, HttpListenSocket* socket) { request_to_socket_io_[request] = socket; SocketToRequestsMap::iterator it = socket_to_requests_io_.find(socket); if (it == socket_to_requests_io_.end()) { std::pair<HttpListenSocket*, std::set<URLRequest*> > value( socket, std::set<URLRequest*>()); it = socket_to_requests_io_.insert(value).first; } it->second.insert(request); request_to_buffer_io_[request] = new net::IOBuffer(kBufferSize); } void DevToolsHttpProtocolHandler::RequestCompleted(URLRequest* request) { RequestToSocketMap::iterator it = request_to_socket_io_.find(request); if (it == request_to_socket_io_.end()) return; HttpListenSocket* socket = it->second; request_to_socket_io_.erase(request); SocketToRequestsMap::iterator it2 = socket_to_requests_io_.find(socket); it2->second.erase(request); request_to_buffer_io_.erase(request); delete request; } void DevToolsHttpProtocolHandler::Send200(HttpListenSocket* socket, const std::string& data, const std::string& mime_type) { ChromeThread::PostTask( ChromeThread::IO, FROM_HERE, NewRunnableMethod(socket, &HttpListenSocket::Send200, data, mime_type)); } void DevToolsHttpProtocolHandler::Send404(HttpListenSocket* socket) { ChromeThread::PostTask( ChromeThread::IO, FROM_HERE, NewRunnableMethod(socket, &HttpListenSocket::Send404)); } void DevToolsHttpProtocolHandler::Send500(HttpListenSocket* socket, const std::string& message) { ChromeThread::PostTask( ChromeThread::IO, FROM_HERE, NewRunnableMethod(socket, &HttpListenSocket::Send500, message)); } void DevToolsHttpProtocolHandler::AcceptWebSocket( HttpListenSocket* socket, const HttpServerRequestInfo& request) { ChromeThread::PostTask( ChromeThread::IO, FROM_HERE, NewRunnableMethod(socket, &HttpListenSocket::AcceptWebSocket, request)); } TabContents* DevToolsHttpProtocolHandler::GetTabContents(int session_id) { for (BrowserList::const_iterator it = BrowserList::begin(), end = BrowserList::end(); it != end; ++it) { TabStripModel* model = (*it)->tabstrip_model(); for (int i = 0, size = model->count(); i < size; ++i) { NavigationController& controller = model->GetTabContentsAt(i)->controller(); if (controller.session_id().id() == session_id) return controller.tab_contents(); } } return NULL; } <|endoftext|>
<commit_before>#include <iostream> #include "itkMeshTovtkPolyData.h" #ifndef vtkDoubleType #define vtkDoubleType double #endif #ifndef vtkFloatingPointType #define vtkFloatingPointType vtkFloatingPointType typedef float vtkFloatingPointType; #endif itkMeshTovtkPolyData ::itkMeshTovtkPolyData() { m_itkTriangleMesh = TriangleMeshType::New(); m_Points = vtkSmartPointer<vtkPoints>::New(); m_PolyData = vtkSmartPointer<vtkPolyData>::New(); m_Polys = vtkSmartPointer<vtkCellArray>::New(); } itkMeshTovtkPolyData ::~itkMeshTovtkPolyData() { } void itkMeshTovtkPolyData ::SetInput(TriangleMeshType::Pointer mesh) { m_itkTriangleMesh = mesh; this->ConvertitkTovtk(); } vtkSmartPointer<vtkPolyData> itkMeshTovtkPolyData::GetOutput() { return m_PolyData; } void itkMeshTovtkPolyData ::ConvertitkTovtk() { int numPoints = m_itkTriangleMesh->GetNumberOfPoints(); InputPointsContainerPointer myPoints = m_itkTriangleMesh->GetPoints(); InputPointsContainerIterator points = myPoints->Begin(); PointType point; if( numPoints == 0 ) { printf( "Aborting: No Points in GRID\n"); return; } m_Points->SetNumberOfPoints(numPoints); int idx = 0; double vpoint[3]; while( points != myPoints->End() ) { point = points.Value(); vpoint[0] = point[0]; vpoint[1] = point[1]; vpoint[2] = point[2]; m_Points->SetPoint(idx++, vpoint); points++; } m_PolyData->SetPoints(m_Points); CellsContainerPointer cells = m_itkTriangleMesh->GetCells(); CellsContainerIterator cellIt = cells->Begin(); vtkIdType pts[3]; while( cellIt != cells->End() ) { CellType * nextCell = cellIt->Value(); CellType::PointIdIterator pointIt = nextCell->PointIdsBegin(); PointType p; int i; switch( nextCell->GetType() ) { case CellType::VERTEX_CELL: case CellType::LINE_CELL: case CellType::POLYGON_CELL: break; case CellType::TRIANGLE_CELL: i = 0; while( pointIt != nextCell->PointIdsEnd() ) { pts[i++] = *pointIt++; } m_Polys->InsertNextCell(3, pts); break; default: printf("something \n"); } cellIt++; } m_PolyData->SetPolys(m_Polys); } <commit_msg>COMP: Remove unused variable in itkMeshTovtkPolyData::ConvertitkTovtk<commit_after>#include <iostream> #include "itkMeshTovtkPolyData.h" #ifndef vtkDoubleType #define vtkDoubleType double #endif #ifndef vtkFloatingPointType #define vtkFloatingPointType vtkFloatingPointType typedef float vtkFloatingPointType; #endif itkMeshTovtkPolyData ::itkMeshTovtkPolyData() { m_itkTriangleMesh = TriangleMeshType::New(); m_Points = vtkSmartPointer<vtkPoints>::New(); m_PolyData = vtkSmartPointer<vtkPolyData>::New(); m_Polys = vtkSmartPointer<vtkCellArray>::New(); } itkMeshTovtkPolyData ::~itkMeshTovtkPolyData() { } void itkMeshTovtkPolyData ::SetInput(TriangleMeshType::Pointer mesh) { m_itkTriangleMesh = mesh; this->ConvertitkTovtk(); } vtkSmartPointer<vtkPolyData> itkMeshTovtkPolyData::GetOutput() { return m_PolyData; } void itkMeshTovtkPolyData ::ConvertitkTovtk() { int numPoints = m_itkTriangleMesh->GetNumberOfPoints(); InputPointsContainerPointer myPoints = m_itkTriangleMesh->GetPoints(); InputPointsContainerIterator points = myPoints->Begin(); PointType point; if( numPoints == 0 ) { printf( "Aborting: No Points in GRID\n"); return; } m_Points->SetNumberOfPoints(numPoints); int idx = 0; double vpoint[3]; while( points != myPoints->End() ) { point = points.Value(); vpoint[0] = point[0]; vpoint[1] = point[1]; vpoint[2] = point[2]; m_Points->SetPoint(idx++, vpoint); points++; } m_PolyData->SetPoints(m_Points); CellsContainerPointer cells = m_itkTriangleMesh->GetCells(); CellsContainerIterator cellIt = cells->Begin(); vtkIdType pts[3]; while( cellIt != cells->End() ) { CellType * nextCell = cellIt->Value(); CellType::PointIdIterator pointIt = nextCell->PointIdsBegin(); int i; switch( nextCell->GetType() ) { case CellType::VERTEX_CELL: case CellType::LINE_CELL: case CellType::POLYGON_CELL: break; case CellType::TRIANGLE_CELL: i = 0; while( pointIt != nextCell->PointIdsEnd() ) { pts[i++] = *pointIt++; } m_Polys->InsertNextCell(3, pts); break; default: printf("something \n"); } cellIt++; } m_PolyData->SetPolys(m_Polys); } <|endoftext|>
<commit_before>// Copyright (c) 2009 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/extensions/sandboxed_extension_unpacker.h" #include <set> #include "base/base64.h" #include "base/crypto/signature_verifier.h" #include "base/file_util.h" #include "base/message_loop.h" #include "base/scoped_handle.h" #include "base/task.h" #include "chrome/browser/chrome_thread.h" #include "chrome/browser/extensions/extensions_service.h" #include "chrome/browser/renderer_host/resource_dispatcher_host.h" #include "chrome/common/chrome_switches.h" #include "chrome/common/extensions/extension.h" #include "chrome/common/extensions/extension_constants.h" #include "chrome/common/extensions/extension_file_util.h" #include "chrome/common/extensions/extension_l10n_util.h" #include "chrome/common/extensions/extension_unpacker.h" #include "chrome/common/json_value_serializer.h" #include "gfx/codec/png_codec.h" #include "third_party/skia/include/core/SkBitmap.h" const char SandboxedExtensionUnpacker::kExtensionHeaderMagic[] = "Cr24"; SandboxedExtensionUnpacker::SandboxedExtensionUnpacker( const FilePath& crx_path, ResourceDispatcherHost* rdh, SandboxedExtensionUnpackerClient* client) : crx_path_(crx_path), thread_identifier_(ChromeThread::ID_COUNT), rdh_(rdh), client_(client), got_response_(false) { } void SandboxedExtensionUnpacker::Start() { // We assume that we are started on the thread that the client wants us to do // file IO on. CHECK(ChromeThread::GetCurrentThreadIdentifier(&thread_identifier_)); // Create a temporary directory to work in. if (!temp_dir_.CreateUniqueTempDir()) { ReportFailure("Could not create temporary directory."); return; } // Initialize the path that will eventually contain the unpacked extension. extension_root_ = temp_dir_.path().AppendASCII("TEMP_INSTALL"); // Extract the public key and validate the package. if (!ValidateSignature()) return; // ValidateSignature() already reported the error. // Copy the crx file into our working directory. FilePath temp_crx_path = temp_dir_.path().Append(crx_path_.BaseName()); if (!file_util::CopyFile(crx_path_, temp_crx_path)) { ReportFailure("Failed to copy extension file to temporary directory."); return; } // If we are supposed to use a subprocess, copy the crx to the temp directory // and kick off the subprocess. // // TODO(asargent) we shouldn't need to do this branch here - instead // UtilityProcessHost should handle it for us. (http://crbug.com/19192) bool use_utility_process = rdh_ && !CommandLine::ForCurrentProcess()->HasSwitch(switches::kSingleProcess); if (use_utility_process) { ChromeThread::PostTask( ChromeThread::IO, FROM_HERE, NewRunnableMethod( this, &SandboxedExtensionUnpacker::StartProcessOnIOThread, temp_crx_path)); } else { // Otherwise, unpack the extension in this process. ExtensionUnpacker unpacker(temp_crx_path); if (unpacker.Run() && unpacker.DumpImagesToFile() && unpacker.DumpMessageCatalogsToFile()) { OnUnpackExtensionSucceeded(*unpacker.parsed_manifest()); } else { OnUnpackExtensionFailed(unpacker.error_message()); } } } void SandboxedExtensionUnpacker::StartProcessOnIOThread( const FilePath& temp_crx_path) { UtilityProcessHost* host = new UtilityProcessHost( rdh_, this, thread_identifier_); host->StartExtensionUnpacker(temp_crx_path); } void SandboxedExtensionUnpacker::OnUnpackExtensionSucceeded( const DictionaryValue& manifest) { // Skip check for unittests. if (thread_identifier_ != ChromeThread::ID_COUNT) DCHECK(ChromeThread::CurrentlyOn(thread_identifier_)); got_response_ = true; scoped_ptr<DictionaryValue> final_manifest(RewriteManifestFile(manifest)); if (!final_manifest.get()) return; // Create an extension object that refers to the temporary location the // extension was unpacked to. We use this until the extension is finally // installed. For example, the install UI shows images from inside the // extension. extension_.reset(new Extension(extension_root_)); // Localize manifest now, so confirm UI gets correct extension name. std::string error; if (!extension_l10n_util::LocalizeExtension(extension_.get(), final_manifest.get(), &error)) { ReportFailure(error); return; } if (!extension_->InitFromValue(*final_manifest, true, &error)) { ReportFailure(std::string("Manifest is invalid: ") + error); return; } if (!RewriteImageFiles()) return; if (!RewriteCatalogFiles()) return; ReportSuccess(); } void SandboxedExtensionUnpacker::OnUnpackExtensionFailed( const std::string& error) { DCHECK(ChromeThread::CurrentlyOn(thread_identifier_)); got_response_ = true; ReportFailure(error); } void SandboxedExtensionUnpacker::OnProcessCrashed() { // Don't report crashes if they happen after we got a response. if (got_response_) return; ReportFailure("Utility process crashed while trying to install."); } bool SandboxedExtensionUnpacker::ValidateSignature() { ScopedStdioHandle file(file_util::OpenFile(crx_path_, "rb")); if (!file.get()) { ReportFailure("Could not open crx file for reading"); return false; } // Read and verify the header. ExtensionHeader header; size_t len; // TODO(erikkay): Yuck. I'm not a big fan of this kind of code, but it // appears that we don't have any endian/alignment aware serialization // code in the code base. So for now, this assumes that we're running // on a little endian machine with 4 byte alignment. len = fread(&header, 1, sizeof(ExtensionHeader), file.get()); if (len < sizeof(ExtensionHeader)) { ReportFailure("Invalid crx header"); return false; } if (strncmp(kExtensionHeaderMagic, header.magic, sizeof(header.magic))) { ReportFailure("Bad magic number"); return false; } if (header.version != kCurrentVersion) { ReportFailure("Bad version number"); return false; } if (header.key_size > kMaxPublicKeySize || header.signature_size > kMaxSignatureSize) { ReportFailure("Excessively large key or signature"); return false; } std::vector<uint8> key; key.resize(header.key_size); len = fread(&key.front(), sizeof(uint8), header.key_size, file.get()); if (len < header.key_size) { ReportFailure("Invalid public key"); return false; } std::vector<uint8> signature; signature.resize(header.signature_size); len = fread(&signature.front(), sizeof(uint8), header.signature_size, file.get()); if (len < header.signature_size) { ReportFailure("Invalid signature"); return false; } // Note: this structure is an ASN.1 which encodes the algorithm used // with its parameters. This is defined in PKCS #1 v2.1 (RFC 3447). // It is encoding: { OID sha1WithRSAEncryption PARAMETERS NULL } // TODO(aa): This needs to be factored away someplace common. const uint8 signature_algorithm[15] = { 0x30, 0x0d, 0x06, 0x09, 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x01, 0x01, 0x05, 0x05, 0x00 }; base::SignatureVerifier verifier; if (!verifier.VerifyInit(signature_algorithm, sizeof(signature_algorithm), &signature.front(), signature.size(), &key.front(), key.size())) { ReportFailure("Signature verification initialization failed. " "This is most likely caused by a public key in " "the wrong format (should encode algorithm)."); return false; } unsigned char buf[1 << 12]; while ((len = fread(buf, 1, sizeof(buf), file.get())) > 0) verifier.VerifyUpdate(buf, len); if (!verifier.VerifyFinal()) { ReportFailure("Signature verification failed"); return false; } base::Base64Encode(std::string(reinterpret_cast<char*>(&key.front()), key.size()), &public_key_); return true; } void SandboxedExtensionUnpacker::ReportFailure(const std::string& error) { client_->OnUnpackFailure(error); } void SandboxedExtensionUnpacker::ReportSuccess() { // Client takes ownership of temporary directory and extension. client_->OnUnpackSuccess(temp_dir_.Take(), extension_root_, extension_.release()); } DictionaryValue* SandboxedExtensionUnpacker::RewriteManifestFile( const DictionaryValue& manifest) { // Add the public key extracted earlier to the parsed manifest and overwrite // the original manifest. We do this to ensure the manifest doesn't contain an // exploitable bug that could be used to compromise the browser. scoped_ptr<DictionaryValue> final_manifest( static_cast<DictionaryValue*>(manifest.DeepCopy())); final_manifest->SetString(extension_manifest_keys::kPublicKey, public_key_); // Override the origin if appropriate. bool web_content_enabled = false; if (final_manifest->GetBoolean(extension_manifest_keys::kWebContentEnabled, &web_content_enabled) && web_content_enabled && web_origin_.is_valid()) { if (final_manifest->HasKey(extension_manifest_keys::kWebOrigin)) { ReportFailure("Unexpected 'web_content.origin' key in manifest."); return NULL; } final_manifest->SetString(extension_manifest_keys::kWebOrigin, web_origin_.spec()); } std::string manifest_json; JSONStringValueSerializer serializer(&manifest_json); serializer.set_pretty_print(true); if (!serializer.Serialize(*final_manifest)) { ReportFailure("Error serializing manifest.json."); return NULL; } FilePath manifest_path = extension_root_.Append(Extension::kManifestFilename); if (!file_util::WriteFile(manifest_path, manifest_json.data(), manifest_json.size())) { ReportFailure("Error saving manifest.json."); return NULL; } return final_manifest.release(); } bool SandboxedExtensionUnpacker::RewriteImageFiles() { ExtensionUnpacker::DecodedImages images; if (!ExtensionUnpacker::ReadImagesFromFile(temp_dir_.path(), &images)) { ReportFailure("Couldn't read image data from disk."); return false; } // Delete any images that may be used by the browser. We're going to write // out our own versions of the parsed images, and we want to make sure the // originals are gone for good. std::set<FilePath> image_paths = extension_->GetBrowserImages(); if (image_paths.size() != images.size()) { ReportFailure("Decoded images don't match what's in the manifest."); return false; } for (std::set<FilePath>::iterator it = image_paths.begin(); it != image_paths.end(); ++it) { FilePath path = *it; if (path.IsAbsolute() || path.ReferencesParent()) { ReportFailure("Invalid path for browser image."); return false; } if (!file_util::Delete(extension_root_.Append(path), false)) { ReportFailure("Error removing old image file."); return false; } } // Write our parsed images back to disk as well. for (size_t i = 0; i < images.size(); ++i) { const SkBitmap& image = images[i].a; FilePath path_suffix = images[i].b; if (path_suffix.IsAbsolute() || path_suffix.ReferencesParent()) { ReportFailure("Invalid path for bitmap image."); return false; } FilePath path = extension_root_.Append(path_suffix); std::vector<unsigned char> image_data; // TODO(mpcomplete): It's lame that we're encoding all images as PNG, even // though they may originally be .jpg, etc. Figure something out. // http://code.google.com/p/chromium/issues/detail?id=12459 if (!gfx::PNGCodec::EncodeBGRASkBitmap(image, false, &image_data)) { ReportFailure("Error re-encoding theme image."); return false; } // Note: we're overwriting existing files that the utility process wrote, // so we can be sure the directory exists. const char* image_data_ptr = reinterpret_cast<const char*>(&image_data[0]); if (!file_util::WriteFile(path, image_data_ptr, image_data.size())) { ReportFailure("Error saving theme image."); return false; } } return true; } bool SandboxedExtensionUnpacker::RewriteCatalogFiles() { DictionaryValue catalogs; if (!ExtensionUnpacker::ReadMessageCatalogsFromFile(temp_dir_.path(), &catalogs)) { ReportFailure("Could not read catalog data from disk."); return false; } // Write our parsed catalogs back to disk. for (DictionaryValue::key_iterator key_it = catalogs.begin_keys(); key_it != catalogs.end_keys(); ++key_it) { DictionaryValue* catalog; if (!catalogs.GetDictionaryWithoutPathExpansion(*key_it, &catalog)) { ReportFailure("Invalid catalog data."); return false; } FilePath relative_path = FilePath::FromWStringHack(*key_it); relative_path = relative_path.Append(Extension::kMessagesFilename); if (relative_path.IsAbsolute() || relative_path.ReferencesParent()) { ReportFailure("Invalid path for catalog."); return false; } FilePath path = extension_root_.Append(relative_path); std::string catalog_json; JSONStringValueSerializer serializer(&catalog_json); serializer.set_pretty_print(true); if (!serializer.Serialize(*catalog)) { ReportFailure("Error serializing catalog."); return false; } // Note: we're overwriting existing files that the utility process read, // so we can be sure the directory exists. if (!file_util::WriteFile(path, catalog_json.c_str(), catalog_json.size())) { ReportFailure("Error saving catalog."); return false; } } return true; } <commit_msg>loosen origin requirements for apps for now<commit_after>// Copyright (c) 2009 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/extensions/sandboxed_extension_unpacker.h" #include <set> #include "base/base64.h" #include "base/crypto/signature_verifier.h" #include "base/file_util.h" #include "base/message_loop.h" #include "base/scoped_handle.h" #include "base/task.h" #include "chrome/browser/chrome_thread.h" #include "chrome/browser/extensions/extensions_service.h" #include "chrome/browser/renderer_host/resource_dispatcher_host.h" #include "chrome/common/chrome_switches.h" #include "chrome/common/extensions/extension.h" #include "chrome/common/extensions/extension_constants.h" #include "chrome/common/extensions/extension_file_util.h" #include "chrome/common/extensions/extension_l10n_util.h" #include "chrome/common/extensions/extension_unpacker.h" #include "chrome/common/json_value_serializer.h" #include "gfx/codec/png_codec.h" #include "third_party/skia/include/core/SkBitmap.h" const char SandboxedExtensionUnpacker::kExtensionHeaderMagic[] = "Cr24"; SandboxedExtensionUnpacker::SandboxedExtensionUnpacker( const FilePath& crx_path, ResourceDispatcherHost* rdh, SandboxedExtensionUnpackerClient* client) : crx_path_(crx_path), thread_identifier_(ChromeThread::ID_COUNT), rdh_(rdh), client_(client), got_response_(false) { } void SandboxedExtensionUnpacker::Start() { // We assume that we are started on the thread that the client wants us to do // file IO on. CHECK(ChromeThread::GetCurrentThreadIdentifier(&thread_identifier_)); // Create a temporary directory to work in. if (!temp_dir_.CreateUniqueTempDir()) { ReportFailure("Could not create temporary directory."); return; } // Initialize the path that will eventually contain the unpacked extension. extension_root_ = temp_dir_.path().AppendASCII("TEMP_INSTALL"); // Extract the public key and validate the package. if (!ValidateSignature()) return; // ValidateSignature() already reported the error. // Copy the crx file into our working directory. FilePath temp_crx_path = temp_dir_.path().Append(crx_path_.BaseName()); if (!file_util::CopyFile(crx_path_, temp_crx_path)) { ReportFailure("Failed to copy extension file to temporary directory."); return; } // If we are supposed to use a subprocess, copy the crx to the temp directory // and kick off the subprocess. // // TODO(asargent) we shouldn't need to do this branch here - instead // UtilityProcessHost should handle it for us. (http://crbug.com/19192) bool use_utility_process = rdh_ && !CommandLine::ForCurrentProcess()->HasSwitch(switches::kSingleProcess); if (use_utility_process) { ChromeThread::PostTask( ChromeThread::IO, FROM_HERE, NewRunnableMethod( this, &SandboxedExtensionUnpacker::StartProcessOnIOThread, temp_crx_path)); } else { // Otherwise, unpack the extension in this process. ExtensionUnpacker unpacker(temp_crx_path); if (unpacker.Run() && unpacker.DumpImagesToFile() && unpacker.DumpMessageCatalogsToFile()) { OnUnpackExtensionSucceeded(*unpacker.parsed_manifest()); } else { OnUnpackExtensionFailed(unpacker.error_message()); } } } void SandboxedExtensionUnpacker::StartProcessOnIOThread( const FilePath& temp_crx_path) { UtilityProcessHost* host = new UtilityProcessHost( rdh_, this, thread_identifier_); host->StartExtensionUnpacker(temp_crx_path); } void SandboxedExtensionUnpacker::OnUnpackExtensionSucceeded( const DictionaryValue& manifest) { // Skip check for unittests. if (thread_identifier_ != ChromeThread::ID_COUNT) DCHECK(ChromeThread::CurrentlyOn(thread_identifier_)); got_response_ = true; scoped_ptr<DictionaryValue> final_manifest(RewriteManifestFile(manifest)); if (!final_manifest.get()) return; // Create an extension object that refers to the temporary location the // extension was unpacked to. We use this until the extension is finally // installed. For example, the install UI shows images from inside the // extension. extension_.reset(new Extension(extension_root_)); // Localize manifest now, so confirm UI gets correct extension name. std::string error; if (!extension_l10n_util::LocalizeExtension(extension_.get(), final_manifest.get(), &error)) { ReportFailure(error); return; } if (!extension_->InitFromValue(*final_manifest, true, &error)) { ReportFailure(std::string("Manifest is invalid: ") + error); return; } if (!RewriteImageFiles()) return; if (!RewriteCatalogFiles()) return; ReportSuccess(); } void SandboxedExtensionUnpacker::OnUnpackExtensionFailed( const std::string& error) { DCHECK(ChromeThread::CurrentlyOn(thread_identifier_)); got_response_ = true; ReportFailure(error); } void SandboxedExtensionUnpacker::OnProcessCrashed() { // Don't report crashes if they happen after we got a response. if (got_response_) return; ReportFailure("Utility process crashed while trying to install."); } bool SandboxedExtensionUnpacker::ValidateSignature() { ScopedStdioHandle file(file_util::OpenFile(crx_path_, "rb")); if (!file.get()) { ReportFailure("Could not open crx file for reading"); return false; } // Read and verify the header. ExtensionHeader header; size_t len; // TODO(erikkay): Yuck. I'm not a big fan of this kind of code, but it // appears that we don't have any endian/alignment aware serialization // code in the code base. So for now, this assumes that we're running // on a little endian machine with 4 byte alignment. len = fread(&header, 1, sizeof(ExtensionHeader), file.get()); if (len < sizeof(ExtensionHeader)) { ReportFailure("Invalid crx header"); return false; } if (strncmp(kExtensionHeaderMagic, header.magic, sizeof(header.magic))) { ReportFailure("Bad magic number"); return false; } if (header.version != kCurrentVersion) { ReportFailure("Bad version number"); return false; } if (header.key_size > kMaxPublicKeySize || header.signature_size > kMaxSignatureSize) { ReportFailure("Excessively large key or signature"); return false; } std::vector<uint8> key; key.resize(header.key_size); len = fread(&key.front(), sizeof(uint8), header.key_size, file.get()); if (len < header.key_size) { ReportFailure("Invalid public key"); return false; } std::vector<uint8> signature; signature.resize(header.signature_size); len = fread(&signature.front(), sizeof(uint8), header.signature_size, file.get()); if (len < header.signature_size) { ReportFailure("Invalid signature"); return false; } // Note: this structure is an ASN.1 which encodes the algorithm used // with its parameters. This is defined in PKCS #1 v2.1 (RFC 3447). // It is encoding: { OID sha1WithRSAEncryption PARAMETERS NULL } // TODO(aa): This needs to be factored away someplace common. const uint8 signature_algorithm[15] = { 0x30, 0x0d, 0x06, 0x09, 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x01, 0x01, 0x05, 0x05, 0x00 }; base::SignatureVerifier verifier; if (!verifier.VerifyInit(signature_algorithm, sizeof(signature_algorithm), &signature.front(), signature.size(), &key.front(), key.size())) { ReportFailure("Signature verification initialization failed. " "This is most likely caused by a public key in " "the wrong format (should encode algorithm)."); return false; } unsigned char buf[1 << 12]; while ((len = fread(buf, 1, sizeof(buf), file.get())) > 0) verifier.VerifyUpdate(buf, len); if (!verifier.VerifyFinal()) { ReportFailure("Signature verification failed"); return false; } base::Base64Encode(std::string(reinterpret_cast<char*>(&key.front()), key.size()), &public_key_); return true; } void SandboxedExtensionUnpacker::ReportFailure(const std::string& error) { client_->OnUnpackFailure(error); } void SandboxedExtensionUnpacker::ReportSuccess() { // Client takes ownership of temporary directory and extension. client_->OnUnpackSuccess(temp_dir_.Take(), extension_root_, extension_.release()); } DictionaryValue* SandboxedExtensionUnpacker::RewriteManifestFile( const DictionaryValue& manifest) { // Add the public key extracted earlier to the parsed manifest and overwrite // the original manifest. We do this to ensure the manifest doesn't contain an // exploitable bug that could be used to compromise the browser. scoped_ptr<DictionaryValue> final_manifest( static_cast<DictionaryValue*>(manifest.DeepCopy())); final_manifest->SetString(extension_manifest_keys::kPublicKey, public_key_); // Override the origin if appropriate. bool web_content_enabled = false; if (final_manifest->GetBoolean(extension_manifest_keys::kWebContentEnabled, &web_content_enabled) && web_content_enabled && web_origin_.is_valid()) { // TODO(erikkay): Finalize origin policy. This is intentionally loose // until we can test from the gallery. http://crbug.com/40848. if (!final_manifest->Get(extension_manifest_keys::kWebOrigin, NULL)) { final_manifest->SetString(extension_manifest_keys::kWebOrigin, web_origin_.spec()); } } std::string manifest_json; JSONStringValueSerializer serializer(&manifest_json); serializer.set_pretty_print(true); if (!serializer.Serialize(*final_manifest)) { ReportFailure("Error serializing manifest.json."); return NULL; } FilePath manifest_path = extension_root_.Append(Extension::kManifestFilename); if (!file_util::WriteFile(manifest_path, manifest_json.data(), manifest_json.size())) { ReportFailure("Error saving manifest.json."); return NULL; } return final_manifest.release(); } bool SandboxedExtensionUnpacker::RewriteImageFiles() { ExtensionUnpacker::DecodedImages images; if (!ExtensionUnpacker::ReadImagesFromFile(temp_dir_.path(), &images)) { ReportFailure("Couldn't read image data from disk."); return false; } // Delete any images that may be used by the browser. We're going to write // out our own versions of the parsed images, and we want to make sure the // originals are gone for good. std::set<FilePath> image_paths = extension_->GetBrowserImages(); if (image_paths.size() != images.size()) { ReportFailure("Decoded images don't match what's in the manifest."); return false; } for (std::set<FilePath>::iterator it = image_paths.begin(); it != image_paths.end(); ++it) { FilePath path = *it; if (path.IsAbsolute() || path.ReferencesParent()) { ReportFailure("Invalid path for browser image."); return false; } if (!file_util::Delete(extension_root_.Append(path), false)) { ReportFailure("Error removing old image file."); return false; } } // Write our parsed images back to disk as well. for (size_t i = 0; i < images.size(); ++i) { const SkBitmap& image = images[i].a; FilePath path_suffix = images[i].b; if (path_suffix.IsAbsolute() || path_suffix.ReferencesParent()) { ReportFailure("Invalid path for bitmap image."); return false; } FilePath path = extension_root_.Append(path_suffix); std::vector<unsigned char> image_data; // TODO(mpcomplete): It's lame that we're encoding all images as PNG, even // though they may originally be .jpg, etc. Figure something out. // http://code.google.com/p/chromium/issues/detail?id=12459 if (!gfx::PNGCodec::EncodeBGRASkBitmap(image, false, &image_data)) { ReportFailure("Error re-encoding theme image."); return false; } // Note: we're overwriting existing files that the utility process wrote, // so we can be sure the directory exists. const char* image_data_ptr = reinterpret_cast<const char*>(&image_data[0]); if (!file_util::WriteFile(path, image_data_ptr, image_data.size())) { ReportFailure("Error saving theme image."); return false; } } return true; } bool SandboxedExtensionUnpacker::RewriteCatalogFiles() { DictionaryValue catalogs; if (!ExtensionUnpacker::ReadMessageCatalogsFromFile(temp_dir_.path(), &catalogs)) { ReportFailure("Could not read catalog data from disk."); return false; } // Write our parsed catalogs back to disk. for (DictionaryValue::key_iterator key_it = catalogs.begin_keys(); key_it != catalogs.end_keys(); ++key_it) { DictionaryValue* catalog; if (!catalogs.GetDictionaryWithoutPathExpansion(*key_it, &catalog)) { ReportFailure("Invalid catalog data."); return false; } FilePath relative_path = FilePath::FromWStringHack(*key_it); relative_path = relative_path.Append(Extension::kMessagesFilename); if (relative_path.IsAbsolute() || relative_path.ReferencesParent()) { ReportFailure("Invalid path for catalog."); return false; } FilePath path = extension_root_.Append(relative_path); std::string catalog_json; JSONStringValueSerializer serializer(&catalog_json); serializer.set_pretty_print(true); if (!serializer.Serialize(*catalog)) { ReportFailure("Error serializing catalog."); return false; } // Note: we're overwriting existing files that the utility process read, // so we can be sure the directory exists. if (!file_util::WriteFile(path, catalog_json.c_str(), catalog_json.size())) { ReportFailure("Error saving catalog."); return false; } } return true; } <|endoftext|>
<commit_before><commit_msg>Trim a whitespace (#6272)<commit_after><|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: isethint.cxx,v $ * * $Revision: 1.6 $ * * last change: $Author: rt $ $Date: 2005-09-08 16:30:30 $ * * 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 GCC #pragma hdrstop #endif #include "isethint.hxx" #include "itemset.hxx" //==================================================================== TYPEINIT1(SfxItemSetHint, SfxHint); //==================================================================== SfxItemSetHint::SfxItemSetHint( SfxItemSet *pItemSet ) /* [Beschreibung] Dieser Ctor "ubernimmt das als Parameter "ubergeben <SfxItemSet>, das im Dtor gel"oscht wird. */ : _pItemSet( pItemSet ) { } //-------------------------------------------------------------------- SfxItemSetHint::SfxItemSetHint( const SfxItemSet &rItemSet ) /* [Beschreibung] Dieser Ctor kopiert das als Parameter "ubergeben <SfxItemSet>. */ : _pItemSet( rItemSet.Clone() ) { } //-------------------------------------------------------------------- SfxItemSetHint::~SfxItemSetHint() { delete _pItemSet; } //-------------------------------------------------------------------- <commit_msg>INTEGRATION: CWS pchfix02 (1.6.324); FILE MERGED 2006/09/01 17:43:25 kaib 1.6.324.1: #i68856# Added header markers and pch files<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: isethint.cxx,v $ * * $Revision: 1.7 $ * * last change: $Author: obo $ $Date: 2006-09-17 15:18:48 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_svtools.hxx" #ifndef GCC #endif #include "isethint.hxx" #include "itemset.hxx" //==================================================================== TYPEINIT1(SfxItemSetHint, SfxHint); //==================================================================== SfxItemSetHint::SfxItemSetHint( SfxItemSet *pItemSet ) /* [Beschreibung] Dieser Ctor "ubernimmt das als Parameter "ubergeben <SfxItemSet>, das im Dtor gel"oscht wird. */ : _pItemSet( pItemSet ) { } //-------------------------------------------------------------------- SfxItemSetHint::SfxItemSetHint( const SfxItemSet &rItemSet ) /* [Beschreibung] Dieser Ctor kopiert das als Parameter "ubergeben <SfxItemSet>. */ : _pItemSet( rItemSet.Clone() ) { } //-------------------------------------------------------------------- SfxItemSetHint::~SfxItemSetHint() { delete _pItemSet; } //-------------------------------------------------------------------- <|endoftext|>
<commit_before>/* * Version: MPL 1.1 / GPLv3+ / LGPLv3+ * * The contents of this file are subject to the Mozilla Public 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.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Initial Developer of the Original Code is * Miklos Vajna <[email protected]> (SUSE, Inc.) * Portions created by the Initial Developer are Copyright (C) 2012 the * Initial Developer. All Rights Reserved. * * Contributor(s): * * Alternatively, the contents of this file may be used under the terms of * either the GNU General Public License Version 3 or later (the "GPLv3+"), or * the GNU Lesser General Public License Version 3 or later (the "LGPLv3+"), * in which case the provisions of the GPLv3+ or the LGPLv3+ are applicable * instead of those above. */ #include "../swmodeltestbase.hxx" #include <com/sun/star/awt/XBitmap.hpp> #include <com/sun/star/beans/XPropertySet.hpp> #include <com/sun/star/drawing/XDrawPageSupplier.hpp> #include <com/sun/star/lang/XServiceInfo.hpp> #include <com/sun/star/text/HoriOrientation.hpp> #include <com/sun/star/text/SetVariableType.hpp> #include <com/sun/star/text/TextContentAnchorType.hpp> #include <com/sun/star/text/XDependentTextField.hpp> #include <com/sun/star/text/XPageCursor.hpp> #include <com/sun/star/text/XTextFieldsSupplier.hpp> #include <com/sun/star/text/XTextFramesSupplier.hpp> #include <com/sun/star/text/XTextViewCursorSupplier.hpp> #include <vcl/svapp.hxx> using rtl::OString; using rtl::OUString; using rtl::OUStringBuffer; class Test : public SwModelTestBase { public: void testN751054(); void testN751117(); void testN751017(); void testN750935(); void testN757890(); void testFdo49940(); void testN751077(); void testN705956_1(); void testN705956_2(); CPPUNIT_TEST_SUITE(Test); #if !defined(MACOSX) && !defined(WNT) CPPUNIT_TEST(testN751054); CPPUNIT_TEST(testN751117); CPPUNIT_TEST(testN751017); CPPUNIT_TEST(testN750935); CPPUNIT_TEST(testN757890); CPPUNIT_TEST(testFdo49940); CPPUNIT_TEST(testN751077); CPPUNIT_TEST(testN705956_1); CPPUNIT_TEST(testN705956_2); #endif CPPUNIT_TEST_SUITE_END(); private: /// Load an OOXML file and make the document available via mxComponent. void load(const OUString& rURL); }; void Test::load(const OUString& rFilename) { mxComponent = loadFromDesktop(getURLFromSrc("/sw/qa/extras/ooxmltok/data/") + rFilename); } void Test::testN751054() { load("n751054.docx"); uno::Reference<drawing::XDrawPageSupplier> xDrawPageSupplier(mxComponent, uno::UNO_QUERY); uno::Reference<container::XIndexAccess> xDraws(xDrawPageSupplier->getDrawPage(), uno::UNO_QUERY); uno::Reference<beans::XPropertySet> xPropertySet(xDraws->getByIndex(0), uno::UNO_QUERY); text::TextContentAnchorType eValue; xPropertySet->getPropertyValue("AnchorType") >>= eValue; CPPUNIT_ASSERT(eValue != text::TextContentAnchorType_AS_CHARACTER); } void Test::testN751117() { load("n751117.docx"); uno::Reference<drawing::XDrawPageSupplier> xDrawPageSupplier(mxComponent, uno::UNO_QUERY); uno::Reference<container::XIndexAccess> xDraws(xDrawPageSupplier->getDrawPage(), uno::UNO_QUERY); // First shape: the end should be an arrow, should be rotated and should be flipped. uno::Reference<beans::XPropertySet> xPropertySet(xDraws->getByIndex(0), uno::UNO_QUERY); OUString aValue; xPropertySet->getPropertyValue("LineEndName") >>= aValue; CPPUNIT_ASSERT(aValue.indexOf("Arrow") != -1); sal_Int32 nValue = 0; xPropertySet->getPropertyValue("RotateAngle") >>= nValue; CPPUNIT_ASSERT_EQUAL(sal_Int32(90 * 100), nValue); uno::Reference<drawing::XShape> xShape(xPropertySet, uno::UNO_QUERY); awt::Size aActualSize(xShape->getSize()); CPPUNIT_ASSERT(aActualSize.Width < 0); // The second shape should be a line uno::Reference<lang::XServiceInfo> xServiceInfo(xDraws->getByIndex(1), uno::UNO_QUERY); CPPUNIT_ASSERT(xServiceInfo->supportsService("com.sun.star.drawing.LineShape")); } void Test::testN751017() { load("n751017.docx"); uno::Reference<text::XTextFieldsSupplier> xTextFieldsSupplier(mxComponent, uno::UNO_QUERY); uno::Reference<container::XNameAccess> xMasters(xTextFieldsSupplier->getTextFieldMasters()); // Make sure we have a variable named foo. CPPUNIT_ASSERT(xMasters->hasByName("com.sun.star.text.FieldMaster.SetExpression.foo")); uno::Reference<container::XEnumerationAccess> xFieldsAccess(xTextFieldsSupplier->getTextFields()); uno::Reference<container::XEnumeration> xFields(xFieldsAccess->createEnumeration()); bool bFoundSet(false), bFoundGet(false); while (xFields->hasMoreElements()) { uno::Reference<lang::XServiceInfo> xServiceInfo(xFields->nextElement(), uno::UNO_QUERY); uno::Reference<beans::XPropertySet> xPropertySet(xServiceInfo, uno::UNO_QUERY); sal_Int16 nValue = 0; OUString aValue; if (xServiceInfo->supportsService("com.sun.star.text.TextField.SetExpression")) { bFoundSet = true; uno::Reference<text::XDependentTextField> xDependentTextField(xServiceInfo, uno::UNO_QUERY); uno::Reference<beans::XPropertySet> xMasterProps(xDependentTextField->getTextFieldMaster()); // First step: did we set foo to "bar"? xMasterProps->getPropertyValue("Name") >>= aValue; CPPUNIT_ASSERT_EQUAL(OUString("foo"), aValue); xPropertySet->getPropertyValue("SubType") >>= nValue; CPPUNIT_ASSERT_EQUAL(text::SetVariableType::STRING, nValue); xPropertySet->getPropertyValue("Content") >>= aValue; CPPUNIT_ASSERT_EQUAL(OUString("bar"), aValue); } else if (xServiceInfo->supportsService("com.sun.star.text.TextField.GetExpression")) { // Second step: check the value of foo. bFoundGet = true; xPropertySet->getPropertyValue("Content") >>= aValue; CPPUNIT_ASSERT_EQUAL(OUString("foo"), aValue); xPropertySet->getPropertyValue("SubType") >>= nValue; CPPUNIT_ASSERT_EQUAL(text::SetVariableType::STRING, nValue); xPropertySet->getPropertyValue("CurrentPresentation") >>= aValue; CPPUNIT_ASSERT_EQUAL(OUString("bar"), aValue); } } CPPUNIT_ASSERT(bFoundSet); CPPUNIT_ASSERT(bFoundGet); } void Test::testN750935() { load("n750935.docx"); uno::Reference<frame::XModel> xModel(mxComponent, uno::UNO_QUERY); uno::Reference<text::XTextViewCursorSupplier> xTextViewCursorSupplier(xModel->getCurrentController(), uno::UNO_QUERY); uno::Reference<text::XPageCursor> xCursor(xTextViewCursorSupplier->getViewCursor(), uno::UNO_QUERY); xCursor->jumpToLastPage(); CPPUNIT_ASSERT_EQUAL(sal_Int16(5), xCursor->getPage()); } void Test::testN757890() { load("n757890.docx"); // The w:pStyle token affected the text outside the textbox. uno::Reference<text::XTextDocument> xTextDocument(mxComponent, uno::UNO_QUERY); uno::Reference<container::XEnumerationAccess> xParaEnumAccess(xTextDocument->getText(), uno::UNO_QUERY); uno::Reference<container::XEnumeration> xParaEnum = xParaEnumAccess->createEnumeration(); uno::Reference<beans::XPropertySet> xPara(xParaEnum->nextElement(), uno::UNO_QUERY); OUString aValue; xPara->getPropertyValue("ParaStyleName") >>= aValue; CPPUNIT_ASSERT_EQUAL(OUString("Heading 1"), aValue); // This wan't centered uno::Reference<text::XTextFramesSupplier> xTextFramesSupplier(mxComponent, uno::UNO_QUERY); uno::Reference<container::XIndexAccess> xIndexAccess(xTextFramesSupplier->getTextFrames(), uno::UNO_QUERY); uno::Reference<beans::XPropertySet> xFrame(xIndexAccess->getByIndex(0), uno::UNO_QUERY); sal_Int16 nValue; xFrame->getPropertyValue("HoriOrient") >>= nValue; CPPUNIT_ASSERT_EQUAL(text::HoriOrientation::CENTER, nValue); } void Test::testFdo49940() { load("fdo49940.docx"); uno::Reference<text::XTextDocument> xTextDocument(mxComponent, uno::UNO_QUERY); uno::Reference<container::XEnumerationAccess> xParaEnumAccess(xTextDocument->getText(), uno::UNO_QUERY); uno::Reference<container::XEnumeration> xParaEnum = xParaEnumAccess->createEnumeration(); uno::Reference<beans::XPropertySet> xPara(xParaEnum->nextElement(), uno::UNO_QUERY); OUString aValue; xPara->getPropertyValue("PageStyleName") >>= aValue; CPPUNIT_ASSERT_EQUAL(OUString("First Page"), aValue); } void Test::testN751077() { load( "n751077.docx" ); /* enum = ThisComponent.Text.createEnumeration enum.NextElement para = enum.NextElement xray para.String xray para.PageStyleName */ uno::Reference<text::XTextDocument> textDocument(mxComponent, uno::UNO_QUERY); uno::Reference<container::XEnumerationAccess> paraEnumAccess(textDocument->getText(), uno::UNO_QUERY); // list of paragraphs uno::Reference<container::XEnumeration> paraEnum = paraEnumAccess->createEnumeration(); // go to 1st paragraph (void) paraEnum->nextElement(); // get the 2nd paragraph uno::Reference<uno::XInterface> paragraph(paraEnum->nextElement(), uno::UNO_QUERY); OUString value; // text of the paragraph uno::Reference<text::XTextRange> text(paragraph, uno::UNO_QUERY); CPPUNIT_ASSERT_EQUAL( OUString( "TEXT1" ), text->getString()); // we want to test the paragraph is on the first page (it was put onto another page without the fix), // use a small trick and instead of checking the page layout, check the page style uno::Reference<beans::XPropertySet> paragraphProperties(paragraph, uno::UNO_QUERY); paragraphProperties->getPropertyValue( "PageStyleName" ) >>= value; CPPUNIT_ASSERT_EQUAL( OUString( "First Page" ), value ); } void Test::testN705956_1() { load( "n705956-1.docx" ); /* Get the first image in the document and check it's the one image in the document. image = ThisComponent.DrawPage.getByIndex(0) graphic = image.Graphic xray graphic.Size */ uno::Reference<text::XTextDocument> textDocument(mxComponent, uno::UNO_QUERY); uno::Reference<drawing::XDrawPageSupplier> drawPageSupplier(textDocument, uno::UNO_QUERY); uno::Reference<drawing::XDrawPage> drawPage = drawPageSupplier->getDrawPage(); CPPUNIT_ASSERT_EQUAL( 1, drawPage->getCount()); uno::Reference<drawing::XShape> image; drawPage->getByIndex(0) >>= image; uno::Reference<beans::XPropertySet> imageProperties(image, uno::UNO_QUERY); uno::Reference<graphic::XGraphic> graphic; imageProperties->getPropertyValue( "Graphic" ) >>= graphic; uno::Reference<awt::XBitmap> bitmap(graphic, uno::UNO_QUERY); CPPUNIT_ASSERT_EQUAL( static_cast<sal_Int32>(120), bitmap->getSize().Width ); CPPUNIT_ASSERT_EQUAL( static_cast<sal_Int32>(106), bitmap->getSize().Height ); } void Test::testN705956_2() { load( "n705956-2.docx" ); /* <v:shapetype> must be global, reachable even from <v:shape> inside another <w:pict> image = ThisComponent.DrawPage.getByIndex(0) xray image.FillColor */ uno::Reference<text::XTextDocument> textDocument(mxComponent, uno::UNO_QUERY); uno::Reference<drawing::XDrawPageSupplier> drawPageSupplier(textDocument, uno::UNO_QUERY); uno::Reference<drawing::XDrawPage> drawPage = drawPageSupplier->getDrawPage(); uno::Reference<drawing::XShape> image; drawPage->getByIndex(0) >>= image; uno::Reference<beans::XPropertySet> imageProperties(image, uno::UNO_QUERY); sal_Int32 fillColor; imageProperties->getPropertyValue( "FillColor" ) >>= fillColor; CPPUNIT_ASSERT_EQUAL( 0xc0504d, fillColor ); } CPPUNIT_TEST_SUITE_REGISTRATION(Test); CPPUNIT_PLUGIN_IMPLEMENT(); /* vim:set shiftwidth=4 softtabstop=4 expandtab: */ <commit_msg>++I_hate_sal_Int32<commit_after>/* * Version: MPL 1.1 / GPLv3+ / LGPLv3+ * * The contents of this file are subject to the Mozilla Public 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.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Initial Developer of the Original Code is * Miklos Vajna <[email protected]> (SUSE, Inc.) * Portions created by the Initial Developer are Copyright (C) 2012 the * Initial Developer. All Rights Reserved. * * Contributor(s): * * Alternatively, the contents of this file may be used under the terms of * either the GNU General Public License Version 3 or later (the "GPLv3+"), or * the GNU Lesser General Public License Version 3 or later (the "LGPLv3+"), * in which case the provisions of the GPLv3+ or the LGPLv3+ are applicable * instead of those above. */ #include "../swmodeltestbase.hxx" #include <com/sun/star/awt/XBitmap.hpp> #include <com/sun/star/beans/XPropertySet.hpp> #include <com/sun/star/drawing/XDrawPageSupplier.hpp> #include <com/sun/star/lang/XServiceInfo.hpp> #include <com/sun/star/text/HoriOrientation.hpp> #include <com/sun/star/text/SetVariableType.hpp> #include <com/sun/star/text/TextContentAnchorType.hpp> #include <com/sun/star/text/XDependentTextField.hpp> #include <com/sun/star/text/XPageCursor.hpp> #include <com/sun/star/text/XTextFieldsSupplier.hpp> #include <com/sun/star/text/XTextFramesSupplier.hpp> #include <com/sun/star/text/XTextViewCursorSupplier.hpp> #include <vcl/svapp.hxx> using rtl::OString; using rtl::OUString; using rtl::OUStringBuffer; class Test : public SwModelTestBase { public: void testN751054(); void testN751117(); void testN751017(); void testN750935(); void testN757890(); void testFdo49940(); void testN751077(); void testN705956_1(); void testN705956_2(); CPPUNIT_TEST_SUITE(Test); #if !defined(MACOSX) && !defined(WNT) CPPUNIT_TEST(testN751054); CPPUNIT_TEST(testN751117); CPPUNIT_TEST(testN751017); CPPUNIT_TEST(testN750935); CPPUNIT_TEST(testN757890); CPPUNIT_TEST(testFdo49940); CPPUNIT_TEST(testN751077); CPPUNIT_TEST(testN705956_1); CPPUNIT_TEST(testN705956_2); #endif CPPUNIT_TEST_SUITE_END(); private: /// Load an OOXML file and make the document available via mxComponent. void load(const OUString& rURL); }; void Test::load(const OUString& rFilename) { mxComponent = loadFromDesktop(getURLFromSrc("/sw/qa/extras/ooxmltok/data/") + rFilename); } void Test::testN751054() { load("n751054.docx"); uno::Reference<drawing::XDrawPageSupplier> xDrawPageSupplier(mxComponent, uno::UNO_QUERY); uno::Reference<container::XIndexAccess> xDraws(xDrawPageSupplier->getDrawPage(), uno::UNO_QUERY); uno::Reference<beans::XPropertySet> xPropertySet(xDraws->getByIndex(0), uno::UNO_QUERY); text::TextContentAnchorType eValue; xPropertySet->getPropertyValue("AnchorType") >>= eValue; CPPUNIT_ASSERT(eValue != text::TextContentAnchorType_AS_CHARACTER); } void Test::testN751117() { load("n751117.docx"); uno::Reference<drawing::XDrawPageSupplier> xDrawPageSupplier(mxComponent, uno::UNO_QUERY); uno::Reference<container::XIndexAccess> xDraws(xDrawPageSupplier->getDrawPage(), uno::UNO_QUERY); // First shape: the end should be an arrow, should be rotated and should be flipped. uno::Reference<beans::XPropertySet> xPropertySet(xDraws->getByIndex(0), uno::UNO_QUERY); OUString aValue; xPropertySet->getPropertyValue("LineEndName") >>= aValue; CPPUNIT_ASSERT(aValue.indexOf("Arrow") != -1); sal_Int32 nValue = 0; xPropertySet->getPropertyValue("RotateAngle") >>= nValue; CPPUNIT_ASSERT_EQUAL(sal_Int32(90 * 100), nValue); uno::Reference<drawing::XShape> xShape(xPropertySet, uno::UNO_QUERY); awt::Size aActualSize(xShape->getSize()); CPPUNIT_ASSERT(aActualSize.Width < 0); // The second shape should be a line uno::Reference<lang::XServiceInfo> xServiceInfo(xDraws->getByIndex(1), uno::UNO_QUERY); CPPUNIT_ASSERT(xServiceInfo->supportsService("com.sun.star.drawing.LineShape")); } void Test::testN751017() { load("n751017.docx"); uno::Reference<text::XTextFieldsSupplier> xTextFieldsSupplier(mxComponent, uno::UNO_QUERY); uno::Reference<container::XNameAccess> xMasters(xTextFieldsSupplier->getTextFieldMasters()); // Make sure we have a variable named foo. CPPUNIT_ASSERT(xMasters->hasByName("com.sun.star.text.FieldMaster.SetExpression.foo")); uno::Reference<container::XEnumerationAccess> xFieldsAccess(xTextFieldsSupplier->getTextFields()); uno::Reference<container::XEnumeration> xFields(xFieldsAccess->createEnumeration()); bool bFoundSet(false), bFoundGet(false); while (xFields->hasMoreElements()) { uno::Reference<lang::XServiceInfo> xServiceInfo(xFields->nextElement(), uno::UNO_QUERY); uno::Reference<beans::XPropertySet> xPropertySet(xServiceInfo, uno::UNO_QUERY); sal_Int16 nValue = 0; OUString aValue; if (xServiceInfo->supportsService("com.sun.star.text.TextField.SetExpression")) { bFoundSet = true; uno::Reference<text::XDependentTextField> xDependentTextField(xServiceInfo, uno::UNO_QUERY); uno::Reference<beans::XPropertySet> xMasterProps(xDependentTextField->getTextFieldMaster()); // First step: did we set foo to "bar"? xMasterProps->getPropertyValue("Name") >>= aValue; CPPUNIT_ASSERT_EQUAL(OUString("foo"), aValue); xPropertySet->getPropertyValue("SubType") >>= nValue; CPPUNIT_ASSERT_EQUAL(text::SetVariableType::STRING, nValue); xPropertySet->getPropertyValue("Content") >>= aValue; CPPUNIT_ASSERT_EQUAL(OUString("bar"), aValue); } else if (xServiceInfo->supportsService("com.sun.star.text.TextField.GetExpression")) { // Second step: check the value of foo. bFoundGet = true; xPropertySet->getPropertyValue("Content") >>= aValue; CPPUNIT_ASSERT_EQUAL(OUString("foo"), aValue); xPropertySet->getPropertyValue("SubType") >>= nValue; CPPUNIT_ASSERT_EQUAL(text::SetVariableType::STRING, nValue); xPropertySet->getPropertyValue("CurrentPresentation") >>= aValue; CPPUNIT_ASSERT_EQUAL(OUString("bar"), aValue); } } CPPUNIT_ASSERT(bFoundSet); CPPUNIT_ASSERT(bFoundGet); } void Test::testN750935() { load("n750935.docx"); uno::Reference<frame::XModel> xModel(mxComponent, uno::UNO_QUERY); uno::Reference<text::XTextViewCursorSupplier> xTextViewCursorSupplier(xModel->getCurrentController(), uno::UNO_QUERY); uno::Reference<text::XPageCursor> xCursor(xTextViewCursorSupplier->getViewCursor(), uno::UNO_QUERY); xCursor->jumpToLastPage(); CPPUNIT_ASSERT_EQUAL(sal_Int16(5), xCursor->getPage()); } void Test::testN757890() { load("n757890.docx"); // The w:pStyle token affected the text outside the textbox. uno::Reference<text::XTextDocument> xTextDocument(mxComponent, uno::UNO_QUERY); uno::Reference<container::XEnumerationAccess> xParaEnumAccess(xTextDocument->getText(), uno::UNO_QUERY); uno::Reference<container::XEnumeration> xParaEnum = xParaEnumAccess->createEnumeration(); uno::Reference<beans::XPropertySet> xPara(xParaEnum->nextElement(), uno::UNO_QUERY); OUString aValue; xPara->getPropertyValue("ParaStyleName") >>= aValue; CPPUNIT_ASSERT_EQUAL(OUString("Heading 1"), aValue); // This wan't centered uno::Reference<text::XTextFramesSupplier> xTextFramesSupplier(mxComponent, uno::UNO_QUERY); uno::Reference<container::XIndexAccess> xIndexAccess(xTextFramesSupplier->getTextFrames(), uno::UNO_QUERY); uno::Reference<beans::XPropertySet> xFrame(xIndexAccess->getByIndex(0), uno::UNO_QUERY); sal_Int16 nValue; xFrame->getPropertyValue("HoriOrient") >>= nValue; CPPUNIT_ASSERT_EQUAL(text::HoriOrientation::CENTER, nValue); } void Test::testFdo49940() { load("fdo49940.docx"); uno::Reference<text::XTextDocument> xTextDocument(mxComponent, uno::UNO_QUERY); uno::Reference<container::XEnumerationAccess> xParaEnumAccess(xTextDocument->getText(), uno::UNO_QUERY); uno::Reference<container::XEnumeration> xParaEnum = xParaEnumAccess->createEnumeration(); uno::Reference<beans::XPropertySet> xPara(xParaEnum->nextElement(), uno::UNO_QUERY); OUString aValue; xPara->getPropertyValue("PageStyleName") >>= aValue; CPPUNIT_ASSERT_EQUAL(OUString("First Page"), aValue); } void Test::testN751077() { load( "n751077.docx" ); /* enum = ThisComponent.Text.createEnumeration enum.NextElement para = enum.NextElement xray para.String xray para.PageStyleName */ uno::Reference<text::XTextDocument> textDocument(mxComponent, uno::UNO_QUERY); uno::Reference<container::XEnumerationAccess> paraEnumAccess(textDocument->getText(), uno::UNO_QUERY); // list of paragraphs uno::Reference<container::XEnumeration> paraEnum = paraEnumAccess->createEnumeration(); // go to 1st paragraph (void) paraEnum->nextElement(); // get the 2nd paragraph uno::Reference<uno::XInterface> paragraph(paraEnum->nextElement(), uno::UNO_QUERY); OUString value; // text of the paragraph uno::Reference<text::XTextRange> text(paragraph, uno::UNO_QUERY); CPPUNIT_ASSERT_EQUAL( OUString( "TEXT1" ), text->getString()); // we want to test the paragraph is on the first page (it was put onto another page without the fix), // use a small trick and instead of checking the page layout, check the page style uno::Reference<beans::XPropertySet> paragraphProperties(paragraph, uno::UNO_QUERY); paragraphProperties->getPropertyValue( "PageStyleName" ) >>= value; CPPUNIT_ASSERT_EQUAL( OUString( "First Page" ), value ); } void Test::testN705956_1() { load( "n705956-1.docx" ); /* Get the first image in the document and check it's the one image in the document. image = ThisComponent.DrawPage.getByIndex(0) graphic = image.Graphic xray graphic.Size */ uno::Reference<text::XTextDocument> textDocument(mxComponent, uno::UNO_QUERY); uno::Reference<drawing::XDrawPageSupplier> drawPageSupplier(textDocument, uno::UNO_QUERY); uno::Reference<drawing::XDrawPage> drawPage = drawPageSupplier->getDrawPage(); CPPUNIT_ASSERT_EQUAL( sal_Int32( 1 ), drawPage->getCount()); uno::Reference<drawing::XShape> image; drawPage->getByIndex(0) >>= image; uno::Reference<beans::XPropertySet> imageProperties(image, uno::UNO_QUERY); uno::Reference<graphic::XGraphic> graphic; imageProperties->getPropertyValue( "Graphic" ) >>= graphic; uno::Reference<awt::XBitmap> bitmap(graphic, uno::UNO_QUERY); CPPUNIT_ASSERT_EQUAL( static_cast<sal_Int32>(120), bitmap->getSize().Width ); CPPUNIT_ASSERT_EQUAL( static_cast<sal_Int32>(106), bitmap->getSize().Height ); } void Test::testN705956_2() { load( "n705956-2.docx" ); /* <v:shapetype> must be global, reachable even from <v:shape> inside another <w:pict> image = ThisComponent.DrawPage.getByIndex(0) xray image.FillColor */ uno::Reference<text::XTextDocument> textDocument(mxComponent, uno::UNO_QUERY); uno::Reference<drawing::XDrawPageSupplier> drawPageSupplier(textDocument, uno::UNO_QUERY); uno::Reference<drawing::XDrawPage> drawPage = drawPageSupplier->getDrawPage(); uno::Reference<drawing::XShape> image; drawPage->getByIndex(0) >>= image; uno::Reference<beans::XPropertySet> imageProperties(image, uno::UNO_QUERY); sal_Int32 fillColor; imageProperties->getPropertyValue( "FillColor" ) >>= fillColor; CPPUNIT_ASSERT_EQUAL( sal_Int32( 0xc0504d ), fillColor ); } CPPUNIT_TEST_SUITE_REGISTRATION(Test); CPPUNIT_PLUGIN_IMPLEMENT(); /* vim:set shiftwidth=4 softtabstop=4 expandtab: */ <|endoftext|>
<commit_before>/* ** Copyright 2011 Merethis ** This file is part of Centreon Broker. ** ** Centreon Broker is free software: you can redistribute it and/or ** modify it under the terms of the GNU General Public License version 2 ** as published by the Free Software Foundation. ** ** Centreon Broker 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 Centreon Broker. If not, see ** <http://www.gnu.org/licenses/>. */ #include <algorithm> #include <assert.h> #include <QCoreApplication> #include <QMutexLocker> #include <stdlib.h> #include "com/centreon/broker/config/applier/endpoint.hh" #include "com/centreon/broker/exceptions/msg.hh" #include "com/centreon/broker/io/endpoint.hh" #include "com/centreon/broker/io/protocols.hh" #include "com/centreon/broker/logging/logging.hh" using namespace com::centreon::broker; using namespace com::centreon::broker::config::applier; /************************************** * * * Local Objects * * * **************************************/ /** * Comparison classes. */ class failover_match_name { private: QString _failover; public: failover_match_name(QString const& fo) : _failover(fo) {} failover_match_name(failover_match_name const& fmn) : _failover(fmn._failover) {} ~failover_match_name() {} failover_match_name& operator=(failover_match_name& fmn) { _failover = fmn._failover; return (*this); } bool operator()(config::endpoint const& endp) const { return (_failover == endp.name); } }; class name_match_failover { private: QString _name; public: name_match_failover(QString const& name) : _name(name) {} name_match_failover(name_match_failover const& nmf) : _name(nmf._name) {} ~name_match_failover() {} name_match_failover& operator=(name_match_failover const& nmf) { _name = nmf._name; return (*this); } bool operator()(config::endpoint const& endp) const { return (_name == endp.failover); } }; /************************************** * * * Private Methods * * * **************************************/ /** * Default constructor. */ endpoint::endpoint() : QObject() {} /** * @brief Copy constructor. * * Any call to this constructor will result in a call to abort(). * * @param[in] e Object to copy. */ endpoint::endpoint(endpoint const& e) : QObject() { (void)e; assert(false); abort(); } /** * @brief Assignment operator. * * Any call to this method will result in a call to abort(). * * @param[in] e Object to copy. * * @return This object. */ endpoint& endpoint::operator=(endpoint const& e) { (void)e; assert(false); abort(); return (*this); } /** * Create and register an endpoint according to configuration. * * @param[in] cfg Endpoint configuration. * @param[in] is_input true if the endpoint will act as input. * @param[in] is_output true if the endpoint will act as output. * @param[in] l List of endpoints. */ processing::failover* endpoint::_create_endpoint(config::endpoint const& cfg, bool is_input, bool is_output, QList<config::endpoint> const& l) { // Debug message. logging::config << logging::MEDIUM << "endpoint applier: creating new endpoint '" << cfg.name << "'"; // Check that failover is configured. QSharedPointer<processing::failover> failovr; if (!cfg.failover.isEmpty()) { QList<config::endpoint>::const_iterator it(std::find_if(l.begin(), l.end(), failover_match_name(cfg.failover))); if (it == l.end()) throw (exceptions::msg() << "endpoint applier: could not find " \ "failover '" << cfg.failover << "' for endpoint '" << cfg.name << "'"); failovr = QSharedPointer<processing::failover>(_create_endpoint(*it, is_input || is_output, is_output, l)); } // Create endpoint object. QSharedPointer<io::endpoint> endp; bool is_acceptor(false); int level(0); for (QMap<QString, io::protocols::protocol>::const_iterator it = io::protocols::instance().begin(), end = io::protocols::instance().end(); it != end; ++it) { if ((it.value().osi_from == 1) && it.value().endpntfactry->has_endpoint(cfg, !is_output, is_output)) { endp = QSharedPointer<io::endpoint>(it.value().endpntfactry->new_endpoint(cfg, is_input, is_output, is_acceptor)); level = it.value().osi_to + 1; break ; } } if (endp.isNull()) throw (exceptions::msg() << "endpoint applier: no matching " \ "protocol found for endpoint '" << cfg.name << "'"); // Create remaining objects. while (level <= 7) { // Browse protocol list. QMap<QString, io::protocols::protocol>::const_iterator it(io::protocols::instance().begin()); QMap<QString, io::protocols::protocol>::const_iterator end(io::protocols::instance().end()); while (it != end) { if ((it.value().osi_from == level) && (it.value().endpntfactry->has_endpoint(cfg, !is_output, is_output))) { QSharedPointer<io::endpoint> current(it.value().endpntfactry->new_endpoint(cfg, !is_output, is_output, is_acceptor)); current->from(endp); endp = current; level = it.value().osi_to; break ; } ++it; } if ((7 == level) && (it == end)) throw (exceptions::msg() << "endpoint applier: no matching " \ "protocol found for endpoint '" << cfg.name << "'"); ++level; } // Return failover thread. QScopedPointer<processing::failover> fo(new processing::failover(is_output)); fo->set_retry_interval(cfg.retry_interval); fo->set_endpoint(endp); fo->set_failover(failovr); return (fo.take()); } /** * Diff the current configuration with the new configuration. * * @param[in] current Current endpoints. * @param[in] new_endpoints New endpoints configuration. * @param[out] to_create Endpoints that should be created. */ void endpoint::_diff_endpoints(QMap<config::endpoint, processing::failover*> & current, QList<config::endpoint> const& new_endpoints, QList<config::endpoint>& to_create) { // Find which endpoints will be kept, created and deleted. QMap<config::endpoint, processing::failover*> to_delete(current); for (QList<config::endpoint>::const_iterator it = new_endpoints.begin(), end = new_endpoints.end(); it != end; ++it) { QMap<config::endpoint, processing::failover*>::iterator endp(to_delete.find(*it)); if (endp != to_delete.end()) to_delete.erase(endp); else to_create.push_back(*it); } // Remove old endpoints. for (QMap<config::endpoint, processing::failover*>::iterator it = to_delete.begin(), end = to_delete.end(); it != end; ++it) { // Send only termination request, object will be destroyed by event // loop on termination. But wait for threads because they hold // resources that might be used by other endpoints. (*it)->exit(); (*it)->wait(); } return ; } /************************************** * * * Public Methods * * * **************************************/ /** * Destructor. */ endpoint::~endpoint() {} /** * Apply the endpoint configuration. * * @param[in] inputs Inputs configuration. * @param[in] outputs Outputs configuration. */ void endpoint::apply(QList<config::endpoint> const& inputs, QList<config::endpoint> const& outputs) { // Log messages. logging::config << logging::HIGH << "endpoint applier: loading configuration"; logging::debug << logging::HIGH << "endpoint applier: " << inputs.size() << " inputs and " << outputs.size() << " outputs to apply"; // Remove old inputs and generate inputs to create. QList<config::endpoint> in_to_create; { QMutexLocker lock(&_inputsm); _diff_endpoints(_inputs, inputs, in_to_create); } // Remove old outputs and generate outputs to create. QList<config::endpoint> out_to_create; { QMutexLocker lock(&_outputsm); _diff_endpoints(_outputs, outputs, out_to_create); } // Debug message. logging::debug << logging::HIGH << "endpoint applier: " << in_to_create.size() << " inputs to create, " << out_to_create.size() << " outputs to create"; // Create new outputs. for (QList<config::endpoint>::iterator it = out_to_create.begin(), end = out_to_create.end(); it != end; ++it) // Check that output is not a failover. if (it->name.isEmpty() || (std::find_if(out_to_create.begin(), out_to_create.end(), name_match_failover(it->name)) == out_to_create.end())) { // Create endpoint. QScopedPointer<processing::failover> endp(_create_endpoint(*it, false, true, out_to_create)); connect(endp.data(), SIGNAL(finished()), this, SLOT(terminated_output())); connect(endp.data(), SIGNAL(terminated()), this, SLOT(terminated_output())); connect(endp.data(), SIGNAL(finished()), endp.data(), SLOT(deleteLater())); { QMutexLocker lock(&_outputsm); _outputs[*it] = endp.data(); } // Run thread. logging::debug << logging::MEDIUM << "endpoint applier: output thread 0x" << QString().setNum((qulonglong)static_cast<QObject*>(endp.data()), 16) << " is registered and ready to run"; endp.take()->start(); } // Create new inputs. for (QList<config::endpoint>::iterator it = in_to_create.begin(), end = in_to_create.end(); it != end; ++it) // Check that output is not a failover. if (it->name.isEmpty() || (std::find_if(in_to_create.begin(), in_to_create.end(), name_match_failover(it->name)) == in_to_create.end())) { // Create endpoint. QScopedPointer<processing::failover> endp(_create_endpoint(*it, true, false, in_to_create)); connect(endp.data(), SIGNAL(finished()), this, SLOT(terminated_input())); connect(endp.data(), SIGNAL(terminated()), this, SLOT(terminated_input())); connect(endp.data(), SIGNAL(finished()), endp.data(), SLOT(deleteLater())); { QMutexLocker lock(&_inputsm); _inputs[*it] = endp.data(); } // Run thread. logging::debug << logging::MEDIUM << "endpoint applier: input thread 0x" << QString().setNum((qulonglong)static_cast<QObject*>(endp.data()), 16) << " is registered and ready to run"; endp.take()->start(); } return ; } /** * Get the class instance. * * @return Class instance. */ endpoint& endpoint::instance() { static endpoint gl_endpoint; return (gl_endpoint); } /** * An input thread finished executing. */ void endpoint::terminated_input() { QObject* sendr(QObject::sender()); logging::debug << logging::MEDIUM << "endpoint applier: input thread 0x" << QString().setNum((qulonglong)sendr, 16) << " terminated"; QMutexLocker lock(&_inputsm); QList<config::endpoint> keys(_inputs.keys( static_cast<processing::failover*>(sendr))); for (QList<config::endpoint>::iterator it = keys.begin(), end = keys.end(); it != end; ++it) _inputs.remove(*it); return ; } /** * An output thread finished executing. */ void endpoint::terminated_output() { QObject* sendr(QObject::sender()); logging::debug << logging::MEDIUM << "endpoint applier: output thread 0x" << QString().setNum((qulonglong)sendr, 16) << " terminated"; QMutexLocker lock(&_outputsm); QList<config::endpoint> keys(_outputs.keys( static_cast<processing::failover*>(sendr))); for (QList<config::endpoint>::iterator it = keys.begin(), end = keys.end(); it != end; ++it) _outputs.remove(*it); return ; } /** * Unload the singleton. */ void endpoint::unload() { logging::debug << logging::HIGH << "endpoint applier: destruction"; // Exit input threads. { logging::debug << logging::MEDIUM << "endpoint applier: " \ "requesting input threads termination"; QMutexLocker lock(&_inputsm); // Send termination requests. for (QMap<config::endpoint, processing::failover*>::iterator it = _inputs.begin(), end = _inputs.end(); it != end; ++it) (*it)->exit(); // Wait for threads. while (!_inputs.empty()) { logging::debug << logging::LOW << "endpoint applier: " << _inputs.size() << " input threads remaining"; lock.unlock(); time_t now(time(NULL)); do { QCoreApplication::processEvents(QEventLoop::AllEvents, 1000); } while (time(NULL) <= now); lock.relock(); } logging::debug << logging::MEDIUM << "endpoint applier: all " \ "input threads are terminated"; _inputs.clear(); } // Exit output threads. { logging::debug << logging::MEDIUM << "endpoint applier: " \ "requesting output threads termination"; QMutexLocker lock(&_outputsm); // Send termination requests. for (QMap<config::endpoint, processing::failover*>::iterator it = _outputs.begin(), end = _outputs.end(); it != end; ++it) (*it)->exit(); // Wait for threads. while (!_outputs.empty()) { logging::debug << logging::LOW << "endpoint applier: " << _outputs.size() << " output threads remaining"; lock.unlock(); time_t now(time(NULL)); do { QCoreApplication::processEvents(QEventLoop::AllEvents, 1000); } while (time(NULL) <= now); lock.relock(); } logging::debug << logging::MEDIUM << "endpoint applier :all " \ "output threads are terminated"; _outputs.clear(); } } <commit_msg>Fix for failover endpoint creation.<commit_after>/* ** Copyright 2011 Merethis ** ** This file is part of Centreon Broker. ** ** Centreon Broker is free software: you can redistribute it and/or ** modify it under the terms of the GNU General Public License version 2 ** as published by the Free Software Foundation. ** ** Centreon Broker 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 Centreon Broker. If not, see ** <http://www.gnu.org/licenses/>. */ #include <algorithm> #include <assert.h> #include <QCoreApplication> #include <QMutexLocker> #include <stdlib.h> #include "com/centreon/broker/config/applier/endpoint.hh" #include "com/centreon/broker/exceptions/msg.hh" #include "com/centreon/broker/io/endpoint.hh" #include "com/centreon/broker/io/protocols.hh" #include "com/centreon/broker/logging/logging.hh" using namespace com::centreon::broker; using namespace com::centreon::broker::config::applier; /************************************** * * * Local Objects * * * **************************************/ /** * Comparison classes. */ class failover_match_name { private: QString _failover; public: failover_match_name(QString const& fo) : _failover(fo) {} failover_match_name(failover_match_name const& fmn) : _failover(fmn._failover) {} ~failover_match_name() {} failover_match_name& operator=(failover_match_name& fmn) { _failover = fmn._failover; return (*this); } bool operator()(config::endpoint const& endp) const { return (_failover == endp.name); } }; class name_match_failover { private: QString _name; public: name_match_failover(QString const& name) : _name(name) {} name_match_failover(name_match_failover const& nmf) : _name(nmf._name) {} ~name_match_failover() {} name_match_failover& operator=(name_match_failover const& nmf) { _name = nmf._name; return (*this); } bool operator()(config::endpoint const& endp) const { return (_name == endp.failover); } }; /************************************** * * * Private Methods * * * **************************************/ /** * Default constructor. */ endpoint::endpoint() : QObject() {} /** * @brief Copy constructor. * * Any call to this constructor will result in a call to abort(). * * @param[in] e Object to copy. */ endpoint::endpoint(endpoint const& e) : QObject() { (void)e; assert(false); abort(); } /** * @brief Assignment operator. * * Any call to this method will result in a call to abort(). * * @param[in] e Object to copy. * * @return This object. */ endpoint& endpoint::operator=(endpoint const& e) { (void)e; assert(false); abort(); return (*this); } /** * Create and register an endpoint according to configuration. * * @param[in] cfg Endpoint configuration. * @param[in] is_input true if the endpoint will act as input. * @param[in] is_output true if the endpoint will act as output. * @param[in] l List of endpoints. */ processing::failover* endpoint::_create_endpoint(config::endpoint const& cfg, bool is_input, bool is_output, QList<config::endpoint> const& l) { // Debug message. logging::config << logging::MEDIUM << "endpoint applier: creating new endpoint '" << cfg.name << "'"; // Check that failover is configured. QSharedPointer<processing::failover> failovr; if (!cfg.failover.isEmpty()) { QList<config::endpoint>::const_iterator it(std::find_if(l.begin(), l.end(), failover_match_name(cfg.failover))); if (it == l.end()) throw (exceptions::msg() << "endpoint applier: could not find " \ "failover '" << cfg.failover << "' for endpoint '" << cfg.name << "'"); failovr = QSharedPointer<processing::failover>(_create_endpoint(*it, is_input || is_output, is_output, l)); } // Create endpoint object. QSharedPointer<io::endpoint> endp; bool is_acceptor(false); int level(0); for (QMap<QString, io::protocols::protocol>::const_iterator it = io::protocols::instance().begin(), end = io::protocols::instance().end(); it != end; ++it) { if ((it.value().osi_from == 1) && it.value().endpntfactry->has_endpoint(cfg, !is_output, is_output)) { endp = QSharedPointer<io::endpoint>(it.value().endpntfactry->new_endpoint(cfg, is_input, is_output, is_acceptor)); level = it.value().osi_to + 1; break ; } } if (endp.isNull()) throw (exceptions::msg() << "endpoint applier: no matching " \ "protocol found for endpoint '" << cfg.name << "'"); // Create remaining objects. while (level <= 7) { // Browse protocol list. QMap<QString, io::protocols::protocol>::const_iterator it(io::protocols::instance().begin()); QMap<QString, io::protocols::protocol>::const_iterator end(io::protocols::instance().end()); while (it != end) { if ((it.value().osi_from == level) && (it.value().endpntfactry->has_endpoint(cfg, !is_output, is_output))) { QSharedPointer<io::endpoint> current(it.value().endpntfactry->new_endpoint(cfg, is_input, is_output, is_acceptor)); current->from(endp); endp = current; level = it.value().osi_to; break ; } ++it; } if ((7 == level) && (it == end)) throw (exceptions::msg() << "endpoint applier: no matching " \ "protocol found for endpoint '" << cfg.name << "'"); ++level; } // Return failover thread. QScopedPointer<processing::failover> fo(new processing::failover(is_output)); fo->set_retry_interval(cfg.retry_interval); fo->set_endpoint(endp); fo->set_failover(failovr); return (fo.take()); } /** * Diff the current configuration with the new configuration. * * @param[in] current Current endpoints. * @param[in] new_endpoints New endpoints configuration. * @param[out] to_create Endpoints that should be created. */ void endpoint::_diff_endpoints(QMap<config::endpoint, processing::failover*> & current, QList<config::endpoint> const& new_endpoints, QList<config::endpoint>& to_create) { // Find which endpoints will be kept, created and deleted. QMap<config::endpoint, processing::failover*> to_delete(current); for (QList<config::endpoint>::const_iterator it = new_endpoints.begin(), end = new_endpoints.end(); it != end; ++it) { QMap<config::endpoint, processing::failover*>::iterator endp(to_delete.find(*it)); if (endp != to_delete.end()) to_delete.erase(endp); else to_create.push_back(*it); } // Remove old endpoints. for (QMap<config::endpoint, processing::failover*>::iterator it = to_delete.begin(), end = to_delete.end(); it != end; ++it) { // Send only termination request, object will be destroyed by event // loop on termination. But wait for threads because they hold // resources that might be used by other endpoints. (*it)->exit(); (*it)->wait(); } return ; } /************************************** * * * Public Methods * * * **************************************/ /** * Destructor. */ endpoint::~endpoint() {} /** * Apply the endpoint configuration. * * @param[in] inputs Inputs configuration. * @param[in] outputs Outputs configuration. */ void endpoint::apply(QList<config::endpoint> const& inputs, QList<config::endpoint> const& outputs) { // Log messages. logging::config << logging::HIGH << "endpoint applier: loading configuration"; logging::debug << logging::HIGH << "endpoint applier: " << inputs.size() << " inputs and " << outputs.size() << " outputs to apply"; // Remove old inputs and generate inputs to create. QList<config::endpoint> in_to_create; { QMutexLocker lock(&_inputsm); _diff_endpoints(_inputs, inputs, in_to_create); } // Remove old outputs and generate outputs to create. QList<config::endpoint> out_to_create; { QMutexLocker lock(&_outputsm); _diff_endpoints(_outputs, outputs, out_to_create); } // Debug message. logging::debug << logging::HIGH << "endpoint applier: " << in_to_create.size() << " inputs to create, " << out_to_create.size() << " outputs to create"; // Create new outputs. for (QList<config::endpoint>::iterator it = out_to_create.begin(), end = out_to_create.end(); it != end; ++it) // Check that output is not a failover. if (it->name.isEmpty() || (std::find_if(out_to_create.begin(), out_to_create.end(), name_match_failover(it->name)) == out_to_create.end())) { // Create endpoint. QScopedPointer<processing::failover> endp(_create_endpoint(*it, false, true, out_to_create)); connect(endp.data(), SIGNAL(finished()), this, SLOT(terminated_output())); connect(endp.data(), SIGNAL(terminated()), this, SLOT(terminated_output())); connect(endp.data(), SIGNAL(finished()), endp.data(), SLOT(deleteLater())); { QMutexLocker lock(&_outputsm); _outputs[*it] = endp.data(); } // Run thread. logging::debug << logging::MEDIUM << "endpoint applier: output thread 0x" << QString().setNum((qulonglong)static_cast<QObject*>(endp.data()), 16) << " is registered and ready to run"; endp.take()->start(); } // Create new inputs. for (QList<config::endpoint>::iterator it = in_to_create.begin(), end = in_to_create.end(); it != end; ++it) // Check that output is not a failover. if (it->name.isEmpty() || (std::find_if(in_to_create.begin(), in_to_create.end(), name_match_failover(it->name)) == in_to_create.end())) { // Create endpoint. QScopedPointer<processing::failover> endp(_create_endpoint(*it, true, false, in_to_create)); connect(endp.data(), SIGNAL(finished()), this, SLOT(terminated_input())); connect(endp.data(), SIGNAL(terminated()), this, SLOT(terminated_input())); connect(endp.data(), SIGNAL(finished()), endp.data(), SLOT(deleteLater())); { QMutexLocker lock(&_inputsm); _inputs[*it] = endp.data(); } // Run thread. logging::debug << logging::MEDIUM << "endpoint applier: input thread 0x" << QString().setNum((qulonglong)static_cast<QObject*>(endp.data()), 16) << " is registered and ready to run"; endp.take()->start(); } return ; } /** * Get the class instance. * * @return Class instance. */ endpoint& endpoint::instance() { static endpoint gl_endpoint; return (gl_endpoint); } /** * An input thread finished executing. */ void endpoint::terminated_input() { QObject* sendr(QObject::sender()); logging::debug << logging::MEDIUM << "endpoint applier: input thread 0x" << QString().setNum((qulonglong)sendr, 16) << " terminated"; QMutexLocker lock(&_inputsm); QList<config::endpoint> keys(_inputs.keys( static_cast<processing::failover*>(sendr))); for (QList<config::endpoint>::iterator it = keys.begin(), end = keys.end(); it != end; ++it) _inputs.remove(*it); return ; } /** * An output thread finished executing. */ void endpoint::terminated_output() { QObject* sendr(QObject::sender()); logging::debug << logging::MEDIUM << "endpoint applier: output thread 0x" << QString().setNum((qulonglong)sendr, 16) << " terminated"; QMutexLocker lock(&_outputsm); QList<config::endpoint> keys(_outputs.keys( static_cast<processing::failover*>(sendr))); for (QList<config::endpoint>::iterator it = keys.begin(), end = keys.end(); it != end; ++it) _outputs.remove(*it); return ; } /** * Unload the singleton. */ void endpoint::unload() { logging::debug << logging::HIGH << "endpoint applier: destruction"; // Exit input threads. { logging::debug << logging::MEDIUM << "endpoint applier: " \ "requesting input threads termination"; QMutexLocker lock(&_inputsm); // Send termination requests. for (QMap<config::endpoint, processing::failover*>::iterator it = _inputs.begin(), end = _inputs.end(); it != end; ++it) (*it)->exit(); // Wait for threads. while (!_inputs.empty()) { logging::debug << logging::LOW << "endpoint applier: " << _inputs.size() << " input threads remaining"; lock.unlock(); time_t now(time(NULL)); do { QCoreApplication::processEvents(QEventLoop::AllEvents, 1000); } while (time(NULL) <= now); lock.relock(); } logging::debug << logging::MEDIUM << "endpoint applier: all " \ "input threads are terminated"; _inputs.clear(); } // Exit output threads. { logging::debug << logging::MEDIUM << "endpoint applier: " \ "requesting output threads termination"; QMutexLocker lock(&_outputsm); // Send termination requests. for (QMap<config::endpoint, processing::failover*>::iterator it = _outputs.begin(), end = _outputs.end(); it != end; ++it) (*it)->exit(); // Wait for threads. while (!_outputs.empty()) { logging::debug << logging::LOW << "endpoint applier: " << _outputs.size() << " output threads remaining"; lock.unlock(); time_t now(time(NULL)); do { QCoreApplication::processEvents(QEventLoop::AllEvents, 1000); } while (time(NULL) <= now); lock.relock(); } logging::debug << logging::MEDIUM << "endpoint applier :all " \ "output threads are terminated"; _outputs.clear(); } } <|endoftext|>
<commit_before>/****************************************************************************** * _ _____ __________ * * | | / / _ | / __/_ __/ Visibility * * | |/ / __ |_\ \ / / Across * * |___/_/ |_/___/ /_/ Space and Time * * * * This file is part of VAST. It is subject to the license terms in the * * LICENSE file found in the top-level directory of this distribution and at * * http://vast.io/license. No part of VAST, including this file, may be * * copied, modified, propagated, or distributed except according to the terms * * contained in the LICENSE file. * ******************************************************************************/ #pragma once #include <map> #include <string> #include <caf/stateful_actor.hpp> #include <caf/replies_to.hpp> #include <caf/typed_actor.hpp> #include "vast/optional.hpp" #include "vast/system/atoms.hpp" #include "vast/detail/radix_tree.hpp" namespace vast::system { /// State maintained per component. struct component_state { caf::actor actor; std::string label; }; template <class Inspector> auto inspect(Inspector& f, component_state& cs) { return f(cs.actor, cs.label); } /// Maps a component type ("archive", "index", etc.) to its state. using component_state_map = std::multimap<std::string, component_state>; /// Maps node names to component state. using component_map = std::map<std::string, component_state_map>; /// An entry of the `component_map`. using component_map_entry = std::pair<std::string, component_state_map>; /// The graph of connected components.. //using link_map = std::unordered_multimap<caf::actor, caf::actor>; /// Tracker meta data: components and their links. struct registry { component_map components; //link_map links; }; template <class Inspector> auto inspect(Inspector& f, registry& r) { //return f(r.components, r.links); return f(r.components); } struct tracker_state { std::string node; vast::system::registry registry; static inline const char* name = "tracker"; }; using tracker_type = caf::typed_actor< // Adds a component. caf::replies_to<put_atom, std::string, caf::actor, std::string> ::with<ok_atom>, // Adds a component if it doesn't yet exist. caf::reacts_to<try_put_atom, std::string, caf::actor, std::string>, // Propagated PUT received from peer. caf::reacts_to<put_atom, std::string, std::string, caf::actor, std::string>, // Retrieves the component registry. caf::replies_to<get_atom>::with<registry>, // The peering between two trackers A and B comprises 3 messages: // (1) B -> A: Respond to a peering request from new remote peer A. caf::replies_to<peer_atom, caf::actor, std::string> ::with<state_atom, registry>, // (2) A -> B: Confirm peering handshake after receiving state. caf::replies_to<state_atom, registry>::with<ok_atom>, // (3) A -> B: Broadcast own state to peers caf::reacts_to<state_atom, component_map_entry> >; /// Keeps track of the topology in a VAST deployment. /// @param self The actor handle. /// @param node The name of the local node. tracker_type::behavior_type tracker(tracker_type::stateful_pointer<tracker_state> self, std::string node); } // namespace vast::system <commit_msg>Enable heterogenous lookups for maps in tracker<commit_after>/****************************************************************************** * _ _____ __________ * * | | / / _ | / __/_ __/ Visibility * * | |/ / __ |_\ \ / / Across * * |___/_/ |_/___/ /_/ Space and Time * * * * This file is part of VAST. It is subject to the license terms in the * * LICENSE file found in the top-level directory of this distribution and at * * http://vast.io/license. No part of VAST, including this file, may be * * copied, modified, propagated, or distributed except according to the terms * * contained in the LICENSE file. * ******************************************************************************/ #pragma once #include <map> #include <string> #include <caf/stateful_actor.hpp> #include <caf/replies_to.hpp> #include <caf/typed_actor.hpp> #include "vast/optional.hpp" #include "vast/system/atoms.hpp" #include "vast/detail/radix_tree.hpp" namespace vast::system { /// State maintained per component. struct component_state { caf::actor actor; std::string label; }; template <class Inspector> auto inspect(Inspector& f, component_state& cs) { return f(cs.actor, cs.label); } /// Maps a component type ("archive", "index", etc.) to its state. using component_state_map = std::multimap<std::string, component_state, std::less<>>; /// Maps node names to component state. using component_map = std::map<std::string, component_state_map, std::less<>>; /// An entry of the `component_map`. using component_map_entry = std::pair<std::string, component_state_map>; /// The graph of connected components.. //using link_map = std::unordered_multimap<caf::actor, caf::actor>; /// Tracker meta data: components and their links. struct registry { component_map components; //link_map links; }; template <class Inspector> auto inspect(Inspector& f, registry& r) { //return f(r.components, r.links); return f(r.components); } struct tracker_state { std::string node; vast::system::registry registry; static inline const char* name = "tracker"; }; using tracker_type = caf::typed_actor< // Adds a component. caf::replies_to<put_atom, std::string, caf::actor, std::string> ::with<ok_atom>, // Adds a component if it doesn't yet exist. caf::reacts_to<try_put_atom, std::string, caf::actor, std::string>, // Propagated PUT received from peer. caf::reacts_to<put_atom, std::string, std::string, caf::actor, std::string>, // Retrieves the component registry. caf::replies_to<get_atom>::with<registry>, // The peering between two trackers A and B comprises 3 messages: // (1) B -> A: Respond to a peering request from new remote peer A. caf::replies_to<peer_atom, caf::actor, std::string> ::with<state_atom, registry>, // (2) A -> B: Confirm peering handshake after receiving state. caf::replies_to<state_atom, registry>::with<ok_atom>, // (3) A -> B: Broadcast own state to peers caf::reacts_to<state_atom, component_map_entry> >; /// Keeps track of the topology in a VAST deployment. /// @param self The actor handle. /// @param node The name of the local node. tracker_type::behavior_type tracker(tracker_type::stateful_pointer<tracker_state> self, std::string node); } // namespace vast::system <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: mmoutputpage.hxx,v $ * * $Revision: 1.4 $ * * last change: $Author: kz $ $Date: 2005-03-01 15:27:15 $ * * 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 _MAILMERGEOUTPUTPAGE_HXX #define _MAILMERGEOUTPUTPAGE_HXX #ifndef _SVTOOLS_WIZARDMACHINE_HXX_ #include <svtools/wizardmachine.hxx> #endif #ifndef _SV_BUTTON_HXX #include <vcl/button.hxx> #endif #ifndef _STDCTRL_HXX #include <svtools/stdctrl.hxx> #endif #ifndef _SV_COMBOBOX_HXX #include <vcl/combobox.hxx> #endif #ifndef _SV_FIELD_HXX #include <vcl/field.hxx> #endif #ifndef _SV_LSTBOX_HXX #include <vcl/lstbox.hxx> #endif #ifndef _SFX_OBJSH_HXX #include <sfx2/objsh.hxx> #endif #ifndef _BASEDLGS_HXX #include <sfx2/basedlgs.hxx> #endif #ifndef _SVTABBX_HXX #include <svtools/svtabbx.hxx> #endif #ifndef _HEADBAR_HXX #include <svtools/headbar.hxx> #endif #ifndef _PRGSBAR_HXX #include <svtools/prgsbar.hxx> #endif #ifndef INCLUDED_SWDLLAPI_H #include "swdllapi.h" #endif #ifndef _MAILMERGEHELPER_HXX #include "mailmergehelper.hxx" #endif class SwMailMergeWizard; class SfxPrinter; class SwSendMailDialog; namespace com{ namespace sun{ namespace star{ namespace mail{ class XMailMessage; } }}} /*-- 02.04.2004 09:21:06--------------------------------------------------- -----------------------------------------------------------------------*/ class SwMailMergeOutputPage : public svt::OWizardPage { SwBoldFixedInfo m_aHeaderFI; FixedInfo m_aOptionsFI; RadioButton m_aSaveStartDocRB; RadioButton m_aSaveMergedDocRB; RadioButton m_aPrintRB; RadioButton m_aSendMailRB; FixedLine m_aSeparatorFL; PushButton m_aSaveStartDocPB; RadioButton m_aSaveAsOneRB; RadioButton m_aSaveIndividualRB; RadioButton m_aPrintAllRB; //has to be here for tab control reasons RadioButton m_aSendAllRB; //has to be here for tab control reasons //this group is used in save and print RadioButton m_aFromRB; NumericField m_aFromNF; FixedText m_aToFT; NumericField m_aToNF; PushButton m_aSaveNowPB; FixedText m_aPrinterFT; ListBox m_aPrinterLB; PushButton m_aPrinterSettingsPB; PushButton m_aPrintNowPB; FixedText m_aMailToFT; ListBox m_aMailToLB; PushButton m_aCopyToPB; FixedText m_aSubjectFT; Edit m_aSubjectED; FixedText m_aSendAsFT; ListBox m_aSendAsLB; FixedText m_aAttachmentFT; Edit m_aAttachmentED; PushButton m_aSendAsPB; PushButton m_aSendDocumentsPB; SwMailMergeWizard* m_pWizard; //some FixedLine labels String m_sSaveStartST; String m_sSaveMergedST; String m_sPrintST; String m_sSendMailST; //misc strings String m_sDefaultAttachmentST; String m_sNoSubjectQueryST; String m_sNoSubjectST; String m_sNoAttachmentNameST; String m_sConfigureMail; String m_sBody; long m_nFromToRBPos; long m_nFromToFTPos; long m_nFromToNFPos; long m_nRBOffset; //some dialog data Printer* m_pTempPrinter; SfxPrinter* m_pDocumentPrinterCopy; String m_sCC; String m_sBCC; DECL_LINK(OutputTypeHdl_Impl, RadioButton*); DECL_LINK(CopyToHdl_Impl, PushButton*); DECL_LINK(SaveStartHdl_Impl, PushButton* ); DECL_LINK(SaveOutputHdl_Impl, PushButton* ); DECL_LINK(PrinterChangeHdl_Impl, ListBox* ); DECL_LINK(PrintHdl_Impl, PushButton* ); DECL_LINK(PrinterSetupHdl_Impl, PushButton* ); DECL_LINK(SendTypeHdl_Impl, ListBox*); DECL_LINK(SendAsHdl_Impl, PushButton*); DECL_LINK(SendDocumentsHdl_Impl, PushButton*); protected: virtual sal_Bool determineNextButtonState(); virtual void ActivatePage(); public: SwMailMergeOutputPage( SwMailMergeWizard* _pParent); ~SwMailMergeOutputPage(); }; /*-- 21.05.2004 12:48:50--------------------------------------------------- -----------------------------------------------------------------------*/ struct SwMailDescriptor { ::rtl::OUString sEMail; ::rtl::OUString sAttachmentURL; ::rtl::OUString sAttachmentName; ::rtl::OUString sMimeType; ::rtl::OUString sSubject; ::rtl::OUString sBodyMimeType; ::rtl::OUString sBodyContent; ::rtl::OUString sCC; ::rtl::OUString sBCC; }; struct SwSendMailDialog_Impl; class MailProgressBar_Impl; class SwMailMergeConfigItem; class SW_DLLPUBLIC SwSendMailDialog : public ModelessDialog //SfxModalDialog { FixedLine m_aStatusFL; FixedText m_aStatusFT; FixedLine m_aTransferStatusFL; FixedText m_aTransferStatusFT; FixedInfo m_PausedFI; ProgressBar m_aProgressBar; FixedText m_aErrorStatusFT; PushButton m_aDetailsPB; HeaderBar m_aStatusHB; SvTabListBox m_aStatusLB; FixedLine m_aSeparatorFL; PushButton m_aStopPB; PushButton m_aClosePB; String m_sMore; String m_sLess; String m_sContinue; String m_sStop; String m_sSend; String m_sTransferStatus; String m_sErrorStatus; String m_sSendingTo; String m_sCompleted; String m_sFailed; String m_sTerminateQuery; bool m_bCancel; bool m_bDesctructionEnabled; ImageList m_aImageList; ImageList m_aImageListHC; SwSendMailDialog_Impl* m_pImpl; SwMailMergeConfigItem* m_pConfigItem; sal_Int32 m_nStatusHeight; sal_Int32 m_nSendCount; sal_Int32 m_nErrorCount; SW_DLLPRIVATE DECL_LINK( DetailsHdl_Impl, PushButton* ); SW_DLLPRIVATE DECL_LINK( StopHdl_Impl, PushButton* ); SW_DLLPRIVATE DECL_LINK( CloseHdl_Impl, PushButton* ); SW_DLLPRIVATE DECL_STATIC_LINK( SwSendMailDialog, StartSendMails, SwSendMailDialog* ); SW_DLLPRIVATE DECL_STATIC_LINK( SwSendMailDialog, StopSendMails, SwSendMailDialog* ); SW_DLLPRIVATE DECL_STATIC_LINK( SwSendMailDialog, RemoveThis, Timer* ); SW_DLLPRIVATE void IterateMails(); SW_DLLPRIVATE void SendMails(); SW_DLLPRIVATE void UpdateTransferStatus(); virtual void StateChanged( StateChangedType nStateChange ); public: SwSendMailDialog( Window* pParent, SwMailMergeConfigItem& ); ~SwSendMailDialog(); void AddDocument( SwMailDescriptor& rDesc ); void SetDocumentCount( sal_Int32 nAllDocuments ); void EnableDesctruction() {m_bDesctructionEnabled = true;} void Show(); void DocumentSent( ::com::sun::star::uno::Reference< ::com::sun::star::mail::XMailMessage>, bool bResult, const ::rtl::OUString* pError ); void AllMailsSent(); }; #endif <commit_msg>INTEGRATION: CWS ooo19126 (1.4.290); FILE MERGED 2005/09/05 13:43:48 rt 1.4.290.1: #i54170# Change license header: remove SISSL<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: mmoutputpage.hxx,v $ * * $Revision: 1.5 $ * * last change: $Author: rt $ $Date: 2005-09-09 07:04:21 $ * * 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 _MAILMERGEOUTPUTPAGE_HXX #define _MAILMERGEOUTPUTPAGE_HXX #ifndef _SVTOOLS_WIZARDMACHINE_HXX_ #include <svtools/wizardmachine.hxx> #endif #ifndef _SV_BUTTON_HXX #include <vcl/button.hxx> #endif #ifndef _STDCTRL_HXX #include <svtools/stdctrl.hxx> #endif #ifndef _SV_COMBOBOX_HXX #include <vcl/combobox.hxx> #endif #ifndef _SV_FIELD_HXX #include <vcl/field.hxx> #endif #ifndef _SV_LSTBOX_HXX #include <vcl/lstbox.hxx> #endif #ifndef _SFX_OBJSH_HXX #include <sfx2/objsh.hxx> #endif #ifndef _BASEDLGS_HXX #include <sfx2/basedlgs.hxx> #endif #ifndef _SVTABBX_HXX #include <svtools/svtabbx.hxx> #endif #ifndef _HEADBAR_HXX #include <svtools/headbar.hxx> #endif #ifndef _PRGSBAR_HXX #include <svtools/prgsbar.hxx> #endif #ifndef INCLUDED_SWDLLAPI_H #include "swdllapi.h" #endif #ifndef _MAILMERGEHELPER_HXX #include "mailmergehelper.hxx" #endif class SwMailMergeWizard; class SfxPrinter; class SwSendMailDialog; namespace com{ namespace sun{ namespace star{ namespace mail{ class XMailMessage; } }}} /*-- 02.04.2004 09:21:06--------------------------------------------------- -----------------------------------------------------------------------*/ class SwMailMergeOutputPage : public svt::OWizardPage { SwBoldFixedInfo m_aHeaderFI; FixedInfo m_aOptionsFI; RadioButton m_aSaveStartDocRB; RadioButton m_aSaveMergedDocRB; RadioButton m_aPrintRB; RadioButton m_aSendMailRB; FixedLine m_aSeparatorFL; PushButton m_aSaveStartDocPB; RadioButton m_aSaveAsOneRB; RadioButton m_aSaveIndividualRB; RadioButton m_aPrintAllRB; //has to be here for tab control reasons RadioButton m_aSendAllRB; //has to be here for tab control reasons //this group is used in save and print RadioButton m_aFromRB; NumericField m_aFromNF; FixedText m_aToFT; NumericField m_aToNF; PushButton m_aSaveNowPB; FixedText m_aPrinterFT; ListBox m_aPrinterLB; PushButton m_aPrinterSettingsPB; PushButton m_aPrintNowPB; FixedText m_aMailToFT; ListBox m_aMailToLB; PushButton m_aCopyToPB; FixedText m_aSubjectFT; Edit m_aSubjectED; FixedText m_aSendAsFT; ListBox m_aSendAsLB; FixedText m_aAttachmentFT; Edit m_aAttachmentED; PushButton m_aSendAsPB; PushButton m_aSendDocumentsPB; SwMailMergeWizard* m_pWizard; //some FixedLine labels String m_sSaveStartST; String m_sSaveMergedST; String m_sPrintST; String m_sSendMailST; //misc strings String m_sDefaultAttachmentST; String m_sNoSubjectQueryST; String m_sNoSubjectST; String m_sNoAttachmentNameST; String m_sConfigureMail; String m_sBody; long m_nFromToRBPos; long m_nFromToFTPos; long m_nFromToNFPos; long m_nRBOffset; //some dialog data Printer* m_pTempPrinter; SfxPrinter* m_pDocumentPrinterCopy; String m_sCC; String m_sBCC; DECL_LINK(OutputTypeHdl_Impl, RadioButton*); DECL_LINK(CopyToHdl_Impl, PushButton*); DECL_LINK(SaveStartHdl_Impl, PushButton* ); DECL_LINK(SaveOutputHdl_Impl, PushButton* ); DECL_LINK(PrinterChangeHdl_Impl, ListBox* ); DECL_LINK(PrintHdl_Impl, PushButton* ); DECL_LINK(PrinterSetupHdl_Impl, PushButton* ); DECL_LINK(SendTypeHdl_Impl, ListBox*); DECL_LINK(SendAsHdl_Impl, PushButton*); DECL_LINK(SendDocumentsHdl_Impl, PushButton*); protected: virtual sal_Bool determineNextButtonState(); virtual void ActivatePage(); public: SwMailMergeOutputPage( SwMailMergeWizard* _pParent); ~SwMailMergeOutputPage(); }; /*-- 21.05.2004 12:48:50--------------------------------------------------- -----------------------------------------------------------------------*/ struct SwMailDescriptor { ::rtl::OUString sEMail; ::rtl::OUString sAttachmentURL; ::rtl::OUString sAttachmentName; ::rtl::OUString sMimeType; ::rtl::OUString sSubject; ::rtl::OUString sBodyMimeType; ::rtl::OUString sBodyContent; ::rtl::OUString sCC; ::rtl::OUString sBCC; }; struct SwSendMailDialog_Impl; class MailProgressBar_Impl; class SwMailMergeConfigItem; class SW_DLLPUBLIC SwSendMailDialog : public ModelessDialog //SfxModalDialog { FixedLine m_aStatusFL; FixedText m_aStatusFT; FixedLine m_aTransferStatusFL; FixedText m_aTransferStatusFT; FixedInfo m_PausedFI; ProgressBar m_aProgressBar; FixedText m_aErrorStatusFT; PushButton m_aDetailsPB; HeaderBar m_aStatusHB; SvTabListBox m_aStatusLB; FixedLine m_aSeparatorFL; PushButton m_aStopPB; PushButton m_aClosePB; String m_sMore; String m_sLess; String m_sContinue; String m_sStop; String m_sSend; String m_sTransferStatus; String m_sErrorStatus; String m_sSendingTo; String m_sCompleted; String m_sFailed; String m_sTerminateQuery; bool m_bCancel; bool m_bDesctructionEnabled; ImageList m_aImageList; ImageList m_aImageListHC; SwSendMailDialog_Impl* m_pImpl; SwMailMergeConfigItem* m_pConfigItem; sal_Int32 m_nStatusHeight; sal_Int32 m_nSendCount; sal_Int32 m_nErrorCount; SW_DLLPRIVATE DECL_LINK( DetailsHdl_Impl, PushButton* ); SW_DLLPRIVATE DECL_LINK( StopHdl_Impl, PushButton* ); SW_DLLPRIVATE DECL_LINK( CloseHdl_Impl, PushButton* ); SW_DLLPRIVATE DECL_STATIC_LINK( SwSendMailDialog, StartSendMails, SwSendMailDialog* ); SW_DLLPRIVATE DECL_STATIC_LINK( SwSendMailDialog, StopSendMails, SwSendMailDialog* ); SW_DLLPRIVATE DECL_STATIC_LINK( SwSendMailDialog, RemoveThis, Timer* ); SW_DLLPRIVATE void IterateMails(); SW_DLLPRIVATE void SendMails(); SW_DLLPRIVATE void UpdateTransferStatus(); virtual void StateChanged( StateChangedType nStateChange ); public: SwSendMailDialog( Window* pParent, SwMailMergeConfigItem& ); ~SwSendMailDialog(); void AddDocument( SwMailDescriptor& rDesc ); void SetDocumentCount( sal_Int32 nAllDocuments ); void EnableDesctruction() {m_bDesctructionEnabled = true;} void Show(); void DocumentSent( ::com::sun::star::uno::Reference< ::com::sun::star::mail::XMailMessage>, bool bResult, const ::rtl::OUString* pError ); void AllMailsSent(); }; #endif <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: regexpmap.hxx,v $ * * $Revision: 1.2 $ * * last change: $Author: rt $ $Date: 2003-12-01 15:55:41 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (the "License"); You may not use this file * except in compliance with the License. You may obtain a copy of the * License at http://www.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #ifndef _UCB_REGEXPMAP_HXX_ #define _UCB_REGEXPMAP_HXX_ #ifndef _RTL_OUSTRING_HXX_ #include <rtl/ustring.hxx> #endif #ifndef _SAL_TYPES_H_ #include <sal/types.h> #endif namespace ucb { template< typename Val > class RegexpMap; template< typename Val > class RegexpMapIter; //============================================================================ template< typename Val > class RegexpMapEntry { public: inline RegexpMapEntry(rtl::OUString const & rTheRegexp, Val * pTheValue): m_aRegexp(rTheRegexp), m_pValue(pTheValue) {} rtl::OUString getRegexp() const { return m_aRegexp; } Val const & getValue() const { return *m_pValue; } Val & getValue() { return *m_pValue; } private: rtl::OUString m_aRegexp; Val * m_pValue; }; //============================================================================ template< typename Val > class RegexpMapIterImpl; // MSC doesn't like this to be a private RegexpMapConstIter member // class... template< typename Val > class RegexpMapConstIter { friend class RegexpMap< Val >; // to access m_pImpl, ctor friend class RegexpMapIter< Val >; // to access m_pImpl, ctor public: RegexpMapConstIter(); RegexpMapConstIter(RegexpMapConstIter const & rOther); ~RegexpMapConstIter(); RegexpMapConstIter & operator =(RegexpMapConstIter const & rOther); RegexpMapConstIter & operator ++(); RegexpMapConstIter operator ++(int); RegexpMapEntry< Val > const & operator *() const; RegexpMapEntry< Val > const * operator ->() const; bool equals(RegexpMapConstIter const & rOther) const; // for free operator ==(), operator !=() private: RegexpMapIterImpl< Val > * m_pImpl; RegexpMapConstIter(RegexpMapIterImpl< Val > * pTheImpl); }; //============================================================================ template< typename Val > class RegexpMapIter: public RegexpMapConstIter< Val > { friend class RegexpMap< Val >; // to access ctor public: RegexpMapIter() {} RegexpMapIter & operator ++(); RegexpMapIter operator ++(int); RegexpMapEntry< Val > & operator *(); RegexpMapEntry< Val > const & operator *() const; RegexpMapEntry< Val > * operator ->(); RegexpMapEntry< Val > const * operator ->() const; private: RegexpMapIter(RegexpMapIterImpl< Val > * pTheImpl); }; //============================================================================ template< typename Val > struct RegexpMapImpl; // MSC doesn't like this to be a RegexpMap member class... template< typename Val > class RegexpMap { public: typedef sal_uInt32 size_type; typedef RegexpMapIter< Val > iterator; typedef RegexpMapConstIter< Val > const_iterator; RegexpMap(); RegexpMap(RegexpMap const & rOther); ~RegexpMap(); RegexpMap & operator =(RegexpMap const & rOther); bool add(rtl::OUString const & rKey, Val const & rValue, bool bOverwrite, rtl::OUString * pReverse = 0); // throws com::sun::star::lang::IllegalArgumentException iterator find(rtl::OUString const & rKey, rtl::OUString * pReverse = 0); // throws com::sun::star::lang::IllegalArgumentException void erase(iterator const & rPos); iterator begin(); const_iterator begin() const; iterator end(); const_iterator end() const; bool empty() const; size_type size() const; Val const * map(rtl::OUString const & rString, rtl::OUString * pTranslation = 0, bool * pTranslated = 0) const; private: RegexpMapImpl< Val > * m_pImpl; }; } //============================================================================ template< typename Val > inline bool operator ==(ucb::RegexpMapConstIter< Val > const & rIter1, ucb::RegexpMapConstIter< Val > const & rIter2) { return rIter1.equals(rIter2); } template< typename Val > inline bool operator !=(ucb::RegexpMapConstIter< Val > const & rIter1, ucb::RegexpMapConstIter< Val > const & rIter2) { return !rIter1.equals(rIter2); } #endif // _UCB_REGEXPMAP_HXX_ <commit_msg>INTEGRATION: CWS ooo19126 (1.2.124); FILE MERGED 2005/09/05 18:44:56 rt 1.2.124.1: #i54170# Change license header: remove SISSL<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: regexpmap.hxx,v $ * * $Revision: 1.3 $ * * last change: $Author: rt $ $Date: 2005-09-09 15:18:30 $ * * 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 _UCB_REGEXPMAP_HXX_ #define _UCB_REGEXPMAP_HXX_ #ifndef _RTL_OUSTRING_HXX_ #include <rtl/ustring.hxx> #endif #ifndef _SAL_TYPES_H_ #include <sal/types.h> #endif namespace ucb { template< typename Val > class RegexpMap; template< typename Val > class RegexpMapIter; //============================================================================ template< typename Val > class RegexpMapEntry { public: inline RegexpMapEntry(rtl::OUString const & rTheRegexp, Val * pTheValue): m_aRegexp(rTheRegexp), m_pValue(pTheValue) {} rtl::OUString getRegexp() const { return m_aRegexp; } Val const & getValue() const { return *m_pValue; } Val & getValue() { return *m_pValue; } private: rtl::OUString m_aRegexp; Val * m_pValue; }; //============================================================================ template< typename Val > class RegexpMapIterImpl; // MSC doesn't like this to be a private RegexpMapConstIter member // class... template< typename Val > class RegexpMapConstIter { friend class RegexpMap< Val >; // to access m_pImpl, ctor friend class RegexpMapIter< Val >; // to access m_pImpl, ctor public: RegexpMapConstIter(); RegexpMapConstIter(RegexpMapConstIter const & rOther); ~RegexpMapConstIter(); RegexpMapConstIter & operator =(RegexpMapConstIter const & rOther); RegexpMapConstIter & operator ++(); RegexpMapConstIter operator ++(int); RegexpMapEntry< Val > const & operator *() const; RegexpMapEntry< Val > const * operator ->() const; bool equals(RegexpMapConstIter const & rOther) const; // for free operator ==(), operator !=() private: RegexpMapIterImpl< Val > * m_pImpl; RegexpMapConstIter(RegexpMapIterImpl< Val > * pTheImpl); }; //============================================================================ template< typename Val > class RegexpMapIter: public RegexpMapConstIter< Val > { friend class RegexpMap< Val >; // to access ctor public: RegexpMapIter() {} RegexpMapIter & operator ++(); RegexpMapIter operator ++(int); RegexpMapEntry< Val > & operator *(); RegexpMapEntry< Val > const & operator *() const; RegexpMapEntry< Val > * operator ->(); RegexpMapEntry< Val > const * operator ->() const; private: RegexpMapIter(RegexpMapIterImpl< Val > * pTheImpl); }; //============================================================================ template< typename Val > struct RegexpMapImpl; // MSC doesn't like this to be a RegexpMap member class... template< typename Val > class RegexpMap { public: typedef sal_uInt32 size_type; typedef RegexpMapIter< Val > iterator; typedef RegexpMapConstIter< Val > const_iterator; RegexpMap(); RegexpMap(RegexpMap const & rOther); ~RegexpMap(); RegexpMap & operator =(RegexpMap const & rOther); bool add(rtl::OUString const & rKey, Val const & rValue, bool bOverwrite, rtl::OUString * pReverse = 0); // throws com::sun::star::lang::IllegalArgumentException iterator find(rtl::OUString const & rKey, rtl::OUString * pReverse = 0); // throws com::sun::star::lang::IllegalArgumentException void erase(iterator const & rPos); iterator begin(); const_iterator begin() const; iterator end(); const_iterator end() const; bool empty() const; size_type size() const; Val const * map(rtl::OUString const & rString, rtl::OUString * pTranslation = 0, bool * pTranslated = 0) const; private: RegexpMapImpl< Val > * m_pImpl; }; } //============================================================================ template< typename Val > inline bool operator ==(ucb::RegexpMapConstIter< Val > const & rIter1, ucb::RegexpMapConstIter< Val > const & rIter2) { return rIter1.equals(rIter2); } template< typename Val > inline bool operator !=(ucb::RegexpMapConstIter< Val > const & rIter1, ucb::RegexpMapConstIter< Val > const & rIter2) { return !rIter1.equals(rIter2); } #endif // _UCB_REGEXPMAP_HXX_ <|endoftext|>
<commit_before>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ /* * This file is part of the LibreOffice project. * * 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/. * * This file incorporates work covered by the following license notice: * * 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 . */ #include <tools/urlobj.hxx> #include <vcl/dialog.hxx> #include <vcl/msgbox.hxx> #include <vcl/button.hxx> #include <vcl/fixed.hxx> #include <vcl/lstbox.hxx> #include <svl/fstathelper.hxx> #include <unotools/pathoptions.hxx> #include <unotools/transliterationwrapper.hxx> #include <swtypes.hxx> #include <swmodule.hxx> #include <shellio.hxx> #include <initui.hxx> #include <glosdoc.hxx> #include <gloslst.hxx> #include <swunohelper.hxx> #include <vector> #include <utlui.hrc> #define STRING_DELIM (char)0x0A #define GLOS_TIMEOUT 30000 // update every 30 seconds #define FIND_MAX_GLOS 20 struct TripleString { OUString sGroup; OUString sBlock; OUString sShort; }; class SwGlossDecideDlg : public ModalDialog { OKButton* m_pOk; ListBox* m_pListLB; DECL_LINK(DoubleClickHdl, void*); DECL_LINK(SelectHdl, void*); public: SwGlossDecideDlg(Window* pParent); ListBox& GetListBox() {return *m_pListLB;} }; SwGlossDecideDlg::SwGlossDecideDlg(Window* pParent) : ModalDialog(pParent, "SelectAutoTextDialog", "modules/swriter/ui/selectautotextdialog.ui") { get(m_pOk, "ok"); get(m_pListLB, "treeview"); m_pListLB->set_height_request(m_pListLB->GetTextHeight() * 10); m_pListLB->SetDoubleClickHdl(LINK(this, SwGlossDecideDlg, DoubleClickHdl)); m_pListLB->SetSelectHdl(LINK(this, SwGlossDecideDlg, SelectHdl)); } IMPL_LINK_NOARG(SwGlossDecideDlg, DoubleClickHdl) { EndDialog(RET_OK); return 0; } IMPL_LINK_NOARG(SwGlossDecideDlg, SelectHdl) { m_pOk->Enable(LISTBOX_ENTRY_NOTFOUND != m_pListLB->GetSelectEntryPos()); return 0; } SwGlossaryList::SwGlossaryList() : bFilled(false) { SvtPathOptions aPathOpt; sPath = aPathOpt.GetAutoTextPath(); SetTimeout(GLOS_TIMEOUT); } SwGlossaryList::~SwGlossaryList() { ClearGroups(); } // If the GroupName is already known, then only rShortName // will be filled. Otherwise also rGroupName will be set and // on demand asked for the right group. bool SwGlossaryList::GetShortName(const OUString& rLongName, OUString& rShortName, OUString& rGroupName ) { if(!bFilled) Update(); std::vector<TripleString> aTripleStrings; size_t nCount = aGroupArr.size(); for(size_t i = 0; i < nCount; i++ ) { AutoTextGroup* pGroup = aGroupArr[i]; if(!rGroupName.isEmpty() && rGroupName != pGroup->sName) continue; for(sal_uInt16 j = 0; j < pGroup->nCount; j++) { OUString sLong = pGroup->sLongNames.getToken(j, STRING_DELIM); if(rLongName != sLong) continue; TripleString pTriple; pTriple.sGroup = pGroup->sName; pTriple.sBlock = sLong; pTriple.sShort = pGroup->sShortNames.getToken(j, STRING_DELIM); aTripleStrings.push_back(pTriple); } } bool bRet = false; nCount = aTripleStrings.size(); if(1 == nCount) { const TripleString& pTriple(aTripleStrings.front()); rShortName = pTriple.sShort; rGroupName = pTriple.sGroup; bRet = true; } else if(1 < nCount) { SwGlossDecideDlg aDlg(0); OUString sTitle = aDlg.GetText() + " " + aTripleStrings.front().sBlock; aDlg.SetText(sTitle); ListBox& rLB = aDlg.GetListBox(); for(std::vector<TripleString>::const_iterator i = aTripleStrings.begin(); i != aTripleStrings.end(); ++i) rLB.InsertEntry(i->sGroup.getToken(0, GLOS_DELIM)); rLB.SelectEntryPos(0); if(RET_OK == aDlg.Execute() && LISTBOX_ENTRY_NOTFOUND != rLB.GetSelectEntryPos()) { const TripleString& pTriple(aTripleStrings[rLB.GetSelectEntryPos()]); rShortName = pTriple.sShort; rGroupName = pTriple.sGroup; bRet = true; } else bRet = false; } return bRet; } sal_uInt16 SwGlossaryList::GetGroupCount() { if(!bFilled) Update(); return aGroupArr.size(); } OUString SwGlossaryList::GetGroupName(sal_uInt16 nPos, bool bNoPath) { OSL_ENSURE(aGroupArr.size() > nPos, "group not available"); if(nPos < aGroupArr.size()) { AutoTextGroup* pGroup = aGroupArr[nPos]; OUString sRet = pGroup->sName; if(bNoPath) sRet = sRet.getToken(0, GLOS_DELIM); return sRet; } return OUString(); } OUString SwGlossaryList::GetGroupTitle(sal_uInt16 nPos) { OSL_ENSURE(aGroupArr.size() > nPos, "group not available"); if(nPos < aGroupArr.size()) { AutoTextGroup* pGroup = aGroupArr[nPos]; return pGroup->sTitle; } return OUString(); } sal_uInt16 SwGlossaryList::GetBlockCount(sal_uInt16 nGroup) { OSL_ENSURE(aGroupArr.size() > nGroup, "group not available"); if(nGroup < aGroupArr.size()) { AutoTextGroup* pGroup = aGroupArr[nGroup]; return pGroup->nCount; } return 0; } OUString SwGlossaryList::GetBlockLongName(sal_uInt16 nGroup, sal_uInt16 nBlock) { OSL_ENSURE(aGroupArr.size() > nGroup, "group not available"); if(nGroup < aGroupArr.size()) { AutoTextGroup* pGroup = aGroupArr[nGroup]; return pGroup->sLongNames.getToken(nBlock, STRING_DELIM); } return OUString(); } OUString SwGlossaryList::GetBlockShortName(sal_uInt16 nGroup, sal_uInt16 nBlock) { OSL_ENSURE(aGroupArr.size() > nGroup, "group not available"); if(nGroup < aGroupArr.size()) { AutoTextGroup* pGroup = aGroupArr[nGroup]; return pGroup->sShortNames.getToken(nBlock, STRING_DELIM); } return OUString(); } void SwGlossaryList::Update() { if(!IsActive()) Start(); SvtPathOptions aPathOpt; OUString sTemp( aPathOpt.GetAutoTextPath() ); if(sTemp != sPath) { sPath = sTemp; bFilled = false; ClearGroups(); } SwGlossaries* pGlossaries = ::GetGlossaries(); const std::vector<OUString> & rPathArr = pGlossaries->GetPathArray(); const OUString sExt( SwGlossaries::GetExtension() ); if(!bFilled) { const sal_uInt16 nGroupCount = pGlossaries->GetGroupCnt(); for(sal_uInt16 i = 0; i < nGroupCount; i++) { OUString sGrpName = pGlossaries->GetGroupName(i); const size_t nPath = static_cast<size_t>( sGrpName.getToken(1, GLOS_DELIM).toInt32()); if( nPath < rPathArr.size() ) { AutoTextGroup* pGroup = new AutoTextGroup; pGroup->sName = sGrpName; FillGroup(pGroup, pGlossaries); OUString sName = rPathArr[nPath] + "/" + pGroup->sName.getToken(0, GLOS_DELIM) + sExt; FStatHelper::GetModifiedDateTimeOfFile( sName, &pGroup->aDateModified, &pGroup->aDateModified ); aGroupArr.insert( aGroupArr.begin(), pGroup ); } } bFilled = true; } else { for( size_t nPath = 0; nPath < rPathArr.size(); nPath++ ) { std::vector<OUString> aFoundGroupNames; std::vector<OUString> aFiles; std::vector<DateTime*> aDateTimeArr; SWUnoHelper::UCB_GetFileListOfFolder( rPathArr[nPath], aFiles, &sExt, &aDateTimeArr ); for( size_t nFiles = 0; nFiles < aFiles.size(); ++nFiles ) { const OUString aTitle = aFiles[ nFiles ]; ::DateTime* pDT = (::DateTime*) aDateTimeArr[ nFiles ]; OUString sName( aTitle.copy( 0, aTitle.getLength() - sExt.getLength() )); aFoundGroupNames.push_back(sName); sName += OUString(GLOS_DELIM) + OUString::number( static_cast<sal_uInt16>(nPath) ); AutoTextGroup* pFound = FindGroup( sName ); if( !pFound ) { pFound = new AutoTextGroup; pFound->sName = sName; FillGroup( pFound, pGlossaries ); pFound->aDateModified = *pDT; aGroupArr.push_back(pFound); } else if( pFound->aDateModified < *pDT ) { FillGroup(pFound, pGlossaries); pFound->aDateModified = *pDT; } // don't need any more these pointers delete pDT; } const size_t nArrCount = aGroupArr.size(); for( size_t i = nArrCount; i; --i) { // maybe remove deleted groups AutoTextGroup* pGroup = aGroupArr[i - 1]; const size_t nGroupPath = static_cast<size_t>( pGroup->sName.getToken( 1, GLOS_DELIM).toInt32()); // Only the groups will be checked which are registered // for the current subpath. if( nGroupPath == nPath ) { bool bFound = false; OUString sCompareGroup = pGroup->sName.getToken(0, GLOS_DELIM); for(std::vector<OUString>::const_iterator j = aFoundGroupNames.begin(); j != aFoundGroupNames.end() && !bFound; ++j) bFound = (sCompareGroup == *j); if(!bFound) { aGroupArr.erase(aGroupArr.begin() + i - 1); delete pGroup; } } } } } } void SwGlossaryList::Timeout() { // Only update automatically if a SwView has the focus. if(::GetActiveView()) Update(); } AutoTextGroup* SwGlossaryList::FindGroup(const OUString& rGroupName) { for(size_t i = 0; i < aGroupArr.size(); ++i) { AutoTextGroup* pRet = aGroupArr[i]; if(pRet->sName == rGroupName) return pRet; } return 0; } void SwGlossaryList::FillGroup(AutoTextGroup* pGroup, SwGlossaries* pGlossaries) { SwTextBlocks* pBlock = pGlossaries->GetGroupDoc(pGroup->sName); pGroup->nCount = pBlock ? pBlock->GetCount() : 0; pGroup->sLongNames = pGroup->sShortNames = OUString(); if(pBlock) pGroup->sTitle = pBlock->GetName(); for(sal_uInt16 j = 0; j < pGroup->nCount; j++) { pGroup->sLongNames += pBlock->GetLongName(j); pGroup->sLongNames += OUString(STRING_DELIM); pGroup->sShortNames += pBlock->GetShortName(j); pGroup->sShortNames += OUString(STRING_DELIM); } pGlossaries->PutGroupDoc(pBlock); } // Give back all (not exceeding FIND_MAX_GLOS) found modules // with matching beginning. bool SwGlossaryList::HasLongName(const OUString& rBegin, std::vector<OUString> *pLongNames) { if(!bFilled) Update(); sal_uInt16 nFound = 0; const size_t nCount = aGroupArr.size(); sal_Int32 nBeginLen = rBegin.getLength(); const ::utl::TransliterationWrapper& rSCmp = GetAppCmpStrIgnore(); for(size_t i = 0; i < nCount; ++i) { AutoTextGroup* pGroup = aGroupArr[i]; for(sal_uInt16 j = 0; j < pGroup->nCount; j++) { OUString sBlock = pGroup->sLongNames.getToken(j, STRING_DELIM); if( nBeginLen + 1 < sBlock.getLength() && rSCmp.isEqual( sBlock.copy(0, nBeginLen), rBegin )) { pLongNames->push_back( sBlock ); nFound++; if(FIND_MAX_GLOS == nFound) break; } } } return nFound > 0; } void SwGlossaryList::ClearGroups() { const size_t nCount = aGroupArr.size(); for( size_t i = 0; i < nCount; ++i ) delete aGroupArr[ i ]; aGroupArr.clear(); bFilled = false; } /* vim:set shiftwidth=4 softtabstop=4 expandtab: */ <commit_msg>Avoid temporary and reduce computations<commit_after>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ /* * This file is part of the LibreOffice project. * * 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/. * * This file incorporates work covered by the following license notice: * * 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 . */ #include <tools/urlobj.hxx> #include <vcl/dialog.hxx> #include <vcl/msgbox.hxx> #include <vcl/button.hxx> #include <vcl/fixed.hxx> #include <vcl/lstbox.hxx> #include <svl/fstathelper.hxx> #include <unotools/pathoptions.hxx> #include <unotools/transliterationwrapper.hxx> #include <swtypes.hxx> #include <swmodule.hxx> #include <shellio.hxx> #include <initui.hxx> #include <glosdoc.hxx> #include <gloslst.hxx> #include <swunohelper.hxx> #include <vector> #include <utlui.hrc> #define STRING_DELIM (char)0x0A #define GLOS_TIMEOUT 30000 // update every 30 seconds #define FIND_MAX_GLOS 20 struct TripleString { OUString sGroup; OUString sBlock; OUString sShort; }; class SwGlossDecideDlg : public ModalDialog { OKButton* m_pOk; ListBox* m_pListLB; DECL_LINK(DoubleClickHdl, void*); DECL_LINK(SelectHdl, void*); public: SwGlossDecideDlg(Window* pParent); ListBox& GetListBox() {return *m_pListLB;} }; SwGlossDecideDlg::SwGlossDecideDlg(Window* pParent) : ModalDialog(pParent, "SelectAutoTextDialog", "modules/swriter/ui/selectautotextdialog.ui") { get(m_pOk, "ok"); get(m_pListLB, "treeview"); m_pListLB->set_height_request(m_pListLB->GetTextHeight() * 10); m_pListLB->SetDoubleClickHdl(LINK(this, SwGlossDecideDlg, DoubleClickHdl)); m_pListLB->SetSelectHdl(LINK(this, SwGlossDecideDlg, SelectHdl)); } IMPL_LINK_NOARG(SwGlossDecideDlg, DoubleClickHdl) { EndDialog(RET_OK); return 0; } IMPL_LINK_NOARG(SwGlossDecideDlg, SelectHdl) { m_pOk->Enable(LISTBOX_ENTRY_NOTFOUND != m_pListLB->GetSelectEntryPos()); return 0; } SwGlossaryList::SwGlossaryList() : bFilled(false) { SvtPathOptions aPathOpt; sPath = aPathOpt.GetAutoTextPath(); SetTimeout(GLOS_TIMEOUT); } SwGlossaryList::~SwGlossaryList() { ClearGroups(); } // If the GroupName is already known, then only rShortName // will be filled. Otherwise also rGroupName will be set and // on demand asked for the right group. bool SwGlossaryList::GetShortName(const OUString& rLongName, OUString& rShortName, OUString& rGroupName ) { if(!bFilled) Update(); std::vector<TripleString> aTripleStrings; size_t nCount = aGroupArr.size(); for(size_t i = 0; i < nCount; i++ ) { AutoTextGroup* pGroup = aGroupArr[i]; if(!rGroupName.isEmpty() && rGroupName != pGroup->sName) continue; for(sal_uInt16 j = 0; j < pGroup->nCount; j++) { OUString sLong = pGroup->sLongNames.getToken(j, STRING_DELIM); if(rLongName != sLong) continue; TripleString pTriple; pTriple.sGroup = pGroup->sName; pTriple.sBlock = sLong; pTriple.sShort = pGroup->sShortNames.getToken(j, STRING_DELIM); aTripleStrings.push_back(pTriple); } } bool bRet = false; nCount = aTripleStrings.size(); if(1 == nCount) { const TripleString& pTriple(aTripleStrings.front()); rShortName = pTriple.sShort; rGroupName = pTriple.sGroup; bRet = true; } else if(1 < nCount) { SwGlossDecideDlg aDlg(0); OUString sTitle = aDlg.GetText() + " " + aTripleStrings.front().sBlock; aDlg.SetText(sTitle); ListBox& rLB = aDlg.GetListBox(); for(std::vector<TripleString>::const_iterator i = aTripleStrings.begin(); i != aTripleStrings.end(); ++i) rLB.InsertEntry(i->sGroup.getToken(0, GLOS_DELIM)); rLB.SelectEntryPos(0); if(RET_OK == aDlg.Execute() && LISTBOX_ENTRY_NOTFOUND != rLB.GetSelectEntryPos()) { const TripleString& pTriple(aTripleStrings[rLB.GetSelectEntryPos()]); rShortName = pTriple.sShort; rGroupName = pTriple.sGroup; bRet = true; } else bRet = false; } return bRet; } sal_uInt16 SwGlossaryList::GetGroupCount() { if(!bFilled) Update(); return aGroupArr.size(); } OUString SwGlossaryList::GetGroupName(sal_uInt16 nPos, bool bNoPath) { OSL_ENSURE(aGroupArr.size() > nPos, "group not available"); if(nPos < aGroupArr.size()) { AutoTextGroup* pGroup = aGroupArr[nPos]; OUString sRet = pGroup->sName; if(bNoPath) sRet = sRet.getToken(0, GLOS_DELIM); return sRet; } return OUString(); } OUString SwGlossaryList::GetGroupTitle(sal_uInt16 nPos) { OSL_ENSURE(aGroupArr.size() > nPos, "group not available"); if(nPos < aGroupArr.size()) { AutoTextGroup* pGroup = aGroupArr[nPos]; return pGroup->sTitle; } return OUString(); } sal_uInt16 SwGlossaryList::GetBlockCount(sal_uInt16 nGroup) { OSL_ENSURE(aGroupArr.size() > nGroup, "group not available"); if(nGroup < aGroupArr.size()) { AutoTextGroup* pGroup = aGroupArr[nGroup]; return pGroup->nCount; } return 0; } OUString SwGlossaryList::GetBlockLongName(sal_uInt16 nGroup, sal_uInt16 nBlock) { OSL_ENSURE(aGroupArr.size() > nGroup, "group not available"); if(nGroup < aGroupArr.size()) { AutoTextGroup* pGroup = aGroupArr[nGroup]; return pGroup->sLongNames.getToken(nBlock, STRING_DELIM); } return OUString(); } OUString SwGlossaryList::GetBlockShortName(sal_uInt16 nGroup, sal_uInt16 nBlock) { OSL_ENSURE(aGroupArr.size() > nGroup, "group not available"); if(nGroup < aGroupArr.size()) { AutoTextGroup* pGroup = aGroupArr[nGroup]; return pGroup->sShortNames.getToken(nBlock, STRING_DELIM); } return OUString(); } void SwGlossaryList::Update() { if(!IsActive()) Start(); SvtPathOptions aPathOpt; OUString sTemp( aPathOpt.GetAutoTextPath() ); if(sTemp != sPath) { sPath = sTemp; bFilled = false; ClearGroups(); } SwGlossaries* pGlossaries = ::GetGlossaries(); const std::vector<OUString> & rPathArr = pGlossaries->GetPathArray(); const OUString sExt( SwGlossaries::GetExtension() ); if(!bFilled) { const sal_uInt16 nGroupCount = pGlossaries->GetGroupCnt(); for(sal_uInt16 i = 0; i < nGroupCount; i++) { OUString sGrpName = pGlossaries->GetGroupName(i); const size_t nPath = static_cast<size_t>( sGrpName.getToken(1, GLOS_DELIM).toInt32()); if( nPath < rPathArr.size() ) { AutoTextGroup* pGroup = new AutoTextGroup; pGroup->sName = sGrpName; FillGroup(pGroup, pGlossaries); OUString sName = rPathArr[nPath] + "/" + pGroup->sName.getToken(0, GLOS_DELIM) + sExt; FStatHelper::GetModifiedDateTimeOfFile( sName, &pGroup->aDateModified, &pGroup->aDateModified ); aGroupArr.insert( aGroupArr.begin(), pGroup ); } } bFilled = true; } else { for( size_t nPath = 0; nPath < rPathArr.size(); nPath++ ) { std::vector<OUString> aFoundGroupNames; std::vector<OUString> aFiles; std::vector<DateTime*> aDateTimeArr; SWUnoHelper::UCB_GetFileListOfFolder( rPathArr[nPath], aFiles, &sExt, &aDateTimeArr ); for( size_t nFiles = 0; nFiles < aFiles.size(); ++nFiles ) { const OUString aTitle = aFiles[ nFiles ]; ::DateTime* pDT = (::DateTime*) aDateTimeArr[ nFiles ]; OUString sName( aTitle.copy( 0, aTitle.getLength() - sExt.getLength() )); aFoundGroupNames.push_back(sName); sName += OUString(GLOS_DELIM) + OUString::number( static_cast<sal_uInt16>(nPath) ); AutoTextGroup* pFound = FindGroup( sName ); if( !pFound ) { pFound = new AutoTextGroup; pFound->sName = sName; FillGroup( pFound, pGlossaries ); pFound->aDateModified = *pDT; aGroupArr.push_back(pFound); } else if( pFound->aDateModified < *pDT ) { FillGroup(pFound, pGlossaries); pFound->aDateModified = *pDT; } // don't need any more these pointers delete pDT; } for( size_t i = aGroupArr.size(); i>0; ) { --i; // maybe remove deleted groups AutoTextGroup* pGroup = aGroupArr[i]; const size_t nGroupPath = static_cast<size_t>( pGroup->sName.getToken( 1, GLOS_DELIM).toInt32()); // Only the groups will be checked which are registered // for the current subpath. if( nGroupPath == nPath ) { bool bFound = false; OUString sCompareGroup = pGroup->sName.getToken(0, GLOS_DELIM); for(std::vector<OUString>::const_iterator j = aFoundGroupNames.begin(); j != aFoundGroupNames.end() && !bFound; ++j) bFound = (sCompareGroup == *j); if(!bFound) { aGroupArr.erase(aGroupArr.begin() + i); delete pGroup; } } } } } } void SwGlossaryList::Timeout() { // Only update automatically if a SwView has the focus. if(::GetActiveView()) Update(); } AutoTextGroup* SwGlossaryList::FindGroup(const OUString& rGroupName) { for(size_t i = 0; i < aGroupArr.size(); ++i) { AutoTextGroup* pRet = aGroupArr[i]; if(pRet->sName == rGroupName) return pRet; } return 0; } void SwGlossaryList::FillGroup(AutoTextGroup* pGroup, SwGlossaries* pGlossaries) { SwTextBlocks* pBlock = pGlossaries->GetGroupDoc(pGroup->sName); pGroup->nCount = pBlock ? pBlock->GetCount() : 0; pGroup->sLongNames = pGroup->sShortNames = OUString(); if(pBlock) pGroup->sTitle = pBlock->GetName(); for(sal_uInt16 j = 0; j < pGroup->nCount; j++) { pGroup->sLongNames += pBlock->GetLongName(j); pGroup->sLongNames += OUString(STRING_DELIM); pGroup->sShortNames += pBlock->GetShortName(j); pGroup->sShortNames += OUString(STRING_DELIM); } pGlossaries->PutGroupDoc(pBlock); } // Give back all (not exceeding FIND_MAX_GLOS) found modules // with matching beginning. bool SwGlossaryList::HasLongName(const OUString& rBegin, std::vector<OUString> *pLongNames) { if(!bFilled) Update(); sal_uInt16 nFound = 0; const size_t nCount = aGroupArr.size(); sal_Int32 nBeginLen = rBegin.getLength(); const ::utl::TransliterationWrapper& rSCmp = GetAppCmpStrIgnore(); for(size_t i = 0; i < nCount; ++i) { AutoTextGroup* pGroup = aGroupArr[i]; for(sal_uInt16 j = 0; j < pGroup->nCount; j++) { OUString sBlock = pGroup->sLongNames.getToken(j, STRING_DELIM); if( nBeginLen + 1 < sBlock.getLength() && rSCmp.isEqual( sBlock.copy(0, nBeginLen), rBegin )) { pLongNames->push_back( sBlock ); nFound++; if(FIND_MAX_GLOS == nFound) break; } } } return nFound > 0; } void SwGlossaryList::ClearGroups() { const size_t nCount = aGroupArr.size(); for( size_t i = 0; i < nCount; ++i ) delete aGroupArr[ i ]; aGroupArr.clear(); bFilled = false; } /* vim:set shiftwidth=4 softtabstop=4 expandtab: */ <|endoftext|>
<commit_before>// math_cart3d_baseline.cc -- reprsentative small test computations // IEEE double precision #include <cmath> #include <stdio.h> #include <gtest/gtest.h> #include "math/Cart3d.h" using namespace cart3; void print_cart3d(Cart3d& vec) { printf("%4.2f %4.2f %4.2f\n", vec[0], vec[1], vec[2]); } void print_cart3d(const Cart3d& vec) { Cart3d v = vec; print_cart3d(v); } const Cart3d vector_345 = Cart3d(3.0, 4.0, 5.0); const Cart3d vector_100 = Cart3d(1.0, 0.0, 0.0); const Cart3d vector_010 = Cart3d(0.0, 1.0, 0.0); const Cart3d vector_001 = Cart3d(0.0, 0.0, 1.0); const Cart3d vector_zero = Cart3d(0.0, 0.0, 0.0); TEST(MathCart3dBaseline, First) { Cart3d a = Cart3d(0.0, 1.0, 2.0); EXPECT_EQ(a[0], 0.0); print_cart3d(a); } TEST(MathCart3dBaseline, CompoundAsgnAdd) { Cart3d sum = vector_345; sum += vector_100; sum += vector_010; sum += vector_001; EXPECT_EQ(vector_345, Cart3d(3.0, 4.0, 5.0)); EXPECT_EQ(sum, Cart3d(4.0, 5.0, 6.0)); Cart3d diff = vector_345; diff -= vector_100; EXPECT_EQ(diff, Cart3d(2.0, 4.0, 5.0)); } TEST(MathCart3dBaseline, CompoundAsgnMult) { Cart3d result = vector_345; result *= 2.0; EXPECT_EQ(result, Cart3d(6.0, 8.0, 10.0)); result /= 2.0; EXPECT_EQ(result, Cart3d(3.0, 4.0, 5.0)); } TEST(MathCart3dBaseline, Index) { enum { x=0, y=1, z=2 }; Cart3d a = Cart3d(0.0, 1.0, 2.0); EXPECT_EQ(a[x], 0.0); EXPECT_EQ(a[y], 1.0); EXPECT_EQ(a[z], 2.0); float a2 = a[x]; EXPECT_EQ(a2, 0.0); a[z] = a[x]; EXPECT_EQ(a[2], 0.0); EXPECT_EQ(a, Cart3d(0.0, 1.0, 0.0)); } TEST(MathCart3dBaseline, BinAdd) { Cart3d result = vector_100 + vector_010; EXPECT_EQ(result, Cart3d(1.0, 1.0, 0.0)); result = vector_100 - vector_010; EXPECT_EQ(result, Cart3d(1.0, -1.0, 0.0)); } TEST(MathCart3dBaseline, BinMult) { Cart3d result = vector_345 * 2.0; EXPECT_EQ(result, Cart3d(6.0, 8.0, 10.0)); result = vector_345 / 2.0; EXPECT_EQ(result, Cart3d(1.5, 2.0, 2.5)); } TEST(MathCart3dBaseline, BinMultSV) { // friend: scalar * vector Cart3d result = 2.0 * vector_345; EXPECT_EQ(result, Cart3d(6.0, 8.0, 10.0)); } TEST(MathCart3dBaseline, BinMultCross) { Cart3d result = vector_100 ^ vector_010; EXPECT_EQ(result, vector_001); } TEST(MathCart3dBaseline, BinMultDot) { float result = vector_100 * vector_010; EXPECT_EQ(result, 0.0); } TEST(MathCart3dBaseline, Unary) { Cart3d result = -vector_345; EXPECT_EQ(result, Cart3d(-3.0, -4.0, -5.0)); } <commit_msg>Scalar should be double-precision.<commit_after>// math_cart3d_baseline.cc -- reprsentative small test computations // IEEE double precision #include <cmath> #include <stdio.h> #include <gtest/gtest.h> #include "math/Cart3d.h" using namespace cart3; void print_cart3d(Cart3d& vec) { printf("%4.2f %4.2f %4.2f\n", vec[0], vec[1], vec[2]); } void print_cart3d(const Cart3d& vec) { Cart3d v = vec; print_cart3d(v); } const Cart3d vector_345 = Cart3d(3.0, 4.0, 5.0); const Cart3d vector_100 = Cart3d(1.0, 0.0, 0.0); const Cart3d vector_010 = Cart3d(0.0, 1.0, 0.0); const Cart3d vector_001 = Cart3d(0.0, 0.0, 1.0); const Cart3d vector_zero = Cart3d(0.0, 0.0, 0.0); TEST(MathCart3dBaseline, First) { Cart3d a = Cart3d(0.0, 1.0, 2.0); EXPECT_EQ(a[0], 0.0); print_cart3d(a); } TEST(MathCart3dBaseline, CompoundAsgnAdd) { Cart3d sum = vector_345; sum += vector_100; sum += vector_010; sum += vector_001; EXPECT_EQ(vector_345, Cart3d(3.0, 4.0, 5.0)); EXPECT_EQ(sum, Cart3d(4.0, 5.0, 6.0)); Cart3d diff = vector_345; diff -= vector_100; EXPECT_EQ(diff, Cart3d(2.0, 4.0, 5.0)); } TEST(MathCart3dBaseline, CompoundAsgnMult) { Cart3d result = vector_345; result *= 2.0; EXPECT_EQ(result, Cart3d(6.0, 8.0, 10.0)); result /= 2.0; EXPECT_EQ(result, Cart3d(3.0, 4.0, 5.0)); } TEST(MathCart3dBaseline, Index) { enum { x=0, y=1, z=2 }; Cart3d a = Cart3d(0.0, 1.0, 2.0); EXPECT_EQ(a[x], 0.0); EXPECT_EQ(a[y], 1.0); EXPECT_EQ(a[z], 2.0); double a2 = a[x]; EXPECT_EQ(a2, 0.0); a[z] = a[x]; EXPECT_EQ(a[2], 0.0); EXPECT_EQ(a, Cart3d(0.0, 1.0, 0.0)); } TEST(MathCart3dBaseline, BinAdd) { Cart3d result = vector_100 + vector_010; EXPECT_EQ(result, Cart3d(1.0, 1.0, 0.0)); result = vector_100 - vector_010; EXPECT_EQ(result, Cart3d(1.0, -1.0, 0.0)); } TEST(MathCart3dBaseline, BinMult) { Cart3d result = vector_345 * 2.0; EXPECT_EQ(result, Cart3d(6.0, 8.0, 10.0)); result = vector_345 / 2.0; EXPECT_EQ(result, Cart3d(1.5, 2.0, 2.5)); } TEST(MathCart3dBaseline, BinMultSV) { // friend: scalar * vector Cart3d result = 2.0 * vector_345; EXPECT_EQ(result, Cart3d(6.0, 8.0, 10.0)); } TEST(MathCart3dBaseline, BinMultCross) { Cart3d result = vector_100 ^ vector_010; EXPECT_EQ(result, vector_001); } TEST(MathCart3dBaseline, BinMultDot) { double result = vector_100 * vector_010; EXPECT_EQ(result, 0.0); } TEST(MathCart3dBaseline, Unary) { Cart3d result = -vector_345; EXPECT_EQ(result, Cart3d(-3.0, -4.0, -5.0)); } <|endoftext|>
<commit_before>// Copyright 2012 Software Freedom Conservancy // 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 "resource.h" #include "IEServer.h" // TODO(JimEvans): Change the prototypes of these functions in the // IEDriver project to match the prototype specified here. typedef void (__cdecl *STARTSERVERPROC)(int); typedef void (__cdecl *STOPSERVERPROC)(void); #define ERR_DLL_EXTRACT_FAIL 1 #define ERR_DLL_LOAD_FAIL 2 #define ERR_FUNCTION_NOT_FOUND 3 #define RESOURCE_TYPE L"BINARY" #define TEMP_FILE_PREFIX L"IEDriver" #define START_SERVER_API_NAME "StartServer" #define STOP_SERVER_API_NAME "StopServer" bool ExtractResource(unsigned short resource_id, const std::wstring& output_file_name) { bool success = false; try { // First find and load the required resource HRSRC resource_handle = ::FindResource(NULL, MAKEINTRESOURCE(resource_id), RESOURCE_TYPE); HGLOBAL global_resouce_handle = ::LoadResource(NULL, resource_handle); // Now open and map this to a disk file LPVOID file_pointer = ::LockResource(global_resouce_handle); DWORD resource_size = ::SizeofResource(NULL, resource_handle); // Open the file and filemap HANDLE file_handle = ::CreateFile(output_file_name.c_str(), GENERIC_READ | GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL); HANDLE file_mapping_handle = ::CreateFileMapping(file_handle, NULL, PAGE_READWRITE, 0, resource_size, NULL); LPVOID base_address_pointer = ::MapViewOfFile(file_mapping_handle, FILE_MAP_WRITE, 0, 0, 0); // Write the file ::CopyMemory(base_address_pointer, file_pointer, resource_size); // Unmap the file and close the handles ::UnmapViewOfFile(base_address_pointer); ::CloseHandle(file_mapping_handle); ::CloseHandle(file_handle); success = true; } catch(...) { // Ignore all type of errors } return success; } int GetPort(int argc, _TCHAR* argv[]) { int port = 5555; if (argc >=3) { std::wstring arg_name(argv[1]); std::wstring arg_value(argv[2]); if (arg_name == L"--port" || arg_name == L"-p" || arg_name == L"/port" || arg_name == L"/p") { port = _wtoi(arg_value.c_str()); } } return port; } int _tmain(int argc, _TCHAR* argv[]) { vector<TCHAR> temp_file_name_buffer(MAX_PATH); vector<TCHAR> temp_path_buffer(MAX_PATH); // Gets the temp path env string (no guarantee it's a valid path). unsigned long temp_path_length = ::GetTempPath(MAX_PATH, &temp_path_buffer[0]); unsigned int error_code = ::GetTempFileName(&temp_path_buffer[0], TEMP_FILE_PREFIX, 0, &temp_file_name_buffer[0]); std::wstring temp_file_name(&temp_file_name_buffer[0]); if (!ExtractResource(IDR_DRIVER_LIBRARY, temp_file_name)) { return ERR_DLL_EXTRACT_FAIL; } HMODULE module_handle = ::LoadLibrary(temp_file_name.c_str()); if (module_handle == NULL) { return ERR_DLL_LOAD_FAIL; } STARTSERVERPROC start_server_proc = reinterpret_cast<STARTSERVERPROC>( ::GetProcAddress(module_handle, START_SERVER_API_NAME)); STOPSERVERPROC stop_server_proc = reinterpret_cast<STOPSERVERPROC>( ::GetProcAddress(module_handle, STOP_SERVER_API_NAME)); if (start_server_proc == NULL || stop_server_proc == NULL) { return ERR_FUNCTION_NOT_FOUND; } int port = GetPort(argc, argv); start_server_proc(port); std::cout << "Listening on port " << port << std::endl; // Create the shutdown event and wait for it to be signaled. HANDLE event_handle = ::CreateEvent(NULL, TRUE, FALSE, IESERVER_SHUTDOWN_EVENT_NAME); ::WaitForSingleObject(event_handle, INFINITE); ::CloseHandle(event_handle); stop_server_proc(); ::FreeLibrary(module_handle); ::DeleteFile(temp_file_name.c_str()); return 0; } <commit_msg>JimEvans: Standalone IE driver server executable now uses same format for port command-line argument.<commit_after>// Copyright 2012 Software Freedom Conservancy // 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 "resource.h" #include "IEServer.h" // TODO(JimEvans): Change the prototypes of these functions in the // IEDriver project to match the prototype specified here. typedef void (__cdecl *STARTSERVERPROC)(int); typedef void (__cdecl *STOPSERVERPROC)(void); #define ERR_DLL_EXTRACT_FAIL 1 #define ERR_DLL_LOAD_FAIL 2 #define ERR_FUNCTION_NOT_FOUND 3 #define RESOURCE_TYPE L"BINARY" #define TEMP_FILE_PREFIX L"IEDriver" #define START_SERVER_API_NAME "StartServer" #define STOP_SERVER_API_NAME "StopServer" bool ExtractResource(unsigned short resource_id, const std::wstring& output_file_name) { bool success = false; try { // First find and load the required resource HRSRC resource_handle = ::FindResource(NULL, MAKEINTRESOURCE(resource_id), RESOURCE_TYPE); HGLOBAL global_resouce_handle = ::LoadResource(NULL, resource_handle); // Now open and map this to a disk file LPVOID file_pointer = ::LockResource(global_resouce_handle); DWORD resource_size = ::SizeofResource(NULL, resource_handle); // Open the file and filemap HANDLE file_handle = ::CreateFile(output_file_name.c_str(), GENERIC_READ | GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL); HANDLE file_mapping_handle = ::CreateFileMapping(file_handle, NULL, PAGE_READWRITE, 0, resource_size, NULL); LPVOID base_address_pointer = ::MapViewOfFile(file_mapping_handle, FILE_MAP_WRITE, 0, 0, 0); // Write the file ::CopyMemory(base_address_pointer, file_pointer, resource_size); // Unmap the file and close the handles ::UnmapViewOfFile(base_address_pointer); ::CloseHandle(file_mapping_handle); ::CloseHandle(file_handle); success = true; } catch(...) { // Ignore all type of errors } return success; } int GetPort(int argc, _TCHAR* argv[]) { int port = 5555; if (argc >= 2) { for (int i = 1; i < argc; i++) { std::wstring arg(argv[i]); if (arg.find(L"--port=") == 0 || arg.find(L"-port=") == 0 || arg.find(L"/port=") == 0) { int equal_pos = arg.find(L"="); std::wstring port_string = arg.substr(equal_pos + 1); int port_value = _wtoi(port_string.c_str()); if (port_value > 0) { port = port_value; } break; } } } return port; } int _tmain(int argc, _TCHAR* argv[]) { vector<TCHAR> temp_file_name_buffer(MAX_PATH); vector<TCHAR> temp_path_buffer(MAX_PATH); // Gets the temp path env string (no guarantee it's a valid path). unsigned long temp_path_length = ::GetTempPath(MAX_PATH, &temp_path_buffer[0]); unsigned int error_code = ::GetTempFileName(&temp_path_buffer[0], TEMP_FILE_PREFIX, 0, &temp_file_name_buffer[0]); std::wstring temp_file_name(&temp_file_name_buffer[0]); if (!ExtractResource(IDR_DRIVER_LIBRARY, temp_file_name)) { return ERR_DLL_EXTRACT_FAIL; } HMODULE module_handle = ::LoadLibrary(temp_file_name.c_str()); if (module_handle == NULL) { return ERR_DLL_LOAD_FAIL; } STARTSERVERPROC start_server_proc = reinterpret_cast<STARTSERVERPROC>( ::GetProcAddress(module_handle, START_SERVER_API_NAME)); STOPSERVERPROC stop_server_proc = reinterpret_cast<STOPSERVERPROC>( ::GetProcAddress(module_handle, STOP_SERVER_API_NAME)); if (start_server_proc == NULL || stop_server_proc == NULL) { return ERR_FUNCTION_NOT_FOUND; } int port = GetPort(argc, argv); start_server_proc(port); std::cout << "Started InternetExplorerDriver" << std::endl; std::cout << "Listening on port " << port << std::endl; // Create the shutdown event and wait for it to be signaled. HANDLE event_handle = ::CreateEvent(NULL, TRUE, FALSE, IESERVER_SHUTDOWN_EVENT_NAME); ::WaitForSingleObject(event_handle, INFINITE); ::CloseHandle(event_handle); stop_server_proc(); ::FreeLibrary(module_handle); ::DeleteFile(temp_file_name.c_str()); return 0; } <|endoftext|>
<commit_before>namespace Complex { class Foo { int a_; int b_; public: int a() { return a_; } int b() { return b_; } void setA(int a) { a_ = a; } void setB(int b) { b_ = b; } Foo(int a, int b) : a_(a), b_(b){}; }; class Bar { public: Foo f; Bar() : f(0, 0) {} }; class Outer { public: Bar inner; }; int user_input() { return 42; } void sink(int x) { } void bar(Outer &b) { // The library correctly finds that the four `user_input` sources can make it // to the `sink` calls, but it also finds some source/sink combinations that // are impossible. Those false positives here are a consequence of how the // shared data flow library overapproximates field flow. The library only // tracks the final two fields (`f` and `inner`) and the length (3) of the field // access path, and then it tracks that both `a_` and `b_` have followed `f.inner` // in _some_ access path somewhere in the search. That makes the library conclude // that there could be flow to `b.inner.f.a_` even when the flow was actually to // `b.inner.f.b_`. sink(b.inner.f.a()); // $ast=flow 61:19 $f+:ast=flow 62:19 $ast=flow 63:19 $f+:ast=flow 64:19 $f-:ir=flow sink(b.inner.f.b()); // $f+:ast=flow 61:19 $ast=flow 62:19 $f+:ast=flow 63:19 $ast=flow 64:19 $f-:ir=flow } void foo() { Outer b1; Outer b2; Outer b3; Outer b4; b1.inner.f.setA(user_input()); b2.inner.f.setB(user_input()); b3.inner.f.setA(user_input()); b3.inner.f.setB(user_input()); // Only a() should alert bar(b1); // Only b() should alert bar(b2); // Both a() and b() should alert bar(b3); // Nothing should alert bar(b4); } }; // namespace Complex <commit_msg>C++: Fix off-by-one in test annotation<commit_after>namespace Complex { class Foo { int a_; int b_; public: int a() { return a_; } int b() { return b_; } void setA(int a) { a_ = a; } void setB(int b) { b_ = b; } Foo(int a, int b) : a_(a), b_(b){}; }; class Bar { public: Foo f; Bar() : f(0, 0) {} }; class Outer { public: Bar inner; }; int user_input() { return 42; } void sink(int x) { } void bar(Outer &b) { // The library correctly finds that the four `user_input` sources can make it // to the `sink` calls, but it also finds some source/sink combinations that // are impossible. Those false positives here are a consequence of how the // shared data flow library overapproximates field flow. The library only // tracks the final two fields (`f` and `inner`) and the length (3) of the field // access path, and then it tracks that both `a_` and `b_` have followed `f.inner` // in _some_ access path somewhere in the search. That makes the library conclude // that there could be flow to `b.inner.f.a_` even when the flow was actually to // `b.inner.f.b_`. sink(b.inner.f.a()); // $ast=flow 62:19 $f+:ast=flow 63:19 $ast=flow 64:19 $f+:ast=flow 65:19 $f-:ir=flow sink(b.inner.f.b()); // $f+:ast=flow 62:19 $ast=flow 63:19 $f+:ast=flow 64:19 $ast=flow 65:19 $f-:ir=flow } void foo() { Outer b1; Outer b2; Outer b3; Outer b4; b1.inner.f.setA(user_input()); b2.inner.f.setB(user_input()); b3.inner.f.setA(user_input()); b3.inner.f.setB(user_input()); // Only a() should alert bar(b1); // Only b() should alert bar(b2); // Both a() and b() should alert bar(b3); // Nothing should alert bar(b4); } }; // namespace Complex <|endoftext|>
<commit_before>#include "swift/Basic/OptionSet.h" #include "gtest/gtest.h" using namespace swift; TEST(OptionSet, contains) { enum class Flags { A = 1 << 0, B = 1 << 1, C = 1 << 2 }; OptionSet<Flags> emptySet; OptionSet<Flags> aSet = Flags::A; OptionSet<Flags> abSet = aSet | Flags::B; OptionSet<Flags> abcSet = abSet | Flags::C; OptionSet<Flags> bcSet = abcSet - Flags::A; OptionSet<Flags> cSet = bcSet - Flags::B; EXPECT_TRUE(emptySet.contains(emptySet)); EXPECT_FALSE(emptySet.contains(aSet)); EXPECT_FALSE(emptySet.contains(abSet)); EXPECT_FALSE(emptySet.contains(abcSet)); EXPECT_FALSE(emptySet.contains(bcSet)); EXPECT_FALSE(emptySet.contains(cSet)); EXPECT_TRUE(aSet.contains(emptySet)); EXPECT_TRUE(aSet.contains(aSet)); EXPECT_FALSE(aSet.contains(abSet)); EXPECT_FALSE(aSet.contains(abcSet)); EXPECT_FALSE(aSet.contains(bcSet)); EXPECT_FALSE(aSet.contains(cSet)); EXPECT_TRUE(abSet.contains(emptySet)); EXPECT_TRUE(abSet.contains(aSet)); EXPECT_TRUE(abSet.contains(abSet)); EXPECT_FALSE(abSet.contains(abcSet)); EXPECT_FALSE(abSet.contains(bcSet)); EXPECT_FALSE(abSet.contains(cSet)); EXPECT_TRUE(abcSet.contains(emptySet)); EXPECT_TRUE(abcSet.contains(aSet)); EXPECT_TRUE(abcSet.contains(abSet)); EXPECT_TRUE(abcSet.contains(abcSet)); EXPECT_TRUE(abcSet.contains(bcSet)); EXPECT_TRUE(abcSet.contains(cSet)); } TEST(OptionSet, intptr_t) { enum class Small : int8_t { A = 1 << 0 }; OptionSet<Small> small = Small::A; EXPECT_EQ(static_cast<intptr_t>(Small::A), static_cast<intptr_t>(small)); enum class UPtr : uintptr_t { A = std::numeric_limits<uintptr_t>::max() }; OptionSet<UPtr> uptr = UPtr::A; EXPECT_EQ(static_cast<intptr_t>(UPtr::A), static_cast<intptr_t>(uptr)); enum class Ptr : intptr_t { A = std::numeric_limits<intptr_t>::min() }; OptionSet<Ptr> ptr = Ptr::A; EXPECT_EQ(static_cast<intptr_t>(Ptr::A), static_cast<intptr_t>(ptr)); enum class LongLong : unsigned long long { A = 1 }; bool isConvertible = std::is_constructible<intptr_t, OptionSet<LongLong>>::value; if (sizeof(intptr_t) < sizeof(long long)) { EXPECT_FALSE(isConvertible); } else { EXPECT_TRUE(isConvertible); } } <commit_msg>[unittests] Fix OptionSet->intptr_t test for older Clang versions.<commit_after>#include "swift/Basic/OptionSet.h" #include "gtest/gtest.h" using namespace swift; TEST(OptionSet, contains) { enum class Flags { A = 1 << 0, B = 1 << 1, C = 1 << 2 }; OptionSet<Flags> emptySet; OptionSet<Flags> aSet = Flags::A; OptionSet<Flags> abSet = aSet | Flags::B; OptionSet<Flags> abcSet = abSet | Flags::C; OptionSet<Flags> bcSet = abcSet - Flags::A; OptionSet<Flags> cSet = bcSet - Flags::B; EXPECT_TRUE(emptySet.contains(emptySet)); EXPECT_FALSE(emptySet.contains(aSet)); EXPECT_FALSE(emptySet.contains(abSet)); EXPECT_FALSE(emptySet.contains(abcSet)); EXPECT_FALSE(emptySet.contains(bcSet)); EXPECT_FALSE(emptySet.contains(cSet)); EXPECT_TRUE(aSet.contains(emptySet)); EXPECT_TRUE(aSet.contains(aSet)); EXPECT_FALSE(aSet.contains(abSet)); EXPECT_FALSE(aSet.contains(abcSet)); EXPECT_FALSE(aSet.contains(bcSet)); EXPECT_FALSE(aSet.contains(cSet)); EXPECT_TRUE(abSet.contains(emptySet)); EXPECT_TRUE(abSet.contains(aSet)); EXPECT_TRUE(abSet.contains(abSet)); EXPECT_FALSE(abSet.contains(abcSet)); EXPECT_FALSE(abSet.contains(bcSet)); EXPECT_FALSE(abSet.contains(cSet)); EXPECT_TRUE(abcSet.contains(emptySet)); EXPECT_TRUE(abcSet.contains(aSet)); EXPECT_TRUE(abcSet.contains(abSet)); EXPECT_TRUE(abcSet.contains(abcSet)); EXPECT_TRUE(abcSet.contains(bcSet)); EXPECT_TRUE(abcSet.contains(cSet)); } TEST(OptionSet, intptr_t) { enum class Small : int8_t { A = 1 << 0 }; OptionSet<Small> small = Small::A; EXPECT_EQ(static_cast<intptr_t>(Small::A), static_cast<intptr_t>(small)); enum class UPtr : uintptr_t { A = std::numeric_limits<uintptr_t>::max() }; OptionSet<UPtr> uptr = UPtr::A; EXPECT_EQ(static_cast<intptr_t>(UPtr::A), static_cast<intptr_t>(uptr)); enum class Ptr : intptr_t { A = std::numeric_limits<intptr_t>::min() }; OptionSet<Ptr> ptr = Ptr::A; EXPECT_EQ(static_cast<intptr_t>(Ptr::A), static_cast<intptr_t>(ptr)); } TEST(OptionSet, intptr_t_isConstructible) { // First check that std::is_constructible counts explicit conversion // operators. class AlwaysConvertible { public: explicit operator intptr_t () const { return 0; } }; if (!std::is_constructible<intptr_t, AlwaysConvertible>::value) { // std::is_constructible doesn't test what we want it to. Just exit early. return; } enum class LongLong : unsigned long long { A = 1 }; bool isConvertible = std::is_constructible<intptr_t, OptionSet<LongLong>>::value; if (sizeof(intptr_t) < sizeof(long long)) { EXPECT_FALSE(isConvertible); } else { EXPECT_TRUE(isConvertible); } } <|endoftext|>
<commit_before>//===- llvm/unittest/IR/WaymarkTest.cpp - getUser() unit tests ------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // we perform white-box tests // #include "llvm/IR/Function.h" #include "llvm/IR/Instructions.h" #include "llvm/IR/LLVMContext.h" #include "gtest/gtest.h" #include <algorithm> namespace llvm { namespace { Constant *char2constant(char c) { return ConstantInt::get(Type::getInt8Ty(getGlobalContext()), c); } TEST(WaymarkTest, NativeArray) { static uint8_t tail[22] = "s02s33s30y2y0s1x0syxS"; Value * values[22]; std::transform(tail, tail + 22, values, char2constant); FunctionType *FT = FunctionType::get(Type::getVoidTy(getGlobalContext()), true); Function *F = Function::Create(FT, GlobalValue::ExternalLinkage); const CallInst *A = CallInst::Create(F, makeArrayRef(values)); ASSERT_NE(A, (const CallInst*)NULL); ASSERT_EQ(1U + 22, A->getNumOperands()); const Use *U = &A->getOperandUse(0); const Use *Ue = &A->getOperandUse(22); for (; U != Ue; ++U) { EXPECT_EQ(A, U->getUser()); } } TEST(WaymarkTest, TwoBit) { Use* many = (Use*)calloc(sizeof(Use), 8212 + 1); ASSERT_TRUE(many); Use::initTags(many, many + 8212); for (Use *U = many, *Ue = many + 8212 - 1; U != Ue; ++U) { EXPECT_EQ(reinterpret_cast<User *>(Ue + 1), U->getUser()); } } } // end anonymous namespace } // end namespace llvm <commit_msg>Untabify.<commit_after>//===- llvm/unittest/IR/WaymarkTest.cpp - getUser() unit tests ------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // we perform white-box tests // #include "llvm/IR/Function.h" #include "llvm/IR/Instructions.h" #include "llvm/IR/LLVMContext.h" #include "gtest/gtest.h" #include <algorithm> namespace llvm { namespace { Constant *char2constant(char c) { return ConstantInt::get(Type::getInt8Ty(getGlobalContext()), c); } TEST(WaymarkTest, NativeArray) { static uint8_t tail[22] = "s02s33s30y2y0s1x0syxS"; Value * values[22]; std::transform(tail, tail + 22, values, char2constant); FunctionType *FT = FunctionType::get(Type::getVoidTy(getGlobalContext()), true); Function *F = Function::Create(FT, GlobalValue::ExternalLinkage); const CallInst *A = CallInst::Create(F, makeArrayRef(values)); ASSERT_NE(A, (const CallInst*)NULL); ASSERT_EQ(1U + 22, A->getNumOperands()); const Use *U = &A->getOperandUse(0); const Use *Ue = &A->getOperandUse(22); for (; U != Ue; ++U) { EXPECT_EQ(A, U->getUser()); } } TEST(WaymarkTest, TwoBit) { Use* many = (Use*)calloc(sizeof(Use), 8212 + 1); ASSERT_TRUE(many); Use::initTags(many, many + 8212); for (Use *U = many, *Ue = many + 8212 - 1; U != Ue; ++U) { EXPECT_EQ(reinterpret_cast<User *>(Ue + 1), U->getUser()); } } } // end anonymous namespace } // end namespace llvm <|endoftext|>
<commit_before>/* Copyright (c) 2014, Randolph Voorhies, Shane Grant 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 cereal 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 RANDOLPH VOORHIES AND SHANE GRANT 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 "common.hpp" #include <boost/test/unit_test.hpp> template <class IArchive, class OArchive> void test_opt() { std::random_device rd; std::mt19937 gen(rd()); auto rng = [&](){ return random_value<int>(gen); }; for(int ii=0; ii<100; ++ii) { boost::optional<int> o_podOptEmpty; boost::optional<int> o_podopt = {rng()}; boost::optional<StructInternalSerialize> o_iseropt = { { rng(), rng() } }; boost::optional<StructInternalSplit> o_isplopt = { { rng(), rng() }}; boost::optional<StructExternalSerialize> o_eseropt = { { rng(), rng() } }; boost::optional<StructExternalSplit> o_esplopt = { { rng(), rng() } }; std::ostringstream os; { OArchive oar(os); oar(o_podOptEmpty); oar(o_podopt); oar(o_iseropt); oar(o_isplopt); oar(o_eseropt); oar(o_esplopt); } boost::optional<int> i_podOptEmpty; boost::optional<int> i_podopt; boost::optional<StructInternalSerialize> i_iseropt; boost::optional<StructInternalSplit> i_isplopt; boost::optional<StructExternalSerialize> i_eseropt; boost::optional<StructExternalSplit> i_esplopt; std::istringstream is(os.str()); { IArchive iar(is); iar(i_podOptEmpty); iar(i_podopt); iar(i_iseropt); iar(i_isplopt); iar(i_eseropt); iar(i_esplopt); } BOOST_CHECK_EQUAL( i_podOptEmpty, o_podOptEmpty); BOOST_CHECK(!i_podOptEmpty); // unitialized optionals should evaluate to false BOOST_CHECK_EQUAL( i_podopt, o_podopt ); BOOST_CHECK_EQUAL( i_iseropt, o_iseropt ); BOOST_CHECK_EQUAL( i_isplopt, o_isplopt ); BOOST_CHECK_EQUAL( i_eseropt, o_eseropt ); BOOST_CHECK_EQUAL( i_esplopt, o_esplopt ); } } BOOST_AUTO_TEST_CASE( binary_opt ) { test_opt<cereal::BinaryInputArchive, cereal::BinaryOutputArchive>(); } BOOST_AUTO_TEST_CASE( portable_binary_opt ) { test_opt<cereal::PortableBinaryInputArchive, cereal::PortableBinaryOutputArchive>(); } BOOST_AUTO_TEST_CASE( xml_opt ) { test_opt<cereal::XMLInputArchive, cereal::XMLOutputArchive>(); } BOOST_AUTO_TEST_CASE( json_opt ) { test_opt<cereal::JSONInputArchive, cereal::JSONOutputArchive>(); } <commit_msg>Update copyright, disclaimer<commit_after>/* Copyright (c) 2014, Steve Hickman 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 cereal 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 STEVE HICKMAN 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 "common.hpp" #include <boost/test/unit_test.hpp> template <class IArchive, class OArchive> void test_opt() { std::random_device rd; std::mt19937 gen(rd()); auto rng = [&](){ return random_value<int>(gen); }; for(int ii=0; ii<100; ++ii) { boost::optional<int> o_podOptEmpty; boost::optional<int> o_podopt = {rng()}; boost::optional<StructInternalSerialize> o_iseropt = { { rng(), rng() } }; boost::optional<StructInternalSplit> o_isplopt = { { rng(), rng() }}; boost::optional<StructExternalSerialize> o_eseropt = { { rng(), rng() } }; boost::optional<StructExternalSplit> o_esplopt = { { rng(), rng() } }; std::ostringstream os; { OArchive oar(os); oar(o_podOptEmpty); oar(o_podopt); oar(o_iseropt); oar(o_isplopt); oar(o_eseropt); oar(o_esplopt); } boost::optional<int> i_podOptEmpty; boost::optional<int> i_podopt; boost::optional<StructInternalSerialize> i_iseropt; boost::optional<StructInternalSplit> i_isplopt; boost::optional<StructExternalSerialize> i_eseropt; boost::optional<StructExternalSplit> i_esplopt; std::istringstream is(os.str()); { IArchive iar(is); iar(i_podOptEmpty); iar(i_podopt); iar(i_iseropt); iar(i_isplopt); iar(i_eseropt); iar(i_esplopt); } BOOST_CHECK_EQUAL( i_podOptEmpty, o_podOptEmpty); BOOST_CHECK(!i_podOptEmpty); // unitialized optionals should evaluate to false BOOST_CHECK_EQUAL( i_podopt, o_podopt ); BOOST_CHECK_EQUAL( i_iseropt, o_iseropt ); BOOST_CHECK_EQUAL( i_isplopt, o_isplopt ); BOOST_CHECK_EQUAL( i_eseropt, o_eseropt ); BOOST_CHECK_EQUAL( i_esplopt, o_esplopt ); } } BOOST_AUTO_TEST_CASE( binary_opt ) { test_opt<cereal::BinaryInputArchive, cereal::BinaryOutputArchive>(); } BOOST_AUTO_TEST_CASE( portable_binary_opt ) { test_opt<cereal::PortableBinaryInputArchive, cereal::PortableBinaryOutputArchive>(); } BOOST_AUTO_TEST_CASE( xml_opt ) { test_opt<cereal::XMLInputArchive, cereal::XMLOutputArchive>(); } BOOST_AUTO_TEST_CASE( json_opt ) { test_opt<cereal::JSONInputArchive, cereal::JSONOutputArchive>(); } <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: dp_gui_updatability.hxx,v $ * * $Revision: 1.3 $ * * last change: $Author: rt $ $Date: 2007-07-26 08:53:58 $ * * 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 2006 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 INCLUDED_DESKTOP_SOURCE_DEPLOYMENT_GUI_DP_GUI_UPDATABILITY_HXX #define INCLUDED_DESKTOP_SOURCE_DEPLOYMENT_GUI_DP_GUI_UPDATABILITY_HXX #ifndef _SAL_CONFIG_H_ #include "sal/config.h" #endif #ifndef _COM_SUN_STAR_UNO_REFERENCE_HXX_ #include "com/sun/star/uno/Reference.hxx" #endif #ifndef _COM_SUN_STAR_UNO_SEQUENCE_HXX_ #include "com/sun/star/uno/Sequence.hxx" #endif #ifndef _RTL_REF_HXX_ #include "rtl/ref.hxx" #endif /// @HTML class Window; namespace com { namespace sun { namespace star { namespace deployment { class XPackageManager; } namespace uno { class XComponentContext; } } } } namespace dp_gui { /** Asynchronously determine whether <code>dp_gui::DialogImpl</code>'s &ldquo;Check for Updates...&rdquo; button shall be enabled (which theoretically can take some time). <p>Note that, due to the asynchronous operation, the button may be enabled even if there are no updatable extensions.</p> <p>Each instance of this class must be called from a single thread in order to adhere to the following protocol: <code>stop</code> must be called exactly once, with no intervening calls to <code>start</code>, before the destructor is called.</p> */ class Updatability { public: /** Create an instance. @param packageManagers a list of non-null package managers @param enabled <code>dp_gui::DialogImpl</code>'s &ldquo;Check for Updates...&rdquo; button; will only be accessed with the solar mutex locked */ Updatability( com::sun::star::uno::Sequence< com::sun::star::uno::Reference< com::sun::star::deployment::XPackageManager > > const & packageManagers, Window & enabled); ~Updatability(); /** (Re-)start determining whether <code>dp_gui::DialogImpl</code>'s &ldquo;Check for Updates...&rdquo; button shall be enabled. */ void start(); /** Orderly shut down this instance. */ void stop(); private: Updatability(Updatability &); // not defined void operator =(Updatability &); // not defined class Thread; rtl::Reference< Thread > m_thread; }; } #endif <commit_msg>INTEGRATION: CWS changefileheader (1.3.182); FILE MERGED 2008/04/01 15:13:06 thb 1.3.182.2: #i85898# Stripping all external header guards 2008/03/28 15:26:37 rt 1.3.182.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: dp_gui_updatability.hxx,v $ * $Revision: 1.4 $ * * 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. * ************************************************************************/ #ifndef INCLUDED_DESKTOP_SOURCE_DEPLOYMENT_GUI_DP_GUI_UPDATABILITY_HXX #define INCLUDED_DESKTOP_SOURCE_DEPLOYMENT_GUI_DP_GUI_UPDATABILITY_HXX #include "sal/config.h" #include "com/sun/star/uno/Reference.hxx" #include "com/sun/star/uno/Sequence.hxx" #include "rtl/ref.hxx" /// @HTML class Window; namespace com { namespace sun { namespace star { namespace deployment { class XPackageManager; } namespace uno { class XComponentContext; } } } } namespace dp_gui { /** Asynchronously determine whether <code>dp_gui::DialogImpl</code>'s &ldquo;Check for Updates...&rdquo; button shall be enabled (which theoretically can take some time). <p>Note that, due to the asynchronous operation, the button may be enabled even if there are no updatable extensions.</p> <p>Each instance of this class must be called from a single thread in order to adhere to the following protocol: <code>stop</code> must be called exactly once, with no intervening calls to <code>start</code>, before the destructor is called.</p> */ class Updatability { public: /** Create an instance. @param packageManagers a list of non-null package managers @param enabled <code>dp_gui::DialogImpl</code>'s &ldquo;Check for Updates...&rdquo; button; will only be accessed with the solar mutex locked */ Updatability( com::sun::star::uno::Sequence< com::sun::star::uno::Reference< com::sun::star::deployment::XPackageManager > > const & packageManagers, Window & enabled); ~Updatability(); /** (Re-)start determining whether <code>dp_gui::DialogImpl</code>'s &ldquo;Check for Updates...&rdquo; button shall be enabled. */ void start(); /** Orderly shut down this instance. */ void stop(); private: Updatability(Updatability &); // not defined void operator =(Updatability &); // not defined class Thread; rtl::Reference< Thread > m_thread; }; } #endif <|endoftext|>
<commit_before><commit_msg>[DOC] Added assignment file for sequence tutorial.<commit_after><|endoftext|>
<commit_before>#include "test_process_reader.h" #include "logic/process_reader.h" #include "logic/settings.h" #include "test.h" #include "ui/mainwindow.h" #include <QProcess> #include <QString> #include <QStringList> #include <fstream> void test_args_construction() { struct Test_cases { QString arg_text; QStringList args; } test_cases[] = { {"", {}}, {"test", {"test"}}, {R"("test")", {"test"}}, {"multi arg", {"multi", "arg"}}, {"many multi arg", {"many", "multi", "arg"}}, {R"("multi arg")", {"multi arg"}}, {R"(many "multi arg" things)", {"many", "multi arg", "things"}}, {R"("many multi" "arg things")", {"many multi", "arg things"}}, }; for (const auto &test_case : test_cases) { assert_equal(detail::create_arguments_list(test_case.arg_text), test_case.args); } } void test_process_reading() { struct Test_cases { Tool tool; std::string_view code; std::string_view expected_output; std::string_view expected_error; } test_cases[] = { {.tool = {}, .code = R"(int main(){})"}, // {.tool = {}, .code = R"(#include <iostream> int main(){ std::cout << "test"; })", .expected_output = "test"}, // {.tool = {}, .code = R"(#include <iostream> int main(){ std::cerr << "test"; })", .expected_output = "", .expected_error = "test"}, // {.tool = {}, .code = R"(#include <iostream> int main(){ std::cout << "multi\nline\ntest\noutput\n"; std::cerr << "multi\nline\ntest\nerror\n"; })", .expected_output = "multi\nline\ntest\noutput\n", .expected_error = "multi\nline\ntest\nerror\n"}, // {.tool = {}, .code = R"(#include <iostream> #include <thread> #include <chrono> int main(){ std::cout << "Hello" << std::flush; std::this_thread::sleep_for(std::chrono::milliseconds{500}); std::cout << "World"; })", .expected_output = "HelloWorld"}, // }; for (auto &test_case : test_cases) { const auto cpp_file = "/tmp/SCE_test_process_code.cpp"; const auto exe_file = "/tmp/SCE_test_process_exe"; assert_true(std::ofstream{cpp_file} << test_case.code); assert_equal(QProcess::execute("g++", {"-std=c++17", cpp_file, "-o", exe_file}), 0); test_case.tool.path = exe_file; Process_reader p{test_case.tool}; assert_equal(p.get_output(), test_case.expected_output); assert_equal(p.get_error(), test_case.expected_error); } } void test_process_reader() { test_args_construction(); test_process_reading(); } <commit_msg>Refactored process reader test cases.<commit_after>#include "test_process_reader.h" #include "logic/process_reader.h" #include "logic/settings.h" #include "test.h" #include "ui/mainwindow.h" #include <QProcess> #include <QString> #include <QStringList> #include <fstream> void test_args_construction() { struct Test_cases { QString arg_text; QStringList args; } test_cases[] = { {"", {}}, {"test", {"test"}}, {R"("test")", {"test"}}, {"multi arg", {"multi", "arg"}}, {"many multi arg", {"many", "multi", "arg"}}, {R"("multi arg")", {"multi arg"}}, {R"(many "multi arg" things)", {"many", "multi arg", "things"}}, {R"("many multi" "arg things")", {"many multi", "arg things"}}, }; for (const auto &test_case : test_cases) { assert_equal(detail::create_arguments_list(test_case.arg_text), test_case.args); } } void test_process_reading() { struct Test_cases { std::string_view code; std::string_view expected_output; std::string_view expected_error; } test_cases[] = { {.code = R"(int main(){})"}, {.code = R"(#include <iostream> int main(){ std::cout << "test"; })", .expected_output = "test"}, {.code = R"(#include <iostream> int main(){ std::cerr << "test"; })", .expected_output = "", .expected_error = "test"}, {.code = R"(#include <iostream> int main(){ std::cout << "multi\nline\ntest\noutput\n"; std::cerr << "multi\nline\ntest\nerror\n"; })", .expected_output = "multi\nline\ntest\noutput\n", .expected_error = "multi\nline\ntest\nerror\n"}, {.code = R"(#include <iostream> #include <thread> #include <chrono> int main(){ std::cout << "Hello" << std::flush; std::this_thread::sleep_for(std::chrono::milliseconds{500}); std::cout << "World"; })", .expected_output = "HelloWorld"}, }; for (auto &test_case : test_cases) { const auto cpp_file = "/tmp/SCE_test_process_code.cpp"; const auto exe_file = "/tmp/SCE_test_process_exe"; assert_true(std::ofstream{cpp_file} << test_case.code); assert_equal(QProcess::execute("g++", {"-std=c++17", cpp_file, "-o", exe_file}), 0); Tool tool; tool.path = exe_file; Process_reader p{tool}; assert_equal(p.get_output(), test_case.expected_output); assert_equal(p.get_error(), test_case.expected_error); } } void test_process_reader() { test_args_construction(); test_process_reading(); } <|endoftext|>
<commit_before>/* * Author(s): * - Chris Kilner <[email protected]> * - Cedric Gestes <[email protected]> * * Copyright (C) 2010 Aldebaran Robotics */ #include <qi/transport/src/zmq/zmq_poll_client.hpp> #include <qi/exceptions/exceptions.hpp> #include <iostream> #include <qi/log.hpp> namespace qi { namespace transport { namespace detail { ZMQPollClient::ZMQPollClient(zmq::socket_t &socket) : _zsocket(socket), _first_time(1) { _items[0].socket = _zsocket; _items[0].fd = 0; _items[0].events = ZMQ_POLLIN; _items[0].revents = 0; } //return -1 on error, 0 otherwise int ZMQPollClient::pollRecv(long timeout) { int rc = 0; rc = zmq::poll(_items, 1, timeout); qisDebug << "ZMQPollClient: timeout:" << timeout << std::endl; if ((rc <= 0) || (!(_items[0].revents & ZMQ_POLLIN))) return -1; return 0; } void ZMQPollClient::recv(zmq::message_t *msg, long usTimeout) { if (_first_time) { int rc = 0; long elapsed = 0; _first_time = 0; do { rc = pollRecv(1000); elapsed += 1; } while (rc < 0 && elapsed < usTimeout); if (rc < 0) throw qi::transport::Exception("no response"); } else { pollRecv(usTimeout); } _zsocket.recv(msg); } } } } <commit_msg>transport: zmq: poll: do not call recv if poll failed<commit_after>/* * Author(s): * - Chris Kilner <[email protected]> * - Cedric Gestes <[email protected]> * * Copyright (C) 2010 Aldebaran Robotics */ #include <qi/transport/src/zmq/zmq_poll_client.hpp> #include <qi/exceptions/exceptions.hpp> #include <iostream> #include <qi/log.hpp> namespace qi { namespace transport { namespace detail { ZMQPollClient::ZMQPollClient(zmq::socket_t &socket) : _zsocket(socket), _first_time(1) { _items[0].socket = _zsocket; _items[0].fd = 0; _items[0].events = ZMQ_POLLIN; _items[0].revents = 0; } //return -1 on error, 0 otherwise int ZMQPollClient::pollRecv(long timeout) { int rc = 0; rc = zmq::poll(_items, 1, timeout); qisDebug << "ZMQPollClient: timeout:" << timeout << std::endl; if ((rc <= 0) || (!(_items[0].revents & ZMQ_POLLIN))) return -1; return 0; } void ZMQPollClient::recv(zmq::message_t *msg, long usTimeout) { if (_first_time) { int rc = 0; long elapsed = 0; _first_time = 0; do { rc = pollRecv(1000); elapsed += 1; } while (rc < 0 && elapsed < usTimeout); if (rc < 0) throw qi::transport::Exception("no response"); } else { if (pollRecv(usTimeout) < 0) throw qi::transport::Exception("no response"); } _zsocket.recv(msg); } } } } <|endoftext|>
<commit_before>// // Copyright (c) 2017-2019 the rbfx project. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // #include <Urho3D/IO/FileSystem.h> #include <Urho3D/IO/Log.h> #include <Urho3D/Core/ProcessUtils.h> #include "Project.h" #include "Pipeline/Asset.h" #include "Pipeline/Importers/ModelImporter.h" namespace Urho3D { static const char* MODEL_IMPORTER_OUTPUT_ANIM = "Output animations"; static const char* MODEL_IMPORTER_OUTPUT_MAT = "Output materials"; static const char* MODEL_IMPORTER_OUTPUT_MAT_TEX = "Output material textures"; static const char* MODEL_IMPORTER_USE_MAT_DIFFUSE = "Use material diffuse color"; static const char* MODEL_IMPORTER_FIX_INFACING_NORMALS = "Fix in-facing normals"; static const char* MODEL_IMPORTER_MAX_BONES = "Max number of bones"; static const char* MODEL_IMPORTER_ANIM_TICK = "Animation tick frequency"; static const char* MODEL_IMPORTER_EMISSIVE_AO = "Emissive is ambient occlusion"; static const char* MODEL_IMPORTER_FBX_PIVOT = "Suppress $fbx pivot nodes"; ModelImporter::ModelImporter(Context* context) : AssetImporter(context) { } void ModelImporter::RegisterObject(Context* context) { context->RegisterFactory<ModelImporter>(); URHO3D_COPY_BASE_ATTRIBUTES(AssetImporter); URHO3D_ATTRIBUTE(MODEL_IMPORTER_OUTPUT_ANIM, bool, outputAnimations_, true, AM_DEFAULT); URHO3D_ATTRIBUTE(MODEL_IMPORTER_OUTPUT_MAT, bool, outputMaterials_, true, AM_DEFAULT); URHO3D_ATTRIBUTE(MODEL_IMPORTER_OUTPUT_MAT_TEX, bool, outputMaterialTextures_, true, AM_DEFAULT); URHO3D_ATTRIBUTE(MODEL_IMPORTER_USE_MAT_DIFFUSE, bool, useMaterialDiffuse_, true, AM_DEFAULT); URHO3D_ATTRIBUTE(MODEL_IMPORTER_FIX_INFACING_NORMALS, bool, fixInFacingNormals_, true, AM_DEFAULT); URHO3D_ATTRIBUTE(MODEL_IMPORTER_MAX_BONES, int, maxBones_, 64, AM_DEFAULT); URHO3D_ATTRIBUTE(MODEL_IMPORTER_ANIM_TICK, int, animationTick_, 4800, AM_DEFAULT); URHO3D_ATTRIBUTE(MODEL_IMPORTER_EMISSIVE_AO, bool, emissiveIsAmbientOcclusion_, false, AM_DEFAULT); URHO3D_ATTRIBUTE(MODEL_IMPORTER_FBX_PIVOT, bool, noFbxPivot_, false, AM_DEFAULT); } void ModelImporter::RenderInspector(const char* filter) { BaseClassName::RenderInspector(filter); } bool ModelImporter::Execute(Urho3D::Asset* input, const ea::string& outputPath) { // outputPath - absolute path to Cache or Cache/{flavor} folder. if (!BaseClassName::Execute(input, outputPath)) return false; auto* fs = GetFileSystem(); auto* project = GetSubsystem<Project>(); // A path mimicking structure of cache directory, but with byproducts of this import procedure only. It serves us to allow easy // detection of all byproducts of this import procedure. ea::string tempPath = project->GetProjectPath() + "Temp." + GenerateUUID() + "/"; // Actual output destination AssetImporter will be writing. ea::string resourceBaseName = GetPath(input->GetName()) + GetFileName(input->GetName()) + "/"; // Strips file extension ea::string tempOutput = tempPath + resourceBaseName; fs->CreateDirsRecursive(tempOutput); ea::string output = tempOutput + "Model.mdl"; ea::vector<ea::string> args{"model", input->GetResourcePath(), output}; if (!GetAttribute(MODEL_IMPORTER_OUTPUT_ANIM).GetBool()) args.emplace_back("-na"); if (!GetAttribute(MODEL_IMPORTER_OUTPUT_MAT).GetBool()) args.emplace_back("-nm"); if (!GetAttribute(MODEL_IMPORTER_OUTPUT_MAT_TEX).GetBool()) args.emplace_back("-nt"); if (!GetAttribute(MODEL_IMPORTER_USE_MAT_DIFFUSE).GetBool()) args.emplace_back("-nc"); if (!GetAttribute(MODEL_IMPORTER_FIX_INFACING_NORMALS).GetBool()) args.emplace_back("-nf"); args.emplace_back("-pp"); args.emplace_back(resourceBaseName); args.emplace_back("-mb"); args.emplace_back(ea::to_string(GetAttribute(MODEL_IMPORTER_MAX_BONES).GetBool())); args.emplace_back("-f"); args.emplace_back(ea::to_string(GetAttribute(MODEL_IMPORTER_ANIM_TICK).GetInt())); if (!GetAttribute(MODEL_IMPORTER_EMISSIVE_AO).GetBool()) args.emplace_back("-eao"); if (!GetAttribute(MODEL_IMPORTER_FBX_PIVOT).GetBool()) args.emplace_back("-np"); int result = fs->SystemRun(fs->GetProgramDir() + "AssetImporter", args); if (result != 0) { URHO3D_LOGERROR("Importing asset '{}' failed.", input->GetName()); return false; } unsigned mtime = fs->GetLastModifiedTime(input->GetResourcePath()); StringVector tmpByproducts; fs->ScanDir(tmpByproducts, tempPath, "*.*", SCAN_FILES, true); tmpByproducts.erase_first("."); tmpByproducts.erase_first(".."); for (const ea::string& byproduct : tmpByproducts) { ea::string byproductPath = tempPath + byproduct; ea::string moveTo = outputPath + byproduct; if (fs->FileExists(moveTo)) fs->Delete(moveTo); else if (fs->DirExists(moveTo)) fs->RemoveDir(moveTo, true); fs->CreateDirsRecursive(GetPath(moveTo)); fs->Rename(byproductPath, moveTo); fs->SetLastModifiedTime(moveTo, mtime); AddByproduct(byproduct); } fs->RemoveDir(tempPath, true); return !tmpByproducts.empty(); } bool ModelImporter::Accepts(const ea::string& path) const { if (path.ends_with(".fbx")) return true; if (path.ends_with(".blend")) return true; return false; } } <commit_msg>Editor: ModelImporter shows clickable link now.<commit_after>// // Copyright (c) 2017-2019 the rbfx project. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // #include <Urho3D/IO/FileSystem.h> #include <Urho3D/IO/Log.h> #include <Urho3D/Core/ProcessUtils.h> #include "Project.h" #include "Pipeline/Asset.h" #include "Pipeline/Importers/ModelImporter.h" namespace Urho3D { static const char* MODEL_IMPORTER_OUTPUT_ANIM = "Output animations"; static const char* MODEL_IMPORTER_OUTPUT_MAT = "Output materials"; static const char* MODEL_IMPORTER_OUTPUT_MAT_TEX = "Output material textures"; static const char* MODEL_IMPORTER_USE_MAT_DIFFUSE = "Use material diffuse color"; static const char* MODEL_IMPORTER_FIX_INFACING_NORMALS = "Fix in-facing normals"; static const char* MODEL_IMPORTER_MAX_BONES = "Max number of bones"; static const char* MODEL_IMPORTER_ANIM_TICK = "Animation tick frequency"; static const char* MODEL_IMPORTER_EMISSIVE_AO = "Emissive is ambient occlusion"; static const char* MODEL_IMPORTER_FBX_PIVOT = "Suppress $fbx pivot nodes"; ModelImporter::ModelImporter(Context* context) : AssetImporter(context) { } void ModelImporter::RegisterObject(Context* context) { context->RegisterFactory<ModelImporter>(); URHO3D_COPY_BASE_ATTRIBUTES(AssetImporter); URHO3D_ATTRIBUTE(MODEL_IMPORTER_OUTPUT_ANIM, bool, outputAnimations_, true, AM_DEFAULT); URHO3D_ATTRIBUTE(MODEL_IMPORTER_OUTPUT_MAT, bool, outputMaterials_, true, AM_DEFAULT); URHO3D_ATTRIBUTE(MODEL_IMPORTER_OUTPUT_MAT_TEX, bool, outputMaterialTextures_, true, AM_DEFAULT); URHO3D_ATTRIBUTE(MODEL_IMPORTER_USE_MAT_DIFFUSE, bool, useMaterialDiffuse_, true, AM_DEFAULT); URHO3D_ATTRIBUTE(MODEL_IMPORTER_FIX_INFACING_NORMALS, bool, fixInFacingNormals_, true, AM_DEFAULT); URHO3D_ATTRIBUTE(MODEL_IMPORTER_MAX_BONES, int, maxBones_, 64, AM_DEFAULT); URHO3D_ATTRIBUTE(MODEL_IMPORTER_ANIM_TICK, int, animationTick_, 4800, AM_DEFAULT); URHO3D_ATTRIBUTE(MODEL_IMPORTER_EMISSIVE_AO, bool, emissiveIsAmbientOcclusion_, false, AM_DEFAULT); URHO3D_ATTRIBUTE(MODEL_IMPORTER_FBX_PIVOT, bool, noFbxPivot_, false, AM_DEFAULT); } void ModelImporter::RenderInspector(const char* filter) { BaseClassName::RenderInspector(filter); } bool ModelImporter::Execute(Urho3D::Asset* input, const ea::string& outputPath) { // outputPath - absolute path to Cache or Cache/{flavor} folder. if (!BaseClassName::Execute(input, outputPath)) return false; auto* fs = GetFileSystem(); auto* project = GetSubsystem<Project>(); // A path mimicking structure of cache directory, but with byproducts of this import procedure only. It serves us to allow easy // detection of all byproducts of this import procedure. ea::string tempPath = project->GetProjectPath() + "Temp." + GenerateUUID() + "/"; // Actual output destination AssetImporter will be writing. ea::string resourceBaseName = GetPath(input->GetName()) + GetFileName(input->GetName()) + "/"; // Strips file extension ea::string tempOutput = tempPath + resourceBaseName; fs->CreateDirsRecursive(tempOutput); ea::string output = tempOutput + "Model.mdl"; ea::vector<ea::string> args{"model", input->GetResourcePath(), output}; if (!GetAttribute(MODEL_IMPORTER_OUTPUT_ANIM).GetBool()) args.emplace_back("-na"); if (!GetAttribute(MODEL_IMPORTER_OUTPUT_MAT).GetBool()) args.emplace_back("-nm"); if (!GetAttribute(MODEL_IMPORTER_OUTPUT_MAT_TEX).GetBool()) args.emplace_back("-nt"); if (!GetAttribute(MODEL_IMPORTER_USE_MAT_DIFFUSE).GetBool()) args.emplace_back("-nc"); if (!GetAttribute(MODEL_IMPORTER_FIX_INFACING_NORMALS).GetBool()) args.emplace_back("-nf"); args.emplace_back("-pp"); args.emplace_back(resourceBaseName); args.emplace_back("-mb"); args.emplace_back(ea::to_string(GetAttribute(MODEL_IMPORTER_MAX_BONES).GetBool())); args.emplace_back("-f"); args.emplace_back(ea::to_string(GetAttribute(MODEL_IMPORTER_ANIM_TICK).GetInt())); if (!GetAttribute(MODEL_IMPORTER_EMISSIVE_AO).GetBool()) args.emplace_back("-eao"); if (!GetAttribute(MODEL_IMPORTER_FBX_PIVOT).GetBool()) args.emplace_back("-np"); int result = fs->SystemRun(fs->GetProgramDir() + "AssetImporter", args); if (result != 0) { URHO3D_LOGERROR("Importing asset 'res://{}' failed.", input->GetName()); return false; } unsigned mtime = fs->GetLastModifiedTime(input->GetResourcePath()); StringVector tmpByproducts; fs->ScanDir(tmpByproducts, tempPath, "*.*", SCAN_FILES, true); tmpByproducts.erase_first("."); tmpByproducts.erase_first(".."); for (const ea::string& byproduct : tmpByproducts) { ea::string byproductPath = tempPath + byproduct; ea::string moveTo = outputPath + byproduct; if (fs->FileExists(moveTo)) fs->Delete(moveTo); else if (fs->DirExists(moveTo)) fs->RemoveDir(moveTo, true); fs->CreateDirsRecursive(GetPath(moveTo)); fs->Rename(byproductPath, moveTo); fs->SetLastModifiedTime(moveTo, mtime); AddByproduct(byproduct); } fs->RemoveDir(tempPath, true); return !tmpByproducts.empty(); } bool ModelImporter::Accepts(const ea::string& path) const { if (path.ends_with(".fbx")) return true; if (path.ends_with(".blend")) return true; return false; } } <|endoftext|>
<commit_before>// Copyright (c) 2010-2020, Lawrence Livermore National Security, LLC. Produced // at the Lawrence Livermore National Laboratory. All Rights reserved. See files // LICENSE and NOTICE for details. LLNL-CODE-806117. // // This file is part of the MFEM library. For more information and source code // availability visit https://mfem.org. // // MFEM is free software; you can redistribute it and/or modify it under the // terms of the BSD-3 license. We welcome feedback and contributions, see file // CONTRIBUTING.md for details. #define CATCH_CONFIG_RUNNER #include "catch.hpp" #include "mfem.hpp" #include <fstream> #include <iostream> #include "../../../fem/libceed/ceed.hpp" using namespace mfem; namespace ceed_test { double coeff_function(const Vector &x) { return 1 + x[0]*x[0]; } static std::string getString(AssemblyLevel assembly) { switch (assembly) { case AssemblyLevel::NONE: return "NONE"; break; case AssemblyLevel::PARTIAL: return "PARTIAL"; break; case AssemblyLevel::ELEMENT: return "ELEMENT"; break; case AssemblyLevel::FULL: return "FULL"; break; case AssemblyLevel::LEGACYFULL: return "LEGACYFULL"; break; } } static std::string getString(CeedCoeff coeff_type) { switch (coeff_type) { case CeedCoeff::Const: return "Const"; break; case CeedCoeff::Grid: return "Grid"; break; case CeedCoeff::Quad: return "Quad"; break; } } enum class Problem {Mass, Diffusion, VectorMass, VectorDiffusion}; static std::string getString(Problem pb) { switch (pb) { case Problem::Mass: return "Mass"; break; case Problem::Diffusion: return "Diffusion"; break; case Problem::VectorMass: return "VectorMass"; break; case Problem::VectorDiffusion: return "VectorDiffusion"; break; } } void test_ceed_operator(const char* input, int order, const CeedCoeff coeff_type, const Problem pb, const AssemblyLevel assembly) { std::string section = "assembly: " + getString(assembly) + "\n" + "coeff_type: " + getString(coeff_type) + "\n" + "pb: " + getString(pb) + "\n" + "order: " + std::to_string(order) + "\n" + "mesh: " + input; INFO(section); Mesh mesh(input, 1, 1); mesh.EnsureNodes(); int dim = mesh.Dimension(); H1_FECollection fec(order, dim); bool vecOp = pb == Problem::VectorMass || pb == Problem::VectorDiffusion; const int vdim = vecOp ? dim : 1; FiniteElementSpace fespace(&mesh, &fec, vdim); BilinearForm k_test(&fespace); BilinearForm k_ref(&fespace); GridFunction gf(&fespace); FunctionCoefficient f_coeff(coeff_function); Coefficient *coeff = nullptr; switch (coeff_type) { case CeedCoeff::Const: coeff = new ConstantCoefficient(1.0); break; case CeedCoeff::Grid: gf.ProjectCoefficient(f_coeff); coeff = new GridFunctionCoefficient(&gf); break; case CeedCoeff::Quad: coeff = &f_coeff; break; default: mfem_error("Unexpected coefficient type."); break; } switch (pb) { case Problem::Mass: k_ref.AddDomainIntegrator(new MassIntegrator(*coeff)); k_test.AddDomainIntegrator(new MassIntegrator(*coeff)); break; case Problem::Diffusion: k_ref.AddDomainIntegrator(new DiffusionIntegrator(*coeff)); k_test.AddDomainIntegrator(new DiffusionIntegrator(*coeff)); break; case Problem::VectorMass: k_ref.AddDomainIntegrator(new VectorMassIntegrator(*coeff)); k_test.AddDomainIntegrator(new VectorMassIntegrator(*coeff)); break; case Problem::VectorDiffusion: k_ref.AddDomainIntegrator(new VectorDiffusionIntegrator(*coeff)); k_test.AddDomainIntegrator(new VectorDiffusionIntegrator(*coeff)); break; } k_ref.Assemble(); k_ref.Finalize(); k_test.SetAssemblyLevel(assembly); k_test.Assemble(); GridFunction x(&fespace), y_ref(&fespace), y_test(&fespace); x.Randomize(1); k_ref.Mult(x,y_ref); k_test.Mult(x,y_test); y_test -= y_ref; REQUIRE(y_test.Norml2() < 1.e-12); } TEST_CASE("CEED", "[CEED]") { auto assembly = GENERATE(AssemblyLevel::PARTIAL); auto coeff_type = GENERATE(CeedCoeff::Const,CeedCoeff::Grid,CeedCoeff::Quad); auto pb = GENERATE(Problem::Mass,Problem::Diffusion, Problem::VectorMass,Problem::VectorDiffusion); auto order = GENERATE(4); auto mesh = GENERATE("../../data/inline-quad.mesh","../../data/star-q3.mesh", "../../data/inline-hex.mesh","../../data/fichera-q3.mesh", "../../data/amr-quad.mesh","../../data/fichera-amr.mesh"); test_ceed_operator(mesh, order, coeff_type, pb, assembly); } // test case } // namespace ceed_test int main(int argc, char *argv[]) { // There must be exactly one instance. Catch::Session session; const char *device_str = (argc == 1) ? "ceed-cpu" : argv[argc-1]; // Apply provided command line arguments. int r = session.applyCommandLine((argc == 1) ? argc : argc - 1, argv); if (r != 0) { return r; } Device device(device_str); int result = session.run(); return result; } <commit_msg>Modiify test_ceed for Vector Mass and Diffusion.<commit_after>// Copyright (c) 2010-2020, Lawrence Livermore National Security, LLC. Produced // at the Lawrence Livermore National Laboratory. All Rights reserved. See files // LICENSE and NOTICE for details. LLNL-CODE-806117. // // This file is part of the MFEM library. For more information and source code // availability visit https://mfem.org. // // MFEM is free software; you can redistribute it and/or modify it under the // terms of the BSD-3 license. We welcome feedback and contributions, see file // CONTRIBUTING.md for details. #define CATCH_CONFIG_RUNNER #include "catch.hpp" #include "mfem.hpp" #include <fstream> #include <iostream> #include "../../../fem/libceed/ceed.hpp" using namespace mfem; namespace ceed_test { double coeff_function(const Vector &x) { return 1.0 + x[0]*x[0]; } static std::string getString(AssemblyLevel assembly) { switch (assembly) { case AssemblyLevel::NONE: return "NONE"; break; case AssemblyLevel::PARTIAL: return "PARTIAL"; break; case AssemblyLevel::ELEMENT: return "ELEMENT"; break; case AssemblyLevel::FULL: return "FULL"; break; case AssemblyLevel::LEGACYFULL: return "LEGACYFULL"; break; } } static std::string getString(CeedCoeff coeff_type) { switch (coeff_type) { case CeedCoeff::Const: return "Const"; break; case CeedCoeff::Grid: return "Grid"; break; case CeedCoeff::Quad: return "Quad"; break; } } enum class Problem {Mass, Diffusion, VectorMass, VectorDiffusion}; static std::string getString(Problem pb) { switch (pb) { case Problem::Mass: return "Mass"; break; case Problem::Diffusion: return "Diffusion"; break; case Problem::VectorMass: return "VectorMass"; break; case Problem::VectorDiffusion: return "VectorDiffusion"; break; } } void test_ceed_operator(const char* input, int order, const CeedCoeff coeff_type, const Problem pb, const AssemblyLevel assembly) { std::string section = "assembly: " + getString(assembly) + "\n" + "coeff_type: " + getString(coeff_type) + "\n" + "pb: " + getString(pb) + "\n" + "order: " + std::to_string(order) + "\n" + "mesh: " + input; INFO(section); Mesh mesh(input, 1, 1); mesh.EnsureNodes(); int dim = mesh.Dimension(); H1_FECollection fec(order, dim); bool vecOp = pb == Problem::VectorMass || pb == Problem::VectorDiffusion; const int vdim = vecOp ? dim : 1; FiniteElementSpace fes(&mesh, &fec, vdim); BilinearForm k_test(&fes); BilinearForm k_ref(&fes); FiniteElementSpace coeff_fes(&mesh, &fec); GridFunction gf(&coeff_fes); FunctionCoefficient f_coeff(coeff_function); Coefficient *coeff = nullptr; switch (coeff_type) { case CeedCoeff::Const: coeff = new ConstantCoefficient(1.0); break; case CeedCoeff::Grid: gf.ProjectCoefficient(f_coeff); coeff = new GridFunctionCoefficient(&gf); break; case CeedCoeff::Quad: coeff = &f_coeff; break; } switch (pb) { case Problem::Mass: k_ref.AddDomainIntegrator(new MassIntegrator(*coeff)); k_test.AddDomainIntegrator(new MassIntegrator(*coeff)); break; case Problem::Diffusion: k_ref.AddDomainIntegrator(new DiffusionIntegrator(*coeff)); k_test.AddDomainIntegrator(new DiffusionIntegrator(*coeff)); break; case Problem::VectorMass: k_ref.AddDomainIntegrator(new VectorMassIntegrator(*coeff)); k_test.AddDomainIntegrator(new VectorMassIntegrator(*coeff)); break; case Problem::VectorDiffusion: k_ref.AddDomainIntegrator(new VectorDiffusionIntegrator(*coeff)); k_test.AddDomainIntegrator(new VectorDiffusionIntegrator(*coeff)); break; } k_ref.Assemble(); k_ref.Finalize(); k_test.SetAssemblyLevel(assembly); k_test.Assemble(); GridFunction x(&fes), y_ref(&fes), y_test(&fes); x.Randomize(1); k_ref.Mult(x,y_ref); k_test.Mult(x,y_test); y_test -= y_ref; REQUIRE(y_test.Norml2() < 1.e-12); } TEST_CASE("CEED", "[CEED]") { auto assembly = GENERATE(AssemblyLevel::PARTIAL); auto coeff_type = GENERATE(CeedCoeff::Const,CeedCoeff::Grid,CeedCoeff::Quad); auto pb = GENERATE(Problem::Mass,Problem::Diffusion, Problem::VectorMass,Problem::VectorDiffusion); auto order = GENERATE(1,2,4); auto mesh = GENERATE("../../data/inline-quad.mesh","../../data/inline-hex.mesh", "../../data/star.mesh","../../data/fichera.mesh", // "../../data/star-q3.mesh","../../data/fichera-q3.mesh", "../../data/amr-quad.mesh","../../data/fichera-amr.mesh"); test_ceed_operator(mesh, order, coeff_type, pb, assembly); } // test case } // namespace ceed_test int main(int argc, char *argv[]) { // There must be exactly one instance. Catch::Session session; const char *device_str = (argc == 1) ? "ceed-cpu" : argv[argc-1]; // Apply provided command line arguments. int r = session.applyCommandLine((argc == 1) ? argc : argc - 1, argv); if (r != 0) { return r; } Device device(device_str); int result = session.run(); return result; } <|endoftext|>
<commit_before>/****************************************************************************** * The MIT License (MIT) * * Copyright (c) 2019-2020 Baldur Karlsson * * 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 "CustomPaintWidget.h" #include <math.h> #include <QPainter> #include "Code/Interface/QRDInterface.h" CustomPaintWidget::CustomPaintWidget(QWidget *parent) : QWidget(parent) { m_Ctx = NULL; m_Output = NULL; setAttribute(Qt::WA_OpaquePaintEvent); setMouseTracking(true); m_Tag = QFormatStr("custompaint%1").arg((uintptr_t) this); } CustomPaintWidget::CustomPaintWidget(ICaptureContext *c, QWidget *parent) : QWidget(parent) { m_Ctx = c; m_Output = NULL; setAttribute(Qt::WA_OpaquePaintEvent); if(c) setAttribute(Qt::WA_PaintOnScreen); setMouseTracking(true); m_Tag = QFormatStr("custompaint%1").arg((uintptr_t) this); } CustomPaintWidget::~CustomPaintWidget() { } void CustomPaintWidget::mousePressEvent(QMouseEvent *e) { emit clicked(e); } void CustomPaintWidget::mouseDoubleClickEvent(QMouseEvent *event) { emit(doubleClicked(event)); } void CustomPaintWidget::mouseMoveEvent(QMouseEvent *e) { emit mouseMove(e); } void CustomPaintWidget::wheelEvent(QWheelEvent *e) { emit mouseWheel(e); } void CustomPaintWidget::resizeEvent(QResizeEvent *e) { emit resize(e); } void CustomPaintWidget::keyPressEvent(QKeyEvent *e) { emit keyPress(e); } void CustomPaintWidget::keyReleaseEvent(QKeyEvent *e) { emit keyRelease(e); } void CustomPaintWidget::paintEvent(QPaintEvent *e) { if(m_Ctx) { if(m_Output != NULL) m_Ctx->Replay().AsyncInvoke(m_Tag, [this](IReplayController *r) { m_Output->Display(); }); } else if(m_Dark == m_Light) { QPainter p(this); p.fillRect(rect(), m_Dark); } else { int numX = (int)ceil((float)rect().width() / 64.0f); int numY = (int)ceil((float)rect().height() / 64.0f); QPainter p(this); for(int x = 0; x < numX; x++) { for(int y = 0; y < numY; y++) { QColor &col = ((x % 2) == (y % 2)) ? m_Dark : m_Light; p.fillRect(QRect(x * 64, y * 64, 64, 64), col); } } } } #if defined(RENDERDOC_PLATFORM_APPLE) bool CustomPaintWidget::event(QEvent *e) { if(m_Ctx && e->type() == QEvent::UpdateRequest) paintEvent(NULL); return QWidget::event(e); } #endif <commit_msg>Include "QEvent"<commit_after>/****************************************************************************** * The MIT License (MIT) * * Copyright (c) 2019-2020 Baldur Karlsson * * 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 "CustomPaintWidget.h" #include <math.h> #include <QEvent> #include <QPainter> #include "Code/Interface/QRDInterface.h" CustomPaintWidget::CustomPaintWidget(QWidget *parent) : QWidget(parent) { m_Ctx = NULL; m_Output = NULL; setAttribute(Qt::WA_OpaquePaintEvent); setMouseTracking(true); m_Tag = QFormatStr("custompaint%1").arg((uintptr_t) this); } CustomPaintWidget::CustomPaintWidget(ICaptureContext *c, QWidget *parent) : QWidget(parent) { m_Ctx = c; m_Output = NULL; setAttribute(Qt::WA_OpaquePaintEvent); if(c) setAttribute(Qt::WA_PaintOnScreen); setMouseTracking(true); m_Tag = QFormatStr("custompaint%1").arg((uintptr_t) this); } CustomPaintWidget::~CustomPaintWidget() { } void CustomPaintWidget::mousePressEvent(QMouseEvent *e) { emit clicked(e); } void CustomPaintWidget::mouseDoubleClickEvent(QMouseEvent *event) { emit(doubleClicked(event)); } void CustomPaintWidget::mouseMoveEvent(QMouseEvent *e) { emit mouseMove(e); } void CustomPaintWidget::wheelEvent(QWheelEvent *e) { emit mouseWheel(e); } void CustomPaintWidget::resizeEvent(QResizeEvent *e) { emit resize(e); } void CustomPaintWidget::keyPressEvent(QKeyEvent *e) { emit keyPress(e); } void CustomPaintWidget::keyReleaseEvent(QKeyEvent *e) { emit keyRelease(e); } void CustomPaintWidget::paintEvent(QPaintEvent *e) { if(m_Ctx) { if(m_Output != NULL) m_Ctx->Replay().AsyncInvoke(m_Tag, [this](IReplayController *r) { m_Output->Display(); }); } else if(m_Dark == m_Light) { QPainter p(this); p.fillRect(rect(), m_Dark); } else { int numX = (int)ceil((float)rect().width() / 64.0f); int numY = (int)ceil((float)rect().height() / 64.0f); QPainter p(this); for(int x = 0; x < numX; x++) { for(int y = 0; y < numY; y++) { QColor &col = ((x % 2) == (y % 2)) ? m_Dark : m_Light; p.fillRect(QRect(x * 64, y * 64, 64, 64), col); } } } } #if defined(RENDERDOC_PLATFORM_APPLE) bool CustomPaintWidget::event(QEvent *e) { if(m_Ctx && e->type() == QEvent::UpdateRequest) paintEvent(NULL); return QWidget::event(e); } #endif <|endoftext|>
<commit_before>#include "pch.h" #include <iostream> int _cdecl wmain( __in ULONG argc, __in_ecount(argc) PWCHAR argv[] ) { PrintMessage(L"viogpuap.exe built on %ws %ws\n", _CRT_WIDE(__DATE__) , _CRT_WIDE(__TIME__)); PipeClient* pClient = NULL; if (argc == 2 && iswdigit(argv[1][0])) { std::wstring pipename = PIPE_NAME; pipename.append(argv[1]); if (pipename.length()) { pClient = new PipeClient(pipename); pClient->Init(); } } GpuAdaptersMgr* m_pMgr; m_pMgr = new GpuAdaptersMgr(); if (!m_pMgr || !m_pMgr->Init()) { ErrorHandler("Start GpuAdaptersMgr", GetLastError()); return 0; } if (pClient) { pClient->WaitRunning(); } else { while (getchar() != 'q'); } m_pMgr->Close(); delete m_pMgr; if (pClient) { pClient->Close(); delete pClient; pClient = NULL; } } <commit_msg>[viogpudo] fix a problem reported by Coverity Scan (which for some reason expects int main function to be returning a value explicitly)<commit_after>#include "pch.h" #include <iostream> int _cdecl wmain( __in ULONG argc, __in_ecount(argc) PWCHAR argv[] ) { PrintMessage(L"viogpuap.exe built on %ws %ws\n", _CRT_WIDE(__DATE__) , _CRT_WIDE(__TIME__)); PipeClient* pClient = NULL; if (argc == 2 && iswdigit(argv[1][0])) { std::wstring pipename = PIPE_NAME; pipename.append(argv[1]); if (pipename.length()) { pClient = new PipeClient(pipename); pClient->Init(); } } GpuAdaptersMgr* m_pMgr; m_pMgr = new GpuAdaptersMgr(); if (!m_pMgr || !m_pMgr->Init()) { ErrorHandler("Start GpuAdaptersMgr", GetLastError()); return 0; } if (pClient) { pClient->WaitRunning(); } else { while (getchar() != 'q'); } m_pMgr->Close(); delete m_pMgr; m_pMgr = NULL; if (pClient) { pClient->Close(); delete pClient; pClient = NULL; } return 0; } <|endoftext|>
<commit_before>/*************************************************************************** ** ** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies). ** All rights reserved. ** Contact: Nokia Corporation ([email protected]) ** ** This file is part of Testability Driver Qt Agent ** ** If you have questions regarding the use of this file, please contact ** Nokia at [email protected] . ** ** This library is free software; you can redistribute it and/or ** modify it under the terms of the GNU Lesser General Public ** License version 2.1 as published by the Free Software Foundation ** and appearing in the file LICENSE.LGPL included in the packaging ** of this file. ** ****************************************************************************/ #include <QDebug> #include <QProcess> #include <QCoreApplication> #include <taslogger.h> #include <tascoreutils.h> #include <tasdatashare.h> #include "tasdeviceutils.h" #include "tasclientmanager.h" #include "startappservice.h" #if (defined(Q_OS_WIN32) || defined(Q_OS_WINCE)) #include <windows.h> #elif (defined(Q_OS_UNIX) || defined(Q_OS_WS_MAC)) #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include "private/qcore_unix_p.h" #endif const char* const SET_PARAMS_ONLY = "set_params_only"; const char* const DETACH_MODE = "detached"; const char* const NO_WAIT = "noWait"; StartAppService::StartAppService() {} StartAppService::~StartAppService() {} bool StartAppService::executeService(TasCommandModel& model, TasResponse& response) { if(model.service() == serviceName() ){ // Turn screen on. TasDeviceUtils::resetInactivity(); TasCommand* command = getCommandParameters(model, "Run"); if(command){ startApplication(*command, response); } else{ TasLogger::logger()->error("StartAppService::executeService no Run command found!"); response.setErrorMessage("Could not parse Run command from the request!"); } return true; } else{ return false; } } /*! Attempts to start a process using the application path send in the command model. */ void StartAppService::startApplication(TasCommand& command, TasResponse& response) { QString applicationPath = command.parameter("application_path"); QString args = command.parameter("arguments"); QString envs = command.parameter("environment"); TasLogger::logger()->debug(QString("TasServer::startApplication: '%1'").arg(applicationPath)); TasLogger::logger()->debug(QString("TasServer::startApplication: Arguments: '%1'").arg(args)); TasLogger::logger()->debug(QString("TasServer::startApplication: Environment: '%1'").arg(envs)); QStringList arguments = args.split(","); QStringList environmentVars = envs.split(" "); setRuntimeParams(command); if(arguments.contains(SET_PARAMS_ONLY)){ // do not start app, just need to set the parameters response.requester()->sendResponse(response.messageId(), QString("0")); } else{ arguments.removeAll(DETACH_MODE); arguments.removeAll(NO_WAIT); launchDetached(applicationPath, arguments, environmentVars, response); } } void StartAppService::setRuntimeParams(TasCommand& command) { QString applicationPath = command.parameter("application_path"); QString eventList = command.parameter("events_to_listen"); QString signalList = command.parameter("signals_to_listen"); TasLogger::logger()->debug("StartAppService::setRuntimeParams signals: " + signalList); if(!eventList.isEmpty() || !signalList.isEmpty()){ TasSharedData startupData(eventList.split(","), signalList.split(",")); QString identifier = TasCoreUtils::parseExecutable(applicationPath); if(!TasClientManager::instance()->writeStartupData(identifier, startupData)){ TasLogger::logger()->error("StartAppService::setRuntimeParams could not set run time params for identifier: " + identifier + "!"); } else { TasLogger::logger()->error("StartAppService::setRuntimeParams set with identifier: " + identifier); } } } QHash<QString, QString> StartAppService::parseEnvironmentVariables(const QString& env) { QHash<QString,QString> vars; QStringList var = env.split(" "); foreach(QString str, var) { QStringList key = str.split("="); if (key.size() == 2) { vars[key.at(0)] = key.at(1); } } return vars; } #ifdef Q_OS_SYMBIAN //Qt startDetach seems to leak memory so need to do it for now. //to be removed when fix in qt static void qt_create_symbian_commandline( const QStringList &arguments, const QString &nativeArguments, QString &commandLine) { for (int i = 0; i < arguments.size(); ++i) { QString tmp = arguments.at(i); tmp.replace(QLatin1String("\\\""), QLatin1String("\\\\\"")); tmp.replace(QLatin1String("\""), QLatin1String("\\\"")); if (tmp.isEmpty() || tmp.contains(QLatin1Char(' ')) || tmp.contains(QLatin1Char('\t'))) { QString endQuote(QLatin1String("\"")); int i = tmp.length(); while (i > 0 && tmp.at(i - 1) == QLatin1Char('\\')) { --i; endQuote += QLatin1String("\\"); } commandLine += QLatin1String("\"") + tmp.left(i) + endQuote + QLatin1Char(' '); } else { commandLine += tmp + QLatin1Char(' '); } } if (!nativeArguments.isEmpty()) commandLine += nativeArguments; else if (!commandLine.isEmpty()) // Chop the extra trailing space if any arguments were appended commandLine.chop(1); } #endif void StartAppService::launchDetached(const QString& applicationPath, const QStringList& arguments, const QStringList& environmentVars, TasResponse& response) { #ifdef Q_OS_SYMBIAN //Qt startDetach seems to leak memory so need to do it for now. //to be removed when fix in qt qint64 pid; QString commandLine; QString nativeArguments; qt_create_symbian_commandline(arguments, nativeArguments, commandLine); TPtrC program_ptr(reinterpret_cast<const TText*>(applicationPath.constData())); TPtrC cmdline_ptr(reinterpret_cast<const TText*>(commandLine.constData())); RProcess process; if( process.Create(program_ptr, cmdline_ptr) == KErrNone){ process.Resume(); pid = process.Id().Id(); process.Close(); TasClientManager::instance()->addStartedApp(applicationPath, QDateTime::currentDateTime().toString("yyyyMMddhhmmsszzz")); response.setData(QString::number(pid)); }require 'tdriver' @sut = TDriver.sut(:Id => 'sut_qt') @app = @sut.run(:name => '/usr/bin/calculator') #elif (defined(Q_OS_WIN32) || defined(Q_OS_WINCE)) STARTUPINFO si; PROCESS_INFORMATION pi; ZeroMemory( &si, sizeof(si) ); si.cb = sizeof(si); ZeroMemory( &pi, sizeof(pi) ); // Arguments QString argv = applicationPath + arguments.join(" "); // Environment bloc variable QStringList envList = QProcess::systemEnvironment() << environmentVars; WCHAR envp[envList.join(" ").length() + 2]; // just counting memory in cluding the NULL (\0) string ends and binal NULL block end LPTSTR env = (LPTSTR) envp; for (int i = 0; i < envList.length(); i++) { env = lstrcpy( env, (LPTSTR) envList[i].utf16() ); env += lstrlen( (LPTSTR) envList[i].utf16() ) +1; } *env = (WCHAR) NULL; // DEBUG // LPTSTR lpszVariable = envp; // while (*lpszVariable) //while not null // { // TasLogger::logger()->debug( QString("TasServer::launchDetached: ENV: %1").arg(QString::fromUtf16((ushort *) lpszVariable)) ); // lpszVariable += lstrlen(lpszVariable) + 1; // } // Start the child process. if( CreateProcess( NULL, // No module name (use command line) (WCHAR *) argv.utf16(), // Command line NULL, // Process handle not inheritable NULL, // Thread handle not inheritable FALSE, // Set handle inheritance to FALSE CREATE_UNICODE_ENVIRONMENT, // 0 for no creation flags (LPVOID) envp, // Use parent's environment block NULL, // Use parent's starting directory &si, // Pointer to STARTUPINFO structure &pi ) // Pointer to PROCESS_INFORMATION structure ) { QString pid = QString::number(pi.dwProcessId); CloseHandle( pi.hProcess ); CloseHandle( pi.hThread ); TasLogger::logger()->debug( QString("TasServer::launchDetached: Child PID: %1").arg(pid) ); response.setData(pid); } #elif (defined(Q_OS_UNIX) || defined(Q_OS_WS_MAC)) pid_t pid, sid, grandpid; int pidPipeDesc[2]; qt_safe_pipe(pidPipeDesc); // Create Arguments ARRAY (application path to executable on first element) QStringList paramList; paramList << applicationPath; paramList << arguments; char **paramListArray = new char*[ paramList.length() + 1 ]; for( int i = 0; i < paramList.length(); i++) { QByteArray variable = ((QString) paramList[i]).toLocal8Bit(); char *const variablePtr = new char[variable.length() + 1]; strcpy(variablePtr, variable.data()); paramListArray[i] = variablePtr; } paramListArray[paramList.length()] = NULL; // Create environment Array with NULL end element QStringList envList = QProcess::systemEnvironment() << environmentVars; //TasLogger::logger()->debug(QString("TasServer::startApplication: ALL '%1'").arg(envList.join(","))); //TasLogger::logger()->debug(QString("TasServer::startApplication: USER '%1'").arg(environmentVars.join(","))); char **envListArray = new char*[ envList.length() + 1 ]; for( int i = 0; i < envList.length(); i++) { QByteArray variable = ((QString) envList[i]).toLocal8Bit(); char *const variablePtr = new char[variable.length() + 1]; strcpy(variablePtr, variable.data()); envListArray[i] = variablePtr; } envListArray[envList.length()] = NULL; // START MAKING CHILDREN HERE :D // Child if ( (pid = fork()) == 0) { // We are only going to write on the pipe for papa qt_safe_close(pidPipeDesc[0]); // Create new session for the process (detatch from parent process group) sid = setsid(); if ( sid < 0 ) { TasLogger::logger()->error( QString("TasServer::launchDetached:Failed to detach child.")); exit(1); } // Grandchild if ( ( grandpid = fork() ) == 0 ) { // Try see if we don't need path execve( paramListArray[0], paramListArray, envListArray); // Try also on all path directories if above fails const QString path = QString::fromLocal8Bit(::getenv("PATH")); const QString file = QString::fromLocal8Bit(paramListArray[0]); if (!path.isEmpty()) { QStringList pathEntries = path.split(QLatin1Char(':')); for (int k = 0; k < pathEntries.size(); ++k) { QByteArray tmp = QFile::encodeName(pathEntries.at(k)); if (!tmp.endsWith('/')) tmp += '/'; tmp += QFile::encodeName(file); paramListArray[0] = tmp.data(); TasLogger::logger()->error( QString("TasServer::launchDetached: PATH = '%1'").arg((char *) paramListArray[0])); execve( paramListArray[0], paramListArray, envListArray); } } TasLogger::logger()->error( QString("TasServer::launchDetached: Granhild process died straight away.")); } // Child exit in order to end detachment of grandchild else if( grandpid > 0) { qt_safe_write(pidPipeDesc[1], &grandpid, sizeof(pid_t)); qt_safe_close(pidPipeDesc[1]); _exit(0); } } // Parent else if (pid > 0) { // We are only going to read from the pipe from child qt_safe_close(pidPipeDesc[1]); pid_t actualpid = 0; qt_safe_read(pidPipeDesc[0], &actualpid, sizeof(pid_t)); qt_safe_close(pidPipeDesc[0]); pid = actualpid; // Free memory for (int i = 0; i < paramList.length(); i++ ) { delete [] paramListArray[i]; } delete [] paramListArray; for (int i = 0; i < envList.length(); i++ ) { delete [] envListArray[i]; } delete [] envListArray; TasLogger::logger()->debug( QString("TasServer::launchDetached: Child PID: %1").arg((int)pid) ); response.setData(QString::number((int) pid)); } #else qint64 pid; if(QProcess::startDetached(applicationPath, arguments, ".", &pid)){ TasClientManager::instance()->addStartedApp(applicationPath, QDateTime::currentDateTime().toString("yyyyMMddhhmmsszzz")); response.setData(QString::number(pid)); } #endif else{ TasLogger::logger()->error("TasServer::launchDetached: Could not start the application " + applicationPath); response.setErrorMessage("Could not start the application " + applicationPath); } } <commit_msg>Rolled back changes on startapp service<commit_after>/*************************************************************************** ** ** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies). ** All rights reserved. ** Contact: Nokia Corporation ([email protected]) ** ** This file is part of Testability Driver Qt Agent ** ** If you have questions regarding the use of this file, please contact ** Nokia at [email protected] . ** ** This library is free software; you can redistribute it and/or ** modify it under the terms of the GNU Lesser General Public ** License version 2.1 as published by the Free Software Foundation ** and appearing in the file LICENSE.LGPL included in the packaging ** of this file. ** ****************************************************************************/ #include <QDebug> #include <QProcess> #include <QCoreApplication> #include <taslogger.h> #include <tascoreutils.h> #include <tasdatashare.h> #include "tasdeviceutils.h" #include "tasclientmanager.h" #include "startappservice.h" #if (defined(Q_OS_WIN32) || defined(Q_OS_WINCE)) #include <windows.h> #elif (defined(Q_OS_UNIX) || defined(Q_OS_WS_MAC)) #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include "private/qcore_unix_p.h" #endif const char* const SET_PARAMS_ONLY = "set_params_only"; const char* const DETACH_MODE = "detached"; const char* const NO_WAIT = "noWait"; StartAppService::StartAppService() {} StartAppService::~StartAppService() {} bool StartAppService::executeService(TasCommandModel& model, TasResponse& response) { if(model.service() == serviceName() ){ // Turn screen on. TasDeviceUtils::resetInactivity(); TasCommand* command = getCommandParameters(model, "Run"); if(command){ startApplication(*command, response); } else{ TasLogger::logger()->error("StartAppService::executeService no Run command found!"); response.setErrorMessage("Could not parse Run command from the request!"); } return true; } else{ return false; } } /*! Attempts to start a process using the application path send in the command model. */ void StartAppService::startApplication(TasCommand& command, TasResponse& response) { QString applicationPath = command.parameter("application_path"); QString args = command.parameter("arguments"); QString envs = command.parameter("environment"); TasLogger::logger()->debug(QString("TasServer::startApplication: '%1'").arg(applicationPath)); TasLogger::logger()->debug(QString("TasServer::startApplication: Arguments: '%1'").arg(args)); TasLogger::logger()->debug(QString("TasServer::startApplication: Environment: '%1'").arg(envs)); QStringList arguments = args.split(","); QStringList environmentVars = envs.split(" "); setRuntimeParams(command); if(arguments.contains(SET_PARAMS_ONLY)){ // do not start app, just need to set the parameters response.requester()->sendResponse(response.messageId(), QString("0")); } else{ arguments.removeAll(DETACH_MODE); arguments.removeAll(NO_WAIT); launchDetached(applicationPath, arguments, environmentVars, response); } } void StartAppService::setRuntimeParams(TasCommand& command) { QString applicationPath = command.parameter("application_path"); QString eventList = command.parameter("events_to_listen"); QString signalList = command.parameter("signals_to_listen"); TasLogger::logger()->debug("StartAppService::setRuntimeParams signals: " + signalList); if(!eventList.isEmpty() || !signalList.isEmpty()){ TasSharedData startupData(eventList.split(","), signalList.split(",")); QString identifier = TasCoreUtils::parseExecutable(applicationPath); if(!TasClientManager::instance()->writeStartupData(identifier, startupData)){ TasLogger::logger()->error("StartAppService::setRuntimeParams could not set run time params for identifier: " + identifier + "!"); } else { TasLogger::logger()->error("StartAppService::setRuntimeParams set with identifier: " + identifier); } } } QHash<QString, QString> StartAppService::parseEnvironmentVariables(const QString& env) { QHash<QString,QString> vars; QStringList var = env.split(" "); foreach(QString str, var) { QStringList key = str.split("="); if (key.size() == 2) { vars[key.at(0)] = key.at(1); } } return vars; } #ifdef Q_OS_SYMBIAN //Qt startDetach seems to leak memory so need to do it for now. //to be removed when fix in qt static void qt_create_symbian_commandline( const QStringList &arguments, const QString &nativeArguments, QString &commandLine) { for (int i = 0; i < arguments.size(); ++i) { QString tmp = arguments.at(i); tmp.replace(QLatin1String("\\\""), QLatin1String("\\\\\"")); tmp.replace(QLatin1String("\""), QLatin1String("\\\"")); if (tmp.isEmpty() || tmp.contains(QLatin1Char(' ')) || tmp.contains(QLatin1Char('\t'))) { QString endQuote(QLatin1String("\"")); int i = tmp.length(); while (i > 0 && tmp.at(i - 1) == QLatin1Char('\\')) { --i; endQuote += QLatin1String("\\"); } commandLine += QLatin1String("\"") + tmp.left(i) + endQuote + QLatin1Char(' '); } else { commandLine += tmp + QLatin1Char(' '); } } if (!nativeArguments.isEmpty()) commandLine += nativeArguments; else if (!commandLine.isEmpty()) // Chop the extra trailing space if any arguments were appended commandLine.chop(1); } #endif void StartAppService::launchDetached(const QString& applicationPath, const QStringList& arguments, const QStringList& environmentVars, TasResponse& response) { #ifdef Q_OS_SYMBIAN //Qt startDetach seems to leak memory so need to do it for now. //to be removed when fix in qt qint64 pid; QString commandLine; QString nativeArguments; qt_create_symbian_commandline(arguments, nativeArguments, commandLine); TPtrC program_ptr(reinterpret_cast<const TText*>(applicationPath.constData())); TPtrC cmdline_ptr(reinterpret_cast<const TText*>(commandLine.constData())); RProcess process; if( process.Create(program_ptr, cmdline_ptr) == KErrNone){ process.Resume(); pid = process.Id().Id(); process.Close(); TasClientManager::instance()->addStartedApp(applicationPath, QDateTime::currentDateTime().toString("yyyyMMddhhmmsszzz")); response.setData(QString::number(pid)); }require 'tdriver' @sut = TDriver.sut(:Id => 'sut_qt') @app = @sut.run(:name => '/usr/bin/calculator') #elif (defined(Q_OS_WIN32) && defined(Q_OS_WINCE) && defined(Q_OS_UNIX)) //ignore untill fixed STARTUPINFO si; PROCESS_INFORMATION pi; ZeroMemory( &si, sizeof(si) ); si.cb = sizeof(si); ZeroMemory( &pi, sizeof(pi) ); // Arguments QString argv = applicationPath + arguments.join(" "); // Environment bloc variable QStringList envList = QProcess::systemEnvironment() << environmentVars; WCHAR envp[envList.join(" ").length() + 2]; // just counting memory in cluding the NULL (\0) string ends and binal NULL block end LPTSTR env = (LPTSTR) envp; for (int i = 0; i < envList.length(); i++) { env = lstrcpy( env, (LPTSTR) envList[i].utf16() ); env += lstrlen( (LPTSTR) envList[i].utf16() ) +1; } *env = (WCHAR) NULL; // DEBUG // LPTSTR lpszVariable = envp; // while (*lpszVariable) //while not null // { // TasLogger::logger()->debug( QString("TasServer::launchDetached: ENV: %1").arg(QString::fromUtf16((ushort *) lpszVariable)) ); // lpszVariable += lstrlen(lpszVariable) + 1; // } // Start the child process. if( CreateProcess( NULL, // No module name (use command line) (WCHAR *) argv.utf16(), // Command line NULL, // Process handle not inheritable NULL, // Thread handle not inheritable FALSE, // Set handle inheritance to FALSE CREATE_UNICODE_ENVIRONMENT, // 0 for no creation flags (LPVOID) envp, // Use parent's environment block NULL, // Use parent's starting directory &si, // Pointer to STARTUPINFO structure &pi ) // Pointer to PROCESS_INFORMATION structure ) { QString pid = QString::number(pi.dwProcessId); CloseHandle( pi.hProcess ); CloseHandle( pi.hThread ); TasLogger::logger()->debug( QString("TasServer::launchDetached: Child PID: %1").arg(pid) ); response.setData(pid); } #elif (defined(Q_OS_UNIX) && defined(Q_OS_WS_MAC) && defined(Q_OS_WIN32) ) pid_t pid, sid, grandpid; int pidPipeDesc[2]; qt_safe_pipe(pidPipeDesc); // Create Arguments ARRAY (application path to executable on first element) QStringList paramList; paramList << applicationPath; paramList << arguments; char **paramListArray = new char*[ paramList.length() + 1 ]; for( int i = 0; i < paramList.length(); i++) { QByteArray variable = ((QString) paramList[i]).toLocal8Bit(); char *const variablePtr = new char[variable.length() + 1]; strcpy(variablePtr, variable.data()); paramListArray[i] = variablePtr; } paramListArray[paramList.length()] = NULL; // Create environment Array with NULL end element QStringList envList = QProcess::systemEnvironment() << environmentVars; //TasLogger::logger()->debug(QString("TasServer::startApplication: ALL '%1'").arg(envList.join(","))); //TasLogger::logger()->debug(QString("TasServer::startApplication: USER '%1'").arg(environmentVars.join(","))); char **envListArray = new char*[ envList.length() + 1 ]; for( int i = 0; i < envList.length(); i++) { QByteArray variable = ((QString) envList[i]).toLocal8Bit(); char *const variablePtr = new char[variable.length() + 1]; strcpy(variablePtr, variable.data()); envListArray[i] = variablePtr; } envListArray[envList.length()] = NULL; // START MAKING CHILDREN HERE :D // Child if ( (pid = fork()) == 0) { // We are only going to write on the pipe for papa qt_safe_close(pidPipeDesc[0]); // Create new session for the process (detatch from parent process group) sid = setsid(); if ( sid < 0 ) { TasLogger::logger()->error( QString("TasServer::launchDetached:Failed to detach child.")); exit(1); } // Grandchild if ( ( grandpid = fork() ) == 0 ) { // Try see if we don't need path execve( paramListArray[0], paramListArray, envListArray); // Try also on all path directories if above fails const QString path = QString::fromLocal8Bit(::getenv("PATH")); const QString file = QString::fromLocal8Bit(paramListArray[0]); if (!path.isEmpty()) { QStringList pathEntries = path.split(QLatin1Char(':')); for (int k = 0; k < pathEntries.size(); ++k) { QByteArray tmp = QFile::encodeName(pathEntries.at(k)); if (!tmp.endsWith('/')) tmp += '/'; tmp += QFile::encodeName(file); paramListArray[0] = tmp.data(); TasLogger::logger()->error( QString("TasServer::launchDetached: PATH = '%1'").arg((char *) paramListArray[0])); execve( paramListArray[0], paramListArray, envListArray); } } TasLogger::logger()->error( QString("TasServer::launchDetached: Granhild process died straight away.")); } // Child exit in order to end detachment of grandchild else if( grandpid > 0) { qt_safe_write(pidPipeDesc[1], &grandpid, sizeof(pid_t)); qt_safe_close(pidPipeDesc[1]); _exit(0); } } // Parent else if (pid > 0) { // We are only going to read from the pipe from child qt_safe_close(pidPipeDesc[1]); pid_t actualpid = 0; qt_safe_read(pidPipeDesc[0], &actualpid, sizeof(pid_t)); qt_safe_close(pidPipeDesc[0]); pid = actualpid; // Free memory for (int i = 0; i < paramList.length(); i++ ) { delete [] paramListArray[i]; } delete [] paramListArray; for (int i = 0; i < envList.length(); i++ ) { delete [] envListArray[i]; } delete [] envListArray; TasLogger::logger()->debug( QString("TasServer::launchDetached: Child PID: %1").arg((int)pid) ); response.setData(QString::number((int) pid)); } #else qint64 pid; if(QProcess::startDetached(applicationPath, arguments, ".", &pid)){ TasClientManager::instance()->addStartedApp(applicationPath, QDateTime::currentDateTime().toString("yyyyMMddhhmmsszzz")); response.setData(QString::number(pid)); } #endif else{ TasLogger::logger()->error("TasServer::launchDetached: Could not start the application " + applicationPath); response.setErrorMessage("Could not start the application " + applicationPath); } } <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: exsrcbrw.hxx,v $ * * $Revision: 1.7 $ * * last change: $Author: hr $ $Date: 2004-05-10 13:08:04 $ * * 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 _SBA_EXTCTRLR_HXX #define _SBA_EXTCTRLR_HXX #ifndef _SBA_BWRCTRLR_HXX #include "brwctrlr.hxx" #endif #ifndef _COM_SUN_STAR_FORM_XFORMCONTROLLER_HPP_ #include <com/sun/star/form/XFormController.hpp> #endif #ifndef _COMPHELPER_UNO3_HXX_ #include <comphelper/uno3.hxx> #endif #ifndef _CPPUHELPER_IMPLBASE2_HXX_ #include <cppuhelper/implbase2.hxx> #endif //============================================================================== //= SbaExternalSourceBrowser //============================================================================== namespace dbaui { class SbaXFormAdapter; class SbaExternalSourceBrowser :public SbaXDataBrowserController ,public ::com::sun::star::util::XModifyBroadcaster { ::cppu::OInterfaceContainerHelper m_aModifyListeners; // for multiplexing the modify events SbaXFormAdapter* m_pDataSourceImpl; sal_Bool m_bInQueryDispatch; // our queryDispatch will ask our frame, which first will ask our queryDispatch, so we need to protect against // recursion public: SbaExternalSourceBrowser(const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& _rM); static ::rtl::OUString getImplementationName_Static() throw( ::com::sun::star::uno::RuntimeException ); static ::com::sun::star::uno::Sequence< ::rtl::OUString > getSupportedServiceNames_Static(void) throw( ::com::sun::star::uno::RuntimeException ); static ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface > SAL_CALL Create(const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >&); // UNO DECLARE_UNO3_DEFAULTS(SbaExternalSourceBrowser, OGenericUnoController); virtual ::com::sun::star::uno::Any SAL_CALL queryInterface(const ::com::sun::star::uno::Type& _rType) throw (::com::sun::star::uno::RuntimeException); // virtual ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Reference< ::com::sun::star::reflection::XIdlClass > > getIdlClasses(void); // static ::com::sun::star::uno::Reference< ::com::sun::star::reflection::XIdlClass > getStaticIdlClass(); // ::com::sun::star::frame::XDispatch virtual void SAL_CALL dispatch(const ::com::sun::star::util::URL& aURL, const ::com::sun::star::uno::Sequence< ::com::sun::star::beans::PropertyValue>& aArgs) throw(::com::sun::star::uno::RuntimeException); // ::com::sun::star::frame::XDispatchProvider virtual ::com::sun::star::uno::Reference< ::com::sun::star::frame::XDispatch > SAL_CALL queryDispatch(const ::com::sun::star::util::URL& aURL, const ::rtl::OUString& aTargetFrameName, sal_Int32 nSearchFlags) throw( ::com::sun::star::uno::RuntimeException ); // ::com::sun::star::util::XModifyListener virtual void SAL_CALL modified(const ::com::sun::star::lang::EventObject& aEvent) throw( ::com::sun::star::uno::RuntimeException ); // ::com::sun::star::util::XModifyBroadcaster virtual void SAL_CALL addModifyListener(const ::com::sun::star::uno::Reference< ::com::sun::star::util::XModifyListener > & aListener) throw( ::com::sun::star::uno::RuntimeException ); virtual void SAL_CALL removeModifyListener(const ::com::sun::star::uno::Reference< ::com::sun::star::util::XModifyListener > & aListener) throw( ::com::sun::star::uno::RuntimeException ); // ::com::sun::star::lang::XComponent virtual void SAL_CALL disposing(); // ::com::sun::star::form::XLoadListener virtual void SAL_CALL unloading(const ::com::sun::star::lang::EventObject& aEvent) throw( ::com::sun::star::uno::RuntimeException ); // ::com::sun::star::lang::XEventListener virtual void SAL_CALL disposing(const ::com::sun::star::lang::EventObject& Source) throw( ::com::sun::star::uno::RuntimeException ); // XServiceInfo virtual ::rtl::OUString SAL_CALL getImplementationName() throw(::com::sun::star::uno::RuntimeException); virtual ::comphelper::StringSequence SAL_CALL getSupportedServiceNames() throw(::com::sun::star::uno::RuntimeException); protected: ~SbaExternalSourceBrowser(); virtual ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XRowSet > CreateForm(); virtual sal_Bool InitializeForm(const ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XRowSet > & xForm); virtual sal_Bool LoadForm(); void Attach(const ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XRowSet > & xMaster); void ClearView(); void startListening(); void stopListening(); }; } #endif // _SBA_EXTCTRLR_HXX <commit_msg>INTEGRATION: CWS ooo19126 (1.7.236); FILE MERGED 2005/09/05 17:34:52 rt 1.7.236.1: #i54170# Change license header: remove SISSL<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: exsrcbrw.hxx,v $ * * $Revision: 1.8 $ * * last change: $Author: rt $ $Date: 2005-09-08 15:54:24 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ #ifndef _SBA_EXTCTRLR_HXX #define _SBA_EXTCTRLR_HXX #ifndef _SBA_BWRCTRLR_HXX #include "brwctrlr.hxx" #endif #ifndef _COM_SUN_STAR_FORM_XFORMCONTROLLER_HPP_ #include <com/sun/star/form/XFormController.hpp> #endif #ifndef _COMPHELPER_UNO3_HXX_ #include <comphelper/uno3.hxx> #endif #ifndef _CPPUHELPER_IMPLBASE2_HXX_ #include <cppuhelper/implbase2.hxx> #endif //============================================================================== //= SbaExternalSourceBrowser //============================================================================== namespace dbaui { class SbaXFormAdapter; class SbaExternalSourceBrowser :public SbaXDataBrowserController ,public ::com::sun::star::util::XModifyBroadcaster { ::cppu::OInterfaceContainerHelper m_aModifyListeners; // for multiplexing the modify events SbaXFormAdapter* m_pDataSourceImpl; sal_Bool m_bInQueryDispatch; // our queryDispatch will ask our frame, which first will ask our queryDispatch, so we need to protect against // recursion public: SbaExternalSourceBrowser(const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& _rM); static ::rtl::OUString getImplementationName_Static() throw( ::com::sun::star::uno::RuntimeException ); static ::com::sun::star::uno::Sequence< ::rtl::OUString > getSupportedServiceNames_Static(void) throw( ::com::sun::star::uno::RuntimeException ); static ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface > SAL_CALL Create(const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >&); // UNO DECLARE_UNO3_DEFAULTS(SbaExternalSourceBrowser, OGenericUnoController); virtual ::com::sun::star::uno::Any SAL_CALL queryInterface(const ::com::sun::star::uno::Type& _rType) throw (::com::sun::star::uno::RuntimeException); // virtual ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Reference< ::com::sun::star::reflection::XIdlClass > > getIdlClasses(void); // static ::com::sun::star::uno::Reference< ::com::sun::star::reflection::XIdlClass > getStaticIdlClass(); // ::com::sun::star::frame::XDispatch virtual void SAL_CALL dispatch(const ::com::sun::star::util::URL& aURL, const ::com::sun::star::uno::Sequence< ::com::sun::star::beans::PropertyValue>& aArgs) throw(::com::sun::star::uno::RuntimeException); // ::com::sun::star::frame::XDispatchProvider virtual ::com::sun::star::uno::Reference< ::com::sun::star::frame::XDispatch > SAL_CALL queryDispatch(const ::com::sun::star::util::URL& aURL, const ::rtl::OUString& aTargetFrameName, sal_Int32 nSearchFlags) throw( ::com::sun::star::uno::RuntimeException ); // ::com::sun::star::util::XModifyListener virtual void SAL_CALL modified(const ::com::sun::star::lang::EventObject& aEvent) throw( ::com::sun::star::uno::RuntimeException ); // ::com::sun::star::util::XModifyBroadcaster virtual void SAL_CALL addModifyListener(const ::com::sun::star::uno::Reference< ::com::sun::star::util::XModifyListener > & aListener) throw( ::com::sun::star::uno::RuntimeException ); virtual void SAL_CALL removeModifyListener(const ::com::sun::star::uno::Reference< ::com::sun::star::util::XModifyListener > & aListener) throw( ::com::sun::star::uno::RuntimeException ); // ::com::sun::star::lang::XComponent virtual void SAL_CALL disposing(); // ::com::sun::star::form::XLoadListener virtual void SAL_CALL unloading(const ::com::sun::star::lang::EventObject& aEvent) throw( ::com::sun::star::uno::RuntimeException ); // ::com::sun::star::lang::XEventListener virtual void SAL_CALL disposing(const ::com::sun::star::lang::EventObject& Source) throw( ::com::sun::star::uno::RuntimeException ); // XServiceInfo virtual ::rtl::OUString SAL_CALL getImplementationName() throw(::com::sun::star::uno::RuntimeException); virtual ::comphelper::StringSequence SAL_CALL getSupportedServiceNames() throw(::com::sun::star::uno::RuntimeException); protected: ~SbaExternalSourceBrowser(); virtual ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XRowSet > CreateForm(); virtual sal_Bool InitializeForm(const ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XRowSet > & xForm); virtual sal_Bool LoadForm(); void Attach(const ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XRowSet > & xMaster); void ClearView(); void startListening(); void stopListening(); }; } #endif // _SBA_EXTCTRLR_HXX <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: admindlg.cxx,v $ * * $Revision: 1.4 $ * * last change: $Author: obo $ $Date: 2006-09-17 07:33:40 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_dbaccess.hxx" #ifndef _DBU_REGHELPER_HXX_ #include "dbu_reghelper.hxx" #endif #ifndef _DBAUI_ADMINDLG_HXX #include "admindlg.hxx" #endif #ifndef _DBAUI_DBADMIN_HXX_ #include "dbadmin.hxx" #endif using namespace dbaui; extern "C" void SAL_CALL createRegistryInfo_ODataSourcePropertyDialog() { static OMultiInstanceAutoRegistration< ODataSourcePropertyDialog > aAutoRegistration; } //......................................................................... namespace dbaui { //......................................................................... using namespace ::com::sun::star::uno; using namespace ::com::sun::star::lang; using namespace ::com::sun::star::beans; //========================================================================= //------------------------------------------------------------------------- ODataSourcePropertyDialog::ODataSourcePropertyDialog(const Reference< XMultiServiceFactory >& _rxORB) :ODatabaseAdministrationDialog(_rxORB) { } //------------------------------------------------------------------------- Sequence<sal_Int8> SAL_CALL ODataSourcePropertyDialog::getImplementationId( ) throw(RuntimeException) { static ::cppu::OImplementationId aId; return aId.getImplementationId(); } //------------------------------------------------------------------------- Reference< XInterface > SAL_CALL ODataSourcePropertyDialog::Create(const Reference< XMultiServiceFactory >& _rxFactory) { return *(new ODataSourcePropertyDialog(_rxFactory)); } //------------------------------------------------------------------------- ::rtl::OUString SAL_CALL ODataSourcePropertyDialog::getImplementationName() throw(RuntimeException) { return getImplementationName_Static(); } //------------------------------------------------------------------------- ::rtl::OUString ODataSourcePropertyDialog::getImplementationName_Static() throw(RuntimeException) { return ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("org.openoffice.comp.dbu.ODatasourceAdministrationDialog")); } //------------------------------------------------------------------------- ::comphelper::StringSequence SAL_CALL ODataSourcePropertyDialog::getSupportedServiceNames() throw(RuntimeException) { return getSupportedServiceNames_Static(); } //------------------------------------------------------------------------- ::comphelper::StringSequence ODataSourcePropertyDialog::getSupportedServiceNames_Static() throw(RuntimeException) { ::comphelper::StringSequence aSupported(1); aSupported.getArray()[0] = ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("com.sun.star.sdb.DatasourceAdministrationDialog")); return aSupported; } //------------------------------------------------------------------------- Reference<XPropertySetInfo> SAL_CALL ODataSourcePropertyDialog::getPropertySetInfo() throw(RuntimeException) { Reference<XPropertySetInfo> xInfo( createPropertySetInfo( getInfoHelper() ) ); return xInfo; } //------------------------------------------------------------------------- ::cppu::IPropertyArrayHelper& ODataSourcePropertyDialog::getInfoHelper() { return *const_cast<ODataSourcePropertyDialog*>(this)->getArrayHelper(); } //------------------------------------------------------------------------------ ::cppu::IPropertyArrayHelper* ODataSourcePropertyDialog::createArrayHelper( ) const { Sequence< Property > aProps; describeProperties(aProps); return new ::cppu::OPropertyArrayHelper(aProps); } //------------------------------------------------------------------------------ Dialog* ODataSourcePropertyDialog::createDialog(Window* _pParent) { ODbAdminDialog* pDialog = new ODbAdminDialog(_pParent, m_pDatasourceItems, m_xORB); // the initial selection if ( m_aInitialSelection.hasValue() ) pDialog->selectDataSource(m_aInitialSelection); return pDialog; } //......................................................................... } // namespace dbaui //......................................................................... <commit_msg>INTEGRATION: CWS changefileheader (1.4.258); FILE MERGED 2008/03/31 13:28:10 rt 1.4.258.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: admindlg.cxx,v $ * $Revision: 1.5 $ * * 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_dbaccess.hxx" #ifndef _DBU_REGHELPER_HXX_ #include "dbu_reghelper.hxx" #endif #ifndef _DBAUI_ADMINDLG_HXX #include "admindlg.hxx" #endif #ifndef _DBAUI_DBADMIN_HXX_ #include "dbadmin.hxx" #endif using namespace dbaui; extern "C" void SAL_CALL createRegistryInfo_ODataSourcePropertyDialog() { static OMultiInstanceAutoRegistration< ODataSourcePropertyDialog > aAutoRegistration; } //......................................................................... namespace dbaui { //......................................................................... using namespace ::com::sun::star::uno; using namespace ::com::sun::star::lang; using namespace ::com::sun::star::beans; //========================================================================= //------------------------------------------------------------------------- ODataSourcePropertyDialog::ODataSourcePropertyDialog(const Reference< XMultiServiceFactory >& _rxORB) :ODatabaseAdministrationDialog(_rxORB) { } //------------------------------------------------------------------------- Sequence<sal_Int8> SAL_CALL ODataSourcePropertyDialog::getImplementationId( ) throw(RuntimeException) { static ::cppu::OImplementationId aId; return aId.getImplementationId(); } //------------------------------------------------------------------------- Reference< XInterface > SAL_CALL ODataSourcePropertyDialog::Create(const Reference< XMultiServiceFactory >& _rxFactory) { return *(new ODataSourcePropertyDialog(_rxFactory)); } //------------------------------------------------------------------------- ::rtl::OUString SAL_CALL ODataSourcePropertyDialog::getImplementationName() throw(RuntimeException) { return getImplementationName_Static(); } //------------------------------------------------------------------------- ::rtl::OUString ODataSourcePropertyDialog::getImplementationName_Static() throw(RuntimeException) { return ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("org.openoffice.comp.dbu.ODatasourceAdministrationDialog")); } //------------------------------------------------------------------------- ::comphelper::StringSequence SAL_CALL ODataSourcePropertyDialog::getSupportedServiceNames() throw(RuntimeException) { return getSupportedServiceNames_Static(); } //------------------------------------------------------------------------- ::comphelper::StringSequence ODataSourcePropertyDialog::getSupportedServiceNames_Static() throw(RuntimeException) { ::comphelper::StringSequence aSupported(1); aSupported.getArray()[0] = ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("com.sun.star.sdb.DatasourceAdministrationDialog")); return aSupported; } //------------------------------------------------------------------------- Reference<XPropertySetInfo> SAL_CALL ODataSourcePropertyDialog::getPropertySetInfo() throw(RuntimeException) { Reference<XPropertySetInfo> xInfo( createPropertySetInfo( getInfoHelper() ) ); return xInfo; } //------------------------------------------------------------------------- ::cppu::IPropertyArrayHelper& ODataSourcePropertyDialog::getInfoHelper() { return *const_cast<ODataSourcePropertyDialog*>(this)->getArrayHelper(); } //------------------------------------------------------------------------------ ::cppu::IPropertyArrayHelper* ODataSourcePropertyDialog::createArrayHelper( ) const { Sequence< Property > aProps; describeProperties(aProps); return new ::cppu::OPropertyArrayHelper(aProps); } //------------------------------------------------------------------------------ Dialog* ODataSourcePropertyDialog::createDialog(Window* _pParent) { ODbAdminDialog* pDialog = new ODbAdminDialog(_pParent, m_pDatasourceItems, m_xORB); // the initial selection if ( m_aInitialSelection.hasValue() ) pDialog->selectDataSource(m_aInitialSelection); return pDialog; } //......................................................................... } // namespace dbaui //......................................................................... <|endoftext|>
<commit_before>/* Author: Wolfgang Bangerth, Texas A&M University, 2008 */ /* $Id$ */ /* */ /* Copyright (C) 2013 by the deal.II authors */ /* */ /* This file is subject to QPL and may not be distributed */ /* without copyright and license information. Please refer */ /* to the file deal.II/doc/license.html for the text and */ /* further information on this license. */ #include <deal.II/base/utilities.h> #include <deal.II/base/quadrature_lib.h> #include <deal.II/base/function.h> #include <deal.II/base/logstream.h> #include <deal.II/lac/vector.h> #include <deal.II/lac/full_matrix.h> #include <deal.II/lac/sparse_matrix.h> #include <deal.II/lac/solver_cg.h> #include <deal.II/lac/precondition.h> #include <deal.II/lac/constraint_matrix.h> #include <deal.II/grid/tria.h> #include <deal.II/grid/grid_generator.h> #include <deal.II/grid/grid_out.h> #include <deal.II/grid/tria_accessor.h> #include <deal.II/grid/tria_iterator.h> #include <deal.II/dofs/dof_handler.h> #include <deal.II/dofs/dof_accessor.h> #include <deal.II/dofs/dof_tools.h> #include <deal.II/fe/fe_q.h> #include <deal.II/fe/fe_values.h> #include <deal.II/numerics/data_out.h> #include <deal.II/numerics/vector_tools.h> #include <deal.II/numerics/matrix_tools.h> #include <fstream> #include <iostream> namespace Step26 { using namespace dealii; template<int dim> class HeatEquation { public: HeatEquation(); void run(); private: void setup_system(); void solve_u(); void output_results() const; Triangulation<dim> triangulation; FE_Q<dim> fe; DoFHandler<dim> dof_handler; ConstraintMatrix constraints; SparsityPattern sparsity_pattern; SparseMatrix<double> mass_matrix; SparseMatrix<double> laplace_matrix; SparseMatrix<double> system_matrix; Vector<double> solution; Vector<double> old_solution; Vector<double> system_rhs; double time, time_step; unsigned int timestep_number; const double theta; }; //------------------------------------- template<int dim> class RightHandSide: public Function<dim> { public: RightHandSide() : Function<dim>(), period (0.2) {} virtual double value(const Point<dim> &p, const unsigned int component = 0) const; private: const double period; }; template<int dim> double RightHandSide<dim>::value(const Point<dim> &p, const unsigned int component) const { Assert (component == 0, ExcInternalError()); Assert (dim == 2, ExcNotImplemented()); const double time = this->get_time(); const double point_within_period = (time/period - std::floor(time/period)); if ((point_within_period >= 0.0) && (point_within_period <= 0.2)) { if ((p[0] > 0.5) && (p[1] > -0.5)) return 1; else return 0; } else if ((point_within_period >= 0.5) && (point_within_period <= 0.7)) { if ((p[0] > -0.5) && (p[1] > 0.5)) return 1; else return 0; } else return 0; } template<int dim> class BoundaryValues: public Function<dim> { public: BoundaryValues() : Function<dim>() { } virtual ~BoundaryValues() { } virtual double value(const Point<dim> &p, const unsigned int component = 0) const; }; template<int dim> double BoundaryValues<dim>::value(const Point<dim> &/*p*/, const unsigned int component) const { Assert(component == 0, ExcInternalError()); return 0; // Zero-Dirichlet Boundary } template<int dim> HeatEquation<dim>::HeatEquation() : fe(1), dof_handler(triangulation), time_step(1. / 500), theta(0.5) { } template<int dim> void HeatEquation<dim>::setup_system() { GridGenerator::hyper_L (triangulation); triangulation.refine_global (5); std::cout << "Number of active cells: " << triangulation.n_active_cells() << std::endl; dof_handler.distribute_dofs(fe); std::cout << "Number of degrees of freedom: " << dof_handler.n_dofs() << std::endl << std::endl; sparsity_pattern.reinit(dof_handler.n_dofs(), dof_handler.n_dofs(), dof_handler.max_couplings_between_dofs()); DoFTools::make_sparsity_pattern(dof_handler, sparsity_pattern); sparsity_pattern.compress(); mass_matrix.reinit(sparsity_pattern); laplace_matrix.reinit(sparsity_pattern); system_matrix.reinit(sparsity_pattern); MatrixCreator::create_mass_matrix(dof_handler, QGauss<dim>(3), mass_matrix); MatrixCreator::create_laplace_matrix(dof_handler, QGauss<dim>(3), laplace_matrix); solution.reinit(dof_handler.n_dofs()); old_solution.reinit(dof_handler.n_dofs()); system_rhs.reinit(dof_handler.n_dofs()); constraints.close(); } template<int dim> void HeatEquation<dim>::solve_u() { SolverControl solver_control(1000, 1e-8 * system_rhs.l2_norm()); SolverCG<> cg(solver_control); PreconditionSSOR<> preconditioner; preconditioner.initialize(system_matrix, 1.0); cg.solve(system_matrix, solution, system_rhs, preconditioner); std::cout << " u-equation: " << solver_control.last_step() << " CG iterations." << std::endl; } template<int dim> void HeatEquation<dim>::output_results() const { DataOut<dim> data_out; data_out.attach_dof_handler(dof_handler); data_out.add_data_vector(solution, "U"); data_out.build_patches(); const std::string filename = "solution-" + Utilities::int_to_string(timestep_number, 3) + ".vtk"; std::ofstream output(filename.c_str()); data_out.write_vtk(output); std::cout << " max= " << time << ' ' << solution.linfty_norm() << std::endl; } template<int dim> void HeatEquation<dim>::run() { setup_system(); VectorTools::interpolate(dof_handler, ZeroFunction<dim>(), solution); timestep_number = 0; output_results(); VectorTools::interpolate(dof_handler, ZeroFunction<dim>(), old_solution); Vector<double> tmp(solution.size()); Vector<double> forcing_terms(solution.size()); while (time <= 0.5) { time += time_step; ++timestep_number; std::cout << "Time step " << timestep_number << " at t=" << time << std::endl; mass_matrix.vmult(system_rhs, old_solution); laplace_matrix.vmult(tmp, old_solution); system_rhs.add(-(1 - theta) * time_step, tmp); RightHandSide<dim> rhs_function; rhs_function.set_time(time); VectorTools::create_right_hand_side(dof_handler, QGauss<dim>(2), rhs_function, tmp); forcing_terms = tmp; forcing_terms *= time_step * theta; rhs_function.set_time(time - time_step); VectorTools::create_right_hand_side(dof_handler, QGauss<dim>(2), rhs_function, tmp); forcing_terms.add(time_step * (1 - theta), tmp); system_rhs += forcing_terms; { BoundaryValues<dim> boundary_values_function; boundary_values_function.set_time(time); std::map<unsigned int, double> boundary_values; VectorTools::interpolate_boundary_values(dof_handler, 0, boundary_values_function, boundary_values); system_matrix.copy_from(mass_matrix); system_matrix.add(theta * time_step, laplace_matrix); MatrixTools::apply_boundary_values(boundary_values, system_matrix, solution, system_rhs); } solve_u(); output_results(); old_solution = solution; } } } int main() { try { using namespace dealii; using namespace Step26; deallog.depth_console(0); HeatEquation<2> heat_equation_solver; heat_equation_solver.run(); } catch (std::exception &exc) { std::cerr << std::endl << std::endl << "----------------------------------------------------" << std::endl; std::cerr << "Exception on processing: " << std::endl << exc.what() << std::endl << "Aborting!" << std::endl << "----------------------------------------------------" << std::endl; return 1; } catch (...) { std::cerr << std::endl << std::endl << "----------------------------------------------------" << std::endl; std::cerr << "Unknown exception!" << std::endl << "Aborting!" << std::endl << "----------------------------------------------------" << std::endl; return 1; } return 0; } <commit_msg>More cleanups.<commit_after>/* Author: Wolfgang Bangerth, Texas A&M University, 2008 */ /* $Id$ */ /* */ /* Copyright (C) 2013 by the deal.II authors */ /* */ /* This file is subject to QPL and may not be distributed */ /* without copyright and license information. Please refer */ /* to the file deal.II/doc/license.html for the text and */ /* further information on this license. */ #include <deal.II/base/utilities.h> #include <deal.II/base/quadrature_lib.h> #include <deal.II/base/function.h> #include <deal.II/base/logstream.h> #include <deal.II/lac/vector.h> #include <deal.II/lac/full_matrix.h> #include <deal.II/lac/sparse_matrix.h> #include <deal.II/lac/solver_cg.h> #include <deal.II/lac/precondition.h> #include <deal.II/lac/constraint_matrix.h> #include <deal.II/grid/tria.h> #include <deal.II/grid/grid_generator.h> #include <deal.II/grid/grid_out.h> #include <deal.II/grid/tria_accessor.h> #include <deal.II/grid/tria_iterator.h> #include <deal.II/dofs/dof_handler.h> #include <deal.II/dofs/dof_accessor.h> #include <deal.II/dofs/dof_tools.h> #include <deal.II/fe/fe_q.h> #include <deal.II/fe/fe_values.h> #include <deal.II/numerics/data_out.h> #include <deal.II/numerics/vector_tools.h> #include <deal.II/numerics/matrix_tools.h> #include <fstream> #include <iostream> namespace Step26 { using namespace dealii; template<int dim> class HeatEquation { public: HeatEquation(); void run(); private: void setup_system(); void solve_time_step(); void output_results() const; Triangulation<dim> triangulation; FE_Q<dim> fe; DoFHandler<dim> dof_handler; ConstraintMatrix constraints; SparsityPattern sparsity_pattern; SparseMatrix<double> mass_matrix; SparseMatrix<double> laplace_matrix; SparseMatrix<double> system_matrix; Vector<double> solution; Vector<double> old_solution; Vector<double> system_rhs; double time; double time_step; unsigned int timestep_number; const double theta; }; template<int dim> class RightHandSide: public Function<dim> { public: RightHandSide() : Function<dim>(), period (0.2) {} virtual double value(const Point<dim> &p, const unsigned int component = 0) const; private: const double period; }; template<int dim> double RightHandSide<dim>::value(const Point<dim> &p, const unsigned int component) const { Assert (component == 0, ExcInternalError()); Assert (dim == 2, ExcNotImplemented()); const double time = this->get_time(); const double point_within_period = (time/period - std::floor(time/period)); if ((point_within_period >= 0.0) && (point_within_period <= 0.2)) { if ((p[0] > 0.5) && (p[1] > -0.5)) return 1; else return 0; } else if ((point_within_period >= 0.5) && (point_within_period <= 0.7)) { if ((p[0] > -0.5) && (p[1] > 0.5)) return 1; else return 0; } else return 0; } template<int dim> class BoundaryValues: public Function<dim> { public: BoundaryValues() : Function<dim>() { } virtual double value(const Point<dim> &p, const unsigned int component = 0) const; }; template<int dim> double BoundaryValues<dim>::value(const Point<dim> &/*p*/, const unsigned int component) const { Assert(component == 0, ExcInternalError()); return 0; } template<int dim> HeatEquation<dim>::HeatEquation() : fe(1), dof_handler(triangulation), time_step(1. / 500), theta(0.5) { } template<int dim> void HeatEquation<dim>::setup_system() { GridGenerator::hyper_L (triangulation); triangulation.refine_global (5); std::cout << "Number of active cells: " << triangulation.n_active_cells() << std::endl; dof_handler.distribute_dofs(fe); std::cout << "Number of degrees of freedom: " << dof_handler.n_dofs() << std::endl << std::endl; sparsity_pattern.reinit(dof_handler.n_dofs(), dof_handler.n_dofs(), dof_handler.max_couplings_between_dofs()); DoFTools::make_sparsity_pattern(dof_handler, sparsity_pattern); sparsity_pattern.compress(); mass_matrix.reinit(sparsity_pattern); laplace_matrix.reinit(sparsity_pattern); system_matrix.reinit(sparsity_pattern); MatrixCreator::create_mass_matrix(dof_handler, QGauss<dim>(fe.degree+1), mass_matrix); MatrixCreator::create_laplace_matrix(dof_handler, QGauss<dim>(fe.degree+1), laplace_matrix); solution.reinit(dof_handler.n_dofs()); old_solution.reinit(dof_handler.n_dofs()); system_rhs.reinit(dof_handler.n_dofs()); constraints.close(); } template<int dim> void HeatEquation<dim>::solve_time_step() { SolverControl solver_control(1000, 1e-8 * system_rhs.l2_norm()); SolverCG<> cg(solver_control); PreconditionSSOR<> preconditioner; preconditioner.initialize(system_matrix, 1.0); cg.solve(system_matrix, solution, system_rhs, preconditioner); std::cout << " " << solver_control.last_step() << " CG iterations." << std::endl; } template<int dim> void HeatEquation<dim>::output_results() const { DataOut<dim> data_out; data_out.attach_dof_handler(dof_handler); data_out.add_data_vector(solution, "U"); data_out.build_patches(); const std::string filename = "solution-" + Utilities::int_to_string(timestep_number, 3) + ".vtk"; std::ofstream output(filename.c_str()); data_out.write_vtk(output); } template<int dim> void HeatEquation<dim>::run() { setup_system(); VectorTools::interpolate(dof_handler, ZeroFunction<dim>(), old_solution); solution = old_solution; timestep_number = 0; output_results(); Vector<double> tmp(solution.size()); Vector<double> forcing_terms(solution.size()); while (time <= 0.5) { time += time_step; ++timestep_number; std::cout << "Time step " << timestep_number << " at t=" << time << std::endl; mass_matrix.vmult(system_rhs, old_solution); laplace_matrix.vmult(tmp, old_solution); system_rhs.add(-(1 - theta) * time_step, tmp); RightHandSide<dim> rhs_function; rhs_function.set_time(time); VectorTools::create_right_hand_side(dof_handler, QGauss<dim>(fe.degree+1), rhs_function, tmp); forcing_terms = tmp; forcing_terms *= time_step * theta; rhs_function.set_time(time - time_step); VectorTools::create_right_hand_side(dof_handler, QGauss<dim>(fe.degree+1), rhs_function, tmp); forcing_terms.add(time_step * (1 - theta), tmp); system_rhs += forcing_terms; { BoundaryValues<dim> boundary_values_function; boundary_values_function.set_time(time); std::map<unsigned int, double> boundary_values; VectorTools::interpolate_boundary_values(dof_handler, 0, boundary_values_function, boundary_values); system_matrix.copy_from(mass_matrix); system_matrix.add(theta * time_step, laplace_matrix); MatrixTools::apply_boundary_values(boundary_values, system_matrix, solution, system_rhs); } solve_time_step(); output_results(); old_solution = solution; } } } int main() { try { using namespace dealii; using namespace Step26; deallog.depth_console(0); HeatEquation<2> heat_equation_solver; heat_equation_solver.run(); } catch (std::exception &exc) { std::cerr << std::endl << std::endl << "----------------------------------------------------" << std::endl; std::cerr << "Exception on processing: " << std::endl << exc.what() << std::endl << "Aborting!" << std::endl << "----------------------------------------------------" << std::endl; return 1; } catch (...) { std::cerr << std::endl << std::endl << "----------------------------------------------------" << std::endl; std::cerr << "Unknown exception!" << std::endl << "Aborting!" << std::endl << "----------------------------------------------------" << std::endl; return 1; } return 0; } <|endoftext|>
<commit_before>//===- TpiStream.cpp - PDB Type Info (TPI) Stream 2 Access ----------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "llvm/DebugInfo/PDB/Raw/TpiStream.h" #include "llvm/DebugInfo/CodeView/CVTypeVisitor.h" #include "llvm/DebugInfo/CodeView/CodeView.h" #include "llvm/DebugInfo/CodeView/StreamReader.h" #include "llvm/DebugInfo/CodeView/TypeIndex.h" #include "llvm/DebugInfo/CodeView/TypeRecord.h" #include "llvm/DebugInfo/PDB/Raw/Hash.h" #include "llvm/DebugInfo/PDB/Raw/IndexedStreamData.h" #include "llvm/DebugInfo/PDB/Raw/MappedBlockStream.h" #include "llvm/DebugInfo/PDB/Raw/PDBFile.h" #include "llvm/DebugInfo/PDB/Raw/RawConstants.h" #include "llvm/DebugInfo/PDB/Raw/RawError.h" #include "llvm/DebugInfo/PDB/Raw/RawTypes.h" #include "llvm/Support/Endian.h" using namespace llvm; using namespace llvm::codeview; using namespace llvm::support; using namespace llvm::pdb; namespace { const uint32_t MinHashBuckets = 0x1000; const uint32_t MaxHashBuckets = 0x40000; } // This corresponds to `HDR` in PDB/dbi/tpi.h. struct TpiStream::HeaderInfo { struct EmbeddedBuf { little32_t Off; ulittle32_t Length; }; ulittle32_t Version; ulittle32_t HeaderSize; ulittle32_t TypeIndexBegin; ulittle32_t TypeIndexEnd; ulittle32_t TypeRecordBytes; // The following members correspond to `TpiHash` in PDB/dbi/tpi.h. ulittle16_t HashStreamIndex; ulittle16_t HashAuxStreamIndex; ulittle32_t HashKeySize; ulittle32_t NumHashBuckets; EmbeddedBuf HashValueBuffer; EmbeddedBuf IndexOffsetBuffer; EmbeddedBuf HashAdjBuffer; }; TpiStream::TpiStream(const PDBFile &File, std::unique_ptr<MappedBlockStream> Stream) : Pdb(File), Stream(std::move(Stream)) {} TpiStream::~TpiStream() {} // Corresponds to `fUDTAnon`. template <typename T> static bool isAnonymous(T &Rec) { StringRef Name = Rec.getUniqueName(); return Name == "<unnamed-tag>" || Name == "__unnamed" || Name.endswith("::<unnamed-tag>") || Name.endswith("::__unnamed"); } // Computes a hash for a given TPI record. template <typename T> static uint32_t getTpiHash(T &Rec, const CVRecord<TypeLeafKind> &RawRec) { auto Opts = static_cast<uint16_t>(Rec.getOptions()); bool ForwardRef = Opts & static_cast<uint16_t>(ClassOptions::ForwardReference); bool Scoped = Opts & static_cast<uint16_t>(ClassOptions::Scoped); bool UniqueName = Opts & static_cast<uint16_t>(ClassOptions::HasUniqueName); bool IsAnon = UniqueName && isAnonymous(Rec); if (!ForwardRef && !Scoped && !IsAnon) return hashStringV1(Rec.getName()); if (!ForwardRef && UniqueName && !IsAnon) return hashStringV1(Rec.getUniqueName()); return hashBufferV8(RawRec.RawData); } namespace { class TpiHashVerifier : public TypeVisitorCallbacks { public: TpiHashVerifier(FixedStreamArray<support::ulittle32_t> &HashValues, uint32_t NumHashBuckets) : HashValues(HashValues), NumHashBuckets(NumHashBuckets) {} Error visitUdtSourceLine(UdtSourceLineRecord &Rec) override { return verifySourceLine(Rec); } Error visitUdtModSourceLine(UdtModSourceLineRecord &Rec) override { return verifySourceLine(Rec); } Error visitClass(ClassRecord &Rec) override { return verify(Rec); } Error visitEnum(EnumRecord &Rec) override { return verify(Rec); } Error visitUnion(UnionRecord &Rec) override { return verify(Rec); } Error visitTypeBegin(const CVRecord<TypeLeafKind> &Rec) override { ++Index; RawRecord = &Rec; return Error::success(); } private: template <typename T> Error verify(T &Rec) { uint32_t Hash = getTpiHash(Rec, *RawRecord); if (Hash % NumHashBuckets != HashValues[Index]) return make_error<RawError>(raw_error_code::invalid_tpi_hash); return Error::success(); } template <typename T> Error verifySourceLine(T &Rec) { char Buf[4]; support::endian::write32le(Buf, Rec.getUDT().getIndex()); uint32_t Hash = hashStringV1(StringRef(Buf, 4)); if (Hash % NumHashBuckets != HashValues[Index]) return make_error<RawError>(raw_error_code::invalid_tpi_hash); return Error::success(); } FixedStreamArray<support::ulittle32_t> HashValues; const CVRecord<TypeLeafKind> *RawRecord; uint32_t NumHashBuckets; uint32_t Index = -1; }; } // Verifies that a given type record matches with a given hash value. // Currently we only verify SRC_LINE records. Error TpiStream::verifyHashValues() { TpiHashVerifier Verifier(HashValues, Header->NumHashBuckets); CVTypeVisitor Visitor(Verifier); return Visitor.visitTypeStream(TypeRecords); } Error TpiStream::reload() { StreamReader Reader(*Stream); if (Reader.bytesRemaining() < sizeof(HeaderInfo)) return make_error<RawError>(raw_error_code::corrupt_file, "TPI Stream does not contain a header."); if (Reader.readObject(Header)) return make_error<RawError>(raw_error_code::corrupt_file, "TPI Stream does not contain a header."); if (Header->Version != PdbTpiV80) return make_error<RawError>(raw_error_code::corrupt_file, "Unsupported TPI Version."); if (Header->HeaderSize != sizeof(HeaderInfo)) return make_error<RawError>(raw_error_code::corrupt_file, "Corrupt TPI Header size."); if (Header->HashKeySize != sizeof(ulittle32_t)) return make_error<RawError>(raw_error_code::corrupt_file, "TPI Stream expected 4 byte hash key size."); if (Header->NumHashBuckets < MinHashBuckets || Header->NumHashBuckets > MaxHashBuckets) return make_error<RawError>(raw_error_code::corrupt_file, "TPI Stream Invalid number of hash buckets."); // The actual type records themselves come from this stream if (auto EC = Reader.readArray(TypeRecords, Header->TypeRecordBytes)) return EC; // Hash indices, hash values, etc come from the hash stream. if (Header->HashStreamIndex >= Pdb.getNumStreams()) return make_error<RawError>(raw_error_code::corrupt_file, "Invalid TPI hash stream index."); auto HS = MappedBlockStream::createIndexedStream(Header->HashStreamIndex, Pdb); if (!HS) return HS.takeError(); StreamReader HSR(**HS); uint32_t NumHashValues = Header->HashValueBuffer.Length / sizeof(ulittle32_t); if (NumHashValues != NumTypeRecords()) return make_error<RawError>( raw_error_code::corrupt_file, "TPI hash count does not match with the number of type records."); HSR.setOffset(Header->HashValueBuffer.Off); if (auto EC = HSR.readArray(HashValues, NumHashValues)) return EC; HSR.setOffset(Header->IndexOffsetBuffer.Off); uint32_t NumTypeIndexOffsets = Header->IndexOffsetBuffer.Length / sizeof(TypeIndexOffset); if (auto EC = HSR.readArray(TypeIndexOffsets, NumTypeIndexOffsets)) return EC; HSR.setOffset(Header->HashAdjBuffer.Off); uint32_t NumHashAdjustments = Header->HashAdjBuffer.Length / sizeof(TypeIndexOffset); if (auto EC = HSR.readArray(HashAdjustments, NumHashAdjustments)) return EC; HashStream = std::move(*HS); // TPI hash table is a parallel array for the type records. // Verify that the hash values match with type records. if (auto EC = verifyHashValues()) return EC; return Error::success(); } PdbRaw_TpiVer TpiStream::getTpiVersion() const { uint32_t Value = Header->Version; return static_cast<PdbRaw_TpiVer>(Value); } uint32_t TpiStream::TypeIndexBegin() const { return Header->TypeIndexBegin; } uint32_t TpiStream::TypeIndexEnd() const { return Header->TypeIndexEnd; } uint32_t TpiStream::NumTypeRecords() const { return TypeIndexEnd() - TypeIndexBegin(); } uint16_t TpiStream::getTypeHashStreamIndex() const { return Header->HashStreamIndex; } uint16_t TpiStream::getTypeHashStreamAuxIndex() const { return Header->HashAuxStreamIndex; } uint32_t TpiStream::NumHashBuckets() const { return Header->NumHashBuckets; } uint32_t TpiStream::getHashKeySize() const { return Header->HashKeySize; } FixedStreamArray<support::ulittle32_t> TpiStream::getHashValues() const { return HashValues; } FixedStreamArray<TypeIndexOffset> TpiStream::getTypeIndexOffsets() const { return TypeIndexOffsets; } FixedStreamArray<TypeIndexOffset> TpiStream::getHashAdjustments() const { return HashAdjustments; } iterator_range<CVTypeArray::Iterator> TpiStream::types(bool *HadError) const { return llvm::make_range(TypeRecords.begin(HadError), TypeRecords.end()); } <commit_msg>[PDB] Indicate which type record failed hash validation<commit_after>//===- TpiStream.cpp - PDB Type Info (TPI) Stream 2 Access ----------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "llvm/DebugInfo/PDB/Raw/TpiStream.h" #include "llvm/DebugInfo/CodeView/CVTypeVisitor.h" #include "llvm/DebugInfo/CodeView/CodeView.h" #include "llvm/DebugInfo/CodeView/StreamReader.h" #include "llvm/DebugInfo/CodeView/TypeIndex.h" #include "llvm/DebugInfo/CodeView/TypeRecord.h" #include "llvm/DebugInfo/PDB/Raw/Hash.h" #include "llvm/DebugInfo/PDB/Raw/IndexedStreamData.h" #include "llvm/DebugInfo/PDB/Raw/MappedBlockStream.h" #include "llvm/DebugInfo/PDB/Raw/PDBFile.h" #include "llvm/DebugInfo/PDB/Raw/RawConstants.h" #include "llvm/DebugInfo/PDB/Raw/RawError.h" #include "llvm/DebugInfo/PDB/Raw/RawTypes.h" #include "llvm/Support/Endian.h" using namespace llvm; using namespace llvm::codeview; using namespace llvm::support; using namespace llvm::pdb; namespace { const uint32_t MinHashBuckets = 0x1000; const uint32_t MaxHashBuckets = 0x40000; } // This corresponds to `HDR` in PDB/dbi/tpi.h. struct TpiStream::HeaderInfo { struct EmbeddedBuf { little32_t Off; ulittle32_t Length; }; ulittle32_t Version; ulittle32_t HeaderSize; ulittle32_t TypeIndexBegin; ulittle32_t TypeIndexEnd; ulittle32_t TypeRecordBytes; // The following members correspond to `TpiHash` in PDB/dbi/tpi.h. ulittle16_t HashStreamIndex; ulittle16_t HashAuxStreamIndex; ulittle32_t HashKeySize; ulittle32_t NumHashBuckets; EmbeddedBuf HashValueBuffer; EmbeddedBuf IndexOffsetBuffer; EmbeddedBuf HashAdjBuffer; }; TpiStream::TpiStream(const PDBFile &File, std::unique_ptr<MappedBlockStream> Stream) : Pdb(File), Stream(std::move(Stream)) {} TpiStream::~TpiStream() {} // Corresponds to `fUDTAnon`. template <typename T> static bool isAnonymous(T &Rec) { StringRef Name = Rec.getUniqueName(); return Name == "<unnamed-tag>" || Name == "__unnamed" || Name.endswith("::<unnamed-tag>") || Name.endswith("::__unnamed"); } // Computes a hash for a given TPI record. template <typename T> static uint32_t getTpiHash(T &Rec, const CVRecord<TypeLeafKind> &RawRec) { auto Opts = static_cast<uint16_t>(Rec.getOptions()); bool ForwardRef = Opts & static_cast<uint16_t>(ClassOptions::ForwardReference); bool Scoped = Opts & static_cast<uint16_t>(ClassOptions::Scoped); bool UniqueName = Opts & static_cast<uint16_t>(ClassOptions::HasUniqueName); bool IsAnon = UniqueName && isAnonymous(Rec); if (!ForwardRef && !Scoped && !IsAnon) return hashStringV1(Rec.getName()); if (!ForwardRef && UniqueName && !IsAnon) return hashStringV1(Rec.getUniqueName()); return hashBufferV8(RawRec.RawData); } namespace { class TpiHashVerifier : public TypeVisitorCallbacks { public: TpiHashVerifier(FixedStreamArray<support::ulittle32_t> &HashValues, uint32_t NumHashBuckets) : HashValues(HashValues), NumHashBuckets(NumHashBuckets) {} Error visitUdtSourceLine(UdtSourceLineRecord &Rec) override { return verifySourceLine(Rec); } Error visitUdtModSourceLine(UdtModSourceLineRecord &Rec) override { return verifySourceLine(Rec); } Error visitClass(ClassRecord &Rec) override { return verify(Rec); } Error visitEnum(EnumRecord &Rec) override { return verify(Rec); } Error visitUnion(UnionRecord &Rec) override { return verify(Rec); } Error visitTypeBegin(const CVRecord<TypeLeafKind> &Rec) override { ++Index; RawRecord = &Rec; return Error::success(); } private: template <typename T> Error verify(T &Rec) { uint32_t Hash = getTpiHash(Rec, *RawRecord); if (Hash % NumHashBuckets != HashValues[Index]) return errorInvalidHash(); return Error::success(); } template <typename T> Error verifySourceLine(T &Rec) { char Buf[4]; support::endian::write32le(Buf, Rec.getUDT().getIndex()); uint32_t Hash = hashStringV1(StringRef(Buf, 4)); if (Hash % NumHashBuckets != HashValues[Index]) return errorInvalidHash(); return Error::success(); } Error errorInvalidHash() { return make_error<RawError>( raw_error_code::invalid_tpi_hash, "Type index is 0x" + utohexstr(TypeIndex::FirstNonSimpleIndex + Index)); } FixedStreamArray<support::ulittle32_t> HashValues; const CVRecord<TypeLeafKind> *RawRecord; uint32_t NumHashBuckets; uint32_t Index = -1; }; } // Verifies that a given type record matches with a given hash value. // Currently we only verify SRC_LINE records. Error TpiStream::verifyHashValues() { TpiHashVerifier Verifier(HashValues, Header->NumHashBuckets); CVTypeVisitor Visitor(Verifier); return Visitor.visitTypeStream(TypeRecords); } Error TpiStream::reload() { StreamReader Reader(*Stream); if (Reader.bytesRemaining() < sizeof(HeaderInfo)) return make_error<RawError>(raw_error_code::corrupt_file, "TPI Stream does not contain a header."); if (Reader.readObject(Header)) return make_error<RawError>(raw_error_code::corrupt_file, "TPI Stream does not contain a header."); if (Header->Version != PdbTpiV80) return make_error<RawError>(raw_error_code::corrupt_file, "Unsupported TPI Version."); if (Header->HeaderSize != sizeof(HeaderInfo)) return make_error<RawError>(raw_error_code::corrupt_file, "Corrupt TPI Header size."); if (Header->HashKeySize != sizeof(ulittle32_t)) return make_error<RawError>(raw_error_code::corrupt_file, "TPI Stream expected 4 byte hash key size."); if (Header->NumHashBuckets < MinHashBuckets || Header->NumHashBuckets > MaxHashBuckets) return make_error<RawError>(raw_error_code::corrupt_file, "TPI Stream Invalid number of hash buckets."); // The actual type records themselves come from this stream if (auto EC = Reader.readArray(TypeRecords, Header->TypeRecordBytes)) return EC; // Hash indices, hash values, etc come from the hash stream. if (Header->HashStreamIndex >= Pdb.getNumStreams()) return make_error<RawError>(raw_error_code::corrupt_file, "Invalid TPI hash stream index."); auto HS = MappedBlockStream::createIndexedStream(Header->HashStreamIndex, Pdb); if (!HS) return HS.takeError(); StreamReader HSR(**HS); uint32_t NumHashValues = Header->HashValueBuffer.Length / sizeof(ulittle32_t); if (NumHashValues != NumTypeRecords()) return make_error<RawError>( raw_error_code::corrupt_file, "TPI hash count does not match with the number of type records."); HSR.setOffset(Header->HashValueBuffer.Off); if (auto EC = HSR.readArray(HashValues, NumHashValues)) return EC; HSR.setOffset(Header->IndexOffsetBuffer.Off); uint32_t NumTypeIndexOffsets = Header->IndexOffsetBuffer.Length / sizeof(TypeIndexOffset); if (auto EC = HSR.readArray(TypeIndexOffsets, NumTypeIndexOffsets)) return EC; HSR.setOffset(Header->HashAdjBuffer.Off); uint32_t NumHashAdjustments = Header->HashAdjBuffer.Length / sizeof(TypeIndexOffset); if (auto EC = HSR.readArray(HashAdjustments, NumHashAdjustments)) return EC; HashStream = std::move(*HS); // TPI hash table is a parallel array for the type records. // Verify that the hash values match with type records. if (auto EC = verifyHashValues()) return EC; return Error::success(); } PdbRaw_TpiVer TpiStream::getTpiVersion() const { uint32_t Value = Header->Version; return static_cast<PdbRaw_TpiVer>(Value); } uint32_t TpiStream::TypeIndexBegin() const { return Header->TypeIndexBegin; } uint32_t TpiStream::TypeIndexEnd() const { return Header->TypeIndexEnd; } uint32_t TpiStream::NumTypeRecords() const { return TypeIndexEnd() - TypeIndexBegin(); } uint16_t TpiStream::getTypeHashStreamIndex() const { return Header->HashStreamIndex; } uint16_t TpiStream::getTypeHashStreamAuxIndex() const { return Header->HashAuxStreamIndex; } uint32_t TpiStream::NumHashBuckets() const { return Header->NumHashBuckets; } uint32_t TpiStream::getHashKeySize() const { return Header->HashKeySize; } FixedStreamArray<support::ulittle32_t> TpiStream::getHashValues() const { return HashValues; } FixedStreamArray<TypeIndexOffset> TpiStream::getTypeIndexOffsets() const { return TypeIndexOffsets; } FixedStreamArray<TypeIndexOffset> TpiStream::getHashAdjustments() const { return HashAdjustments; } iterator_range<CVTypeArray::Iterator> TpiStream::types(bool *HadError) const { return llvm::make_range(TypeRecords.begin(HadError), TypeRecords.end()); } <|endoftext|>
<commit_before>/* $Id$ */ /* Author: Toby Young, Polish Academy of Sciences, */ /* Wolfgang Bangerth, Texas A&M University */ /* $Id$ */ /* */ /* Copyright (C) 2009 by the deal.II authors */ /* */ /* This file is subject to QPL and may not be distributed */ /* without copyright and license information. Please refer */ /* to the file deal.II/doc/license.html for the text and */ /* further information on this license. */ // @sect3{Include files} #include <base/logstream.h> #include <base/quadrature_lib.h> #include <base/function.h> #include <base/function_parser.h> #include <base/parameter_handler.h> #include <base/utilities.h> #include <lac/full_matrix.h> #include <lac/petsc_sparse_matrix.h> #include <lac/petsc_vector.h> #include <lac/solver_cg.h> #include <lac/precondition.h> #include <lac/compressed_simple_sparsity_pattern.h> #include <grid/tria.h> #include <grid/grid_generator.h> #include <grid/tria_accessor.h> #include <grid/tria_iterator.h> #include <dofs/dof_handler.h> #include <dofs/dof_accessor.h> #include <dofs/dof_tools.h> #include <fe/fe_q.h> #include <fe/fe_values.h> #include <numerics/vectors.h> #include <numerics/matrices.h> #include <numerics/data_out.h> #include <fstream> #include <iostream> // The final step, as in previous // programs, is to import all the // deal.II class and function names // into the global namespace: using namespace dealii; // @sect3{The <code>EigenvalueProblem</code> class template} template <int dim> class EigenvalueProblem { public: EigenvalueProblem (); void run (); private: void make_grid_and_dofs (); void assemble_system (); void solve (); void output_results () const; Triangulation<dim> triangulation; FE_Q<dim> fe; DoFHandler<dim> dof_handler; PETScWrappers::SparseMatrix stiffness_matrix, mass_matrix; std::vector<PETScWrappers::Vector> eigenfunctions; ParameterHandler parameters; }; // @sect3{Implementation of the <code>EigenvalueProblem</code> class} // @sect4{EigenvalueProblem::EigenvalueProblem} template <int dim> EigenvalueProblem<dim>::EigenvalueProblem () : fe (1), dof_handler (triangulation) { parameters.declare_entry ("Number of eigenvalues/eigenfunctions", "10", Patterns::Integer (0, 100), "The number of eigenvalues/eigenfunctions " "to be computed."); parameters.declare_entry ("Potential", "0", Patterns::Anything(), "A functional description of the potential."); } // @sect4{EigenvalueProblem::make_grid_and_dofs} template <int dim> void EigenvalueProblem<dim>::make_grid_and_dofs () { GridGenerator::hyper_cube (triangulation, -1, 1); triangulation.refine_global (4); dof_handler.distribute_dofs (fe); CompressedSimpleSparsityPattern csp (dof_handler.n_dofs(), dof_handler.n_dofs()); DoFTools::make_sparsity_pattern (dof_handler, csp); stiffness_matrix.reinit (csp); mass_matrix.reinit (csp); eigenfunctions .resize (parameters.get_integer ("Number of eigenvalues/eigenfunctions")); for (unsigned int i=0; i<eigenfunctions.size(); ++i) eigenfunctions[i].reinit (dof_handler.n_dofs()); } // @sect4{EigenvalueProblem::assemble_system} template <int dim> void EigenvalueProblem<dim>::assemble_system () { QGauss<dim> quadrature_formula(2); FEValues<dim> fe_values (fe, quadrature_formula, update_values | update_gradients | update_JxW_values); const unsigned int dofs_per_cell = fe.dofs_per_cell; const unsigned int n_q_points = quadrature_formula.size(); FullMatrix<double> cell_stiffness_matrix (dofs_per_cell, dofs_per_cell); FullMatrix<double> cell_mass_matrix (dofs_per_cell, dofs_per_cell); std::vector<unsigned int> local_dof_indices (dofs_per_cell); FunctionParser<dim> potential; potential.initialize ((dim == 2 ? "x,y" : "x,y,z"), parameters.get ("Potential"), typename FunctionParser<dim>::ConstMap()); ConstraintMatrix constraints; VectorTools::interpolate_boundary_values (dof_handler, 0, ZeroFunction<dim>(), constraints); constraints.close (); typename DoFHandler<dim>::active_cell_iterator cell = dof_handler.begin_active(), endc = dof_handler.end(); for (; cell!=endc; ++cell) { fe_values.reinit (cell); cell_stiffness_matrix = 0; cell_mass_matrix = 0; for (unsigned int q_point=0; q_point<n_q_points; ++q_point) for (unsigned int i=0; i<dofs_per_cell; ++i) for (unsigned int j=0; j<dofs_per_cell; ++j) { cell_stiffness_matrix(i,j) += (fe_values.shape_grad (i, q_point) * fe_values.shape_grad (j, q_point) * fe_values.JxW (q_point)); cell_mass_matrix(i,j) += (fe_values.shape_value (i, q_point) * fe_values.shape_value (j, q_point) * fe_values.JxW (q_point)); } cell->get_dof_indices (local_dof_indices); constraints.distribute_local_to_global (cell_stiffness_matrix, local_dof_indices, stiffness_matrix); constraints.distribute_local_to_global (cell_mass_matrix, local_dof_indices, mass_matrix); } } // @sect4{EigenvalueProblem::solve} template <int dim> void EigenvalueProblem<dim>::solve () { // do whatever is necessary here } // @sect4{EigenvalueProblem::output_results} template <int dim> void EigenvalueProblem<dim>::output_results () const { DataOut<dim> data_out; data_out.attach_dof_handler (dof_handler); for (unsigned int i=0; i<eigenfunctions.size(); ++i) data_out.add_data_vector (eigenfunctions[i], std::string("solution") + Utilities::int_to_string(i)); data_out.build_patches (); std::ofstream output ("eigenvectors.vtk"); data_out.write_vtk (output); } // @sect4{EigenvalueProblem::run} // This is the function which has the // top-level control over everything. It is // the same as for the previous example. template <int dim> void EigenvalueProblem<dim>::run () { std::cout << "Solving problem in " << dim << " space dimensions." << std::endl; make_grid_and_dofs(); assemble_system (); solve (); output_results (); } // @sect3{The <code>main</code> function} int main (int argc, char **argv) { try { PetscInitialize(&argc,&argv,0,0); deallog.depth_console (0); EigenvalueProblem<2> laplace_problem_2d; laplace_problem_2d.run (); } catch (std::exception &exc) { std::cerr << std::endl << std::endl << "----------------------------------------------------" << std::endl; std::cerr << "Exception on processing: " << std::endl << exc.what() << std::endl << "Aborting!" << std::endl << "----------------------------------------------------" << std::endl; return 1; } catch (...) { std::cerr << std::endl << std::endl << "----------------------------------------------------" << std::endl; std::cerr << "Unknown exception!" << std::endl << "Aborting!" << std::endl << "----------------------------------------------------" << std::endl; return 1; } return 0; } <commit_msg>Deal with the potential. Read parameters from file.<commit_after>/* $Id$ */ /* Author: Toby Young, Polish Academy of Sciences, */ /* Wolfgang Bangerth, Texas A&M University */ /* $Id$ */ /* */ /* Copyright (C) 2009 by the deal.II authors */ /* */ /* This file is subject to QPL and may not be distributed */ /* without copyright and license information. Please refer */ /* to the file deal.II/doc/license.html for the text and */ /* further information on this license. */ // @sect3{Include files} #include <base/logstream.h> #include <base/quadrature_lib.h> #include <base/function.h> #include <base/function_parser.h> #include <base/parameter_handler.h> #include <base/utilities.h> #include <lac/full_matrix.h> #include <lac/petsc_sparse_matrix.h> #include <lac/petsc_vector.h> #include <lac/solver_cg.h> #include <lac/precondition.h> #include <lac/compressed_simple_sparsity_pattern.h> #include <grid/tria.h> #include <grid/grid_generator.h> #include <grid/tria_accessor.h> #include <grid/tria_iterator.h> #include <dofs/dof_handler.h> #include <dofs/dof_accessor.h> #include <dofs/dof_tools.h> #include <fe/fe_q.h> #include <fe/fe_values.h> #include <numerics/vectors.h> #include <numerics/matrices.h> #include <numerics/data_out.h> #include <fstream> #include <iostream> // The final step, as in previous // programs, is to import all the // deal.II class and function names // into the global namespace: using namespace dealii; // @sect3{The <code>EigenvalueProblem</code> class template} template <int dim> class EigenvalueProblem { public: EigenvalueProblem (const std::string &prm_file); void run (); private: void make_grid_and_dofs (); void assemble_system (); void solve (); void output_results () const; Triangulation<dim> triangulation; FE_Q<dim> fe; DoFHandler<dim> dof_handler; PETScWrappers::SparseMatrix stiffness_matrix, mass_matrix; std::vector<PETScWrappers::Vector> eigenfunctions; ParameterHandler parameters; }; // @sect3{Implementation of the <code>EigenvalueProblem</code> class} // @sect4{EigenvalueProblem::EigenvalueProblem} template <int dim> EigenvalueProblem<dim>::EigenvalueProblem (const std::string &prm_file) : fe (1), dof_handler (triangulation) { parameters.declare_entry ("Number of eigenvalues/eigenfunctions", "10", Patterns::Integer (0, 100), "The number of eigenvalues/eigenfunctions " "to be computed."); parameters.declare_entry ("Potential", "0", Patterns::Anything(), "A functional description of the potential."); parameters.read_input (prm_file); } // @sect4{EigenvalueProblem::make_grid_and_dofs} template <int dim> void EigenvalueProblem<dim>::make_grid_and_dofs () { GridGenerator::hyper_cube (triangulation, -1, 1); triangulation.refine_global (4); dof_handler.distribute_dofs (fe); CompressedSimpleSparsityPattern csp (dof_handler.n_dofs(), dof_handler.n_dofs()); DoFTools::make_sparsity_pattern (dof_handler, csp); stiffness_matrix.reinit (csp); mass_matrix.reinit (csp); eigenfunctions .resize (parameters.get_integer ("Number of eigenvalues/eigenfunctions")); for (unsigned int i=0; i<eigenfunctions.size(); ++i) eigenfunctions[i].reinit (dof_handler.n_dofs()); } // @sect4{EigenvalueProblem::assemble_system} template <int dim> void EigenvalueProblem<dim>::assemble_system () { QGauss<dim> quadrature_formula(2); FEValues<dim> fe_values (fe, quadrature_formula, update_values | update_gradients | update_quadrature_points | update_JxW_values); const unsigned int dofs_per_cell = fe.dofs_per_cell; const unsigned int n_q_points = quadrature_formula.size(); FullMatrix<double> cell_stiffness_matrix (dofs_per_cell, dofs_per_cell); FullMatrix<double> cell_mass_matrix (dofs_per_cell, dofs_per_cell); std::vector<unsigned int> local_dof_indices (dofs_per_cell); FunctionParser<dim> potential; potential.initialize ((dim == 2 ? "x,y" : "x,y,z"), parameters.get ("Potential"), typename FunctionParser<dim>::ConstMap()); std::vector<double> potential_values (n_q_points); ConstraintMatrix constraints; VectorTools::interpolate_boundary_values (dof_handler, 0, ZeroFunction<dim>(), constraints); constraints.close (); typename DoFHandler<dim>::active_cell_iterator cell = dof_handler.begin_active(), endc = dof_handler.end(); for (; cell!=endc; ++cell) { fe_values.reinit (cell); cell_stiffness_matrix = 0; cell_mass_matrix = 0; potential.value_list (fe_values.get_quadrature_points(), potential_values); for (unsigned int q_point=0; q_point<n_q_points; ++q_point) for (unsigned int i=0; i<dofs_per_cell; ++i) for (unsigned int j=0; j<dofs_per_cell; ++j) { cell_stiffness_matrix(i,j) += ((fe_values.shape_grad (i, q_point) * fe_values.shape_grad (j, q_point) + potential_values[q_point] * fe_values.shape_value (i, q_point) * fe_values.shape_value (j, q_point)) * fe_values.JxW (q_point)); cell_mass_matrix(i,j) += (fe_values.shape_value (i, q_point) * fe_values.shape_value (j, q_point) * fe_values.JxW (q_point)); } cell->get_dof_indices (local_dof_indices); constraints.distribute_local_to_global (cell_stiffness_matrix, local_dof_indices, stiffness_matrix); constraints.distribute_local_to_global (cell_mass_matrix, local_dof_indices, mass_matrix); } } // @sect4{EigenvalueProblem::solve} template <int dim> void EigenvalueProblem<dim>::solve () { // do whatever is necessary here } // @sect4{EigenvalueProblem::output_results} template <int dim> void EigenvalueProblem<dim>::output_results () const { DataOut<dim> data_out; data_out.attach_dof_handler (dof_handler); for (unsigned int i=0; i<eigenfunctions.size(); ++i) data_out.add_data_vector (eigenfunctions[i], std::string("solution") + Utilities::int_to_string(i)); data_out.build_patches (); std::ofstream output ("eigenvectors.vtk"); data_out.write_vtk (output); } // @sect4{EigenvalueProblem::run} // This is the function which has the // top-level control over everything. It is // the same as for the previous example. template <int dim> void EigenvalueProblem<dim>::run () { std::cout << "Solving problem in " << dim << " space dimensions." << std::endl; make_grid_and_dofs(); assemble_system (); solve (); output_results (); } // @sect3{The <code>main</code> function} int main (int argc, char **argv) { try { PetscInitialize(&argc,&argv,0,0); deallog.depth_console (0); EigenvalueProblem<2> problem ("step-36.prm"); problem.run (); } catch (std::exception &exc) { std::cerr << std::endl << std::endl << "----------------------------------------------------" << std::endl; std::cerr << "Exception on processing: " << std::endl << exc.what() << std::endl << "Aborting!" << std::endl << "----------------------------------------------------" << std::endl; return 1; } catch (...) { std::cerr << std::endl << std::endl << "----------------------------------------------------" << std::endl; std::cerr << "Unknown exception!" << std::endl << "Aborting!" << std::endl << "----------------------------------------------------" << std::endl; return 1; } return 0; } <|endoftext|>
<commit_before>#include <FAST/Testing.hpp> #include <FAST/Algorithms/NeuralNetwork/SegmentationNetwork.hpp> #include <FAST/Importers/ImageFileImporter.hpp> #include <FAST/Visualization/SimpleWindow.hpp> #include <FAST/Streamers/ImageFileStreamer.hpp> #include <FAST/Algorithms/NeuralNetwork/InferenceEngineManager.hpp> #include <fstream> #include <FAST/Algorithms/ImagePatch/PatchGenerator.hpp> #include <FAST/Algorithms/ImagePatch/PatchStitcher.hpp> #include <FAST/Importers/WholeSlideImageImporter.hpp> #include <FAST/Algorithms/TissueSegmentation/TissueSegmentation.hpp> #include <FAST/Tools/CommandLineParser.hpp> using namespace fast; int main(int argc, char** argv) { Reporter::setGlobalReportMethod(Reporter::INFO, Reporter::NONE); CommandLineParser parser("Measure neural network performance script"); parser.addOption("disable-case-1"); parser.addOption("disable-case-2"); parser.addOption("disable-case-3"); parser.addOption("disable-warmup"); parser.parse(argc, argv); const int iterations = 10; const bool warmupIteration = !parser.getOption("disable-warmup"); const bool case1 = !parser.getOption("disable-case-1"); const bool case2 = !parser.getOption("disable-case-2"); const bool case3 = !parser.getOption("disable-case-3"); if(case1) { // CASE 1 - ULTRASOUND const std::string resultFilename = "neural-network-runtimes-case-1.csv"; std::ofstream file(resultFilename.c_str()); // Write header file << "Engine;Device Type;Iteration;NN input AVG;NN input STD;NN inference AVG;NN inference STD;NN output AVG;NN output STD;Total\n"; for(auto &engine : InferenceEngineManager::getEngineList()) { std::map<std::string, InferenceDeviceType> deviceTypes = {{"ANY", InferenceDeviceType::ANY}}; if(engine == "OpenVINO") { // On OpenVINO, try all device types deviceTypes = std::map<std::string, InferenceDeviceType>{ {"CPU", InferenceDeviceType::CPU}, {"GPU", InferenceDeviceType::GPU}, {"VPU", InferenceDeviceType::VPU}, }; } for(auto &&deviceType : deviceTypes) { std::cout << engine << " for device type " << deviceType.first << std::endl; std::cout << "====================================" << std::endl; for(int iteration = 0; iteration <= iterations; ++iteration) { auto streamer = ImageFileStreamer::New(); streamer->setFilenameFormat(Config::getTestDataPath() + "US/JugularVein/US-2D_#.mhd"); auto segmentation = SegmentationNetwork::New(); segmentation->setInferenceEngine(engine); segmentation->getInferenceEngine()->setDeviceType(deviceType.second); if(engine.substr(0, 10) == "TensorFlow") { segmentation->setOutputNode(0, "conv2d_23/truediv"); } else if(engine == "TensorRT") { segmentation->setInputNode(0, "input_image", NodeType::IMAGE, TensorShape({-1, 1, 256, 256})); segmentation->setOutputNode(0, "permute_2/transpose", NodeType::TENSOR, TensorShape({-1, 3, 256, 256})); } try { segmentation->load(join(Config::getTestDataPath(), "NeuralNetworkModels/jugular_vein_segmentation." + segmentation->getInferenceEngine()->getDefaultFileExtension())); } catch(Exception &e) { // If a device type is not present, it will fail in load Reporter::warning() << e.what() << Reporter::end(); continue; } segmentation->setScaleFactor(1.0f / 255.0f); //segmentation->setInputConnection(importer->getOutputPort()); segmentation->setInputConnection(streamer->getOutputPort()); segmentation->enableRuntimeMeasurements(); auto start = std::chrono::high_resolution_clock::now(); DataObject::pointer data; do { data = segmentation->updateAndGetOutputData<DataObject>(); } while(!data->isLastFrame()); std::chrono::duration<float, std::milli> timeUsed = std::chrono::high_resolution_clock::now() - start; std::cout << "RUNTIME Ultrasound " << engine << std::endl; std::cout << "=========================================" << std::endl; std::cout << "Total runtime: " << timeUsed.count() << std::endl; std::cout << "NN runtime: " << std::endl; segmentation->getRuntime("input_processing")->print(); segmentation->getRuntime("inference")->print(); segmentation->getRuntime("output_processing")->print(); if(iteration == 0 && warmupIteration) continue; file << engine + ";" + deviceType.first + ";" + std::to_string(iteration) + ";" + std::to_string(segmentation->getRuntime("input_processing")->getAverage()) + ";" + std::to_string(segmentation->getRuntime("input_processing")->getStdDeviation()) + ";" + std::to_string(segmentation->getRuntime("inference")->getAverage()) + ";" + std::to_string(segmentation->getRuntime("inference")->getStdDeviation()) + ";" + std::to_string(segmentation->getRuntime("output_processing")->getAverage()) + ";" + std::to_string(segmentation->getRuntime("output_processing")->getStdDeviation()) + ";" + std::to_string(timeUsed.count()) << std::endl; } } } } if(case2) { // CASE 2 - VOLUME SEGMENTATION const std::string resultFilename = "neural-network-runtimes-case-2.csv"; std::ofstream file(resultFilename.c_str()); // Write header file << "Engine;Device Type;Iteration;Patch generator AVG;Patch generator STD;NN input AVG;NN input STD;NN inference AVG;NN inference STD;NN output AVG;NN output STD;Patch stitcher AVG;Patch stitcher STD;Total\n"; //Reporter::setGlobalReportMethod(Reporter::NONE); for(std::string engine : {"TensorFlowCUDA", "TensorFlowCPU"}) { std::map<std::string, InferenceDeviceType> deviceTypes = {{"ANY", InferenceDeviceType::ANY}}; if(engine == "OpenVINO") { // On OpenVINO, try all device types deviceTypes = std::map<std::string, InferenceDeviceType>{ {"CPU", InferenceDeviceType::CPU}, {"GPU", InferenceDeviceType::GPU}, {"VPU", InferenceDeviceType::VPU}, }; } for(auto &&deviceType : deviceTypes) { std::cout << engine << " for device type " << deviceType.first << std::endl; std::cout << "====================================" << std::endl; for(int iteration = 0; iteration <= iterations; ++iteration) { auto importer = ImageFileImporter::New(); importer->setFilename(Config::getTestDataPath() + "/CT/LIDC-IDRI-0072/01-01-2000-CT CHEST W CONT-45499/4-Recon 3-88650/000001.dcm"); auto generator = PatchGenerator::New(); generator->setPatchSize(512, 512, 64); generator->setInputConnection(importer->getOutputPort()); generator->enableRuntimeMeasurements(); auto network = SegmentationNetwork::New(); network->setInferenceEngine(engine); network->getInferenceEngine()->setDeviceType(deviceType.second); network->setInferenceEngine(engine); network->load(Config::getTestDataPath() + "/NeuralNetworkModels/lung_nodule_model.pb"); network->setMinAndMaxIntensity(-1200.0f, 400.0f); network->setScaleFactor(1.0f/(400+1200)); network->setMeanAndStandardDeviation(-1200.0f, 1.0f); network->setOutputNode(0, "conv3d_18/truediv"); network->setInputConnection(generator->getOutputPort()); network->setResizeBackToOriginalSize(true); network->setThreshold(0.3); network->enableRuntimeMeasurements(); auto stitcher = PatchStitcher::New(); stitcher->setInputConnection(network->getOutputPort()); stitcher->enableRuntimeMeasurements(); auto start = std::chrono::high_resolution_clock::now(); DataObject::pointer data; do { data = stitcher->updateAndGetOutputData<DataObject>(); } while(!data->isLastFrame()); std::chrono::duration<float, std::milli> timeUsed = std::chrono::high_resolution_clock::now() - start; std::cout << "Total runtime: " << timeUsed.count() << std::endl; std::cout << "Patch generator runtime: " << std::endl; generator->getRuntime("create patch")->print(); std::cout << "NN runtime: " << std::endl; network->getRuntime()->print(); std::cout << "Patch stitcher runtime: " << std::endl; stitcher->getRuntime()->print(); if(iteration == 0 && warmupIteration) continue; file << engine + ";" + deviceType.first + ";" + std::to_string(iteration) + ";" + std::to_string(generator->getRuntime("create patch")->getAverage()) + ";" + std::to_string(generator->getRuntime("create patch")->getStdDeviation()) + ";" + std::to_string(network->getRuntime("input_processing")->getAverage()) + ";" + std::to_string(network->getRuntime("input_processing")->getStdDeviation()) + ";" + std::to_string(network->getRuntime("inference")->getAverage()) + ";" + std::to_string(network->getRuntime("inference")->getStdDeviation()) + ";" + std::to_string(network->getRuntime("output_processing")->getAverage()) + ";" + std::to_string(network->getRuntime("output_processing")->getStdDeviation()) + ";" + std::to_string(stitcher->getRuntime()->getAverage()) + ";" + std::to_string(stitcher->getRuntime()->getStdDeviation()) + ";" + std::to_string(timeUsed.count()) << std::endl; } } } } if(case3) { // CASE 3 - WSI CLASSIFICATION const std::string resultFilename = "neural-network-runtimes-case-3.csv"; std::ofstream file(resultFilename.c_str()); // Write header file << "Engine;Device Type;Iteration;Patch generator AVG;Patch generator STD;NN input AVG;NN input STD;NN inference AVG;NN inference STD;NN output AVG;NN output STD;Patch stitcher AVG;Patch stitcher STD;Total\n"; for(auto &engine : InferenceEngineManager::getEngineList()) { std::map<std::string, InferenceDeviceType> deviceTypes = {{"ANY", InferenceDeviceType::ANY}}; if(engine == "OpenVINO") { // On OpenVINO, try all device types deviceTypes = std::map<std::string, InferenceDeviceType>{ {"CPU", InferenceDeviceType::CPU}, {"GPU", InferenceDeviceType::GPU}, {"VPU", InferenceDeviceType::VPU}, }; } for(auto &&deviceType : deviceTypes) { std::cout << engine << " for device type " << deviceType.first << std::endl; std::cout << "====================================" << std::endl; for(int iteration = 0; iteration <= iterations; ++iteration) { auto importer = WholeSlideImageImporter::New(); importer->setFilename(Config::getTestDataPath() + "/CMU-1.tiff"); auto tissueSegmentation = TissueSegmentation::New(); tissueSegmentation->setInputConnection(importer->getOutputPort()); auto generator = PatchGenerator::New(); generator->setPatchSize(512, 512); generator->setPatchLevel(0); generator->setInputConnection(importer->getOutputPort()); generator->setInputConnection(1, tissueSegmentation->getOutputPort()); generator->enableRuntimeMeasurements(); auto network = NeuralNetwork::New(); network->setInferenceEngine(engine); std::string postfix; if(engine.substr(0, 10) == "TensorFlow") { network->setOutputNode(0, "dense_1/Softmax", NodeType::TENSOR); } else if(engine == "TensorRT") { network->setInputNode(0, "input_1", NodeType::IMAGE, TensorShape{-1, 3, 512, 512}); network->setOutputNode(0, "dense_1/Softmax", NodeType::TENSOR, TensorShape{-1, 3}); } else if(engine == "OpenVINO") { network->getInferenceEngine()->setDeviceType(deviceType.second); if(deviceType.first == "VPU") { postfix = "_fp16"; } } network->load(Config::getTestDataPath() + "NeuralNetworkModels/bc_grade_model_3_grades_10x_512_heavy_HSV" + postfix + "." + network->getInferenceEngine()->getDefaultFileExtension()); network->setInputConnection(generator->getOutputPort()); network->setScaleFactor(1.0f / 255.0f); network->enableRuntimeMeasurements(); auto stitcher = PatchStitcher::New(); stitcher->setInputConnection(network->getOutputPort()); stitcher->enableRuntimeMeasurements(); auto start = std::chrono::high_resolution_clock::now(); DataObject::pointer data; do { data = stitcher->updateAndGetOutputData<DataObject>(); } while(!data->isLastFrame()); std::chrono::duration<float, std::milli> timeUsed = std::chrono::high_resolution_clock::now() - start; std::cout << "Total runtime: " << timeUsed.count() << std::endl; std::cout << "Patch generator runtime: " << std::endl; generator->getRuntime("create patch")->print(); std::cout << "NN runtime: " << std::endl; network->getRuntime()->print(); std::cout << "Patch stitcher runtime: " << std::endl; stitcher->getRuntime()->print(); if(iteration == 0 && warmupIteration) continue; file << engine + ";" + deviceType.first + ";" + std::to_string(iteration) + ";" + std::to_string(generator->getRuntime("create patch")->getAverage()) + ";" + std::to_string(generator->getRuntime("create patch")->getStdDeviation()) + ";" + std::to_string(network->getRuntime("input_processing")->getAverage()) + ";" + std::to_string(network->getRuntime("input_processing")->getStdDeviation()) + ";" + std::to_string(network->getRuntime("inference")->getAverage()) + ";" + std::to_string(network->getRuntime("inference")->getStdDeviation()) + ";" + std::to_string(network->getRuntime("output_processing")->getAverage()) + ";" + std::to_string(network->getRuntime("output_processing")->getStdDeviation()) + ";" + std::to_string(stitcher->getRuntime()->getAverage()) + ";" + std::to_string(stitcher->getRuntime()->getStdDeviation()) + ";" + std::to_string(timeUsed.count()) << std::endl; } } } } } <commit_msg>fp 16 postfix for NN case 1<commit_after>#include <FAST/Testing.hpp> #include <FAST/Algorithms/NeuralNetwork/SegmentationNetwork.hpp> #include <FAST/Importers/ImageFileImporter.hpp> #include <FAST/Visualization/SimpleWindow.hpp> #include <FAST/Streamers/ImageFileStreamer.hpp> #include <FAST/Algorithms/NeuralNetwork/InferenceEngineManager.hpp> #include <fstream> #include <FAST/Algorithms/ImagePatch/PatchGenerator.hpp> #include <FAST/Algorithms/ImagePatch/PatchStitcher.hpp> #include <FAST/Importers/WholeSlideImageImporter.hpp> #include <FAST/Algorithms/TissueSegmentation/TissueSegmentation.hpp> #include <FAST/Tools/CommandLineParser.hpp> using namespace fast; int main(int argc, char** argv) { Reporter::setGlobalReportMethod(Reporter::INFO, Reporter::NONE); CommandLineParser parser("Measure neural network performance script"); parser.addOption("disable-case-1"); parser.addOption("disable-case-2"); parser.addOption("disable-case-3"); parser.addOption("disable-warmup"); parser.parse(argc, argv); const int iterations = 10; const bool warmupIteration = !parser.getOption("disable-warmup"); const bool case1 = !parser.getOption("disable-case-1"); const bool case2 = !parser.getOption("disable-case-2"); const bool case3 = !parser.getOption("disable-case-3"); if(case1) { // CASE 1 - ULTRASOUND const std::string resultFilename = "neural-network-runtimes-case-1.csv"; std::ofstream file(resultFilename.c_str()); // Write header file << "Engine;Device Type;Iteration;NN input AVG;NN input STD;NN inference AVG;NN inference STD;NN output AVG;NN output STD;Total\n"; for(auto &engine : InferenceEngineManager::getEngineList()) { std::map<std::string, InferenceDeviceType> deviceTypes = {{"ANY", InferenceDeviceType::ANY}}; if(engine == "OpenVINO") { // On OpenVINO, try all device types deviceTypes = std::map<std::string, InferenceDeviceType>{ {"CPU", InferenceDeviceType::CPU}, {"GPU", InferenceDeviceType::GPU}, {"VPU", InferenceDeviceType::VPU}, }; } for(auto &&deviceType : deviceTypes) { std::cout << engine << " for device type " << deviceType.first << std::endl; std::cout << "====================================" << std::endl; for(int iteration = 0; iteration <= iterations; ++iteration) { auto streamer = ImageFileStreamer::New(); streamer->setFilenameFormat(Config::getTestDataPath() + "US/JugularVein/US-2D_#.mhd"); auto segmentation = SegmentationNetwork::New(); segmentation->setInferenceEngine(engine); segmentation->getInferenceEngine()->setDeviceType(deviceType.second); std::string postfix = ""; if(engine.substr(0, 10) == "TensorFlow") { segmentation->setOutputNode(0, "conv2d_23/truediv"); } else if(engine == "TensorRT") { segmentation->setInputNode(0, "input_image", NodeType::IMAGE, TensorShape({-1, 1, 256, 256})); segmentation->setOutputNode(0, "permute_2/transpose", NodeType::TENSOR, TensorShape({-1, 3, 256, 256})); } else if(engine == "OpenVINO") { if (deviceType.first == "VPU") { postfix = "_fp16"; } } try { segmentation->load(join(Config::getTestDataPath(), "NeuralNetworkModels/jugular_vein_segmentation"+postfix+"." + segmentation->getInferenceEngine()->getDefaultFileExtension())); } catch(Exception &e) { // If a device type is not present, it will fail in load Reporter::warning() << e.what() << Reporter::end(); continue; } segmentation->setScaleFactor(1.0f / 255.0f); //segmentation->setInputConnection(importer->getOutputPort()); segmentation->setInputConnection(streamer->getOutputPort()); segmentation->enableRuntimeMeasurements(); auto start = std::chrono::high_resolution_clock::now(); DataObject::pointer data; do { data = segmentation->updateAndGetOutputData<DataObject>(); } while(!data->isLastFrame()); std::chrono::duration<float, std::milli> timeUsed = std::chrono::high_resolution_clock::now() - start; std::cout << "RUNTIME Ultrasound " << engine << std::endl; std::cout << "=========================================" << std::endl; std::cout << "Total runtime: " << timeUsed.count() << std::endl; std::cout << "NN runtime: " << std::endl; segmentation->getRuntime("input_processing")->print(); segmentation->getRuntime("inference")->print(); segmentation->getRuntime("output_processing")->print(); if(iteration == 0 && warmupIteration) continue; file << engine + ";" + deviceType.first + ";" + std::to_string(iteration) + ";" + std::to_string(segmentation->getRuntime("input_processing")->getAverage()) + ";" + std::to_string(segmentation->getRuntime("input_processing")->getStdDeviation()) + ";" + std::to_string(segmentation->getRuntime("inference")->getAverage()) + ";" + std::to_string(segmentation->getRuntime("inference")->getStdDeviation()) + ";" + std::to_string(segmentation->getRuntime("output_processing")->getAverage()) + ";" + std::to_string(segmentation->getRuntime("output_processing")->getStdDeviation()) + ";" + std::to_string(timeUsed.count()) << std::endl; } } } } if(case2) { // CASE 2 - VOLUME SEGMENTATION const std::string resultFilename = "neural-network-runtimes-case-2.csv"; std::ofstream file(resultFilename.c_str()); // Write header file << "Engine;Device Type;Iteration;Patch generator AVG;Patch generator STD;NN input AVG;NN input STD;NN inference AVG;NN inference STD;NN output AVG;NN output STD;Patch stitcher AVG;Patch stitcher STD;Total\n"; //Reporter::setGlobalReportMethod(Reporter::NONE); for(std::string engine : {"TensorFlowCUDA", "TensorFlowCPU"}) { std::map<std::string, InferenceDeviceType> deviceTypes = {{"ANY", InferenceDeviceType::ANY}}; if(engine == "OpenVINO") { // On OpenVINO, try all device types deviceTypes = std::map<std::string, InferenceDeviceType>{ {"CPU", InferenceDeviceType::CPU}, {"GPU", InferenceDeviceType::GPU}, {"VPU", InferenceDeviceType::VPU}, }; } for(auto &&deviceType : deviceTypes) { std::cout << engine << " for device type " << deviceType.first << std::endl; std::cout << "====================================" << std::endl; for(int iteration = 0; iteration <= iterations; ++iteration) { auto importer = ImageFileImporter::New(); importer->setFilename(Config::getTestDataPath() + "/CT/LIDC-IDRI-0072/01-01-2000-CT CHEST W CONT-45499/4-Recon 3-88650/000001.dcm"); auto generator = PatchGenerator::New(); generator->setPatchSize(512, 512, 64); generator->setInputConnection(importer->getOutputPort()); generator->enableRuntimeMeasurements(); auto network = SegmentationNetwork::New(); network->setInferenceEngine(engine); network->getInferenceEngine()->setDeviceType(deviceType.second); network->setInferenceEngine(engine); network->load(Config::getTestDataPath() + "/NeuralNetworkModels/lung_nodule_model.pb"); network->setMinAndMaxIntensity(-1200.0f, 400.0f); network->setScaleFactor(1.0f/(400+1200)); network->setMeanAndStandardDeviation(-1200.0f, 1.0f); network->setOutputNode(0, "conv3d_18/truediv"); network->setInputConnection(generator->getOutputPort()); network->setResizeBackToOriginalSize(true); network->setThreshold(0.3); network->enableRuntimeMeasurements(); auto stitcher = PatchStitcher::New(); stitcher->setInputConnection(network->getOutputPort()); stitcher->enableRuntimeMeasurements(); auto start = std::chrono::high_resolution_clock::now(); DataObject::pointer data; do { data = stitcher->updateAndGetOutputData<DataObject>(); } while(!data->isLastFrame()); std::chrono::duration<float, std::milli> timeUsed = std::chrono::high_resolution_clock::now() - start; std::cout << "Total runtime: " << timeUsed.count() << std::endl; std::cout << "Patch generator runtime: " << std::endl; generator->getRuntime("create patch")->print(); std::cout << "NN runtime: " << std::endl; network->getRuntime()->print(); std::cout << "Patch stitcher runtime: " << std::endl; stitcher->getRuntime()->print(); if(iteration == 0 && warmupIteration) continue; file << engine + ";" + deviceType.first + ";" + std::to_string(iteration) + ";" + std::to_string(generator->getRuntime("create patch")->getAverage()) + ";" + std::to_string(generator->getRuntime("create patch")->getStdDeviation()) + ";" + std::to_string(network->getRuntime("input_processing")->getAverage()) + ";" + std::to_string(network->getRuntime("input_processing")->getStdDeviation()) + ";" + std::to_string(network->getRuntime("inference")->getAverage()) + ";" + std::to_string(network->getRuntime("inference")->getStdDeviation()) + ";" + std::to_string(network->getRuntime("output_processing")->getAverage()) + ";" + std::to_string(network->getRuntime("output_processing")->getStdDeviation()) + ";" + std::to_string(stitcher->getRuntime()->getAverage()) + ";" + std::to_string(stitcher->getRuntime()->getStdDeviation()) + ";" + std::to_string(timeUsed.count()) << std::endl; } } } } if(case3) { // CASE 3 - WSI CLASSIFICATION const std::string resultFilename = "neural-network-runtimes-case-3.csv"; std::ofstream file(resultFilename.c_str()); // Write header file << "Engine;Device Type;Iteration;Patch generator AVG;Patch generator STD;NN input AVG;NN input STD;NN inference AVG;NN inference STD;NN output AVG;NN output STD;Patch stitcher AVG;Patch stitcher STD;Total\n"; for(auto &engine : InferenceEngineManager::getEngineList()) { std::map<std::string, InferenceDeviceType> deviceTypes = {{"ANY", InferenceDeviceType::ANY}}; if(engine == "OpenVINO") { // On OpenVINO, try all device types deviceTypes = std::map<std::string, InferenceDeviceType>{ {"CPU", InferenceDeviceType::CPU}, {"GPU", InferenceDeviceType::GPU}, {"VPU", InferenceDeviceType::VPU}, }; } for(auto &&deviceType : deviceTypes) { std::cout << engine << " for device type " << deviceType.first << std::endl; std::cout << "====================================" << std::endl; for(int iteration = 0; iteration <= iterations; ++iteration) { auto importer = WholeSlideImageImporter::New(); importer->setFilename(Config::getTestDataPath() + "/CMU-1.tiff"); auto tissueSegmentation = TissueSegmentation::New(); tissueSegmentation->setInputConnection(importer->getOutputPort()); auto generator = PatchGenerator::New(); generator->setPatchSize(512, 512); generator->setPatchLevel(0); generator->setInputConnection(importer->getOutputPort()); generator->setInputConnection(1, tissueSegmentation->getOutputPort()); generator->enableRuntimeMeasurements(); auto network = NeuralNetwork::New(); network->setInferenceEngine(engine); std::string postfix; if(engine.substr(0, 10) == "TensorFlow") { network->setOutputNode(0, "dense_1/Softmax", NodeType::TENSOR); } else if(engine == "TensorRT") { network->setInputNode(0, "input_1", NodeType::IMAGE, TensorShape{-1, 3, 512, 512}); network->setOutputNode(0, "dense_1/Softmax", NodeType::TENSOR, TensorShape{-1, 3}); } else if(engine == "OpenVINO") { network->getInferenceEngine()->setDeviceType(deviceType.second); if(deviceType.first == "VPU") { postfix = "_fp16"; } } network->load(Config::getTestDataPath() + "NeuralNetworkModels/bc_grade_model_3_grades_10x_512_heavy_HSV" + postfix + "." + network->getInferenceEngine()->getDefaultFileExtension()); network->setInputConnection(generator->getOutputPort()); network->setScaleFactor(1.0f / 255.0f); network->enableRuntimeMeasurements(); auto stitcher = PatchStitcher::New(); stitcher->setInputConnection(network->getOutputPort()); stitcher->enableRuntimeMeasurements(); auto start = std::chrono::high_resolution_clock::now(); DataObject::pointer data; do { data = stitcher->updateAndGetOutputData<DataObject>(); } while(!data->isLastFrame()); std::chrono::duration<float, std::milli> timeUsed = std::chrono::high_resolution_clock::now() - start; std::cout << "Total runtime: " << timeUsed.count() << std::endl; std::cout << "Patch generator runtime: " << std::endl; generator->getRuntime("create patch")->print(); std::cout << "NN runtime: " << std::endl; network->getRuntime()->print(); std::cout << "Patch stitcher runtime: " << std::endl; stitcher->getRuntime()->print(); if(iteration == 0 && warmupIteration) continue; file << engine + ";" + deviceType.first + ";" + std::to_string(iteration) + ";" + std::to_string(generator->getRuntime("create patch")->getAverage()) + ";" + std::to_string(generator->getRuntime("create patch")->getStdDeviation()) + ";" + std::to_string(network->getRuntime("input_processing")->getAverage()) + ";" + std::to_string(network->getRuntime("input_processing")->getStdDeviation()) + ";" + std::to_string(network->getRuntime("inference")->getAverage()) + ";" + std::to_string(network->getRuntime("inference")->getStdDeviation()) + ";" + std::to_string(network->getRuntime("output_processing")->getAverage()) + ";" + std::to_string(network->getRuntime("output_processing")->getStdDeviation()) + ";" + std::to_string(stitcher->getRuntime()->getAverage()) + ";" + std::to_string(stitcher->getRuntime()->getStdDeviation()) + ";" + std::to_string(timeUsed.count()) << std::endl; } } } } } <|endoftext|>
<commit_before>//===- X86LegalizerInfo.cpp --------------------------------------*- C++ -*-==// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// /// \file /// This file implements the targeting of the Machinelegalizer class for X86. /// \todo This should be generated by TableGen. //===----------------------------------------------------------------------===// #include "X86LegalizerInfo.h" #include "X86Subtarget.h" #include "X86TargetMachine.h" #include "llvm/CodeGen/ValueTypes.h" #include "llvm/IR/DerivedTypes.h" #include "llvm/IR/Type.h" #include "llvm/Target/TargetOpcodes.h" using namespace llvm; using namespace TargetOpcode; X86LegalizerInfo::X86LegalizerInfo(const X86Subtarget &STI, const X86TargetMachine &TM) : Subtarget(STI), TM(TM) { setLegalizerInfo32bit(); setLegalizerInfo64bit(); setLegalizerInfoSSE1(); setLegalizerInfoSSE2(); setLegalizerInfoSSE41(); setLegalizerInfoAVX(); setLegalizerInfoAVX2(); setLegalizerInfoAVX512(); setLegalizerInfoAVX512DQ(); setLegalizerInfoAVX512BW(); computeTables(); } void X86LegalizerInfo::setLegalizerInfo32bit() { if (Subtarget.is64Bit()) return; const LLT p0 = LLT::pointer(0, 32); const LLT s1 = LLT::scalar(1); const LLT s8 = LLT::scalar(8); const LLT s16 = LLT::scalar(16); const LLT s32 = LLT::scalar(32); const LLT s64 = LLT::scalar(64); for (auto Ty : {p0, s1, s8, s16, s32}) setAction({G_IMPLICIT_DEF, Ty}, Legal); for (unsigned BinOp : {G_ADD, G_SUB, G_MUL, G_AND, G_OR, G_XOR}) for (auto Ty : {s8, s16, s32}) setAction({BinOp, Ty}, Legal); for (unsigned Op : {G_UADDE}) { setAction({Op, s32}, Legal); setAction({Op, 1, s1}, Legal); } for (unsigned MemOp : {G_LOAD, G_STORE}) { for (auto Ty : {s8, s16, s32, p0}) setAction({MemOp, Ty}, Legal); setAction({MemOp, s1}, WidenScalar); // And everything's fine in addrspace 0. setAction({MemOp, 1, p0}, Legal); } // Pointer-handling setAction({G_FRAME_INDEX, p0}, Legal); setAction({G_GLOBAL_VALUE, p0}, Legal); setAction({G_GEP, p0}, Legal); setAction({G_GEP, 1, s32}, Legal); for (auto Ty : {s1, s8, s16}) setAction({G_GEP, 1, Ty}, WidenScalar); // Control-flow setAction({G_BRCOND, s1}, Legal); // Constants for (auto Ty : {s8, s16, s32, p0}) setAction({TargetOpcode::G_CONSTANT, Ty}, Legal); setAction({TargetOpcode::G_CONSTANT, s1}, WidenScalar); setAction({TargetOpcode::G_CONSTANT, s64}, NarrowScalar); // Extensions for (auto Ty : {s8, s16, s32}) { setAction({G_ZEXT, Ty}, Legal); setAction({G_SEXT, Ty}, Legal); } for (auto Ty : {s1, s8, s16}) { setAction({G_ZEXT, 1, Ty}, Legal); setAction({G_SEXT, 1, Ty}, Legal); } // Comparison setAction({G_ICMP, s1}, Legal); for (auto Ty : {s8, s16, s32, p0}) setAction({G_ICMP, 1, Ty}, Legal); } void X86LegalizerInfo::setLegalizerInfo64bit() { if (!Subtarget.is64Bit()) return; const LLT p0 = LLT::pointer(0, TM.getPointerSize() * 8); const LLT s1 = LLT::scalar(1); const LLT s8 = LLT::scalar(8); const LLT s16 = LLT::scalar(16); const LLT s32 = LLT::scalar(32); const LLT s64 = LLT::scalar(64); for (auto Ty : {p0, s1, s8, s16, s32, s64}) setAction({G_IMPLICIT_DEF, Ty}, Legal); for (unsigned BinOp : {G_ADD, G_SUB, G_MUL, G_AND, G_OR, G_XOR}) for (auto Ty : {s8, s16, s32, s64}) setAction({BinOp, Ty}, Legal); for (unsigned MemOp : {G_LOAD, G_STORE}) { for (auto Ty : {s8, s16, s32, s64, p0}) setAction({MemOp, Ty}, Legal); setAction({MemOp, s1}, WidenScalar); // And everything's fine in addrspace 0. setAction({MemOp, 1, p0}, Legal); } // Pointer-handling setAction({G_FRAME_INDEX, p0}, Legal); setAction({G_GLOBAL_VALUE, p0}, Legal); setAction({G_GEP, p0}, Legal); setAction({G_GEP, 1, s32}, Legal); setAction({G_GEP, 1, s64}, Legal); for (auto Ty : {s1, s8, s16}) setAction({G_GEP, 1, Ty}, WidenScalar); // Control-flow setAction({G_BRCOND, s1}, Legal); // Constants for (auto Ty : {s8, s16, s32, s64, p0}) setAction({TargetOpcode::G_CONSTANT, Ty}, Legal); setAction({TargetOpcode::G_CONSTANT, s1}, WidenScalar); // Extensions for (auto Ty : {s8, s16, s32, s64}) { setAction({G_ZEXT, Ty}, Legal); setAction({G_SEXT, Ty}, Legal); } for (auto Ty : {s1, s8, s16, s32}) { setAction({G_ZEXT, 1, Ty}, Legal); setAction({G_SEXT, 1, Ty}, Legal); } // Comparison setAction({G_ICMP, s1}, Legal); for (auto Ty : {s8, s16, s32, s64, p0}) setAction({G_ICMP, 1, Ty}, Legal); } void X86LegalizerInfo::setLegalizerInfoSSE1() { if (!Subtarget.hasSSE1()) return; const LLT s32 = LLT::scalar(32); const LLT v4s32 = LLT::vector(4, 32); const LLT v2s64 = LLT::vector(2, 64); for (unsigned BinOp : {G_FADD, G_FSUB, G_FMUL, G_FDIV}) for (auto Ty : {s32, v4s32}) setAction({BinOp, Ty}, Legal); for (unsigned MemOp : {G_LOAD, G_STORE}) for (auto Ty : {v4s32, v2s64}) setAction({MemOp, Ty}, Legal); } void X86LegalizerInfo::setLegalizerInfoSSE2() { if (!Subtarget.hasSSE2()) return; const LLT s64 = LLT::scalar(64); const LLT v16s8 = LLT::vector(16, 8); const LLT v8s16 = LLT::vector(8, 16); const LLT v4s32 = LLT::vector(4, 32); const LLT v2s64 = LLT::vector(2, 64); for (unsigned BinOp : {G_FADD, G_FSUB, G_FMUL, G_FDIV}) for (auto Ty : {s64, v2s64}) setAction({BinOp, Ty}, Legal); for (unsigned BinOp : {G_ADD, G_SUB}) for (auto Ty : {v16s8, v8s16, v4s32, v2s64}) setAction({BinOp, Ty}, Legal); setAction({G_MUL, v8s16}, Legal); } void X86LegalizerInfo::setLegalizerInfoSSE41() { if (!Subtarget.hasSSE41()) return; const LLT v4s32 = LLT::vector(4, 32); setAction({G_MUL, v4s32}, Legal); } void X86LegalizerInfo::setLegalizerInfoAVX() { if (!Subtarget.hasAVX()) return; const LLT v16s8 = LLT::vector(16, 8); const LLT v8s16 = LLT::vector(8, 16); const LLT v4s32 = LLT::vector(4, 32); const LLT v2s64 = LLT::vector(2, 64); const LLT v32s8 = LLT::vector(32, 8); const LLT v16s16 = LLT::vector(16, 16); const LLT v8s32 = LLT::vector(8, 32); const LLT v4s64 = LLT::vector(4, 64); for (unsigned MemOp : {G_LOAD, G_STORE}) for (auto Ty : {v8s32, v4s64}) setAction({MemOp, Ty}, Legal); for (auto Ty : {v32s8, v16s16, v8s32, v4s64}) { setAction({G_INSERT, Ty}, Legal); setAction({G_EXTRACT, 1, Ty}, Legal); } for (auto Ty : {v16s8, v8s16, v4s32, v2s64}) { setAction({G_INSERT, 1, Ty}, Legal); setAction({G_EXTRACT, Ty}, Legal); } } void X86LegalizerInfo::setLegalizerInfoAVX2() { if (!Subtarget.hasAVX2()) return; const LLT v32s8 = LLT::vector(32, 8); const LLT v16s16 = LLT::vector(16, 16); const LLT v8s32 = LLT::vector(8, 32); const LLT v4s64 = LLT::vector(4, 64); for (unsigned BinOp : {G_ADD, G_SUB}) for (auto Ty : {v32s8, v16s16, v8s32, v4s64}) setAction({BinOp, Ty}, Legal); for (auto Ty : {v16s16, v8s32}) setAction({G_MUL, Ty}, Legal); } void X86LegalizerInfo::setLegalizerInfoAVX512() { if (!Subtarget.hasAVX512()) return; const LLT v16s8 = LLT::vector(16, 8); const LLT v8s16 = LLT::vector(8, 16); const LLT v4s32 = LLT::vector(4, 32); const LLT v2s64 = LLT::vector(2, 64); const LLT v32s8 = LLT::vector(32, 8); const LLT v16s16 = LLT::vector(16, 16); const LLT v8s32 = LLT::vector(8, 32); const LLT v4s64 = LLT::vector(4, 64); const LLT v64s8 = LLT::vector(64, 8); const LLT v32s16 = LLT::vector(32, 16); const LLT v16s32 = LLT::vector(16, 32); const LLT v8s64 = LLT::vector(8, 64); for (unsigned BinOp : {G_ADD, G_SUB}) for (auto Ty : {v16s32, v8s64}) setAction({BinOp, Ty}, Legal); setAction({G_MUL, v16s32}, Legal); for (unsigned MemOp : {G_LOAD, G_STORE}) for (auto Ty : {v16s32, v8s64}) setAction({MemOp, Ty}, Legal); for (auto Ty : {v64s8, v32s16, v16s32, v8s64}) { setAction({G_INSERT, Ty}, Legal); setAction({G_EXTRACT, 1, Ty}, Legal); } for (auto Ty : {v32s8, v16s16, v8s32, v4s64, v16s8, v8s16, v4s32, v2s64}) { setAction({G_INSERT, 1, Ty}, Legal); setAction({G_EXTRACT, Ty}, Legal); } /************ VLX *******************/ if (!Subtarget.hasVLX()) return; for (auto Ty : {v4s32, v8s32}) setAction({G_MUL, Ty}, Legal); } void X86LegalizerInfo::setLegalizerInfoAVX512DQ() { if (!(Subtarget.hasAVX512() && Subtarget.hasDQI())) return; const LLT v8s64 = LLT::vector(8, 64); setAction({G_MUL, v8s64}, Legal); /************ VLX *******************/ if (!Subtarget.hasVLX()) return; const LLT v2s64 = LLT::vector(2, 64); const LLT v4s64 = LLT::vector(4, 64); for (auto Ty : {v2s64, v4s64}) setAction({G_MUL, Ty}, Legal); } void X86LegalizerInfo::setLegalizerInfoAVX512BW() { if (!(Subtarget.hasAVX512() && Subtarget.hasBWI())) return; const LLT v64s8 = LLT::vector(64, 8); const LLT v32s16 = LLT::vector(32, 16); for (unsigned BinOp : {G_ADD, G_SUB}) for (auto Ty : {v64s8, v32s16}) setAction({BinOp, Ty}, Legal); setAction({G_MUL, v32s16}, Legal); /************ VLX *******************/ if (!Subtarget.hasVLX()) return; const LLT v8s16 = LLT::vector(8, 16); const LLT v16s16 = LLT::vector(16, 16); for (auto Ty : {v8s16, v16s16}) setAction({G_MUL, Ty}, Legal); } <commit_msg>[GlobalISel][X86] Refactor X86LegalizerInfo. NFC.<commit_after>//===- X86LegalizerInfo.cpp --------------------------------------*- C++ -*-==// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// /// \file /// This file implements the targeting of the Machinelegalizer class for X86. /// \todo This should be generated by TableGen. //===----------------------------------------------------------------------===// #include "X86LegalizerInfo.h" #include "X86Subtarget.h" #include "X86TargetMachine.h" #include "llvm/CodeGen/ValueTypes.h" #include "llvm/IR/DerivedTypes.h" #include "llvm/IR/Type.h" #include "llvm/Target/TargetOpcodes.h" using namespace llvm; using namespace TargetOpcode; X86LegalizerInfo::X86LegalizerInfo(const X86Subtarget &STI, const X86TargetMachine &TM) : Subtarget(STI), TM(TM) { setLegalizerInfo32bit(); setLegalizerInfo64bit(); setLegalizerInfoSSE1(); setLegalizerInfoSSE2(); setLegalizerInfoSSE41(); setLegalizerInfoAVX(); setLegalizerInfoAVX2(); setLegalizerInfoAVX512(); setLegalizerInfoAVX512DQ(); setLegalizerInfoAVX512BW(); computeTables(); } void X86LegalizerInfo::setLegalizerInfo32bit() { const LLT p0 = LLT::pointer(0, TM.getPointerSize() * 8); const LLT s1 = LLT::scalar(1); const LLT s8 = LLT::scalar(8); const LLT s16 = LLT::scalar(16); const LLT s32 = LLT::scalar(32); const LLT s64 = LLT::scalar(64); for (auto Ty : {p0, s1, s8, s16, s32}) setAction({G_IMPLICIT_DEF, Ty}, Legal); for (unsigned BinOp : {G_ADD, G_SUB, G_MUL, G_AND, G_OR, G_XOR}) for (auto Ty : {s8, s16, s32}) setAction({BinOp, Ty}, Legal); for (unsigned Op : {G_UADDE}) { setAction({Op, s32}, Legal); setAction({Op, 1, s1}, Legal); } for (unsigned MemOp : {G_LOAD, G_STORE}) { for (auto Ty : {s8, s16, s32, p0}) setAction({MemOp, Ty}, Legal); setAction({MemOp, s1}, WidenScalar); // And everything's fine in addrspace 0. setAction({MemOp, 1, p0}, Legal); } // Pointer-handling setAction({G_FRAME_INDEX, p0}, Legal); setAction({G_GLOBAL_VALUE, p0}, Legal); setAction({G_GEP, p0}, Legal); setAction({G_GEP, 1, s32}, Legal); for (auto Ty : {s1, s8, s16}) setAction({G_GEP, 1, Ty}, WidenScalar); // Control-flow setAction({G_BRCOND, s1}, Legal); // Constants for (auto Ty : {s8, s16, s32, p0}) setAction({TargetOpcode::G_CONSTANT, Ty}, Legal); setAction({TargetOpcode::G_CONSTANT, s1}, WidenScalar); setAction({TargetOpcode::G_CONSTANT, s64}, NarrowScalar); // Extensions for (auto Ty : {s8, s16, s32}) { setAction({G_ZEXT, Ty}, Legal); setAction({G_SEXT, Ty}, Legal); } for (auto Ty : {s1, s8, s16}) { setAction({G_ZEXT, 1, Ty}, Legal); setAction({G_SEXT, 1, Ty}, Legal); } // Comparison setAction({G_ICMP, s1}, Legal); for (auto Ty : {s8, s16, s32, p0}) setAction({G_ICMP, 1, Ty}, Legal); } void X86LegalizerInfo::setLegalizerInfo64bit() { if (!Subtarget.is64Bit()) return; const LLT s32 = LLT::scalar(32); const LLT s64 = LLT::scalar(64); setAction({G_IMPLICIT_DEF, s64}, Legal); for (unsigned BinOp : {G_ADD, G_SUB, G_MUL, G_AND, G_OR, G_XOR}) setAction({BinOp, s64}, Legal); for (unsigned MemOp : {G_LOAD, G_STORE}) { setAction({MemOp, s64}, Legal); } // Pointer-handling setAction({G_GEP, 1, s64}, Legal); // Constants setAction({TargetOpcode::G_CONSTANT, s64}, Legal); // Extensions setAction({G_ZEXT, s64}, Legal); setAction({G_SEXT, s64}, Legal); setAction({G_ZEXT, 1, s32}, Legal); setAction({G_SEXT, 1, s32}, Legal); // Comparison setAction({G_ICMP, 1, s64}, Legal); } void X86LegalizerInfo::setLegalizerInfoSSE1() { if (!Subtarget.hasSSE1()) return; const LLT s32 = LLT::scalar(32); const LLT v4s32 = LLT::vector(4, 32); const LLT v2s64 = LLT::vector(2, 64); for (unsigned BinOp : {G_FADD, G_FSUB, G_FMUL, G_FDIV}) for (auto Ty : {s32, v4s32}) setAction({BinOp, Ty}, Legal); for (unsigned MemOp : {G_LOAD, G_STORE}) for (auto Ty : {v4s32, v2s64}) setAction({MemOp, Ty}, Legal); } void X86LegalizerInfo::setLegalizerInfoSSE2() { if (!Subtarget.hasSSE2()) return; const LLT s64 = LLT::scalar(64); const LLT v16s8 = LLT::vector(16, 8); const LLT v8s16 = LLT::vector(8, 16); const LLT v4s32 = LLT::vector(4, 32); const LLT v2s64 = LLT::vector(2, 64); for (unsigned BinOp : {G_FADD, G_FSUB, G_FMUL, G_FDIV}) for (auto Ty : {s64, v2s64}) setAction({BinOp, Ty}, Legal); for (unsigned BinOp : {G_ADD, G_SUB}) for (auto Ty : {v16s8, v8s16, v4s32, v2s64}) setAction({BinOp, Ty}, Legal); setAction({G_MUL, v8s16}, Legal); } void X86LegalizerInfo::setLegalizerInfoSSE41() { if (!Subtarget.hasSSE41()) return; const LLT v4s32 = LLT::vector(4, 32); setAction({G_MUL, v4s32}, Legal); } void X86LegalizerInfo::setLegalizerInfoAVX() { if (!Subtarget.hasAVX()) return; const LLT v16s8 = LLT::vector(16, 8); const LLT v8s16 = LLT::vector(8, 16); const LLT v4s32 = LLT::vector(4, 32); const LLT v2s64 = LLT::vector(2, 64); const LLT v32s8 = LLT::vector(32, 8); const LLT v16s16 = LLT::vector(16, 16); const LLT v8s32 = LLT::vector(8, 32); const LLT v4s64 = LLT::vector(4, 64); for (unsigned MemOp : {G_LOAD, G_STORE}) for (auto Ty : {v8s32, v4s64}) setAction({MemOp, Ty}, Legal); for (auto Ty : {v32s8, v16s16, v8s32, v4s64}) { setAction({G_INSERT, Ty}, Legal); setAction({G_EXTRACT, 1, Ty}, Legal); } for (auto Ty : {v16s8, v8s16, v4s32, v2s64}) { setAction({G_INSERT, 1, Ty}, Legal); setAction({G_EXTRACT, Ty}, Legal); } } void X86LegalizerInfo::setLegalizerInfoAVX2() { if (!Subtarget.hasAVX2()) return; const LLT v32s8 = LLT::vector(32, 8); const LLT v16s16 = LLT::vector(16, 16); const LLT v8s32 = LLT::vector(8, 32); const LLT v4s64 = LLT::vector(4, 64); for (unsigned BinOp : {G_ADD, G_SUB}) for (auto Ty : {v32s8, v16s16, v8s32, v4s64}) setAction({BinOp, Ty}, Legal); for (auto Ty : {v16s16, v8s32}) setAction({G_MUL, Ty}, Legal); } void X86LegalizerInfo::setLegalizerInfoAVX512() { if (!Subtarget.hasAVX512()) return; const LLT v16s8 = LLT::vector(16, 8); const LLT v8s16 = LLT::vector(8, 16); const LLT v4s32 = LLT::vector(4, 32); const LLT v2s64 = LLT::vector(2, 64); const LLT v32s8 = LLT::vector(32, 8); const LLT v16s16 = LLT::vector(16, 16); const LLT v8s32 = LLT::vector(8, 32); const LLT v4s64 = LLT::vector(4, 64); const LLT v64s8 = LLT::vector(64, 8); const LLT v32s16 = LLT::vector(32, 16); const LLT v16s32 = LLT::vector(16, 32); const LLT v8s64 = LLT::vector(8, 64); for (unsigned BinOp : {G_ADD, G_SUB}) for (auto Ty : {v16s32, v8s64}) setAction({BinOp, Ty}, Legal); setAction({G_MUL, v16s32}, Legal); for (unsigned MemOp : {G_LOAD, G_STORE}) for (auto Ty : {v16s32, v8s64}) setAction({MemOp, Ty}, Legal); for (auto Ty : {v64s8, v32s16, v16s32, v8s64}) { setAction({G_INSERT, Ty}, Legal); setAction({G_EXTRACT, 1, Ty}, Legal); } for (auto Ty : {v32s8, v16s16, v8s32, v4s64, v16s8, v8s16, v4s32, v2s64}) { setAction({G_INSERT, 1, Ty}, Legal); setAction({G_EXTRACT, Ty}, Legal); } /************ VLX *******************/ if (!Subtarget.hasVLX()) return; for (auto Ty : {v4s32, v8s32}) setAction({G_MUL, Ty}, Legal); } void X86LegalizerInfo::setLegalizerInfoAVX512DQ() { if (!(Subtarget.hasAVX512() && Subtarget.hasDQI())) return; const LLT v8s64 = LLT::vector(8, 64); setAction({G_MUL, v8s64}, Legal); /************ VLX *******************/ if (!Subtarget.hasVLX()) return; const LLT v2s64 = LLT::vector(2, 64); const LLT v4s64 = LLT::vector(4, 64); for (auto Ty : {v2s64, v4s64}) setAction({G_MUL, Ty}, Legal); } void X86LegalizerInfo::setLegalizerInfoAVX512BW() { if (!(Subtarget.hasAVX512() && Subtarget.hasBWI())) return; const LLT v64s8 = LLT::vector(64, 8); const LLT v32s16 = LLT::vector(32, 16); for (unsigned BinOp : {G_ADD, G_SUB}) for (auto Ty : {v64s8, v32s16}) setAction({BinOp, Ty}, Legal); setAction({G_MUL, v32s16}, Legal); /************ VLX *******************/ if (!Subtarget.hasVLX()) return; const LLT v8s16 = LLT::vector(8, 16); const LLT v16s16 = LLT::vector(16, 16); for (auto Ty : {v8s16, v16s16}) setAction({G_MUL, Ty}, Legal); } <|endoftext|>
<commit_before>//===--- CommonOptionsParser.cpp - common options for clang tools ---------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file implements the CommonOptionsParser class used to parse common // command-line options for clang tools, so that they can be run as separate // command-line applications with a consistent common interface for handling // compilation database and input files. // // It provides a common subset of command-line options, common algorithm // for locating a compilation database and source files, and help messages // for the basic command-line interface. // // It creates a CompilationDatabase and reads common command-line options. // // This class uses the Clang Tooling infrastructure, see // http://clang.llvm.org/docs/HowToSetupToolingForLLVM.html // for details on setting it up with LLVM source tree. // //===----------------------------------------------------------------------===// #include "llvm/Support/CommandLine.h" #include "clang/Tooling/ArgumentsAdjusters.h" #include "clang/Tooling/CommonOptionsParser.h" #include "clang/Tooling/Tooling.h" using namespace clang::tooling; using namespace llvm; const char *const CommonOptionsParser::HelpMessage = "\n" "-p <build-path> is used to read a compile command database.\n" "\n" "\tFor example, it can be a CMake build directory in which a file named\n" "\tcompile_commands.json exists (use -DCMAKE_EXPORT_COMPILE_COMMANDS=ON\n" "\tCMake option to get this output). When no build path is specified,\n" "\ta search for compile_commands.json will be attempted through all\n" "\tparent paths of the first input file . See:\n" "\thttp://clang.llvm.org/docs/HowToSetupToolingForLLVM.html for an\n" "\texample of setting up Clang Tooling on a source tree.\n" "\n" "<source0> ... specify the paths of source files. These paths are\n" "\tlooked up in the compile command database. If the path of a file is\n" "\tabsolute, it needs to point into CMake's source tree. If the path is\n" "\trelative, the current working directory needs to be in the CMake\n" "\tsource tree and the file must be in a subdirectory of the current\n" "\tworking directory. \"./\" prefixes in the relative files will be\n" "\tautomatically removed, but the rest of a relative path must be a\n" "\tsuffix of a path in the compile command database.\n" "\n"; namespace { class ArgumentsAdjustingCompilations : public CompilationDatabase { public: ArgumentsAdjustingCompilations( std::unique_ptr<CompilationDatabase> Compilations) : Compilations(std::move(Compilations)) {} void appendArgumentsAdjuster(ArgumentsAdjuster Adjuster) { Adjusters.push_back(Adjuster); } std::vector<CompileCommand> getCompileCommands(StringRef FilePath) const override { return adjustCommands(Compilations->getCompileCommands(FilePath)); } std::vector<std::string> getAllFiles() const override { return Compilations->getAllFiles(); } std::vector<CompileCommand> getAllCompileCommands() const override { return adjustCommands(Compilations->getAllCompileCommands()); } private: std::unique_ptr<CompilationDatabase> Compilations; std::vector<ArgumentsAdjuster> Adjusters; std::vector<CompileCommand> adjustCommands(std::vector<CompileCommand> Commands) const { for (CompileCommand &Command : Commands) for (const auto &Adjuster : Adjusters) Command.CommandLine = Adjuster(Command.CommandLine, Command.Filename); return Commands; } }; } // namespace CommonOptionsParser::CommonOptionsParser( int &argc, const char **argv, cl::OptionCategory &Category, llvm::cl::NumOccurrencesFlag OccurrencesFlag, const char *Overview) { static cl::opt<bool> Help("h", cl::desc("Alias for -help"), cl::Hidden); static cl::opt<std::string> BuildPath("p", cl::desc("Build path"), cl::Optional, cl::cat(Category)); static cl::list<std::string> SourcePaths( cl::Positional, cl::desc("<source0> [... <sourceN>]"), OccurrencesFlag, cl::cat(Category)); static cl::list<std::string> ArgsAfter( "extra-arg", cl::desc("Additional argument to append to the compiler command line"), cl::cat(Category)); static cl::list<std::string> ArgsBefore( "extra-arg-before", cl::desc("Additional argument to prepend to the compiler command line"), cl::cat(Category)); cl::HideUnrelatedOptions(Category); Compilations.reset(FixedCompilationDatabase::loadFromCommandLine(argc, argv)); cl::ParseCommandLineOptions(argc, argv, Overview); SourcePathList = SourcePaths; if ((OccurrencesFlag == cl::ZeroOrMore || OccurrencesFlag == cl::Optional) && SourcePathList.empty()) return; if (!Compilations) { std::string ErrorMessage; if (!BuildPath.empty()) { Compilations = CompilationDatabase::autoDetectFromDirectory(BuildPath, ErrorMessage); } else { Compilations = CompilationDatabase::autoDetectFromSource(SourcePaths[0], ErrorMessage); } if (!Compilations) llvm::report_fatal_error(ErrorMessage); } auto AdjustingCompilations = llvm::make_unique<ArgumentsAdjustingCompilations>( std::move(Compilations)); AdjustingCompilations->appendArgumentsAdjuster( getInsertArgumentAdjuster(ArgsBefore, ArgumentInsertPosition::BEGIN)); AdjustingCompilations->appendArgumentsAdjuster( getInsertArgumentAdjuster(ArgsAfter, ArgumentInsertPosition::END)); Compilations = std::move(AdjustingCompilations); } <commit_msg>Add fall-back mode for clang tools.<commit_after>//===--- CommonOptionsParser.cpp - common options for clang tools ---------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file implements the CommonOptionsParser class used to parse common // command-line options for clang tools, so that they can be run as separate // command-line applications with a consistent common interface for handling // compilation database and input files. // // It provides a common subset of command-line options, common algorithm // for locating a compilation database and source files, and help messages // for the basic command-line interface. // // It creates a CompilationDatabase and reads common command-line options. // // This class uses the Clang Tooling infrastructure, see // http://clang.llvm.org/docs/HowToSetupToolingForLLVM.html // for details on setting it up with LLVM source tree. // //===----------------------------------------------------------------------===// #include "llvm/Support/CommandLine.h" #include "clang/Tooling/ArgumentsAdjusters.h" #include "clang/Tooling/CommonOptionsParser.h" #include "clang/Tooling/Tooling.h" using namespace clang::tooling; using namespace llvm; const char *const CommonOptionsParser::HelpMessage = "\n" "-p <build-path> is used to read a compile command database.\n" "\n" "\tFor example, it can be a CMake build directory in which a file named\n" "\tcompile_commands.json exists (use -DCMAKE_EXPORT_COMPILE_COMMANDS=ON\n" "\tCMake option to get this output). When no build path is specified,\n" "\ta search for compile_commands.json will be attempted through all\n" "\tparent paths of the first input file . See:\n" "\thttp://clang.llvm.org/docs/HowToSetupToolingForLLVM.html for an\n" "\texample of setting up Clang Tooling on a source tree.\n" "\n" "<source0> ... specify the paths of source files. These paths are\n" "\tlooked up in the compile command database. If the path of a file is\n" "\tabsolute, it needs to point into CMake's source tree. If the path is\n" "\trelative, the current working directory needs to be in the CMake\n" "\tsource tree and the file must be in a subdirectory of the current\n" "\tworking directory. \"./\" prefixes in the relative files will be\n" "\tautomatically removed, but the rest of a relative path must be a\n" "\tsuffix of a path in the compile command database.\n" "\n"; namespace { class ArgumentsAdjustingCompilations : public CompilationDatabase { public: ArgumentsAdjustingCompilations( std::unique_ptr<CompilationDatabase> Compilations) : Compilations(std::move(Compilations)) {} void appendArgumentsAdjuster(ArgumentsAdjuster Adjuster) { Adjusters.push_back(Adjuster); } std::vector<CompileCommand> getCompileCommands(StringRef FilePath) const override { return adjustCommands(Compilations->getCompileCommands(FilePath)); } std::vector<std::string> getAllFiles() const override { return Compilations->getAllFiles(); } std::vector<CompileCommand> getAllCompileCommands() const override { return adjustCommands(Compilations->getAllCompileCommands()); } private: std::unique_ptr<CompilationDatabase> Compilations; std::vector<ArgumentsAdjuster> Adjusters; std::vector<CompileCommand> adjustCommands(std::vector<CompileCommand> Commands) const { for (CompileCommand &Command : Commands) for (const auto &Adjuster : Adjusters) Command.CommandLine = Adjuster(Command.CommandLine, Command.Filename); return Commands; } }; } // namespace CommonOptionsParser::CommonOptionsParser( int &argc, const char **argv, cl::OptionCategory &Category, llvm::cl::NumOccurrencesFlag OccurrencesFlag, const char *Overview) { static cl::opt<bool> Help("h", cl::desc("Alias for -help"), cl::Hidden); static cl::opt<std::string> BuildPath("p", cl::desc("Build path"), cl::Optional, cl::cat(Category)); static cl::list<std::string> SourcePaths( cl::Positional, cl::desc("<source0> [... <sourceN>]"), OccurrencesFlag, cl::cat(Category)); static cl::list<std::string> ArgsAfter( "extra-arg", cl::desc("Additional argument to append to the compiler command line"), cl::cat(Category)); static cl::list<std::string> ArgsBefore( "extra-arg-before", cl::desc("Additional argument to prepend to the compiler command line"), cl::cat(Category)); cl::HideUnrelatedOptions(Category); Compilations.reset(FixedCompilationDatabase::loadFromCommandLine(argc, argv)); cl::ParseCommandLineOptions(argc, argv, Overview); SourcePathList = SourcePaths; if ((OccurrencesFlag == cl::ZeroOrMore || OccurrencesFlag == cl::Optional) && SourcePathList.empty()) return; if (!Compilations) { std::string ErrorMessage; if (!BuildPath.empty()) { Compilations = CompilationDatabase::autoDetectFromDirectory(BuildPath, ErrorMessage); } else { Compilations = CompilationDatabase::autoDetectFromSource(SourcePaths[0], ErrorMessage); } if (!Compilations) { llvm::errs() << "Error while trying to load a compilation database:\n" << ErrorMessage << "Running without flags.\n"; Compilations.reset( new FixedCompilationDatabase(".", std::vector<std::string>())); } } auto AdjustingCompilations = llvm::make_unique<ArgumentsAdjustingCompilations>( std::move(Compilations)); AdjustingCompilations->appendArgumentsAdjuster( getInsertArgumentAdjuster(ArgsBefore, ArgumentInsertPosition::BEGIN)); AdjustingCompilations->appendArgumentsAdjuster( getInsertArgumentAdjuster(ArgsAfter, ArgumentInsertPosition::END)); Compilations = std::move(AdjustingCompilations); } <|endoftext|>
<commit_before>#ifndef __LAMBDA_HPP__ #define __LAMBDA_HPP__ #include <type_traits> namespace Lambda { using namespace std; struct Unused { template<typename... _Arguments> Unused(_Arguments&...) {} }; enum True { TRUE = 1 }; enum False { FALSE = 0 }; template<bool const _f> struct Boolean; template <> struct Boolean<true> { typedef True Type; static True constexpr s_Value = TRUE; }; template <> struct Boolean<false> { typedef False Type; static False constexpr s_Value = FALSE; }; template<unsigned int const _i, typename ..._Types> struct FindType { typedef typename FindType<_i - 1, _Types...>::Type Type; }; template<typename _First, typename ..._Others> struct FindType<0, _First, _Others...> { typedef _First Type; }; struct Functor {}; template<typename _Type> struct IsFunctor { typedef typename remove_cv<typename remove_reference<_Type>::type>::type Clean; typedef Boolean<is_base_of<Functor, Clean>::value> BooleanType; static typename BooleanType::Type constexpr s_Value = BooleanType::s_Value; }; template<unsigned int const _i> struct Bind : public Functor { template<typename _First, typename ..._Others> inline typename FindType<_i, _First, _Others...>::Type operator () (_First &&rrFirst, _Others &&...rrOthers) { return Bind<_i - 1>()((_Others&&)rrOthers...); } }; template<> struct Bind<0> : public Functor { template<typename _First, typename ..._Others> inline _First operator () (_First &&rrFirst, _Others &&...rrOthers) { return rrFirst; } }; template<typename _Type, False const _IsFunctor = IsFunctor<_Type>::s_Value> struct Constant : public Functor { _Type m_Value; explicit Constant(_Type &&a_rrValue) : m_Value((_Type&&)a_rrValue) {} template<typename ..._Arguments> inline _Type operator () (_Arguments&&...) { return m_Value; } }; } template<typename _Operand> inline Lambda::Constant<_Operand> _0(_Operand &&rrOperand) { return Lambda::Constant<_Operand>((_Operand&&)rrOperand); } static Lambda::Bind<0> _1; static Lambda::Bind<1> _2; static Lambda::Bind<2> _3; static Lambda::Bind<3> _4; static Lambda::Bind<4> _5; static Lambda::Bind<5> _6; static Lambda::Bind<6> _7; static Lambda::Bind<7> _8; static Lambda::Bind<8> _9; static Lambda::Bind<9> _10; static Lambda::Unused g_Unused = Lambda::Unused(_1, _2, _3, _4, _5, _6, _7, _8, _9, _10); #define LAMBDA_PREFIX_UNARY_FUNCTOR_CLASS(Operator, Name) \ template<typename _Operand, True const _IsFunctor = IsFunctor<_Operand>::s_Value> \ struct Name : \ public UnaryFunctor \ { \ _Operand m_Operand; \ explicit Name(_Operand &&a_rrOperand) \ : \ m_Operand((_Operand&&)a_rrOperand) {} \ template<typename ..._Arguments> \ inline auto operator () (_Arguments &&...rrArguments) -> decltype(Operator(m_Operand((_Arguments&&)rrArguments...))) { \ return Operator(m_Operand((_Arguments&&)rrArguments...)); \ } \ }; #define LAMBDA_POSTFIX_UNARY_FUNCTOR_CLASS(Operator, Name) \ template<typename _Operand, True const _IsFunctor = IsFunctor<_Operand>::s_Value> \ struct Name : \ public UnaryFunctor \ { \ _Operand m_Operand; \ explicit Name(_Operand &&a_rrOperand) \ : \ m_Operand((_Operand&&)a_rrOperand) {} \ template<typename ..._Arguments> \ inline auto operator () (_Arguments &&...rrArguments) -> decltype((m_Operand((_Arguments&&)rrArguments...))Operator) { \ return (m_Operand((_Arguments&&)rrArguments...))Operator; \ } \ }; namespace Lambda { struct UnaryFunctor : public Functor {}; LAMBDA_PREFIX_UNARY_FUNCTOR_CLASS(&, Address) LAMBDA_PREFIX_UNARY_FUNCTOR_CLASS(*, Indirection) LAMBDA_PREFIX_UNARY_FUNCTOR_CLASS(+, UnaryPlus) LAMBDA_PREFIX_UNARY_FUNCTOR_CLASS(-, UnaryMinus) LAMBDA_PREFIX_UNARY_FUNCTOR_CLASS(!, LogicalNot) LAMBDA_PREFIX_UNARY_FUNCTOR_CLASS(~, BitwiseNot) LAMBDA_PREFIX_UNARY_FUNCTOR_CLASS(++, PreIncrement) LAMBDA_PREFIX_UNARY_FUNCTOR_CLASS(--, PreDecrement) LAMBDA_POSTFIX_UNARY_FUNCTOR_CLASS(++, PostIncrement) LAMBDA_POSTFIX_UNARY_FUNCTOR_CLASS(--, PostDecrement) } #define LAMBDA_PREFIX_UNARY_OPERATOR(Operator, Name) \ template<typename _Operand> \ inline Lambda::Name<_Operand> operator Operator (_Operand &&rrOperand) { \ return Lambda::Name<_Operand>((_Operand&&)rrOperand); \ } LAMBDA_PREFIX_UNARY_OPERATOR(&, Address) LAMBDA_PREFIX_UNARY_OPERATOR(*, Indirection) LAMBDA_PREFIX_UNARY_OPERATOR(+, UnaryPlus) LAMBDA_PREFIX_UNARY_OPERATOR(-, UnaryMinus) LAMBDA_PREFIX_UNARY_OPERATOR(!, LogicalNot) LAMBDA_PREFIX_UNARY_OPERATOR(~, BitwiseNot) LAMBDA_PREFIX_UNARY_OPERATOR(++, PreIncrement) LAMBDA_PREFIX_UNARY_OPERATOR(--, PreDecrement) #define LAMBDA_BINARY_FUNCTOR_CLASS(Operator, Name) \ template<typename _Left, typename _Right, \ True const _LeftIsFunctor = IsFunctor<_Left>::s_Value, \ True const _RightIsFunctor = IsFunctor<_Right>::s_Value> \ struct Name : \ public BinaryFunctor \ { \ _Left m_Left; \ _Right m_Right; \ Name(_Left &&a_rrLeft, _Right &&a_rrRight) \ : \ m_Left((_Left&&)a_rrLeft), \ m_Right((_Right&&)a_rrRight) {} \ template<typename ..._Arguments> \ inline auto operator () (_Arguments &&...rrArguments) -> decltype((m_Left((_Arguments&&)rrArguments...)) Operator (m_Right((_Arguments&&)rrArguments...))) { \ return (m_Left((_Arguments&&)rrArguments...)) Operator (m_Right((_Arguments&&)rrArguments...)); \ } \ }; #define LAMBDA_COMMA , namespace Lambda { struct BinaryFunctor : public Functor {}; LAMBDA_BINARY_FUNCTOR_CLASS(+, BinaryPlus) LAMBDA_BINARY_FUNCTOR_CLASS(+=, CompoundPlus) LAMBDA_BINARY_FUNCTOR_CLASS(-, BinaryMinus) LAMBDA_BINARY_FUNCTOR_CLASS(-=, CompoundMinus) LAMBDA_BINARY_FUNCTOR_CLASS(*, Multiply) LAMBDA_BINARY_FUNCTOR_CLASS(*=, CompoundMultiply) LAMBDA_BINARY_FUNCTOR_CLASS(/, Divide) LAMBDA_BINARY_FUNCTOR_CLASS(/=, CompoundDivide) LAMBDA_BINARY_FUNCTOR_CLASS(%, Modulus) LAMBDA_BINARY_FUNCTOR_CLASS(%=, CompoundModulus) LAMBDA_BINARY_FUNCTOR_CLASS(&, BitwiseAnd) LAMBDA_BINARY_FUNCTOR_CLASS(|, BitwiseOr) LAMBDA_BINARY_FUNCTOR_CLASS(^, BitwiseXor) LAMBDA_BINARY_FUNCTOR_CLASS(&=, CompoundAnd) LAMBDA_BINARY_FUNCTOR_CLASS(|=, CompoundOr) LAMBDA_BINARY_FUNCTOR_CLASS(^=, CompoundXor) LAMBDA_BINARY_FUNCTOR_CLASS(&&, LogicalAnd) LAMBDA_BINARY_FUNCTOR_CLASS(||, LogicalOr) LAMBDA_BINARY_FUNCTOR_CLASS(<<, LeftShift) LAMBDA_BINARY_FUNCTOR_CLASS(<<=, CompoundLeftShift) LAMBDA_BINARY_FUNCTOR_CLASS(>>, RightShift) LAMBDA_BINARY_FUNCTOR_CLASS(>>=, CompoundRightShift) LAMBDA_BINARY_FUNCTOR_CLASS(==, Equals) LAMBDA_BINARY_FUNCTOR_CLASS(!=, NotEqual) LAMBDA_BINARY_FUNCTOR_CLASS(<, LessThan) LAMBDA_BINARY_FUNCTOR_CLASS(>, GreaterThan) LAMBDA_BINARY_FUNCTOR_CLASS(<=, LessThanOrEqualTo) LAMBDA_BINARY_FUNCTOR_CLASS(>=, GreaterThanOrEqualTo) LAMBDA_BINARY_FUNCTOR_CLASS(LAMBDA_COMMA, Comma) template<typename _Left, typename _Right, True const _LeftIsFunctor = IsFunctor<_Left>::s_Value, True const _RightIsFunctor = IsFunctor<_Right>::s_Value> struct Subscript : public BinaryFunctor { _Left m_Left; _Right m_Right; Subscript(_Left &&a_rrLeft, _Right &&a_rrRight) : m_Left((_Left&&)a_rrLeft), m_Right((_Right&&)a_rrRight) {} template<typename ..._Arguments> inline auto operator () (_Arguments &&...rrArguments) -> decltype((m_Left((_Arguments&&)rrArguments...))[(m_Right((_Arguments&&)rrArguments...))]) { return (m_Left((_Arguments&&)rrArguments...))[(m_Right((_Arguments&&)rrArguments...))]; } }; } #define LAMBDA_BINARY_OPERATOR(Operator, Name) \ template<typename _Left, typename _Right> \ inline Lambda::Name<_Left, _Right> operator Operator (_Left &&rrLeft, _Right &&rrRight) { \ return Lambda::Name<_Left, _Right>((_Left&&)rrLeft, (_Right&&)rrRight); \ } \ template<typename _Left, typename _Right> \ inline Lambda::Name<Lambda::Constant<_Left>, _Right> operator Operator (_Left &&rrLeft, _Right &&rrRight) { \ return Lambda::Name<Lambda::Constant<_Left>, _Right>(Lambda::Constant<_Left>((_Left&&)rrLeft), (_Right&&)rrRight); \ } \ template<typename _Left, typename _Right> \ inline Lambda::Name<_Left, Lambda::Constant<_Right>> operator Operator (_Left &&rrLeft, _Right &&rrRight) { \ return Lambda::Name<_Left, Lambda::Constant<_Right>>((_Left&&)rrLeft, Lambda::Constant<_Right>((_Right&&)rrRight)); \ } LAMBDA_BINARY_OPERATOR(+, BinaryPlus) LAMBDA_BINARY_OPERATOR(+=, CompoundPlus) LAMBDA_BINARY_OPERATOR(-, BinaryMinus) LAMBDA_BINARY_OPERATOR(-=, CompoundMinus) LAMBDA_BINARY_OPERATOR(*, Multiply) LAMBDA_BINARY_OPERATOR(*=, CompoundMultiply) LAMBDA_BINARY_OPERATOR(/, Divide) LAMBDA_BINARY_OPERATOR(/=, CompoundDivide) LAMBDA_BINARY_OPERATOR(%, Modulus) LAMBDA_BINARY_OPERATOR(%=, CompoundModulus) LAMBDA_BINARY_OPERATOR(&, BitwiseAnd) LAMBDA_BINARY_OPERATOR(|, BitwiseOr) LAMBDA_BINARY_OPERATOR(^, BitwiseXor) LAMBDA_BINARY_OPERATOR(&=, CompoundAnd) LAMBDA_BINARY_OPERATOR(|=, CompoundOr) LAMBDA_BINARY_OPERATOR(^=, CompoundXor) LAMBDA_BINARY_OPERATOR(&&, LogicalAnd) LAMBDA_BINARY_OPERATOR(||, LogicalOr) LAMBDA_BINARY_OPERATOR(<<, LeftShift) LAMBDA_BINARY_OPERATOR(<<=, CompoundLeftShift) LAMBDA_BINARY_OPERATOR(>>, RightShift) LAMBDA_BINARY_OPERATOR(>>=, CompoundRightShift) LAMBDA_BINARY_OPERATOR(==, Equals) LAMBDA_BINARY_OPERATOR(!=, NotEqual) LAMBDA_BINARY_OPERATOR(<, LessThan) LAMBDA_BINARY_OPERATOR(>, GreaterThan) LAMBDA_BINARY_OPERATOR(<=, LessThanOrEqualTo) LAMBDA_BINARY_OPERATOR(>=, GreaterThanOrEqualTo) //LAMBDA_BINARY_OPERATOR(LAMBDA_COMMA, Comma) #endif <commit_msg>Re-enabling comma operator<commit_after>#ifndef __LAMBDA_HPP__ #define __LAMBDA_HPP__ #include <type_traits> namespace Lambda { using namespace std; struct Unused { template<typename... _Arguments> Unused(_Arguments&...) {} }; enum True { TRUE = 1 }; enum False { FALSE = 0 }; template<bool const _f> struct Boolean; template <> struct Boolean<true> { typedef True Type; static True constexpr s_Value = TRUE; }; template <> struct Boolean<false> { typedef False Type; static False constexpr s_Value = FALSE; }; template<unsigned int const _i, typename ..._Types> struct FindType { typedef typename FindType<_i - 1, _Types...>::Type Type; }; template<typename _First, typename ..._Others> struct FindType<0, _First, _Others...> { typedef _First Type; }; struct Functor {}; template<typename _Type> struct IsFunctor { typedef typename remove_cv<typename remove_reference<_Type>::type>::type Clean; typedef Boolean<is_base_of<Functor, Clean>::value> BooleanType; static typename BooleanType::Type constexpr s_Value = BooleanType::s_Value; }; template<unsigned int const _i> struct Bind : public Functor { template<typename _First, typename ..._Others> inline typename FindType<_i, _First, _Others...>::Type operator () (_First &&rrFirst, _Others &&...rrOthers) { return Bind<_i - 1>()((_Others&&)rrOthers...); } }; template<> struct Bind<0> : public Functor { template<typename _First, typename ..._Others> inline _First operator () (_First &&rrFirst, _Others &&...rrOthers) { return rrFirst; } }; template<typename _Type, False const _IsFunctor = IsFunctor<_Type>::s_Value> struct Constant : public Functor { _Type m_Value; explicit Constant(_Type &&a_rrValue) : m_Value((_Type&&)a_rrValue) {} template<typename ..._Arguments> inline _Type operator () (_Arguments&&...) { return m_Value; } }; } template<typename _Operand> inline Lambda::Constant<_Operand> _0(_Operand &&rrOperand) { return Lambda::Constant<_Operand>((_Operand&&)rrOperand); } static Lambda::Bind<0> _1; static Lambda::Bind<1> _2; static Lambda::Bind<2> _3; static Lambda::Bind<3> _4; static Lambda::Bind<4> _5; static Lambda::Bind<5> _6; static Lambda::Bind<6> _7; static Lambda::Bind<7> _8; static Lambda::Bind<8> _9; static Lambda::Bind<9> _10; static Lambda::Unused g_Unused = Lambda::Unused(_1, _2, _3, _4, _5, _6, _7, _8, _9, _10); #define LAMBDA_PREFIX_UNARY_FUNCTOR_CLASS(Operator, Name) \ template<typename _Operand, True const _IsFunctor = IsFunctor<_Operand>::s_Value> \ struct Name : \ public UnaryFunctor \ { \ _Operand m_Operand; \ explicit Name(_Operand &&a_rrOperand) \ : \ m_Operand((_Operand&&)a_rrOperand) {} \ template<typename ..._Arguments> \ inline auto operator () (_Arguments &&...rrArguments) -> decltype(Operator(m_Operand((_Arguments&&)rrArguments...))) { \ return Operator(m_Operand((_Arguments&&)rrArguments...)); \ } \ }; #define LAMBDA_POSTFIX_UNARY_FUNCTOR_CLASS(Operator, Name) \ template<typename _Operand, True const _IsFunctor = IsFunctor<_Operand>::s_Value> \ struct Name : \ public UnaryFunctor \ { \ _Operand m_Operand; \ explicit Name(_Operand &&a_rrOperand) \ : \ m_Operand((_Operand&&)a_rrOperand) {} \ template<typename ..._Arguments> \ inline auto operator () (_Arguments &&...rrArguments) -> decltype((m_Operand((_Arguments&&)rrArguments...))Operator) { \ return (m_Operand((_Arguments&&)rrArguments...))Operator; \ } \ }; namespace Lambda { struct UnaryFunctor : public Functor {}; LAMBDA_PREFIX_UNARY_FUNCTOR_CLASS(&, Address) LAMBDA_PREFIX_UNARY_FUNCTOR_CLASS(*, Indirection) LAMBDA_PREFIX_UNARY_FUNCTOR_CLASS(+, UnaryPlus) LAMBDA_PREFIX_UNARY_FUNCTOR_CLASS(-, UnaryMinus) LAMBDA_PREFIX_UNARY_FUNCTOR_CLASS(!, LogicalNot) LAMBDA_PREFIX_UNARY_FUNCTOR_CLASS(~, BitwiseNot) LAMBDA_PREFIX_UNARY_FUNCTOR_CLASS(++, PreIncrement) LAMBDA_PREFIX_UNARY_FUNCTOR_CLASS(--, PreDecrement) LAMBDA_POSTFIX_UNARY_FUNCTOR_CLASS(++, PostIncrement) LAMBDA_POSTFIX_UNARY_FUNCTOR_CLASS(--, PostDecrement) } #define LAMBDA_PREFIX_UNARY_OPERATOR(Operator, Name) \ template<typename _Operand> \ inline Lambda::Name<_Operand> operator Operator (_Operand &&rrOperand) { \ return Lambda::Name<_Operand>((_Operand&&)rrOperand); \ } LAMBDA_PREFIX_UNARY_OPERATOR(&, Address) LAMBDA_PREFIX_UNARY_OPERATOR(*, Indirection) LAMBDA_PREFIX_UNARY_OPERATOR(+, UnaryPlus) LAMBDA_PREFIX_UNARY_OPERATOR(-, UnaryMinus) LAMBDA_PREFIX_UNARY_OPERATOR(!, LogicalNot) LAMBDA_PREFIX_UNARY_OPERATOR(~, BitwiseNot) LAMBDA_PREFIX_UNARY_OPERATOR(++, PreIncrement) LAMBDA_PREFIX_UNARY_OPERATOR(--, PreDecrement) #define LAMBDA_BINARY_FUNCTOR_CLASS(Operator, Name) \ template<typename _Left, typename _Right, \ True const _LeftIsFunctor = IsFunctor<_Left>::s_Value, \ True const _RightIsFunctor = IsFunctor<_Right>::s_Value> \ struct Name : \ public BinaryFunctor \ { \ _Left m_Left; \ _Right m_Right; \ Name(_Left &&a_rrLeft, _Right &&a_rrRight) \ : \ m_Left((_Left&&)a_rrLeft), \ m_Right((_Right&&)a_rrRight) {} \ template<typename ..._Arguments> \ inline auto operator () (_Arguments &&...rrArguments) -> decltype((m_Left((_Arguments&&)rrArguments...)) Operator (m_Right((_Arguments&&)rrArguments...))) { \ return (m_Left((_Arguments&&)rrArguments...)) Operator (m_Right((_Arguments&&)rrArguments...)); \ } \ }; #define LAMBDA_COMMA , namespace Lambda { struct BinaryFunctor : public Functor {}; LAMBDA_BINARY_FUNCTOR_CLASS(+, BinaryPlus) LAMBDA_BINARY_FUNCTOR_CLASS(+=, CompoundPlus) LAMBDA_BINARY_FUNCTOR_CLASS(-, BinaryMinus) LAMBDA_BINARY_FUNCTOR_CLASS(-=, CompoundMinus) LAMBDA_BINARY_FUNCTOR_CLASS(*, Multiply) LAMBDA_BINARY_FUNCTOR_CLASS(*=, CompoundMultiply) LAMBDA_BINARY_FUNCTOR_CLASS(/, Divide) LAMBDA_BINARY_FUNCTOR_CLASS(/=, CompoundDivide) LAMBDA_BINARY_FUNCTOR_CLASS(%, Modulus) LAMBDA_BINARY_FUNCTOR_CLASS(%=, CompoundModulus) LAMBDA_BINARY_FUNCTOR_CLASS(&, BitwiseAnd) LAMBDA_BINARY_FUNCTOR_CLASS(|, BitwiseOr) LAMBDA_BINARY_FUNCTOR_CLASS(^, BitwiseXor) LAMBDA_BINARY_FUNCTOR_CLASS(&=, CompoundAnd) LAMBDA_BINARY_FUNCTOR_CLASS(|=, CompoundOr) LAMBDA_BINARY_FUNCTOR_CLASS(^=, CompoundXor) LAMBDA_BINARY_FUNCTOR_CLASS(&&, LogicalAnd) LAMBDA_BINARY_FUNCTOR_CLASS(||, LogicalOr) LAMBDA_BINARY_FUNCTOR_CLASS(<<, LeftShift) LAMBDA_BINARY_FUNCTOR_CLASS(<<=, CompoundLeftShift) LAMBDA_BINARY_FUNCTOR_CLASS(>>, RightShift) LAMBDA_BINARY_FUNCTOR_CLASS(>>=, CompoundRightShift) LAMBDA_BINARY_FUNCTOR_CLASS(==, Equals) LAMBDA_BINARY_FUNCTOR_CLASS(!=, NotEqual) LAMBDA_BINARY_FUNCTOR_CLASS(<, LessThan) LAMBDA_BINARY_FUNCTOR_CLASS(>, GreaterThan) LAMBDA_BINARY_FUNCTOR_CLASS(<=, LessThanOrEqualTo) LAMBDA_BINARY_FUNCTOR_CLASS(>=, GreaterThanOrEqualTo) LAMBDA_BINARY_FUNCTOR_CLASS(LAMBDA_COMMA, Comma) template<typename _Left, typename _Right, True const _LeftIsFunctor = IsFunctor<_Left>::s_Value, True const _RightIsFunctor = IsFunctor<_Right>::s_Value> struct Subscript : public BinaryFunctor { _Left m_Left; _Right m_Right; Subscript(_Left &&a_rrLeft, _Right &&a_rrRight) : m_Left((_Left&&)a_rrLeft), m_Right((_Right&&)a_rrRight) {} template<typename ..._Arguments> inline auto operator () (_Arguments &&...rrArguments) -> decltype((m_Left((_Arguments&&)rrArguments...))[(m_Right((_Arguments&&)rrArguments...))]) { return (m_Left((_Arguments&&)rrArguments...))[(m_Right((_Arguments&&)rrArguments...))]; } }; } #define LAMBDA_BINARY_OPERATOR(Operator, Name) \ template<typename _Left, typename _Right> \ inline Lambda::Name<_Left, _Right> operator Operator (_Left &&rrLeft, _Right &&rrRight) { \ return Lambda::Name<_Left, _Right>((_Left&&)rrLeft, (_Right&&)rrRight); \ } \ template<typename _Left, typename _Right> \ inline Lambda::Name<Lambda::Constant<_Left>, _Right> operator Operator (_Left &&rrLeft, _Right &&rrRight) { \ return Lambda::Name<Lambda::Constant<_Left>, _Right>(Lambda::Constant<_Left>((_Left&&)rrLeft), (_Right&&)rrRight); \ } \ template<typename _Left, typename _Right> \ inline Lambda::Name<_Left, Lambda::Constant<_Right>> operator Operator (_Left &&rrLeft, _Right &&rrRight) { \ return Lambda::Name<_Left, Lambda::Constant<_Right>>((_Left&&)rrLeft, Lambda::Constant<_Right>((_Right&&)rrRight)); \ } LAMBDA_BINARY_OPERATOR(+, BinaryPlus) LAMBDA_BINARY_OPERATOR(+=, CompoundPlus) LAMBDA_BINARY_OPERATOR(-, BinaryMinus) LAMBDA_BINARY_OPERATOR(-=, CompoundMinus) LAMBDA_BINARY_OPERATOR(*, Multiply) LAMBDA_BINARY_OPERATOR(*=, CompoundMultiply) LAMBDA_BINARY_OPERATOR(/, Divide) LAMBDA_BINARY_OPERATOR(/=, CompoundDivide) LAMBDA_BINARY_OPERATOR(%, Modulus) LAMBDA_BINARY_OPERATOR(%=, CompoundModulus) LAMBDA_BINARY_OPERATOR(&, BitwiseAnd) LAMBDA_BINARY_OPERATOR(|, BitwiseOr) LAMBDA_BINARY_OPERATOR(^, BitwiseXor) LAMBDA_BINARY_OPERATOR(&=, CompoundAnd) LAMBDA_BINARY_OPERATOR(|=, CompoundOr) LAMBDA_BINARY_OPERATOR(^=, CompoundXor) LAMBDA_BINARY_OPERATOR(&&, LogicalAnd) LAMBDA_BINARY_OPERATOR(||, LogicalOr) LAMBDA_BINARY_OPERATOR(<<, LeftShift) LAMBDA_BINARY_OPERATOR(<<=, CompoundLeftShift) LAMBDA_BINARY_OPERATOR(>>, RightShift) LAMBDA_BINARY_OPERATOR(>>=, CompoundRightShift) LAMBDA_BINARY_OPERATOR(==, Equals) LAMBDA_BINARY_OPERATOR(!=, NotEqual) LAMBDA_BINARY_OPERATOR(<, LessThan) LAMBDA_BINARY_OPERATOR(>, GreaterThan) LAMBDA_BINARY_OPERATOR(<=, LessThanOrEqualTo) LAMBDA_BINARY_OPERATOR(>=, GreaterThanOrEqualTo) LAMBDA_BINARY_OPERATOR(LAMBDA_COMMA, Comma) #endif <|endoftext|>
<commit_before>/******************************************************************************* * thrill/common/fast_string.hpp * * (Hopefully) fast static-length string implementation. * * Part of Project Thrill. * * Copyright (C) 2015 Alexander Noe <[email protected]> * * This file has no license. Only Chuck Norris can compile it. ******************************************************************************/ #pragma once #ifndef THRILL_COMMON_FAST_STRING_HEADER #define THRILL_COMMON_FAST_STRING_HEADER #include <thrill/common/logger.hpp> #include <thrill/data/serialization.hpp> #if __GNUC__ && !__clang__ #include <bits/functional_hash.h> #endif #include <algorithm> #include <string> namespace thrill { namespace common { /** * FastString is a fast implementation of a string, which is basically only * a char pointer and a length. The FastString is defined by the char array given * by those parameters. A copy assignment or copy constructor actually allocates * memory for the data. This allows both non-allocating quick references and persistent * storage of strings. */ class FastString { public: /** * Default constructor for a FastString. * Doesn't do anything. */ FastString() : size_(0) { } /** * Copy constructor for a new FastString. Actually allocates memory. * \param input Input FastString * \return Copy of input */ FastString(const FastString& input) { char* begin = new char[input.size_]; std::copy(input.data_, input.data_ + input.size_, begin); data_ = begin; size_ = input.size_; owns_data_ = true; } /** * Move constructor for a new FastString. Steals data ownership. */ FastString(FastString&& other) : FastString(other.data_, other.size_, other.owns_data_) { other.owns_data_ = false; } /** * Destructor for a FastString. If it holds data, this data gets freed. */ ~FastString() { if (owns_data_) { delete[] (data_); } } /** * Creates a new reference FastString, given a const char* and the size of the FastString. * \param data Pointer to start of data * \param size Size of data in bytes. * \return New FastString object. */ static FastString Ref(const char* data, size_t size) { return FastString(data, size, false); } /** * Creates a new reference FastString, given a const iterator to a std::string * and the size of the FastString. * \param data Pointer to start of data * \param size Size of data in bytes. * \return New FastString object. */ static FastString Ref(const std::string::const_iterator& data, size_t size) { return FastString(&(*data), size, false); } /** * Creates a new FastString and takes data ownership, * given a const char* and the size of the FastString. * \param data Pointer to start of data * \param size Size of data in bytes. * \return New FastString object. */ static FastString Take(const char* data, size_t size) { return FastString(data, size, true); } /** * Creates a new FastString and copies it's data. * \param data Pointer to start of data * \param size Size of data in bytes. * \return New FastString object. */ static FastString Copy(const char* data, size_t size) { char* mem = new char[size]; std::copy(data, data + size, mem); return FastString(mem, size, true); } /** * Creates a new FastString and copies it's data. * \param input Input string, which the new FastString is a copy of * \return New FastString object. */ static FastString Copy(const std::string& input) { return Copy(input.c_str(), input.size()); } /** * Returns a pointer to the start of the data. */ const char * Data() const { return data_; } /** * Returns the size of this FastString */ size_t Size() const { return size_; } /** * Copy assignment operator. * \param other copied FastString * \return reference to this FastString */ FastString& operator = (const FastString& other) { if (owns_data_) delete[] (data_); char* mem = new char[other.size_]; std::copy(other.data_, other.data_ + other.size_, mem); data_ = mem; size_ = other.size_; owns_data_ = true; return *this; } /** * Move assignment operator * \param other moved FastString * \return reference to this FastString */ FastString& operator = (FastString&& other) { if (owns_data_) delete[] (data_); data_ = std::move(other.data_); size_ = other.Size(); owns_data_ = other.owns_data_; other.owns_data_ = false; return *this; } /** * Equality operator to compare a FastString with an std::string * \param other Comparison string * \return true, if data is equal */ bool operator == (const std::string& other) const { return size_ == other.size() && std::equal(data_, data_ + size_, other.c_str()); } /** * Inequality operator to compare a FastString with an std::string * \param other Comparison string * \return false, if data is equal */ bool operator != (const std::string& other) const { return !(operator == (other)); } /** * Equality operator to compare a FastString with another FastString * \param other Comparison FastString * \return true, if data is equal */ bool operator == (const FastString& other) const { return size_ == other.size_ && std::equal(data_, data_ + size_, other.data_); } /** * Inequality operator to compare a FastString with another FastString * \param other Comparison FastString * \return false, if data is equal */ bool operator != (const FastString& other) const { return !(operator == (other)); } /** * Make FastString ostreamable * \param os ostream * \param fs FastString to stream */ friend std::ostream& operator << (std::ostream& os, const FastString& fs) { return os.write(fs.Data(), fs.Size()); } /** * Returns the data of this FastString as an std::string * \return This FastString as an std::string */ std::string ToString() const { return std::string(data_, size_); } protected: /** * Internal constructor, which creates a new FastString and sets parameters * \param data Pointer to data * \param size Size of data in bytes * \param owns_data True, if this FastString has ownership of data */ FastString(const char* data, size_t size, bool owns_data) : data_(data), size_(size), owns_data_(owns_data) { } //! Pointer to data const char* data_ = 0; //! Size of data size_t size_; //! True, if this FastString has ownership of data bool owns_data_ = false; }; } // namespace common namespace data { template <typename Archive> struct Serialization<Archive, common::FastString> { static void Serialize(const common::FastString& fs, Archive& ar) { ar.PutVarint(fs.Size()).Append(fs.Data(), fs.Size()); } static common::FastString Deserialize(Archive& ar) { uint64_t size = ar.GetVarint(); char* outdata = new char[size]; ar.Read(outdata, size); return common::FastString::Take(outdata, size); } static const bool is_fixed_size = false; static const size_t fixed_size = 0; }; } // namespace data } // namespace thrill namespace std { template <> struct hash<thrill::common::FastString> { size_t operator () (const thrill::common::FastString& fs) const { #if __GNUC__ && !__clang__ return std::_Hash_impl::hash(fs.Data(), fs.Size()); #else // Only gcc has bits/functional_hash.h, using other hash function. // taken from: http://www.cse.yorku.ca/~oz/hash.html unsigned int hash = 5381; for (size_t ctr = 0; ctr < fs.Size(); ctr++) { // hash * 33 + c hash = ((hash << 5) + hash) + *(fs.Data() + ctr); } return hash; #endif } }; } // namespace std #endif // !THRILL_COMMON_FAST_STRING_HEADER /******************************************************************************/ <commit_msg>Fixing FastString: always use the low-level hash function.<commit_after>/******************************************************************************* * thrill/common/fast_string.hpp * * (Hopefully) fast static-length string implementation. * * Part of Project Thrill. * * Copyright (C) 2015 Alexander Noe <[email protected]> * * This file has no license. Only Chuck Norris can compile it. ******************************************************************************/ #pragma once #ifndef THRILL_COMMON_FAST_STRING_HEADER #define THRILL_COMMON_FAST_STRING_HEADER #include <thrill/common/logger.hpp> #include <thrill/data/serialization.hpp> #include <algorithm> #include <string> namespace thrill { namespace common { /** * FastString is a fast implementation of a string, which is basically only * a char pointer and a length. The FastString is defined by the char array given * by those parameters. A copy assignment or copy constructor actually allocates * memory for the data. This allows both non-allocating quick references and persistent * storage of strings. */ class FastString { public: using iterator = const char*; /** * Default constructor for a FastString. * Doesn't do anything. */ FastString() : size_(0) { } /** * Copy constructor for a new FastString. Actually allocates memory. * \param input Input FastString * \return Copy of input */ FastString(const FastString& input) { char* begin = new char[input.size_]; std::copy(input.data_, input.data_ + input.size_, begin); data_ = begin; size_ = input.size_; owns_data_ = true; } /** * Move constructor for a new FastString. Steals data ownership. */ FastString(FastString&& other) : FastString(other.data_, other.size_, other.owns_data_) { other.owns_data_ = false; } /** * Destructor for a FastString. If it holds data, this data gets freed. */ ~FastString() { if (owns_data_) { delete[] (data_); } } /** * Creates a new reference FastString, given a const char* and the size of the FastString. * \param data Pointer to start of data * \param size Size of data in bytes. * \return New FastString object. */ static FastString Ref(const char* data, size_t size) { return FastString(data, size, false); } /** * Creates a new reference FastString, given a const iterator to a std::string * and the size of the FastString. * \param data Pointer to start of data * \param size Size of data in bytes. * \return New FastString object. */ static FastString Ref(const std::string::const_iterator& data, size_t size) { return FastString(&(*data), size, false); } /** * Creates a new FastString and takes data ownership, * given a const char* and the size of the FastString. * \param data Pointer to start of data * \param size Size of data in bytes. * \return New FastString object. */ static FastString Take(const char* data, size_t size) { return FastString(data, size, true); } /** * Creates a new FastString and copies it's data. * \param data Pointer to start of data * \param size Size of data in bytes. * \return New FastString object. */ static FastString Copy(const char* data, size_t size) { char* mem = new char[size]; std::copy(data, data + size, mem); return FastString(mem, size, true); } /** * Creates a new FastString and copies it's data. * \param input Input string, which the new FastString is a copy of * \return New FastString object. */ static FastString Copy(const std::string& input) { return Copy(input.c_str(), input.size()); } //! Returns a pointer to the start of the data. const char * Data() const { return data_; } //! Returns a pointer to the beginning of the data. iterator begin() const { return data_; } //! Returns a pointer beyond the end of the data. iterator end() const { return data_ + size_; } //! Returns the size of this FastString size_t Size() const { return size_; } /** * Copy assignment operator. * \param other copied FastString * \return reference to this FastString */ FastString& operator = (const FastString& other) { if (owns_data_) delete[] (data_); char* mem = new char[other.size_]; std::copy(other.data_, other.data_ + other.size_, mem); data_ = mem; size_ = other.size_; owns_data_ = true; return *this; } /** * Move assignment operator * \param other moved FastString * \return reference to this FastString */ FastString& operator = (FastString&& other) { if (owns_data_) delete[] (data_); data_ = std::move(other.data_); size_ = other.Size(); owns_data_ = other.owns_data_; other.owns_data_ = false; return *this; } /** * Equality operator to compare a FastString with an std::string * \param other Comparison string * \return true, if data is equal */ bool operator == (const std::string& other) const { return size_ == other.size() && std::equal(data_, data_ + size_, other.c_str()); } /** * Inequality operator to compare a FastString with an std::string * \param other Comparison string * \return false, if data is equal */ bool operator != (const std::string& other) const { return !(operator == (other)); } /** * Equality operator to compare a FastString with another FastString * \param other Comparison FastString * \return true, if data is equal */ bool operator == (const FastString& other) const { return size_ == other.size_ && std::equal(data_, data_ + size_, other.data_); } /** * Inequality operator to compare a FastString with another FastString * \param other Comparison FastString * \return false, if data is equal */ bool operator != (const FastString& other) const { return !(operator == (other)); } /** * Make FastString ostreamable * \param os ostream * \param fs FastString to stream */ friend std::ostream& operator << (std::ostream& os, const FastString& fs) { return os.write(fs.Data(), fs.Size()); } /** * Returns the data of this FastString as an std::string * \return This FastString as an std::string */ std::string ToString() const { return std::string(data_, size_); } protected: /** * Internal constructor, which creates a new FastString and sets parameters * \param data Pointer to data * \param size Size of data in bytes * \param owns_data True, if this FastString has ownership of data */ FastString(const char* data, size_t size, bool owns_data) : data_(data), size_(size), owns_data_(owns_data) { } //! Pointer to data const char* data_ = 0; //! Size of data size_t size_; //! True, if this FastString has ownership of data bool owns_data_ = false; }; } // namespace common namespace data { template <typename Archive> struct Serialization<Archive, common::FastString> { static void Serialize(const common::FastString& fs, Archive& ar) { ar.PutVarint(fs.Size()).Append(fs.Data(), fs.Size()); } static common::FastString Deserialize(Archive& ar) { uint64_t size = ar.GetVarint(); char* outdata = new char[size]; ar.Read(outdata, size); return common::FastString::Take(outdata, size); } static const bool is_fixed_size = false; static const size_t fixed_size = 0; }; } // namespace data } // namespace thrill namespace std { template <> struct hash<thrill::common::FastString> { size_t operator () (const thrill::common::FastString& fs) const { // simple string hash taken from: http://www.cse.yorku.ca/~oz/hash.html size_t hash = 5381; for (const char* ctr = fs.begin(); ctr != fs.end(); ++ctr) { // hash * 33 + c hash = ((hash << 5) + hash) + *ctr; } return hash; } }; } // namespace std #endif // !THRILL_COMMON_FAST_STRING_HEADER /******************************************************************************/ <|endoftext|>
<commit_before>#include <iostream> #include <cstdlib> #include <stdio.h> #include "list.h" using namespace std; /* A linked list node */ struct node { int data; struct node *next; }; //typedef struct node node; node *start =NULL; /* ************************************************************ Function Name:populate Return type:void Arguments :void Description:It fills the list with values provided ***************************************************************/ void list:: populate() { int val; node *p; node *q; cout<<"Enter the Elements\n"; p=NULL; while (size--) { cin>>val; if (p == NULL) { p=(struct node *) malloc(sizeof(struct node)); p->data = val; p->next = NULL; start=p; } else { q=(struct node *) malloc(sizeof(struct node)); q->data = val; q->next = NULL; p->next = q; p=p->next; } } } /* ************************************************************ Function Name:purging Return type:void Arguments :void Description:compares the element with next element(s) and deletes if same ***************************************************************/ void list::purging() { node *x=start; node *y=start; while(x->next!=NULL){ y=x->next; while(y->next!=NULL) { if (x->data==y->data) { cout<< "inside if\n"; x->next=y->next; y->next=NULL; free(y); y=x->next; } else{ y=y->next; } } if(y->next==NULL){ if (x->data==y->data) //if same then data { cout<< "inside if\n"; x->next=NULL; free(y); return; } } x=x->next; } } /* ************************************************************ Function Name:display Return type:void Arguments :void Description:Displays the values present in list at any instance ***************************************************************/ void list::display() { node *start1=start; if(start1 == NULL) cout<<"\nNo data\n"; else { cout<<"\nThe elements are: "; while(start1!=NULL) { printf(" %d ",start1->data); start1=start1->next; } cout<<"\n"; } } void list::del(int i){ } <commit_msg>Update linkedlist.cpp<commit_after>#include <iostream> #include <cstdlib> #include <stdio.h> #include "list.h" using namespace std; /* A linked list node */ struct node { int data; struct node *next; }; //typedef struct node node; node *start =NULL; /* ************************************************************ Function Name:populate Return type:void Arguments :void Description:It fills the list with values provided ***************************************************************/ void list:: populate() { int val; node *p; node *q; cout<<"Enter the Elements\n"; p=NULL; while (size--) { cin>>val; if (p == NULL) { p=(struct node *) malloc(sizeof(struct node)); p->data = val; p->next = NULL; start=p; } else { q=(struct node *) malloc(sizeof(struct node)); q->data = val; q->next = NULL; p->next = q; p=p->next; } } } /* ************************************************************ Function Name:purging Return type:void Arguments :void Description:compares the element with next element(s) and deletes if same ***************************************************************/ void list::purging() { //13 5 9 5 -13 2 3 -9 13 -9 node *x=start; node *y=start; node *z=start; if(x->next!=NULL) { cout<<"\ninside1: \n"; z=x->next; while (x->next!=NULL) { //cout<<"\ninside while1: \n"; cout<<"\nx: "<<x->data<<" y: "<< y->data <<" z: "<< z->data; if (x->data==z->data) { cout<<"\ndata same\n"; if(z->next!=NULL) //MODIFIACTION 2 { y->next=z->next; cout<<"\ndata deleting is: \n"<<z->data<<endl; z->next=NULL; free(z); z=y->next; } else { cout<<"\n**data deleting is: \n"<<z->data<<endl; y->next=NULL; z->next=NULL; free(z); x=x->next; y=x; if (y->next!=NULL) z=y->next; } } else if(z->next!=NULL) { z=z->next; y=y->next; cout<<"\n**"<<endl; // cout<<"\nz: "<< z->data <<" y: "<< y->data; } else { cout<<"\n***\n"<<endl; x=x->next; y=x; z=x->next; } } /*if(y->next==NULL){ if (x->data==y->data) //if same then data { cout<< "inside if\n"; x->next=NULL; free(y); return; } x=x->next; } */ } } /* ************************************************************ Function Name:display Return type:void Arguments :void Description:Displays the values present in list at any instance ***************************************************************/ void list::display() { node *start1=start; if(start1 == NULL) cout<<"\nNo data\n"; else { cout<<"\nThe elements are: "; while(start1!=NULL) { printf(" %d ",start1->data); start1=start1->next; } cout<<"\n"; } } void list::del(int i){ } <|endoftext|>
<commit_before>/* BEGIN_COMMON_COPYRIGHT_HEADER * (c)LGPL2+ * * LxQt - a lightweight, Qt based, desktop toolset * http://razor-qt.org, http://lxde.org/ * * Copyright: 2010-2011 LxQt team * Authors: * Petr Vanek <[email protected]> * Hong Jen Yee (PCMan) <[email protected]> * * This program or library is free software; you can redistribute it * and/or modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * You should have received a copy of the GNU Lesser General * Public License along with this library; if not, write to the * Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, * Boston, MA 02110-1301 USA * * END_COMMON_COPYRIGHT_HEADER */ #include "lxqtmodman.h" #include <LXQt/Settings> #include <XdgAutoStart> #include <XdgDirs> #include <unistd.h> #include <QDebug> #include <QCoreApplication> #include <QMessageBox> #include <QSystemTrayIcon> #include <QFileInfo> #include <QFileSystemWatcher> #include <QDateTime> #include "wmselectdialog.h" #include "windowmanager.h" #include <wordexp.h> #include <KF5/KWindowSystem/KWindowSystem> #include <KF5/KWindowSystem/netwm.h> #include <QX11Info> #define MAX_CRASHES_PER_APP 5 using namespace LxQt; /** * @brief the constructor, needs a valid modules.conf */ LxQtModuleManager::LxQtModuleManager(const QString & windowManager, QObject* parent) : QObject(parent), mWindowManager(windowManager), mWmProcess(new QProcess(this)), mThemeWatcher(new QFileSystemWatcher(this)), mWmStarted(false), mTrayStarted(false), mWaitLoop(NULL) { connect(mThemeWatcher, SIGNAL(directoryChanged(QString)), SLOT(themeFolderChanged(QString))); connect(LxQt::Settings::globalSettings(), SIGNAL(lxqtThemeChanged()), SLOT(themeChanged())); qApp->installNativeEventFilter(this); } void LxQtModuleManager::startup(LxQt::Settings& s) { // The lxqt-confupdate can update the settings of the WM, so run it first. startConfUpdate(); // Start window manager startWm(&s); startAutostartApps(); QStringList paths; paths << XdgDirs::dataHome(false); paths << XdgDirs::dataDirs(); foreach(QString path, paths) { QFileInfo fi(QString("%1/lxqt/themes").arg(path)); if (fi.exists()) mThemeWatcher->addPath(fi.absoluteFilePath()); } themeChanged(); } void LxQtModuleManager::startAutostartApps() { // XDG autostart XdgDesktopFileList fileList = XdgAutoStart::desktopFileList(); QList<XdgDesktopFile*> trayApps; for (XdgDesktopFileList::iterator i = fileList.begin(); i != fileList.end(); ++i) { if (i->value("X-LXQt-Need-Tray", false).toBool()) trayApps.append(&(*i)); else { startProcess(*i); qDebug() << "start" << i->fileName(); } } if (!trayApps.isEmpty()) { mTrayStarted = QSystemTrayIcon::isSystemTrayAvailable(); if(!mTrayStarted) { QEventLoop waitLoop; mWaitLoop = &waitLoop; // add a timeout to avoid infinite blocking if a WM fail to execute. QTimer::singleShot(60 * 1000, &waitLoop, SLOT(quit())); waitLoop.exec(); mWaitLoop = NULL; } foreach (XdgDesktopFile* f, trayApps) { qDebug() << "start tray app" << f->fileName(); startProcess(*f); } } } void LxQtModuleManager::themeFolderChanged(const QString& /*path*/) { QString newTheme; if (!QFileInfo(mCurrentThemePath).exists()) { const QList<LxQtTheme> &allThemes = lxqtTheme.allThemes(); if (!allThemes.isEmpty()) newTheme = allThemes[0].name(); else return; } else newTheme = lxqtTheme.currentTheme().name(); LxQt::Settings settings("lxqt"); if (newTheme == settings.value("theme")) { // force the same theme to be updated settings.setValue("__theme_updated__", QDateTime::currentMSecsSinceEpoch()); } else settings.setValue("theme", newTheme); sync(); } void LxQtModuleManager::themeChanged() { if (!mCurrentThemePath.isEmpty()) mThemeWatcher->removePath(mCurrentThemePath); if (lxqtTheme.currentTheme().isValid()) { mCurrentThemePath = lxqtTheme.currentTheme().path(); mThemeWatcher->addPath(mCurrentThemePath); } } void LxQtModuleManager::startWm(LxQt::Settings *settings) { // If the WM is active do not run WM. NETRootInfo info(QX11Info::connection(), NET::Supported); if (info.isSupported(NET::SupportingWMCheck)) return; if (mWindowManager.isEmpty()) { mWindowManager = settings->value("window_manager").toString(); } // If previuos WM was removed, we show dialog. if (mWindowManager.isEmpty() || ! findProgram(mWindowManager.split(' ')[0])) { mWindowManager = showWmSelectDialog(); settings->setValue("window_manager", mWindowManager); settings->sync(); } mWmProcess->start(mWindowManager); // other autostart apps will be handled after the WM becomes available // Wait until the WM loads QEventLoop waitLoop; mWaitLoop = &waitLoop; // add a timeout to avoid infinite blocking if a WM fail to execute. QTimer::singleShot(30 * 1000, &waitLoop, SLOT(quit())); waitLoop.exec(); mWaitLoop = NULL; // FIXME: blocking is a bad idea. We need to start as many apps as possible and // only wait for the start of WM when it's absolutely needed. // Maybe we can add a X-Wait-WM=true key in the desktop entry file? } void LxQtModuleManager::startProcess(const XdgDesktopFile& file) { if (!file.value("X-LXQt-Module", false).toBool()) { file.startDetached(); return; } QStringList args = file.expandExecString(); if (args.isEmpty()) { qWarning() << "Wrong desktop file" << file.fileName(); return; } LxQtModule* proc = new LxQtModule(file, this); connect(proc, SIGNAL(moduleStateChanged(QString,bool)), this, SIGNAL(moduleStateChanged(QString,bool))); proc->start(); QString name = QFileInfo(file.fileName()).fileName(); mNameMap[name] = proc; connect(proc, SIGNAL(finished(int, QProcess::ExitStatus)), this, SLOT(restartModules(int, QProcess::ExitStatus))); } void LxQtModuleManager::startProcess(const QString& name) { if (!mNameMap.contains(name)) { foreach (const XdgDesktopFile& file, XdgAutoStart::desktopFileList(false)) { if (QFileInfo(file.fileName()).fileName() == name) { startProcess(file); return; } } } } void LxQtModuleManager::stopProcess(const QString& name) { if (mNameMap.contains(name)) mNameMap[name]->terminate(); } QStringList LxQtModuleManager::listModules() const { return QStringList(mNameMap.keys()); } void LxQtModuleManager::startConfUpdate() { XdgDesktopFile desktop(XdgDesktopFile::ApplicationType, ":lxqt-confupdate", "lxqt-confupdate --watch"); desktop.setValue("Name", "LXQt config updater"); desktop.setValue("X-LXQt-Module", true); startProcess(desktop); } void LxQtModuleManager::restartModules(int exitCode, QProcess::ExitStatus exitStatus) { LxQtModule* proc = qobject_cast<LxQtModule*>(sender()); Q_ASSERT(proc); if (!proc->isTerminating()) { QString procName = proc->file.name(); switch (exitStatus) { case QProcess::NormalExit: qDebug() << "Process" << procName << "(" << proc << ") exited correctly."; break; case QProcess::CrashExit: { qDebug() << "Process" << procName << "(" << proc << ") has to be restarted"; time_t now = time(NULL); mCrashReport[proc].prepend(now); while (now - mCrashReport[proc].back() > 60) mCrashReport[proc].pop_back(); if (mCrashReport[proc].length() >= MAX_CRASHES_PER_APP) { QMessageBox::warning(0, tr("Crash Report"), tr("<b>%1</b> crashed too many times. Its autorestart has been disabled until next login.").arg(procName)); } else { proc->start(); return; } break; } } } mNameMap.remove(proc->fileName); proc->deleteLater(); } LxQtModuleManager::~LxQtModuleManager() { qApp->removeNativeEventFilter(this); qDeleteAll(mNameMap); delete mWmProcess; } /** * @brief this logs us out by terminating our session **/ void LxQtModuleManager::logout() { // modules ModulesMapIterator i(mNameMap); while (i.hasNext()) { i.next(); qDebug() << "Module logout" << i.key(); LxQtModule* p = i.value(); p->terminate(); } i.toFront(); while (i.hasNext()) { i.next(); LxQtModule* p = i.value(); if (p->state() != QProcess::NotRunning && !p->waitForFinished()) { qWarning() << QString("Module '%1' won't terminate ... killing.").arg(i.key()); p->kill(); } } mWmProcess->terminate(); if (mWmProcess->state() != QProcess::NotRunning && !mWmProcess->waitForFinished()) { qWarning() << QString("Window Manager won't terminate ... killing."); mWmProcess->kill(); } QCoreApplication::exit(0); } QString LxQtModuleManager::showWmSelectDialog() { WindowManagerList availableWM = getWindowManagerList(true); if (availableWM.count() == 1) return availableWM.at(0).command; WmSelectDialog dlg(availableWM); dlg.exec(); return dlg.windowManager(); } void LxQtModuleManager::resetCrashReport() { mCrashReport.clear(); } bool LxQtModuleManager::nativeEventFilter(const QByteArray & eventType, void * message, long * result) { if (eventType != "xcb_generic_event_t") // We only want to handle XCB events return false; if(!mWmStarted && mWaitLoop) { NETRootInfo info(QX11Info::connection(), NET::Supported); NET::Properties prop = info.event(reinterpret_cast<xcb_generic_event_t*>(message)); if (prop & NET::SupportingWMCheck) { qDebug() << "Window Manager started"; mWmStarted = true; if (mWaitLoop->isRunning()) mWaitLoop->exit(); } } if (!mTrayStarted && QSystemTrayIcon::isSystemTrayAvailable() && mWaitLoop) { qDebug() << "System Tray started"; mTrayStarted = true; if (mWaitLoop->isRunning()) mWaitLoop->exit(); } return false; } void lxqt_setenv(const char *env, const QByteArray &value) { wordexp_t p; wordexp(value, &p, 0); if (p.we_wordc == 1) { qDebug() << "Environment variable" << env << "=" << p.we_wordv[0]; qputenv(env, p.we_wordv[0]); } else { qWarning() << "Error expanding environment variable" << env << "=" << value; qputenv(env, value); } wordfree(&p); } void lxqt_setenv_prepend(const char *env, const QByteArray &value, const QByteArray &separator) { QByteArray orig(qgetenv(env)); orig = orig.prepend(separator); orig = orig.prepend(value); qDebug() << "Setting special" << env << " variable:" << orig; lxqt_setenv(env, orig); } LxQtModule::LxQtModule(const XdgDesktopFile& file, QObject* parent) : QProcess(parent), file(file), fileName(QFileInfo(file.fileName()).fileName()), mIsTerminating(false) { connect(this, SIGNAL(stateChanged(QProcess::ProcessState)), SLOT(updateState(QProcess::ProcessState))); } void LxQtModule::start() { mIsTerminating = false; QStringList args = file.expandExecString(); QString command = args.takeFirst(); QProcess::start(command, args); } void LxQtModule::terminate() { mIsTerminating = true; QProcess::terminate(); } bool LxQtModule::isTerminating() { return mIsTerminating; } void LxQtModule::updateState(QProcess::ProcessState newState) { if (newState != QProcess::Starting) emit moduleStateChanged(fileName, (newState == QProcess::Running)); } <commit_msg>Better window manager detection<commit_after>/* BEGIN_COMMON_COPYRIGHT_HEADER * (c)LGPL2+ * * LxQt - a lightweight, Qt based, desktop toolset * http://razor-qt.org, http://lxde.org/ * * Copyright: 2010-2011 LxQt team * Authors: * Petr Vanek <[email protected]> * Hong Jen Yee (PCMan) <[email protected]> * * This program or library is free software; you can redistribute it * and/or modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * You should have received a copy of the GNU Lesser General * Public License along with this library; if not, write to the * Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, * Boston, MA 02110-1301 USA * * END_COMMON_COPYRIGHT_HEADER */ #include "lxqtmodman.h" #include <LXQt/Settings> #include <XdgAutoStart> #include <XdgDirs> #include <unistd.h> #include <QDebug> #include <QCoreApplication> #include <QMessageBox> #include <QSystemTrayIcon> #include <QFileInfo> #include <QFileSystemWatcher> #include <QDateTime> #include "wmselectdialog.h" #include "windowmanager.h" #include <wordexp.h> #include <KF5/KWindowSystem/KWindowSystem> #include <KF5/KWindowSystem/netwm.h> #include <QX11Info> #define MAX_CRASHES_PER_APP 5 using namespace LxQt; /** * @brief the constructor, needs a valid modules.conf */ LxQtModuleManager::LxQtModuleManager(const QString & windowManager, QObject* parent) : QObject(parent), mWindowManager(windowManager), mWmProcess(new QProcess(this)), mThemeWatcher(new QFileSystemWatcher(this)), mWmStarted(false), mTrayStarted(false), mWaitLoop(NULL) { connect(mThemeWatcher, SIGNAL(directoryChanged(QString)), SLOT(themeFolderChanged(QString))); connect(LxQt::Settings::globalSettings(), SIGNAL(lxqtThemeChanged()), SLOT(themeChanged())); qApp->installNativeEventFilter(this); } void LxQtModuleManager::startup(LxQt::Settings& s) { // The lxqt-confupdate can update the settings of the WM, so run it first. startConfUpdate(); // Start window manager startWm(&s); startAutostartApps(); QStringList paths; paths << XdgDirs::dataHome(false); paths << XdgDirs::dataDirs(); foreach(QString path, paths) { QFileInfo fi(QString("%1/lxqt/themes").arg(path)); if (fi.exists()) mThemeWatcher->addPath(fi.absoluteFilePath()); } themeChanged(); } void LxQtModuleManager::startAutostartApps() { // XDG autostart XdgDesktopFileList fileList = XdgAutoStart::desktopFileList(); QList<XdgDesktopFile*> trayApps; for (XdgDesktopFileList::iterator i = fileList.begin(); i != fileList.end(); ++i) { if (i->value("X-LXQt-Need-Tray", false).toBool()) trayApps.append(&(*i)); else { startProcess(*i); qDebug() << "start" << i->fileName(); } } if (!trayApps.isEmpty()) { mTrayStarted = QSystemTrayIcon::isSystemTrayAvailable(); if(!mTrayStarted) { QEventLoop waitLoop; mWaitLoop = &waitLoop; // add a timeout to avoid infinite blocking if a WM fail to execute. QTimer::singleShot(60 * 1000, &waitLoop, SLOT(quit())); waitLoop.exec(); mWaitLoop = NULL; } foreach (XdgDesktopFile* f, trayApps) { qDebug() << "start tray app" << f->fileName(); startProcess(*f); } } } void LxQtModuleManager::themeFolderChanged(const QString& /*path*/) { QString newTheme; if (!QFileInfo(mCurrentThemePath).exists()) { const QList<LxQtTheme> &allThemes = lxqtTheme.allThemes(); if (!allThemes.isEmpty()) newTheme = allThemes[0].name(); else return; } else newTheme = lxqtTheme.currentTheme().name(); LxQt::Settings settings("lxqt"); if (newTheme == settings.value("theme")) { // force the same theme to be updated settings.setValue("__theme_updated__", QDateTime::currentMSecsSinceEpoch()); } else settings.setValue("theme", newTheme); sync(); } void LxQtModuleManager::themeChanged() { if (!mCurrentThemePath.isEmpty()) mThemeWatcher->removePath(mCurrentThemePath); if (lxqtTheme.currentTheme().isValid()) { mCurrentThemePath = lxqtTheme.currentTheme().path(); mThemeWatcher->addPath(mCurrentThemePath); } } void LxQtModuleManager::startWm(LxQt::Settings *settings) { // if the WM is active do not run WM. // all window managers must set their name according to the spec if (!QString(NETRootInfo(QX11Info::connection(), NET::SupportingWMCheck).wmName()).isEmpty()) { mWmStarted = true; return; } if (mWindowManager.isEmpty()) { mWindowManager = settings->value("window_manager").toString(); } // If previuos WM was removed, we show dialog. if (mWindowManager.isEmpty() || ! findProgram(mWindowManager.split(' ')[0])) { mWindowManager = showWmSelectDialog(); settings->setValue("window_manager", mWindowManager); settings->sync(); } mWmProcess->start(mWindowManager); // other autostart apps will be handled after the WM becomes available // Wait until the WM loads QEventLoop waitLoop; mWaitLoop = &waitLoop; // add a timeout to avoid infinite blocking if a WM fail to execute. QTimer::singleShot(30 * 1000, &waitLoop, SLOT(quit())); waitLoop.exec(); mWaitLoop = NULL; // FIXME: blocking is a bad idea. We need to start as many apps as possible and // only wait for the start of WM when it's absolutely needed. // Maybe we can add a X-Wait-WM=true key in the desktop entry file? } void LxQtModuleManager::startProcess(const XdgDesktopFile& file) { if (!file.value("X-LXQt-Module", false).toBool()) { file.startDetached(); return; } QStringList args = file.expandExecString(); if (args.isEmpty()) { qWarning() << "Wrong desktop file" << file.fileName(); return; } LxQtModule* proc = new LxQtModule(file, this); connect(proc, SIGNAL(moduleStateChanged(QString,bool)), this, SIGNAL(moduleStateChanged(QString,bool))); proc->start(); QString name = QFileInfo(file.fileName()).fileName(); mNameMap[name] = proc; connect(proc, SIGNAL(finished(int, QProcess::ExitStatus)), this, SLOT(restartModules(int, QProcess::ExitStatus))); } void LxQtModuleManager::startProcess(const QString& name) { if (!mNameMap.contains(name)) { foreach (const XdgDesktopFile& file, XdgAutoStart::desktopFileList(false)) { if (QFileInfo(file.fileName()).fileName() == name) { startProcess(file); return; } } } } void LxQtModuleManager::stopProcess(const QString& name) { if (mNameMap.contains(name)) mNameMap[name]->terminate(); } QStringList LxQtModuleManager::listModules() const { return QStringList(mNameMap.keys()); } void LxQtModuleManager::startConfUpdate() { XdgDesktopFile desktop(XdgDesktopFile::ApplicationType, ":lxqt-confupdate", "lxqt-confupdate --watch"); desktop.setValue("Name", "LXQt config updater"); desktop.setValue("X-LXQt-Module", true); startProcess(desktop); } void LxQtModuleManager::restartModules(int exitCode, QProcess::ExitStatus exitStatus) { LxQtModule* proc = qobject_cast<LxQtModule*>(sender()); Q_ASSERT(proc); if (!proc->isTerminating()) { QString procName = proc->file.name(); switch (exitStatus) { case QProcess::NormalExit: qDebug() << "Process" << procName << "(" << proc << ") exited correctly."; break; case QProcess::CrashExit: { qDebug() << "Process" << procName << "(" << proc << ") has to be restarted"; time_t now = time(NULL); mCrashReport[proc].prepend(now); while (now - mCrashReport[proc].back() > 60) mCrashReport[proc].pop_back(); if (mCrashReport[proc].length() >= MAX_CRASHES_PER_APP) { QMessageBox::warning(0, tr("Crash Report"), tr("<b>%1</b> crashed too many times. Its autorestart has been disabled until next login.").arg(procName)); } else { proc->start(); return; } break; } } } mNameMap.remove(proc->fileName); proc->deleteLater(); } LxQtModuleManager::~LxQtModuleManager() { qApp->removeNativeEventFilter(this); qDeleteAll(mNameMap); delete mWmProcess; } /** * @brief this logs us out by terminating our session **/ void LxQtModuleManager::logout() { // modules ModulesMapIterator i(mNameMap); while (i.hasNext()) { i.next(); qDebug() << "Module logout" << i.key(); LxQtModule* p = i.value(); p->terminate(); } i.toFront(); while (i.hasNext()) { i.next(); LxQtModule* p = i.value(); if (p->state() != QProcess::NotRunning && !p->waitForFinished()) { qWarning() << QString("Module '%1' won't terminate ... killing.").arg(i.key()); p->kill(); } } mWmProcess->terminate(); if (mWmProcess->state() != QProcess::NotRunning && !mWmProcess->waitForFinished()) { qWarning() << QString("Window Manager won't terminate ... killing."); mWmProcess->kill(); } QCoreApplication::exit(0); } QString LxQtModuleManager::showWmSelectDialog() { WindowManagerList availableWM = getWindowManagerList(true); if (availableWM.count() == 1) return availableWM.at(0).command; WmSelectDialog dlg(availableWM); dlg.exec(); return dlg.windowManager(); } void LxQtModuleManager::resetCrashReport() { mCrashReport.clear(); } bool LxQtModuleManager::nativeEventFilter(const QByteArray & eventType, void * message, long * result) { if (eventType != "xcb_generic_event_t") // We only want to handle XCB events return false; if(!mWmStarted && mWaitLoop) { // all window managers must set their name according to the spec if (!QString(NETRootInfo(QX11Info::connection(), NET::SupportingWMCheck).wmName()).isEmpty()) { qDebug() << "Window Manager started"; mWmStarted = true; if (mWaitLoop->isRunning()) mWaitLoop->exit(); } } if (!mTrayStarted && QSystemTrayIcon::isSystemTrayAvailable() && mWaitLoop) { qDebug() << "System Tray started"; mTrayStarted = true; if (mWaitLoop->isRunning()) mWaitLoop->exit(); // window manager and system tray have started qApp->removeNativeEventFilter(this); } return false; } void lxqt_setenv(const char *env, const QByteArray &value) { wordexp_t p; wordexp(value, &p, 0); if (p.we_wordc == 1) { qDebug() << "Environment variable" << env << "=" << p.we_wordv[0]; qputenv(env, p.we_wordv[0]); } else { qWarning() << "Error expanding environment variable" << env << "=" << value; qputenv(env, value); } wordfree(&p); } void lxqt_setenv_prepend(const char *env, const QByteArray &value, const QByteArray &separator) { QByteArray orig(qgetenv(env)); orig = orig.prepend(separator); orig = orig.prepend(value); qDebug() << "Setting special" << env << " variable:" << orig; lxqt_setenv(env, orig); } LxQtModule::LxQtModule(const XdgDesktopFile& file, QObject* parent) : QProcess(parent), file(file), fileName(QFileInfo(file.fileName()).fileName()), mIsTerminating(false) { connect(this, SIGNAL(stateChanged(QProcess::ProcessState)), SLOT(updateState(QProcess::ProcessState))); } void LxQtModule::start() { mIsTerminating = false; QStringList args = file.expandExecString(); QString command = args.takeFirst(); QProcess::start(command, args); } void LxQtModule::terminate() { mIsTerminating = true; QProcess::terminate(); } bool LxQtModule::isTerminating() { return mIsTerminating; } void LxQtModule::updateState(QProcess::ProcessState newState) { if (newState != QProcess::Starting) emit moduleStateChanged(fileName, (newState == QProcess::Running)); } <|endoftext|>
<commit_before>#pragma once //=====================================================================// /*! @file @brief RX64M グループ・PHY 定義 @n Copyright 2017 Kunihito Hiramatsu @author 平松邦仁 ([email protected]) */ //=====================================================================// #include "common/io_utils.hpp" namespace device { //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++// /*! @brief PHY 定義クラス @param[in] ETHC インサーネット・コントローラー */ //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++// template <class ETHC> class phy_t { public: enum class LinkStat : uint8_t { NO_LINK = 0, LINK_10H, LINK_10F, LINK_100H, LINK_100F, }; private: // Media Independent Interface static const int PHY_MII_ST = 1; static const int PHY_MII_READ = 2; static const int PHY_MII_WRITE = 1; /* * PHY address selection. * Please select one of them. */ static const int PHY_MII_ADDR = 0; /* for GR-SAKURA (RX63N). */ static const int PHY_MII_WAIT = 2; /* Standard PHY Registers */ static const int PHY_REG_CONTROL = 0; static const int PHY_REG_STATUS = 1; static const int PHY_REG_IDENTIFIER1 = 2; static const int PHY_REG_IDENTIFIER2 = 3; static const int PHY_REG_AN_ADVERTISEMENT = 4; static const int PHY_REG_AN_LINK_PARTNER = 5; static const int PHY_REG_AN_EXPANSION = 6; /* Vendor Specific PHY Registers */ #ifdef MICREL_KSZ8041NL static const uint16_t PHY_REG_PHY_CONTROL_1 = (0x1E); #endif /* MICREL_KSZ8041NL */ /* Basic Mode Control Register Bit Definitions */ static const uint16_t PHY_CONTROL_RESET = (1 << 15); static const uint16_t PHY_CONTROL_LOOPBACK = (1 << 14); static const uint16_t PHY_CONTROL_100_MBPS = (1 << 13); static const uint16_t PHY_CONTROL_AN_ENABLE = (1 << 12); static const uint16_t PHY_CONTROL_POWER_DOWN = (1 << 11); static const uint16_t PHY_CONTROL_ISOLATE = (1 << 10); static const uint16_t PHY_CONTROL_AN_RESTART = (1 << 9); static const uint16_t PHY_CONTROL_FULL_DUPLEX = (1 << 8); static const uint16_t PHY_CONTROL_COLLISION = (1 << 7); /* Basic Mode Status Register Bit Definitions */ static const uint16_t PHY_STATUS_100_T4 = (1 << 15); static const uint16_t PHY_STATUS_100F = (1 << 14); static const uint16_t PHY_STATUS_100H = (1 << 13); static const uint16_t PHY_STATUS_10F = (1 << 12); static const uint16_t PHY_STATUS_10H = (1 << 11); static const uint16_t PHY_STATUS_AN_COMPLETE = (1 << 5); static const uint16_t PHY_STATUS_RM_FAULT = (1 << 4); static const uint16_t PHY_STATUS_AN_ABILITY = (1 << 3); static const uint16_t PHY_STATUS_LINK_UP = (1 << 2); static const uint16_t PHY_STATUS_JABBER = (1 << 1); static const uint16_t PHY_STATUS_EX_CAPABILITY = (1 << 0); /* Auto Negotiation Advertisement Bit Definitions */ static const uint16_t PHY_AN_ADVERTISEMENT_NEXT_PAGE = (1 << 15); static const uint16_t PHY_AN_ADVERTISEMENT_RM_FAULT = (1 << 13); static const uint16_t PHY_AN_ADVERTISEMENT_ASM_DIR = (1 << 11); static const uint16_t PHY_AN_ADVERTISEMENT_PAUSE = (1 << 10); static const uint16_t PHY_AN_ADVERTISEMENT_100_T4 = (1 << 9); static const uint16_t PHY_AN_ADVERTISEMENT_100F = (1 << 8); static const uint16_t PHY_AN_ADVERTISEMENT_100H = (1 << 7); static const uint16_t PHY_AN_ADVERTISEMENT_10F = (1 << 6); static const uint16_t PHY_AN_ADVERTISEMENT_10H = (1 << 5); static const uint16_t PHY_AN_ADVERTISEMENT_SELECTOR = (1 << 0); /* Auto Negostiate Link Partner Ability Bit Definitions */ static const uint16_t PHY_AN_LINK_PARTNER_NEXT_PAGE = (1 << 15); static const uint16_t PHY_AN_LINK_PARTNER_ACK = (1 << 14); static const uint16_t PHY_AN_LINK_PARTNER_RM_FAULT = (1 << 13); static const uint16_t PHY_AN_LINK_PARTNER_ASM_DIR = (1 << 11); static const uint16_t PHY_AN_LINK_PARTNER_PAUSE = (1 << 10); static const uint16_t PHY_AN_LINK_PARTNER_100_T4 = (1 << 9); static const uint16_t PHY_AN_LINK_PARTNER_100F = (1 << 8); static const uint16_t PHY_AN_LINK_PARTNER_100H = (1 << 7); static const uint16_t PHY_AN_LINK_PARTNER_10F = (1 << 6); static const uint16_t PHY_AN_LINK_PARTNER_10H = (1 << 5); static const uint16_t PHY_AN_LINK_PARTNER_SELECTOR = (1 << 0); /* Delay constants */ static const uint32_t PHY_DELAY_RESET = 0x00020000L; static const uint32_t PHY_DELAY_AN = 0x00800000L; uint16_t local_advertise_; /* * The value is read from the PHY register by the frame format of MII Management Interface provided * for by Table 22-12 of 22.2.4.5 of IEEE 802.3-2008_section2. */ uint16_t read_(uint16_t reg_addr) { preamble_(); reg_set_(reg_addr, PHY_MII_READ); trans_Zto0_(); uint16_t data = reg_read_(); trans_Zto0_(); return data; } /* * The value is read from the PHY register by the frame format of MII Management Interface provided * for by Table 22-12 of 22.2.4.5 of IEEE 802.3-2008_section2. */ void write_(uint16_t reg_addr, uint16_t data) { preamble_(); reg_set_(reg_addr, PHY_MII_WRITE); trans_1to0_(); reg_write_(data); trans_Zto0_(); } /* * The processing of PRE (preamble) about the frame format of MII Management Interface which is * provided by "Table 22-12" of "22.2.4.5" of "IEEE 802.3-2008_section2". */ void preamble_() { int i = 32; while( i > 0 ) { mii_write1_(); i--; } } /* * The processing of ST (start of frame),OP (operation code), PHYAD (PHY Address), and * REGAD (Register Address) about the frame format of MII Management Interface which is * provided by "Table 22-12" of "22.2.4.5" of "IEEE 802.3-2008_section2". */ void reg_set_(uint16_t reg_addr, int32_t option) { uint16_t data = 0; data = (PHY_MII_ST << 14); /* ST code */ if( option == PHY_MII_READ ) { data |= (PHY_MII_READ << 12); /* OP code(RD) */ } else { data |= (PHY_MII_WRITE << 12); /* OP code(WT) */ } data |= (PHY_MII_ADDR << 7); /* PHY Address */ data |= (reg_addr << 2); /* Reg Address */ int i = 14; while( i > 0 ) { if( (data & 0x8000) == 0 ) { mii_write0_(); } else { mii_write1_(); } data <<= 1; i--; } } /* * The processing of DATA (data) about reading of the frame format of MII Management Interface which is * provided by "Table 22-12" of "22.2.4.5" of "IEEE 802.3-2008_section2". */ uint16_t reg_read_() { uint16_t reg_data = 0; int i = 16; while( i > 0 ) { for(int j = PHY_MII_WAIT; j > 0; j--) { ETHC::PIR = 0x00000000; } for(int j = PHY_MII_WAIT; j > 0; j--) { ETHC::PIR = 0x00000001; } reg_data <<= 1; reg_data |= (ETHC::PIR() & 0x00000008) >> 3; /* MDI read */ for(int j = PHY_MII_WAIT; j > 0; j--) { ETHC::PIR = 0x00000001; } for(int j = PHY_MII_WAIT; j > 0; j--) { ETHC::PIR = 0x00000000; } i--; } return reg_data; } /* * The processing of DATA (data) about writing of the frame format of MII Management Interface which is * provided by "Table 22-12" of "22.2.4.5" of "IEEE 802.3-2008_section2". */ void reg_write_(uint16_t data) { int i = 16; while( i > 0 ) { if( (data & 0x8000) == 0 ) { mii_write0_(); } else { mii_write1_(); } i--; data <<= 1; } } /* * The processing of TA (turnaround) about reading of the frame format of MII Management Interface * which is provided by "Table 22-12" of "22.2.4.5" of "IEEE 802.3-2008_section2". */ void trans_Zto0_() { for(int j = PHY_MII_WAIT; j > 0; j--) { ETHC::PIR = 0x00000000; } for(int j = PHY_MII_WAIT; j > 0; j--) { ETHC::PIR = 0x00000001; } for(int j = PHY_MII_WAIT; j > 0; j--) { ETHC::PIR = 0x00000001; } for(int j = PHY_MII_WAIT; j > 0; j--) { ETHC::PIR = 0x00000000; } } /* * The processing of TA (turnaround) about writing of the frame format of MII Management Interface * which is provided by "Table 22-12" of "22.2.4.5" of "IEEE 802.3-2008_section2". */ void trans_1to0_() { mii_write1_(); mii_write0_(); } /* * The processing of one bit about frame format of MII Management Interface which is * provided by "Table 22-12" of "22.2.4.5" of "IEEE 802.3-2008_section2". * The data that 1 is output. */ void mii_write1_() { for(int j = PHY_MII_WAIT; j > 0; j--) { ETHC::PIR = 0x00000006; } for(int j = PHY_MII_WAIT; j > 0; j--) { ETHC::PIR = 0x00000007; } for(int j = PHY_MII_WAIT; j > 0; j--) { ETHC::PIR = 0x00000007; } for(int j = PHY_MII_WAIT; j > 0; j--) { ETHC::PIR = 0x00000006; } } /* * The processing of one bit about frame format of MII Management Interface which is * provided by "Table 22-12" of "22.2.4.5" of "IEEE 802.3-2008_section2". * The data that 0 is output. */ void mii_write0_() { for(int j = PHY_MII_WAIT; j > 0; j--) { ETHC::PIR = 0x00000002; } for(int j = PHY_MII_WAIT; j > 0; j--) { ETHC::PIR = 0x00000003; } for(int j = PHY_MII_WAIT; j > 0; j--) { ETHC::PIR = 0x00000003; } for(int j = PHY_MII_WAIT; j > 0; j--) { ETHC::PIR.LONG = 0x00000002; } } void nop_() const { asm("nop"); } public: //-----------------------------------------------------------------// /*! @brief コンストラクター */ //-----------------------------------------------------------------// phy_t() : local_advertise_(0) { } //-----------------------------------------------------------------// /*! @brief Resets Ethernet PHY device @return OK: true, ERROR: false */ //-----------------------------------------------------------------// bool init() { /* Reset PHY */ write_(PHY_REG_CONTROL, PHY_CONTROL_RESET); uint16_t count = 0; uint16_t reg; /* Reset completion waiting */ do { reg = read_(PHY_REG_CONTROL); count++; } while ( (reg & PHY_CONTROL_RESET) && (count < PHY_DELAY_RESET) ); if( count < PHY_DELAY_RESET ) { /* * When KSZ8041NL of the Micrel, Inc. is used, * the pin that outputs the state of LINK is used combinedly with ACTIVITY in default. * The setting of the pin is changed so that only the state of LINK is output. */ #ifdef MICREL_KSZ8041NL reg = read_(PHY_REG_PHY_CONTROL_1); reg &= ~0x8000; reg |= 0x4000; write_(PHY_REG_PHY_CONTROL_1, reg); #endif return true; } return false; } //-----------------------------------------------------------------// /*! @brief Starts autonegotiate @param[in] PauseFrameEnableFlag */ //-----------------------------------------------------------------// void start_autonegotiate(bool PauseFrameEnableFlag) { /* Set local ability */ /* When pause frame is not used */ if (PauseFrameEnableFlag) { local_advertise_ = (PHY_AN_ADVERTISEMENT_100F | PHY_AN_ADVERTISEMENT_100H | PHY_AN_ADVERTISEMENT_10F | PHY_AN_ADVERTISEMENT_10H | PHY_AN_ADVERTISEMENT_SELECTOR); } else { local_advertise_ = (PHY_AN_ADVERTISEMENT_ASM_DIR | PHY_AN_ADVERTISEMENT_PAUSE | PHY_AN_ADVERTISEMENT_100F | PHY_AN_ADVERTISEMENT_100H | PHY_AN_ADVERTISEMENT_10F | PHY_AN_ADVERTISEMENT_10H | PHY_AN_ADVERTISEMENT_SELECTOR); } /* Configure what the PHY and the Ethernet controller on this board supports */ write_(PHY_REG_AN_ADVERTISEMENT, local_advertise_); write_(PHY_REG_CONTROL, (PHY_CONTROL_AN_ENABLE | PHY_CONTROL_AN_RESTART) ); } //-----------------------------------------------------------------// /*! @brief reports the other side's physical capability @param[in] line_speed_duplex both the line speed and the duplex @param[in] local_pause store the local pause bits. @param[in] partner_pause store the partner pause bits. @return OK: true, ERROR: false */ //-----------------------------------------------------------------// bool set_autonegotiate(LinkStat& line_speed_duplex, uint16_t& local_pause, uint16_t& partner_pause) { line_speed_duplex = LinkStat::NO_LINK; /* Because reading the first time shows the previous state, the Link status bit is read twice. */ uint16_t reg = read_(PHY_REG_STATUS); reg = read_(PHY_REG_STATUS); /* When the link isn't up, return error */ if (!(reg & PHY_STATUS_LINK_UP)) { nop_(); return false; } /* Establish local pause capability */ if (local_advertise_ & PHY_AN_ADVERTISEMENT_PAUSE) { local_pause |= (1 << 1); } if (local_advertise_ & PHY_AN_ADVERTISEMENT_ASM_DIR) { local_pause |= 1; } /* When the auto-negotiation isn't completed, return error */ if (!(reg & PHY_STATUS_AN_COMPLETE)) { return false; } else { /* Get the link partner response */ reg = read_(PHY_REG_AN_LINK_PARTNER); /* Establish partner pause capability */ if ( (reg & PHY_AN_LINK_PARTNER_PAUSE) == PHY_AN_LINK_PARTNER_PAUSE ) { partner_pause = ( 1 << 1 ); } if ( (reg & PHY_AN_LINK_PARTNER_ASM_DIR) == PHY_AN_LINK_PARTNER_ASM_DIR ) { partner_pause |= 1; } /* Establish the line speed and the duplex */ if ( reg & PHY_AN_LINK_PARTNER_10H ) { line_speed_duplex = LinkStat::LINK_10H; } if ( reg & PHY_AN_LINK_PARTNER_10F ) { line_speed_duplex = LinkStat::LINK_10F; } if ( reg & PHY_AN_LINK_PARTNER_100H ) { line_speed_duplex = LinkStat::LINK_100H; } if ( reg & PHY_AN_LINK_PARTNER_100F ) { line_speed_duplex = LinkStat::LINK_100F; } return true; } } //-----------------------------------------------------------------// /*! @brief Returns the status of the physical link @return false: links is down, true: otherwise */ //-----------------------------------------------------------------// bool get_link_status() { /* Because reading the first time shows the previous state, the Link status bit is read twice. */ uint16_t reg = read_(PHY_REG_STATUS); reg = read_(PHY_REG_STATUS); /* When the link isn't up, return error */ if (!(reg & PHY_STATUS_LINK_UP)) { nop_(); /* Link is down */ return false; } else { /* Link is up */ return true; } } }; } <commit_msg>remove file<commit_after><|endoftext|>
<commit_before>/* This file is part of Strigi Desktop Search * * Copyright (C) 2007 Jos van den Oever <[email protected]> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Library General Public * License as published by the Free Software Foundation; either * version 2 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 * Library General Public License for more details. * * You should have received a copy of the GNU Library General Public License * along with this library; see the file COPYING.LIB. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, * Boston, MA 02110-1301, USA. */ #include "strigiconfig.h" #include "oleinputstream.h" #include "oleendanalyzer.h" #include "subinputstream.h" #include "analysisresult.h" #include "fieldtypes.h" #include "textutils.h" #include <sstream> using namespace Strigi; using namespace std; void OleEndAnalyzerFactory::registerFields(FieldRegister& reg) { static const char summaryKey[] = {0xE0,0x85,0x9F,0xF2,0xF9,0x4F,0x68,0x10, 0xAB,0x91,0x08,0x00,0x2B,0x27,0xB3,0xD9}; static const char docSummaryKey[]= {0x02,0xD5,0xCD,0xD5,0x9C,0x2E,0x1B,0x10, 0x93,0x97,0x08,0x00,0x2B,0x2C,0xF9,0xAE}; const RegisteredField* r; string key; map<int,const RegisteredField*>* m; // register the fields for the Summary Information Stream key.assign(summaryKey, 16); m = &fieldsMaps[key]; r = reg.registerField("title", FieldRegister::stringType, 1, 0); if (r) (*m)[2] = r; r = reg.registerField("subject", FieldRegister::stringType, -1, 0); if (r) (*m)[3] = r; r = reg.registerField("author", FieldRegister::stringType, -1, 0); if (r) (*m)[4] = r; r = reg.registerField("keywords", FieldRegister::stringType, -1, 0); if (r) (*m)[5] = r; r = reg.registerField("comments", FieldRegister::stringType, -1, 0); if (r) (*m)[6] = r; // register the fields for the Document Summary Information Stream key.assign(docSummaryKey, 16); m = &fieldsMaps[key]; r = reg.registerField("category", FieldRegister::stringType, 1, 0); if (r) (*m)[2] = r; r = reg.registerField("presentationtarget",FieldRegister::stringType, 1, 0); if (r) (*m)[3] = r; r = reg.registerField("manager", FieldRegister::stringType, 1, 0); if (r) (*m)[14] = r; r = reg.registerField("company", FieldRegister::stringType, 1, 0); if (r) (*m)[15] = r; } const map<int, const RegisteredField*>* OleEndAnalyzerFactory::getFieldMap(const string& key) const { map<string, map<int,const RegisteredField*> >::const_iterator i = fieldsMaps.find(key); return (i == fieldsMaps.end()) ?0 :&i->second; } bool OleEndAnalyzer::checkHeader(const char* header, int32_t headersize) const { return OleInputStream::checkHeader(header, headersize); } bool tryThumbsdbEntry(const string& name, AnalysisResult& ar, InputStream* in) { static const char magic[] = {0x0c, 0, 0, 0, 0x01, 0, 0, 0}; const char* d; uint32_t nread = in->read(d, 12, 12); if (nread != 12 || memcmp(magic, d, 8)) { in->reset(0); return false; } SubInputStream thumb(in, in->size()-12); ar.indexChild(name, 0, &thumb); return true; } void tryPictures(AnalysisResult& ar, InputStream* in) { const char* d; int32_t nread = in->read(d, 25, 25); ostringstream s; int pos = 1; while (nread == 25) { uint32_t size = readLittleEndianInt32(d+4)-17; SubInputStream sub(in, size); s << "Pictures/" << pos++; ar.indexChild(s.str(), 0, &sub); s.str(""); nread = in->read(d, 25, 25); } } // format description: http://jakarta.apache.org/poi/hpsf/internals.html bool OleEndAnalyzer::tryPropertyStream(AnalysisResult& idx, InputStream* in) { static const char magic[] = {0xfe, 0xff, 0, 0}; const char* d; uint32_t nread = in->read(d, 28, 28); in->reset(0); if (nread != 28 || memcmp(magic, d, 4)) { return false; } // read all the data nread = in->read(d, in->size(), in->size()); if (nread != in->size()) { return false; } int32_t n = readLittleEndianUInt32(d+24); if (in->size() < 28+n*20) { return false; } for (int32_t i=0; i<n; ++i) { const char* key = d + 28 + i*20; int32_t offset = readLittleEndianInt32(key+16); if (offset >= in->size()) { return false; } handlePropertyStream(key, d+offset, d+in->size()); } return true; } void OleEndAnalyzer::handleProperty(const RegisteredField* field, const char* data) { int32_t datatype = readLittleEndianInt32(data); // currently we only support null-terminated strings if (datatype == 30) { result->addValue(field, data+4); } } void OleEndAnalyzer::handlePropertyStream(const char* key, const char* data, const char* end) { // get the fieldtable string k(key, 16); const map<int, const RegisteredField*>* table = factory->getFieldMap(k); if (table == 0) { return; } int32_t len = readLittleEndianInt32(data); const char* p = data + 8; const char* n = data + readLittleEndianInt32(data+4)*4 + 8; if (len < 0 || len > end-data || n > end) { return; } map<int, const RegisteredField*>::const_iterator field; while (p < n) { int32_t id = readLittleEndianInt32(p); field = table->find(id); if (field != table->end()) { int32_t offset = readLittleEndianInt32(p+4); handleProperty(field->second, data+offset); } p += 8; } } char OleEndAnalyzer::analyze(AnalysisResult& ar, InputStream* in) { if(!in) return -1; result = &ar; OleInputStream ole(in); InputStream *s = ole.nextEntry(); if (ole.status()) { fprintf(stderr, "error: %s\n", ole.error()); // exit(1); } while (s) { const string& name = ole.entryInfo().filename; if (name.size()) { if (tryThumbsdbEntry(name, ar, s)) { } else if (name[0] == 5) { // todo: handle property stream tryPropertyStream(ar, s); } else if (name == "Pictures") { tryPictures(ar, s); } else { ar.indexChild(name, ole.entryInfo().mtime, s); } } s = ole.nextEntry(); } if (ole.status() == Error) { m_error = ole.error(); return -1; } else { m_error.resize(0); } return 0; } <commit_msg>bit of docu<commit_after>/* This file is part of Strigi Desktop Search * * Copyright (C) 2007 Jos van den Oever <[email protected]> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Library General Public * License as published by the Free Software Foundation; either * version 2 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 * Library General Public License for more details. * * You should have received a copy of the GNU Library General Public License * along with this library; see the file COPYING.LIB. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, * Boston, MA 02110-1301, USA. */ #include "strigiconfig.h" #include "oleinputstream.h" #include "oleendanalyzer.h" #include "subinputstream.h" #include "analysisresult.h" #include "fieldtypes.h" #include "textutils.h" #include <sstream> using namespace Strigi; using namespace std; void OleEndAnalyzerFactory::registerFields(FieldRegister& reg) { static const char summaryKey[] = {0xE0,0x85,0x9F,0xF2,0xF9,0x4F,0x68,0x10, 0xAB,0x91,0x08,0x00,0x2B,0x27,0xB3,0xD9}; static const char docSummaryKey[]= {0x02,0xD5,0xCD,0xD5,0x9C,0x2E,0x1B,0x10, 0x93,0x97,0x08,0x00,0x2B,0x2C,0xF9,0xAE}; const RegisteredField* r; string key; map<int,const RegisteredField*>* m; // register the fields for the Summary Information Stream key.assign(summaryKey, 16); m = &fieldsMaps[key]; r = reg.registerField("title", FieldRegister::stringType, 1, 0); if (r) (*m)[2] = r; r = reg.registerField("subject", FieldRegister::stringType, -1, 0); if (r) (*m)[3] = r; r = reg.registerField("author", FieldRegister::stringType, -1, 0); if (r) (*m)[4] = r; r = reg.registerField("keywords", FieldRegister::stringType, -1, 0); if (r) (*m)[5] = r; r = reg.registerField("comments", FieldRegister::stringType, -1, 0); if (r) (*m)[6] = r; // register the fields for the Document Summary Information Stream key.assign(docSummaryKey, 16); m = &fieldsMaps[key]; r = reg.registerField("category", FieldRegister::stringType, 1, 0); if (r) (*m)[2] = r; r = reg.registerField("presentationtarget",FieldRegister::stringType, 1, 0); if (r) (*m)[3] = r; r = reg.registerField("manager", FieldRegister::stringType, 1, 0); if (r) (*m)[14] = r; r = reg.registerField("company", FieldRegister::stringType, 1, 0); if (r) (*m)[15] = r; } const map<int, const RegisteredField*>* OleEndAnalyzerFactory::getFieldMap(const string& key) const { map<string, map<int,const RegisteredField*> >::const_iterator i = fieldsMaps.find(key); return (i == fieldsMaps.end()) ?0 :&i->second; } bool OleEndAnalyzer::checkHeader(const char* header, int32_t headersize) const { return OleInputStream::checkHeader(header, headersize); } bool tryThumbsdbEntry(const string& name, AnalysisResult& ar, InputStream* in) { static const char magic[] = {0x0c, 0, 0, 0, 0x01, 0, 0, 0}; const char* d; uint32_t nread = in->read(d, 12, 12); if (nread != 12 || memcmp(magic, d, 8)) { in->reset(0); return false; } SubInputStream thumb(in, in->size()-12); ar.indexChild(name, 0, &thumb); return true; } /** * Exctract images from a 'Pictures' field from a ppt file. * http://jakarta.apache.org/poi/apidocs/org/apache/poi/hslf/model/Picture.html **/ void tryPictures(AnalysisResult& ar, InputStream* in) { const char* d; int32_t nread = in->read(d, 25, 25); ostringstream s; int pos = 1; while (nread == 25) { uint32_t size = readLittleEndianInt32(d+4)-17; SubInputStream sub(in, size); s << "Pictures/" << pos++; ar.indexChild(s.str(), 0, &sub); s.str(""); nread = in->read(d, 25, 25); } } // format description: http://jakarta.apache.org/poi/hpsf/internals.html bool OleEndAnalyzer::tryPropertyStream(AnalysisResult& idx, InputStream* in) { static const char magic[] = {0xfe, 0xff, 0, 0}; const char* d; uint32_t nread = in->read(d, 28, 28); in->reset(0); if (nread != 28 || memcmp(magic, d, 4)) { return false; } // read all the data nread = in->read(d, in->size(), in->size()); if (nread != in->size()) { return false; } int32_t n = readLittleEndianUInt32(d+24); if (in->size() < 28+n*20) { return false; } for (int32_t i=0; i<n; ++i) { const char* key = d + 28 + i*20; int32_t offset = readLittleEndianInt32(key+16); if (offset >= in->size()) { return false; } handlePropertyStream(key, d+offset, d+in->size()); } return true; } void OleEndAnalyzer::handleProperty(const RegisteredField* field, const char* data) { int32_t datatype = readLittleEndianInt32(data); // currently we only support null-terminated strings if (datatype == 30) { result->addValue(field, data+4); } } void OleEndAnalyzer::handlePropertyStream(const char* key, const char* data, const char* end) { // get the fieldtable string k(key, 16); const map<int, const RegisteredField*>* table = factory->getFieldMap(k); if (table == 0) { return; } int32_t len = readLittleEndianInt32(data); const char* p = data + 8; const char* n = data + readLittleEndianInt32(data+4)*4 + 8; if (len < 0 || len > end-data || n > end) { return; } map<int, const RegisteredField*>::const_iterator field; while (p < n) { int32_t id = readLittleEndianInt32(p); field = table->find(id); if (field != table->end()) { int32_t offset = readLittleEndianInt32(p+4); handleProperty(field->second, data+offset); } p += 8; } } char OleEndAnalyzer::analyze(AnalysisResult& ar, InputStream* in) { if(!in) return -1; result = &ar; OleInputStream ole(in); InputStream *s = ole.nextEntry(); if (ole.status()) { fprintf(stderr, "error: %s\n", ole.error()); // exit(1); } while (s) { const string& name = ole.entryInfo().filename; if (name.size()) { if (tryThumbsdbEntry(name, ar, s)) { } else if (name[0] == 5) { // todo: handle property stream tryPropertyStream(ar, s); } else if (name == "Pictures") { tryPictures(ar, s); } else { ar.indexChild(name, ole.entryInfo().mtime, s); } } s = ole.nextEntry(); } if (ole.status() == Error) { m_error = ole.error(); return -1; } else { m_error.resize(0); } return 0; } <|endoftext|>
<commit_before>#include <cstdlib> #include <fstream> #include <iostream> #include <ostream> #include <string> #include "Getopt.hpp" #include "snarkfront.hpp" using namespace snarkfront; using namespace snarklib; using namespace std; void printUsage(const char* exeName) { const string PAIR = " -p BN128|Edwards", KEY = " -k", OUT = " [-o output_file]"; cout << "key pair entropy: " << exeName << PAIR << KEY << OUT << endl << "proof entropy: " << exeName << PAIR << OUT << endl; exit(EXIT_FAILURE); } template <typename PAIRING> void writeEntropy(ostream& os, const bool is_keypair) { if (is_keypair) { PPZK_KeypairRandomness<typename PAIRING::Fr, typename PAIRING::Fr> entropy(1); os << entropy; } else { PPZK_ProofRandomness<typename PAIRING::Fr> entropy(0); os << entropy; } } int main(int argc, char *argv[]) { Getopt cmdLine(argc, argv, "po", "", "k"); if (!cmdLine || cmdLine.empty()) printUsage(argv[0]); const auto pairing = cmdLine.getString('p'); const auto outfile = cmdLine.getString('o'); const auto is_keypair = cmdLine.getFlag('k'); if (!validPairingName(pairing)) { cerr << "error: elliptic curve pairing " << pairing << endl; exit(EXIT_FAILURE); } ofstream ofs(outfile); if (!outfile.empty() && !ofs) { cerr << "error: output file " << outfile << endl; exit(EXIT_FAILURE); } ostream& os = outfile.empty() ? cout : ofs; if (pairingBN128(pairing)) { // Barreto-Naehrig 128 bits init_BN128(); writeEntropy<BN128_PAIRING>(os, is_keypair); } else if (pairingEdwards(pairing)) { // Edwards 80 bits init_Edwards(); writeEntropy<EDWARDS_PAIRING>(os, is_keypair); } exit(EXIT_SUCCESS); } <commit_msg>Lagrange point and blind greeks randomness<commit_after>#include <cstdlib> #include <fstream> #include <iostream> #include <ostream> #include <string> #include "Getopt.hpp" #include "snarkfront.hpp" using namespace snarkfront; using namespace snarklib; using namespace std; void printUsage(const char* exeName) { const string PAIR = " -p BN128|Edwards", KEY = " -k", OUT = " [-o output_file]"; cout << "key pair entropy: " << exeName << PAIR << KEY << OUT << endl << "proof entropy: " << exeName << PAIR << OUT << endl; exit(EXIT_FAILURE); } template <typename PAIRING> void writeEntropy(ostream& os, const bool is_keypair) { if (is_keypair) { PPZK_LagrangePoint<typename PAIRING::Fr> lagrangeRand(0); PPZK_BlindGreeks<typename PAIRING::Fr, typename PAIRING::Fr> blindRand(0); os << lagrangeRand << blindRand; } else { PPZK_ProofRandomness<typename PAIRING::Fr> entropy(0); os << entropy; } } int main(int argc, char *argv[]) { Getopt cmdLine(argc, argv, "po", "", "k"); if (!cmdLine || cmdLine.empty()) printUsage(argv[0]); const auto pairing = cmdLine.getString('p'); const auto outfile = cmdLine.getString('o'); const auto is_keypair = cmdLine.getFlag('k'); if (!validPairingName(pairing)) { cerr << "error: elliptic curve pairing " << pairing << endl; exit(EXIT_FAILURE); } ofstream ofs(outfile); if (!outfile.empty() && !ofs) { cerr << "error: output file " << outfile << endl; exit(EXIT_FAILURE); } ostream& os = outfile.empty() ? cout : ofs; if (pairingBN128(pairing)) { // Barreto-Naehrig 128 bits init_BN128(); writeEntropy<BN128_PAIRING>(os, is_keypair); } else if (pairingEdwards(pairing)) { // Edwards 80 bits init_Edwards(); writeEntropy<EDWARDS_PAIRING>(os, is_keypair); } exit(EXIT_SUCCESS); } <|endoftext|>
<commit_before>/* * Copyright 2018 Markus Lindelöw * * 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. */ #define DOCTEST_CONFIG_IMPLEMENT_WITH_MAIN #include "doctest.h" #include <tinycsocket.h> TEST_CASE("init test") { CHECK(tcs_lib_init() == TINYCSOCKET_SUCCESS); CHECK(tcs_lib_free() == TINYCSOCKET_SUCCESS); } <commit_msg>Add UDP test<commit_after>/* * Copyright 2018 Markus Lindelöw * * 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. */ #define DOCTEST_CONFIG_IMPLEMENT_WITH_MAIN #include "doctest.h" #include <tinycsocket.h> #include <thread> TEST_CASE("init test") { CHECK(tcs_lib_init() == TINYCSOCKET_SUCCESS); CHECK(tcs_lib_free() == TINYCSOCKET_SUCCESS); } TEST_CASE("UDP test") { CHECK(tcs_lib_init() == TINYCSOCKET_SUCCESS); struct tcs_addrinfo* address_info = NULL; struct tcs_addrinfo hints = { 0 }; hints.ai_family = TINYCSOCKET_AF_INET; hints.ai_socktype = TINYCSOCKET_SOCK_DGRAM; tcs_getaddrinfo("localhost", "1212", &hints, &address_info); // Setup UDP reciever CHECK(tcs_lib_init() == TINYCSOCKET_SUCCESS); tcs_socket recv_soc = TINYCSOCKET_NULLSOCKET; bool didBind = false; for (struct tcs_addrinfo* address_iterator = address_info; address_iterator != NULL; address_iterator = address_iterator->ai_next) { if (tcs_create(&recv_soc, address_iterator->ai_family, address_iterator->ai_socktype, address_iterator->ai_protocol) != TINYCSOCKET_SUCCESS) continue; if (tcs_bind(recv_soc, address_iterator->ai_addr, address_iterator->ai_addrlen) != TINYCSOCKET_SUCCESS) continue; didBind = true; break; } CHECK(didBind); struct tcs_sockaddr remote_address = { 0 }; size_t remote_address_size = sizeof(remote_address); uint8_t recv_buffer[1024] = { 0 }; size_t bytes_recieved = 0; std::thread recv_thread([&]() { CHECK(tcs_recvfrom(recv_soc, recv_buffer, sizeof(recv_buffer) - sizeof('\0'), 0, &remote_address, &remote_address_size, &bytes_recieved) == TINYCSOCKET_SUCCESS); recv_buffer[bytes_recieved] = '\0'; }); // Setup UDP sender tcs_socket socket = TINYCSOCKET_NULLSOCKET; bool didConnect = false; for (struct tcs_addrinfo* address_iterator = address_info; address_iterator != NULL; address_iterator = address_iterator->ai_next) { if (tcs_create(&socket, address_iterator->ai_family, address_iterator->ai_socktype, address_iterator->ai_protocol) != TINYCSOCKET_SUCCESS) continue; if (tcs_connect(socket, address_iterator->ai_addr, address_iterator->ai_addrlen) != TINYCSOCKET_SUCCESS) continue; didConnect = true; break; } CHECK(didConnect); // Send message uint8_t msg[] = "hello world\n"; CHECK(tcs_send(socket, msg, sizeof(msg), 0, NULL) == TINYCSOCKET_SUCCESS); // Join threads and check if we did send the message correctly recv_thread.join(); CHECK(strcmp(reinterpret_cast<const char*>(recv_buffer), reinterpret_cast<const char*>(msg)) == 0); CHECK(tcs_freeaddrinfo(&address_info) == TINYCSOCKET_SUCCESS); CHECK(tcs_close(&recv_soc) == TINYCSOCKET_SUCCESS); CHECK(tcs_lib_free() == TINYCSOCKET_SUCCESS); } <|endoftext|>
<commit_before>#define CATCH_CONFIG_RUNNER #include <iostream> #include "./Catch/catch.hpp" #include "../include/Elson.hpp" using namespace JSON; TEST_CASE( "base/types", "Basic JSON Data types" ) { Value val = 5; REQUIRE(val.is(JSON_NUMBER)); REQUIRE(val.as<std::string>().compare("5") == 0); val = 3.0; REQUIRE(val.is(JSON_NUMBER)); REQUIRE(val.as<std::string>().compare("3") == 0); val = 1L; REQUIRE(val.is(JSON_NUMBER)); REQUIRE(val.as<std::string>().compare("1") == 0); val = 7u; REQUIRE(val.is(JSON_NUMBER)); REQUIRE(val.as<std::string>().compare("7") == 0); val = -7.5; REQUIRE(val.is(JSON_NUMBER)); REQUIRE(val.as<std::string>().compare("-7.5") == 0); val = -.05; REQUIRE(val.is(JSON_NUMBER)); REQUIRE(val.as<std::string>().compare("-0.05") == 0); val = 1E3; REQUIRE(val.is(JSON_NUMBER)); REQUIRE(val.as<std::string>().compare("1000") == 0); val = -7.5; REQUIRE(val.is(JSON_NUMBER)); REQUIRE(val.as<unsigned int>() == 7); val = "5"; REQUIRE(val.is(JSON_STRING)); REQUIRE(val.as<int>() == 5); val = "5L"; REQUIRE(val.is(JSON_STRING)); REQUIRE(val.as<long>() == 5L); val = "\\"; REQUIRE(val.is(JSON_STRING)); REQUIRE(val.as<std::string>().compare("\\") == 0); val = true; REQUIRE(val.is(JSON_BOOL)); REQUIRE(val.as<bool>()); REQUIRE(val.as<int>() == 1); REQUIRE(val.as<std::string>() == "true"); val = false; REQUIRE(val.is(JSON_BOOL)); REQUIRE(!val.as<bool>()); REQUIRE(val.as<int>() == 0); REQUIRE(val.as<std::string>() == "false"); val = { true, false }; REQUIRE(val[0].is(JSON_BOOL)); REQUIRE(val[1].is(JSON_BOOL)); REQUIRE(val.is(JSON_ARRAY)); REQUIRE(val[0].as<bool>()); REQUIRE(!val[1].as<bool>()); val = { 1, .5, "hello world", true, false, null }; REQUIRE(val[0].is(JSON_NUMBER)); REQUIRE(val[1].is(JSON_NUMBER)); REQUIRE(val[2].is(JSON_STRING)); REQUIRE(val[3].is(JSON_BOOL)); REQUIRE(val[4].is(JSON_BOOL)); REQUIRE(val[5].is(JSON_NULL)); val = { {1,0,0}, {0,1,0},{0,0,1} }; REQUIRE(val.is(JSON_ARRAY)); REQUIRE(val.as<Array>().size() == 3); REQUIRE(val[0].is(JSON_ARRAY)); REQUIRE(val[1].is(JSON_ARRAY)); REQUIRE(val[2].is(JSON_ARRAY)); REQUIRE(val[0].as<Array>().size() == 3); REQUIRE(val[1].as<Array>().size() == 3); REQUIRE(val[2].as<Array>().size() == 3); REQUIRE(val[0][0].is(JSON_NUMBER)); REQUIRE(val[0][1].is(JSON_NUMBER)); REQUIRE(val[0][2].is(JSON_NUMBER)); REQUIRE(val[1][0].is(JSON_NUMBER)); REQUIRE(val[1][1].is(JSON_NUMBER)); REQUIRE(val[1][2].is(JSON_NUMBER)); REQUIRE(val[2][0].is(JSON_NUMBER)); REQUIRE(val[2][1].is(JSON_NUMBER)); REQUIRE(val[2][2].is(JSON_NUMBER)); std::string key = "property"; val = Object { { "property", "value" } }; REQUIRE(val.is(JSON_OBJECT)); REQUIRE(val["property"].is(JSON_STRING)); REQUIRE(val[key].is(JSON_STRING)); REQUIRE(val[std::string("property")].is(JSON_STRING)); REQUIRE(val["property"].as<std::string>().compare("value") == 0); val["property"] = 42; REQUIRE(val["property"].is(JSON_NUMBER)); REQUIRE(val[key].as<unsigned int>() == 42); } TEST_CASE( "base/parse", "Basic parsing") { Parser p; Printer printer; Value val; REQUIRE_THROWS(p.parse(val, "[]a")); REQUIRE_THROWS(p.parse(val, "a[]")); REQUIRE_NOTHROW(p.parse(val, "")); REQUIRE(val.is(JSON_NULL)); auto numbers = {"0", "1", "1E3", "1e-3", "0.5", "-.05e-07"}; for (auto number: numbers) { REQUIRE_NOTHROW(p.parse(val, number)); REQUIRE(val.is(JSON_NUMBER)); } REQUIRE_THROWS(p.parse(val, "-0.5w4")); std::vector<std::string> strings = { "\"\"", "\"0\"", "\"hello world\"", "\"äöüȩéáã\"" }; for (int i = 0; i < strings.size(); i++) { REQUIRE_NOTHROW(p.parse(val, strings[i])); REQUIRE(printer.print(val).compare(strings[i]) == 0); } std::map<std::string, std::string> escapes = { { "\"\\\\\"", "\"\\\"" }, { "\"\\/\"", "\"/\"" }, { "\"\\u5022\"", "\"倢\"" } }; for (auto pair: escapes) { REQUIRE_NOTHROW(p.parse(val, pair.first)); REQUIRE(printer.print(val).compare(pair.second) == 0); } REQUIRE_NOTHROW(p.parse(val, "true")); REQUIRE(val.is(JSON_BOOL)); REQUIRE(val.as<bool>()); REQUIRE(printer.print(val).compare("true") == 0); REQUIRE_NOTHROW(p.parse(val, "false")); REQUIRE(val.is(JSON_BOOL)); REQUIRE(!val.as<bool>()); REQUIRE(printer.print(val).compare("false") == 0); REQUIRE_NOTHROW(p.parse(val, "null")); REQUIRE(val.is(JSON_NULL)); REQUIRE(printer.print(val).compare("null") == 0); REQUIRE_NOTHROW(p.parse(val, "[]")); REQUIRE(val.is(JSON_ARRAY)); REQUIRE(printer.print(val).compare("[]") == 0); REQUIRE(val.as<Array>().size() == 0); REQUIRE_NOTHROW(p.parse(val, "[ 1, 2, 4 ]")); REQUIRE(val.is(JSON_ARRAY)); REQUIRE(printer.print(val).compare("[1,2,4]") == 0); REQUIRE(val.as<Array>().size() == 3); REQUIRE_THROWS(p.parse(val, "[")); REQUIRE_THROWS(p.parse(val, "]")); REQUIRE_THROWS(p.parse(val, "[[")); REQUIRE_THROWS(p.parse(val, "]]")); REQUIRE_THROWS(p.parse(val, "[,]")); REQUIRE_THROWS(p.parse(val, "[][]")); REQUIRE_THROWS(p.parse(val, "[1,]")); REQUIRE_THROWS(p.parse(val, "[,1]")); REQUIRE_THROWS(p.parse(val, "[1,2")); REQUIRE_THROWS(p.parse(val, "1,2]")); REQUIRE_THROWS(p.parse(val, "[[],[]")); REQUIRE_THROWS(p.parse(val, "[[],]]")); REQUIRE_THROWS(p.parse(val, "[[1,2,],[]]")); REQUIRE_THROWS(p.parse(val, "[[1,2,] []]")); REQUIRE_NOTHROW(p.parse(val, "[[]]")); REQUIRE_NOTHROW(p.parse(val, "[[[]]]")); REQUIRE_NOTHROW(p.parse(val, "[[],[]]")); REQUIRE_NOTHROW(p.parse(val, "[[[]],[[]]]")); REQUIRE_NOTHROW(p.parse(val, "[[[1]],[[2]]]")); REQUIRE_NOTHROW(p.parse(val, "[[[1,null,true,false,\"\"]],[[]]]")); REQUIRE(val[0][0][0].is(JSON_NUMBER)); REQUIRE(val[0][0][1].is(JSON_NULL)); REQUIRE(val[0][0][2].is(JSON_BOOL)); REQUIRE(val[0][0][3].is(JSON_BOOL)); REQUIRE(val[0][0][4].is(JSON_STRING)); REQUIRE(val[0][0].as<Array>().size() == 5); REQUIRE(printer.print(val).compare("[[[1,null,true,false,\"\"]],[[]]]") == 0); val[0][0].as<Array>().push_back(null); REQUIRE(val[0][0].as<Array>().size() == 5); val[0][0].asMutable<Array>().push_back(null); REQUIRE(val[0][0].as<Array>().size() == 6); REQUIRE_NOTHROW(p.parse(val, "{}")); REQUIRE_THROWS(p.parse(val, "{1}")); REQUIRE_THROWS(p.parse(val, "{{}}")); REQUIRE_NOTHROW(p.parse(val, "{\"a\": \"b\"}")); REQUIRE(val["a"].as<std::string>().compare("b") == 0); REQUIRE_THROWS(val.as<double>()); REQUIRE_NOTHROW(p.parse(val, "[{}]")); REQUIRE_NOTHROW(p.parse(val, "[{},{}]")); REQUIRE_NOTHROW(p.parse(val, "[{},[]]")); REQUIRE_NOTHROW(p.parse(val, "[[[{}]]]")); REQUIRE_THROWS(p.parse(val, "[[[{}]]")); REQUIRE_THROWS(p.parse(val, "[{}]]")); REQUIRE_THROWS(p.parse(val, "{[]}")); } TEST_CASE( "base/unicode", "Unicode escape handling") { Parser p; Printer printer; Value val; std::map<std::string, std::string> escapes = { { "\"\\u0041\"", "\"A\"" }, { "\"\\u0042\"", "\"B\"" }, { "\"\\u0043\"", "\"C\"" }, { "\"\\u0044\"", "\"D\"" }, { "\"\\u0045\"", "\"E\"" }, { "\"\\u0046\"", "\"F\"" }, { "\"\\u0047\"", "\"G\"" }, { "\"\\u0048\"", "\"H\"" }, { "\"\\u0049\"", "\"I\"" }, { "\"\\u0041\\u0042\\u0043\"", "\"ABC\"" }, { "\"\\u0041B\\u0043\"", "\"ABC\"" }, { "\"A\\u0042\\u0043\"", "\"ABC\"" }, { "\"\\u0041\\u0042C\"", "\"ABC\"" }, { "[\"\\u0041\\u0042C\"]", "[\"ABC\"]" }, { "\"\\u0041\\u004212\"", "\"AB12\"" }, }; for (auto pair: escapes) { REQUIRE_NOTHROW(p.parse(val, pair.first)); REQUIRE(printer.print(val).compare(pair.second) == 0); } REQUIRE_THROWS(p.parse(val, "\"\\u0fg\"")); REQUIRE_THROWS(p.parse(val, "\"\\u00\"")); REQUIRE_THROWS(p.parse(val, "\"\\u\"")); } TEST_CASE( "utils/bas", "Unicode escape handling") { Value val = Object { { "a", 1 }, { "b", 2 }, { "c", 3} }; PropertyList properties = traverse(val); REQUIRE(properties.size() == 3); PropertyList list = filter(traverse(val), [] (std::string name, Value& value) -> bool { return name.compare("b") == 0; }); REQUIRE(list.size() == 2); } int main (int argc, char* const argv[]) { return Catch::Main( argc, argv ); } <commit_msg>travis integration<commit_after>#define CATCH_CONFIG_RUNNER #include <iostream> #include "./Catch/catch.hpp" #include "../include/Elson.hpp" using namespace JSON; TEST_CASE( "base/types", "Basic JSON Data types" ) { Value val = 5; REQUIRE(val.is(JSON_NUMBER)); REQUIRE(val.as<std::string>().compare("5") == 0); val = 3.0; REQUIRE(val.is(JSON_NUMBER)); REQUIRE(val.as<std::string>().compare("3") == 0); val = 1L; REQUIRE(val.is(JSON_NUMBER)); REQUIRE(val.as<std::string>().compare("1") == 0); val = 7u; REQUIRE(val.is(JSON_NUMBER)); REQUIRE(val.as<std::string>().compare("7") == 0); val = -7.5; REQUIRE(val.is(JSON_NUMBER)); REQUIRE(val.as<std::string>().compare("-7.5") == 0); val = -.05; REQUIRE(val.is(JSON_NUMBER)); REQUIRE(val.as<std::string>().compare("-0.05") == 0); val = 1E3; REQUIRE(val.is(JSON_NUMBER)); REQUIRE(val.as<std::string>().compare("1000") == 0); val = -7.5; REQUIRE(val.is(JSON_NUMBER)); REQUIRE(val.as<unsigned int>() == 7); val = "5"; REQUIRE(val.is(JSON_STRING)); REQUIRE(val.as<int>() == 5); val = "5L"; REQUIRE(val.is(JSON_STRING)); REQUIRE(val.as<long>() == 5L); val = "\\"; REQUIRE(val.is(JSON_STRING)); REQUIRE(val.as<std::string>().compare("\\") == 0); val = true; REQUIRE(val.is(JSON_BOOL)); REQUIRE(val.as<bool>()); REQUIRE(val.as<int>() == 1); REQUIRE(val.as<std::string>() == "true"); val = false; REQUIRE(val.is(JSON_BOOL)); REQUIRE(!val.as<bool>()); REQUIRE(val.as<int>() == 0); REQUIRE(val.as<std::string>() == "false"); val = { true, false }; REQUIRE(val[0].is(JSON_BOOL)); REQUIRE(val[1].is(JSON_BOOL)); REQUIRE(val.is(JSON_ARRAY)); REQUIRE(val[0].as<bool>()); REQUIRE(!val[1].as<bool>()); val = { 1, .5, "hello world", true, false, null }; REQUIRE(val[0].is(JSON_NUMBER)); REQUIRE(val[1].is(JSON_NUMBER)); REQUIRE(val[2].is(JSON_STRING)); REQUIRE(val[3].is(JSON_BOOL)); REQUIRE(val[4].is(JSON_BOOL)); REQUIRE(val[5].is(JSON_NULL)); val = { {1,0,0}, {0,1,0},{0,0,1} }; REQUIRE(val.is(JSON_ARRAY)); REQUIRE(val.as<Array>().size() == 3); REQUIRE(val[0].is(JSON_ARRAY)); REQUIRE(val[1].is(JSON_ARRAY)); REQUIRE(val[2].is(JSON_ARRAY)); REQUIRE(val[0].as<Array>().size() == 3); REQUIRE(val[1].as<Array>().size() == 3); REQUIRE(val[2].as<Array>().size() == 3); REQUIRE(val[0][0].is(JSON_NUMBER)); REQUIRE(val[0][1].is(JSON_NUMBER)); REQUIRE(val[0][2].is(JSON_NUMBER)); REQUIRE(val[1][0].is(JSON_NUMBER)); REQUIRE(val[1][1].is(JSON_NUMBER)); REQUIRE(val[1][2].is(JSON_NUMBER)); REQUIRE(val[2][0].is(JSON_NUMBER)); REQUIRE(val[2][1].is(JSON_NUMBER)); REQUIRE(val[2][2].is(JSON_NUMBER)); std::string key = "property"; val = Object { { "property", "value" } }; REQUIRE(val.is(JSON_OBJECT)); REQUIRE(val["property"].is(JSON_STRING)); REQUIRE(val[key].is(JSON_STRING)); REQUIRE(val[std::string("property")].is(JSON_STRING)); REQUIRE(val["property"].as<std::string>().compare("value") == 0); val["property"] = 42; REQUIRE(val["property"].is(JSON_NUMBER)); REQUIRE(val[key].as<unsigned int>() == 42); } TEST_CASE( "base/parse", "Basic parsing") { Parser p; Printer printer; Value val; REQUIRE_THROWS(p.parse(val, "[]a")); REQUIRE_THROWS(p.parse(val, "a[]")); REQUIRE_NOTHROW(p.parse(val, "")); REQUIRE(val.is(JSON_NULL)); auto numbers = {"0", "1", "1E3", "1e-3", "0.5", "-.05e-07"}; for (auto number: numbers) { REQUIRE_NOTHROW(p.parse(val, number)); REQUIRE(val.is(JSON_NUMBER)); } REQUIRE_THROWS(p.parse(val, "-0.5w4")); std::vector<std::string> strings = { "\"\"", "\"0\"", "\"hello world\"", "\"äöüȩéáã\"" }; for (int i = 0; i < strings.size(); i++) { REQUIRE_NOTHROW(p.parse(val, strings[i])); REQUIRE(printer.print(val).compare(strings[i]) == 0); } std::map<std::string, std::string> escapes = { { "\"\\\\\"", "\"\\\"" }, { "\"\\/\"", "\"/\"" }, { "\"\\u5022\"", "\"倢\"" } }; for (auto pair: escapes) { REQUIRE_NOTHROW(p.parse(val, pair.first)); REQUIRE(printer.print(val).compare(pair.second) == 0); } REQUIRE_NOTHROW(p.parse(val, "true")); REQUIRE(val.is(JSON_BOOL)); REQUIRE(val.as<bool>()); REQUIRE(printer.print(val).compare("true") == 0); REQUIRE_NOTHROW(p.parse(val, "false")); REQUIRE(val.is(JSON_BOOL)); REQUIRE(!val.as<bool>()); REQUIRE(printer.print(val).compare("false") == 0); REQUIRE_NOTHROW(p.parse(val, "null")); REQUIRE(val.is(JSON_NULL)); REQUIRE(printer.print(val).compare("null") == 0); REQUIRE_NOTHROW(p.parse(val, "[]")); REQUIRE(val.is(JSON_ARRAY)); REQUIRE(printer.print(val).compare("[]") == 0); REQUIRE(val.as<Array>().size() == 0); REQUIRE_NOTHROW(p.parse(val, "[ 1, 2, 4 ]")); REQUIRE(val.is(JSON_ARRAY)); REQUIRE(printer.print(val).compare("[1,2,4]") == 0); REQUIRE(val.as<Array>().size() == 3); REQUIRE_THROWS(p.parse(val, "[")); REQUIRE_THROWS(p.parse(val, "]")); REQUIRE_THROWS(p.parse(val, "[[")); REQUIRE_THROWS(p.parse(val, "]]")); REQUIRE_THROWS(p.parse(val, "[,]")); REQUIRE_THROWS(p.parse(val, "[][]")); REQUIRE_THROWS(p.parse(val, "[1,]")); REQUIRE_THROWS(p.parse(val, "[,1]")); REQUIRE_THROWS(p.parse(val, "[1,2")); REQUIRE_THROWS(p.parse(val, "1,2]")); REQUIRE_THROWS(p.parse(val, "[[],[]")); REQUIRE_THROWS(p.parse(val, "[[],]]")); REQUIRE_THROWS(p.parse(val, "[[1,2,],[]]")); REQUIRE_THROWS(p.parse(val, "[[1,2,] []]")); REQUIRE_NOTHROW(p.parse(val, "[[]]")); REQUIRE_NOTHROW(p.parse(val, "[[[]]]")); REQUIRE_NOTHROW(p.parse(val, "[[],[]]")); REQUIRE_NOTHROW(p.parse(val, "[[[]],[[]]]")); REQUIRE_NOTHROW(p.parse(val, "[[[1]],[[2]]]")); REQUIRE_NOTHROW(p.parse(val, "[[[1,null,true,false,\"\"]],[[]]]")); REQUIRE(val[0][0][0].is(JSON_NUMBER)); REQUIRE(val[0][0][1].is(JSON_NULL)); REQUIRE(val[0][0][2].is(JSON_BOOL)); REQUIRE(val[0][0][3].is(JSON_BOOL)); REQUIRE(val[0][0][4].is(JSON_STRING)); REQUIRE(val[0][0].as<Array>().size() == 5); REQUIRE(printer.print(val).compare("[[[1,null,true,false,\"\"]],[[]]]") == 0); val[0][0].as<Array>().push_back(null); REQUIRE(val[0][0].as<Array>().size() == 5); val[0][0].asMutable<Array>().push_back(null); REQUIRE(val[0][0].as<Array>().size() == 6); REQUIRE_NOTHROW(p.parse(val, "{}")); REQUIRE_THROWS(p.parse(val, "{1}")); REQUIRE_THROWS(p.parse(val, "{{}}")); REQUIRE_NOTHROW(p.parse(val, "{\"a\": \"b\"}")); REQUIRE(val["a"].as<std::string>().compare("b") == 0); REQUIRE_THROWS(val.as<double>()); REQUIRE_NOTHROW(p.parse(val, "[{}]")); REQUIRE_NOTHROW(p.parse(val, "[{},{}]")); REQUIRE_NOTHROW(p.parse(val, "[{},[]]")); REQUIRE_NOTHROW(p.parse(val, "[[[{}]]]")); REQUIRE_THROWS(p.parse(val, "[[[{}]]")); REQUIRE_THROWS(p.parse(val, "[{}]]")); REQUIRE_THROWS(p.parse(val, "{[]}")); } TEST_CASE( "base/unicode", "Unicode escape handling") { Parser p; Printer printer; Value val; std::map<std::string, std::string> escapes = { { "\"\\u0041\"", "\"A\"" }, { "\"\\u0042\"", "\"B\"" }, { "\"\\u0043\"", "\"C\"" }, { "\"\\u0044\"", "\"D\"" }, { "\"\\u0045\"", "\"E\"" }, { "\"\\u0046\"", "\"F\"" }, { "\"\\u0047\"", "\"G\"" }, { "\"\\u0048\"", "\"H\"" }, { "\"\\u0049\"", "\"I\"" }, { "\"\\u0041\\u0042\\u0043\"", "\"ABC\"" }, { "\"\\u0041B\\u0043\"", "\"ABC\"" }, { "\"A\\u0042\\u0043\"", "\"ABC\"" }, { "\"\\u0041\\u0042C\"", "\"ABC\"" }, { "[\"\\u0041\\u0042C\"]", "[\"ABC\"]" }, { "\"\\u0041\\u004212\"", "\"AB12\"" }, }; for (auto pair: escapes) { REQUIRE_NOTHROW(p.parse(val, pair.first)); REQUIRE(printer.print(val).compare(pair.second) == 0); } REQUIRE_THROWS(p.parse(val, "\"\\u0fg\"")); REQUIRE_THROWS(p.parse(val, "\"\\u00\"")); REQUIRE_THROWS(p.parse(val, "\"\\u\"")); } TEST_CASE( "utils/bas", "Unicode escape handling") { Value val = Object { { "a", 1 }, { "b", 2 }, { "c", 3} }; PropertyList properties = traverse(val); REQUIRE(properties.size() == 3); PropertyList list = filter(traverse(val), [] (std::string name, Value& value) -> bool { return name.compare("b") == 0; }); REQUIRE(list.size() == 2); } int main (int argc, char* const argv[]) { exit(Catch::Main( argc, argv )); return 0; } <|endoftext|>
<commit_before>#include "rasterizer.h" #include <stdlib.h> #include <string.h> #include <assert.h> // Currently sized according to the Larrabee rasterizer's description #define FRAMEBUFFER_TILE_WIDTH_IN_PIXELS 128 #define FRAMEBUFFER_COARSE_BLOCK_WIDTH_IN_PIXELS 16 #define FRAMEBUFFER_FINE_BLOCK_WIDTH_IN_PIXELS 4 // Convenience #define FRAMEBUFFER_PIXELS_PER_TILE (FRAMEBUFFER_TILE_WIDTH_IN_PIXELS * FRAMEBUFFER_TILE_WIDTH_IN_PIXELS) // The swizzle masks, using alternating yxyxyx bit pattern for morton-code swizzling pixels in a tile. // This makes the pixels morton code swizzled within every rasterization level (fine/coarse/tile) // The tiles themselves are stored row major. // For examples of this concept, see: // https://software.intel.com/en-us/node/514045 // https://msdn.microsoft.com/en-us/library/windows/desktop/dn770442%28v=vs.85%29.aspx #define FRAMEBUFFER_TILE_X_SWIZZLE_MASK (0x55555555 & (FRAMEBUFFER_TILE_WIDTH_IN_PIXELS - 1)) #define FRAMEBUFFER_TILE_Y_SWIZZLE_MASK (~FRAMEBUFFER_TILE_X_SWIZZLE_MASK & (FRAMEBUFFER_TILE_WIDTH_IN_PIXELS - 1)) // If there are too many commands and this buffer gets filled up, // then the command buffer for that tile must be flushed. #define TILE_COMMAND_BUFFER_SIZE_IN_DWORDS 128 typedef struct tile_cmdbuf_t { // start and past-the-end of the allocation for the buffer uint32_t* cmdbuf_start; uint32_t* cmdbuf_end; // the next location where to read and write commands uint32_t* cmdbuf_read; uint32_t* cmdbuf_write; } tile_cmdbuf_t; typedef struct framebuffer_t { pixel_t* backbuffer; uint32_t* tile_cmdpool; tile_cmdbuf_t* tile_cmdbufs; uint32_t width_in_pixels; uint32_t height_in_pixels; // num_tiles_per_row * num_pixels_per_tile uint32_t pixels_per_row_of_tiles; // pixels_per_row_of_tiles * num_tile_rows uint32_t pixels_per_slice; } framebuffer_t; framebuffer_t* new_framebuffer(uint32_t width, uint32_t height) { // limits of the rasterizer's precision // this is based on an analysis of the range of results of the 2D cross product between two fixed16.8 numbers. assert(width < 16384); assert(height < 16384); framebuffer_t* fb = (framebuffer_t*)malloc(sizeof(framebuffer_t)); assert(fb); fb->width_in_pixels = width; fb->height_in_pixels = height; // pad framebuffer up to size of next tile // that way the rasterization code doesn't have to handlep otential out of bounds access after tile binning uint32_t padded_width_in_pixels = (width + (FRAMEBUFFER_TILE_WIDTH_IN_PIXELS - 1)) & -FRAMEBUFFER_TILE_WIDTH_IN_PIXELS; uint32_t padded_height_in_pixels = (height + (FRAMEBUFFER_TILE_WIDTH_IN_PIXELS - 1)) & -FRAMEBUFFER_TILE_WIDTH_IN_PIXELS; uint32_t width_in_tiles = padded_width_in_pixels / FRAMEBUFFER_TILE_WIDTH_IN_PIXELS; uint32_t height_in_tiles = padded_height_in_pixels / FRAMEBUFFER_TILE_WIDTH_IN_PIXELS; uint32_t total_num_tiles = width_in_tiles * height_in_tiles; fb->pixels_per_row_of_tiles = padded_width_in_pixels * FRAMEBUFFER_TILE_WIDTH_IN_PIXELS; fb->pixels_per_slice = padded_height_in_pixels / FRAMEBUFFER_TILE_WIDTH_IN_PIXELS * fb->pixels_per_row_of_tiles; fb->backbuffer = (pixel_t*)malloc(fb->pixels_per_slice * sizeof(pixel_t)); assert(fb->backbuffer); // clear to black/transparent initially memset(fb->backbuffer, 0, fb->pixels_per_slice * sizeof(pixel_t)); fb->tile_cmdpool = (uint32_t*)malloc(total_num_tiles * TILE_COMMAND_BUFFER_SIZE_IN_DWORDS * sizeof(uint32_t)); assert(fb->tile_cmdpool); fb->tile_cmdbufs = (tile_cmdbuf_t*)malloc(total_num_tiles * sizeof(tile_cmdbuf_t)); assert(fb->tile_cmdbufs); for (uint32_t i = 0; i < total_num_tiles; i++) { fb->tile_cmdbufs[i].cmdbuf_start = &fb->tile_cmdpool[i * TILE_COMMAND_BUFFER_SIZE_IN_DWORDS]; fb->tile_cmdbufs[i].cmdbuf_end = fb->tile_cmdbufs[i].cmdbuf_start + TILE_COMMAND_BUFFER_SIZE_IN_DWORDS; fb->tile_cmdbufs[i].cmdbuf_read = fb->tile_cmdbufs[i].cmdbuf_start; fb->tile_cmdbufs[i].cmdbuf_write = fb->tile_cmdbufs[i].cmdbuf_start; } return fb; } void delete_framebuffer(framebuffer_t* fb) { if (!fb) return; free(fb->tile_cmdbufs); free(fb->tile_cmdpool); free(fb->backbuffer); free(fb); } void framebuffer_resolve(framebuffer_t* fb) { } void framebuffer_pack_row_major(framebuffer_t* fb, uint32_t x, uint32_t y, uint32_t width, uint32_t height, pixelformat_t format, void* data) { assert(fb); assert(x < fb->width_in_pixels); assert(y < fb->height_in_pixels); assert(width <= fb->width_in_pixels); assert(height <= fb->height_in_pixels); assert(x + width <= fb->width_in_pixels); assert(y + height <= fb->height_in_pixels); assert(data); uint32_t topleft_tile_y = y / FRAMEBUFFER_TILE_WIDTH_IN_PIXELS; uint32_t topleft_tile_x = x / FRAMEBUFFER_TILE_WIDTH_IN_PIXELS; uint32_t bottomright_tile_y = (y + (height - 1)) / FRAMEBUFFER_TILE_WIDTH_IN_PIXELS; uint32_t bottomright_tile_x = (x + (width - 1)) / FRAMEBUFFER_TILE_WIDTH_IN_PIXELS; uint32_t dst_i = 0; uint32_t curr_tile_row_start = topleft_tile_y * fb->pixels_per_row_of_tiles + topleft_tile_x * FRAMEBUFFER_PIXELS_PER_TILE; for (uint32_t tile_y = topleft_tile_y; tile_y <= bottomright_tile_y; tile_y++) { uint32_t curr_tile_start = curr_tile_row_start; for (uint32_t tile_x = topleft_tile_x; tile_x <= bottomright_tile_x; tile_x++) { for (uint32_t pixel_y = 0, pixel_y_bits = 0; pixel_y < FRAMEBUFFER_TILE_WIDTH_IN_PIXELS; pixel_y++, pixel_y_bits = (pixel_y_bits - FRAMEBUFFER_TILE_Y_SWIZZLE_MASK) & FRAMEBUFFER_TILE_Y_SWIZZLE_MASK) { for (uint32_t pixel_x = 0, pixel_x_bits = 0; pixel_x < FRAMEBUFFER_TILE_WIDTH_IN_PIXELS; pixel_x++, pixel_x_bits = (pixel_x_bits - FRAMEBUFFER_TILE_X_SWIZZLE_MASK) & FRAMEBUFFER_TILE_X_SWIZZLE_MASK) { uint32_t src_y = tile_y * FRAMEBUFFER_TILE_WIDTH_IN_PIXELS + pixel_y; uint32_t src_x = tile_x * FRAMEBUFFER_TILE_WIDTH_IN_PIXELS + pixel_x; // don't copy pixels outside src rectangle region if (src_y < y || src_y >= y + height) continue; if (src_x < x || src_x >= x + width) continue; uint32_t src_i = curr_tile_start + (pixel_y_bits | pixel_x_bits); pixel_t src = fb->backbuffer[src_i]; if (format == pixelformat_r8g8b8a8_unorm) { uint8_t* dst = (uint8_t*)data + dst_i * 4; dst[0] = (uint8_t)((src & 0x00FF0000) >> 16); dst[1] = (uint8_t)((src & 0x0000FF00) >> 8); dst[2] = (uint8_t)((src & 0x000000FF) >> 0); dst[3] = (uint8_t)((src & 0xFF000000) >> 24); } else if (format == pixelformat_b8g8r8a8_unorm) { uint8_t* dst = (uint8_t*)data + dst_i * 4; dst[0] = (uint8_t)((src & 0x000000FF) >> 0); dst[1] = (uint8_t)((src & 0x0000FF00) >> 8); dst[2] = (uint8_t)((src & 0x00FF0000) >> 16); dst[3] = (uint8_t)((src & 0xFF000000) >> 24); } else { assert(!"Unknown pixel format"); } dst_i++; } } curr_tile_start += FRAMEBUFFER_PIXELS_PER_TILE; } curr_tile_row_start += fb->pixels_per_row_of_tiles; } } // hack uint32_t g_Color; void rasterize_triangle_fixed16_8( framebuffer_t* fb, uint32_t window_x0, uint32_t window_y0, uint32_t window_z0, uint32_t window_x1, uint32_t window_y1, uint32_t window_z1, uint32_t window_x2, uint32_t window_y2, uint32_t window_z2) { }<commit_msg>unit tests, bug fixes, pack_row_major perf improvement<commit_after>#include "rasterizer.h" #include <stdlib.h> #include <string.h> #include <assert.h> #include <stdio.h> #include <intrin.h> // runs unit tests automatically when the library is used #define RASTERIZER_UNIT_TESTS #ifdef RASTERIZER_UNIT_TESTS void run_rasterizer_unit_tests(); #endif // Sized according to the Larrabee rasterizer's description #define FRAMEBUFFER_TILE_WIDTH_IN_PIXELS 128 #define FRAMEBUFFER_COARSE_BLOCK_WIDTH_IN_PIXELS 16 #define FRAMEBUFFER_FINE_BLOCK_WIDTH_IN_PIXELS 4 // small sizes (for testing) // #define FRAMEBUFFER_TILE_WIDTH_IN_PIXELS 4 // #define FRAMEBUFFER_COARSE_BLOCK_WIDTH_IN_PIXELS 2 // #define FRAMEBUFFER_FINE_BLOCK_WIDTH_IN_PIXELS 1 // Convenience #define FRAMEBUFFER_PIXELS_PER_TILE (FRAMEBUFFER_TILE_WIDTH_IN_PIXELS * FRAMEBUFFER_TILE_WIDTH_IN_PIXELS) // The swizzle masks, using alternating yxyxyx bit pattern for morton-code swizzling pixels in a tile. // This makes the pixels morton code swizzled within every rasterization level (fine/coarse/tile) // The tiles themselves are stored row major. // For examples of this concept, see: // https://software.intel.com/en-us/node/514045 // https://msdn.microsoft.com/en-us/library/windows/desktop/dn770442%28v=vs.85%29.aspx #define FRAMEBUFFER_TILE_X_SWIZZLE_MASK (0x55555555 & (FRAMEBUFFER_PIXELS_PER_TILE - 1)) #define FRAMEBUFFER_TILE_Y_SWIZZLE_MASK (0xAAAAAAAA & (FRAMEBUFFER_PIXELS_PER_TILE - 1)) // If there are too many commands and this buffer gets filled up, // then the command buffer for that tile must be flushed. #define TILE_COMMAND_BUFFER_SIZE_IN_DWORDS 128 // parallel bit deposit low-order source bits according to mask bits #ifdef __AVX2__ __forceinline uint32_t pdep_u32(uint32_t source, uint32_t mask) { return _pdep_u32(source, mask); } #else __forceinline uint32_t pdep_u32(uint32_t source, uint32_t mask) { // horribly inefficient, but that's life without AVX2. // however, typically not a problem since you only need to swizzle once up front. uint32_t dst = 0; for (uint32_t mask_i = 0, dst_i = 0; mask_i < 32; mask_i++) { if (mask & (1 << mask_i)) { uint32_t src_bit = (source & (1 << dst_i)) >> dst_i; dst |= src_bit << mask_i; dst_i++; } } return dst; } #endif typedef struct tile_cmdbuf_t { // start and past-the-end of the allocation for the buffer uint32_t* cmdbuf_start; uint32_t* cmdbuf_end; // the next location where to read and write commands uint32_t* cmdbuf_read; uint32_t* cmdbuf_write; } tile_cmdbuf_t; typedef struct framebuffer_t { pixel_t* backbuffer; uint32_t* tile_cmdpool; tile_cmdbuf_t* tile_cmdbufs; uint32_t width_in_pixels; uint32_t height_in_pixels; // num_tiles_per_row * num_pixels_per_tile uint32_t pixels_per_row_of_tiles; // pixels_per_row_of_tiles * num_tile_rows uint32_t pixels_per_slice; } framebuffer_t; framebuffer_t* new_framebuffer(uint32_t width, uint32_t height) { #ifdef RASTERIZER_UNIT_TESTS static int ran_rasterizer_unit_tests_once = 0; if (!ran_rasterizer_unit_tests_once) { // set this before running the tests, so that unit tests can create framebuffers without causing infinite recursion ran_rasterizer_unit_tests_once = 1; run_rasterizer_unit_tests(); } #endif // limits of the rasterizer's precision // this is based on an analysis of the range of results of the 2D cross product between two fixed16.8 numbers. assert(width < 16384); assert(height < 16384); framebuffer_t* fb = (framebuffer_t*)malloc(sizeof(framebuffer_t)); assert(fb); fb->width_in_pixels = width; fb->height_in_pixels = height; // pad framebuffer up to size of next tile // that way the rasterization code doesn't have to handlep otential out of bounds access after tile binning uint32_t padded_width_in_pixels = (width + (FRAMEBUFFER_TILE_WIDTH_IN_PIXELS - 1)) & -FRAMEBUFFER_TILE_WIDTH_IN_PIXELS; uint32_t padded_height_in_pixels = (height + (FRAMEBUFFER_TILE_WIDTH_IN_PIXELS - 1)) & -FRAMEBUFFER_TILE_WIDTH_IN_PIXELS; uint32_t width_in_tiles = padded_width_in_pixels / FRAMEBUFFER_TILE_WIDTH_IN_PIXELS; uint32_t height_in_tiles = padded_height_in_pixels / FRAMEBUFFER_TILE_WIDTH_IN_PIXELS; uint32_t total_num_tiles = width_in_tiles * height_in_tiles; fb->pixels_per_row_of_tiles = padded_width_in_pixels * FRAMEBUFFER_TILE_WIDTH_IN_PIXELS; fb->pixels_per_slice = padded_height_in_pixels / FRAMEBUFFER_TILE_WIDTH_IN_PIXELS * fb->pixels_per_row_of_tiles; fb->backbuffer = (pixel_t*)malloc(fb->pixels_per_slice * sizeof(pixel_t)); assert(fb->backbuffer); // clear to black/transparent initially memset(fb->backbuffer, 0, fb->pixels_per_slice * sizeof(pixel_t)); // allocate command lists for each tile fb->tile_cmdpool = (uint32_t*)malloc(total_num_tiles * TILE_COMMAND_BUFFER_SIZE_IN_DWORDS * sizeof(uint32_t)); assert(fb->tile_cmdpool); fb->tile_cmdbufs = (tile_cmdbuf_t*)malloc(total_num_tiles * sizeof(tile_cmdbuf_t)); assert(fb->tile_cmdbufs); // command lists are circular queues that are initially empty for (uint32_t i = 0; i < total_num_tiles; i++) { fb->tile_cmdbufs[i].cmdbuf_start = &fb->tile_cmdpool[i * TILE_COMMAND_BUFFER_SIZE_IN_DWORDS]; fb->tile_cmdbufs[i].cmdbuf_end = fb->tile_cmdbufs[i].cmdbuf_start + TILE_COMMAND_BUFFER_SIZE_IN_DWORDS; fb->tile_cmdbufs[i].cmdbuf_read = fb->tile_cmdbufs[i].cmdbuf_start; fb->tile_cmdbufs[i].cmdbuf_write = fb->tile_cmdbufs[i].cmdbuf_start; } return fb; } void delete_framebuffer(framebuffer_t* fb) { if (!fb) return; free(fb->tile_cmdbufs); free(fb->tile_cmdpool); free(fb->backbuffer); free(fb); } void framebuffer_resolve(framebuffer_t* fb) { assert(fb); } void framebuffer_pack_row_major(framebuffer_t* fb, uint32_t x, uint32_t y, uint32_t width, uint32_t height, pixelformat_t format, void* data) { assert(fb); assert(x < fb->width_in_pixels); assert(y < fb->height_in_pixels); assert(width <= fb->width_in_pixels); assert(height <= fb->height_in_pixels); assert(x + width <= fb->width_in_pixels); assert(y + height <= fb->height_in_pixels); assert(data); uint32_t topleft_tile_y = y / FRAMEBUFFER_TILE_WIDTH_IN_PIXELS; uint32_t topleft_tile_x = x / FRAMEBUFFER_TILE_WIDTH_IN_PIXELS; uint32_t bottomright_tile_y = (y + (height - 1)) / FRAMEBUFFER_TILE_WIDTH_IN_PIXELS; uint32_t bottomright_tile_x = (x + (width - 1)) / FRAMEBUFFER_TILE_WIDTH_IN_PIXELS; uint32_t dst_i = 0; uint32_t curr_tile_row_start = topleft_tile_y * fb->pixels_per_row_of_tiles + topleft_tile_x * FRAMEBUFFER_PIXELS_PER_TILE; for (uint32_t tile_y = topleft_tile_y; tile_y <= bottomright_tile_y; tile_y++) { uint32_t curr_tile_start = curr_tile_row_start; for (uint32_t tile_x = topleft_tile_x; tile_x <= bottomright_tile_x; tile_x++) { uint32_t topleft_y = tile_y * FRAMEBUFFER_TILE_WIDTH_IN_PIXELS; uint32_t topleft_x = tile_x * FRAMEBUFFER_TILE_WIDTH_IN_PIXELS; uint32_t bottomright_y = topleft_y + FRAMEBUFFER_TILE_WIDTH_IN_PIXELS; uint32_t bottomright_x = topleft_x + FRAMEBUFFER_TILE_WIDTH_IN_PIXELS; uint32_t pixel_y_min = topleft_y < y ? y : topleft_y; uint32_t pixel_x_min = topleft_x < x ? x : topleft_x; uint32_t pixel_y_max = bottomright_y > y + height ? y + height : bottomright_y; uint32_t pixel_x_max = bottomright_x > x + width ? x + width : bottomright_x; for (uint32_t pixel_y = pixel_y_min, pixel_y_bits = pdep_u32(topleft_y, FRAMEBUFFER_TILE_Y_SWIZZLE_MASK); pixel_y < pixel_y_max; pixel_y++, pixel_y_bits = (pixel_y_bits - FRAMEBUFFER_TILE_Y_SWIZZLE_MASK) & FRAMEBUFFER_TILE_Y_SWIZZLE_MASK) { for (uint32_t pixel_x = pixel_x_min, pixel_x_bits = pdep_u32(topleft_x, FRAMEBUFFER_TILE_X_SWIZZLE_MASK); pixel_x < pixel_x_max; pixel_x++, pixel_x_bits = (pixel_x_bits - FRAMEBUFFER_TILE_X_SWIZZLE_MASK) & FRAMEBUFFER_TILE_X_SWIZZLE_MASK) { uint32_t src_i = curr_tile_start + (pixel_y_bits | pixel_x_bits); pixel_t src = fb->backbuffer[src_i]; if (format == pixelformat_r8g8b8a8_unorm) { uint8_t* dst = (uint8_t*)data + dst_i * 4; dst[0] = (uint8_t)((src & 0x00FF0000) >> 16); dst[1] = (uint8_t)((src & 0x0000FF00) >> 8); dst[2] = (uint8_t)((src & 0x000000FF) >> 0); dst[3] = (uint8_t)((src & 0xFF000000) >> 24); } else if (format == pixelformat_b8g8r8a8_unorm) { uint8_t* dst = (uint8_t*)data + dst_i * 4; dst[0] = (uint8_t)((src & 0x000000FF) >> 0); dst[1] = (uint8_t)((src & 0x0000FF00) >> 8); dst[2] = (uint8_t)((src & 0x00FF0000) >> 16); dst[3] = (uint8_t)((src & 0xFF000000) >> 24); } else { assert(!"Unknown pixel format"); } dst_i++; } } curr_tile_start += FRAMEBUFFER_PIXELS_PER_TILE; } curr_tile_row_start += fb->pixels_per_row_of_tiles; } } // hack uint32_t g_Color; void rasterize_triangle_fixed16_8( framebuffer_t* fb, uint32_t window_x0, uint32_t window_y0, uint32_t window_z0, uint32_t window_x1, uint32_t window_y1, uint32_t window_z1, uint32_t window_x2, uint32_t window_y2, uint32_t window_z2) { } #ifdef RASTERIZER_UNIT_TESTS void run_rasterizer_unit_tests() { // pdep tests // source mask assert(pdep_u32(0b000, 0b000000) == 0b000000); assert(pdep_u32(0b001, 0b000001) == 0b000001); assert(pdep_u32(0b001, 0b000010) == 0b000010); assert(pdep_u32(0b011, 0b001100) == 0b001100); assert(pdep_u32(0b101, 0b101010) == 0b100010); assert(pdep_u32(0b010, 0b010101) == 0b000100); // swizzle test { uint32_t w = FRAMEBUFFER_TILE_WIDTH_IN_PIXELS * 2; uint32_t h = FRAMEBUFFER_TILE_WIDTH_IN_PIXELS * 2; framebuffer_t* fb = new_framebuffer(w, h); uint8_t* rowmajor_data = new uint8_t[w * h * 4]; // write indices of pixels linearly in memory (ignoring swizzling) // this will be read back and checked to verify the layout // For tiles of 4x4 pixels, a 8x8 row major image should look something like: // 0 1 4 5 | 16 17 20 21 // 2 3 6 7 | 18 19 22 23 // 8 9 12 13 | 24 25 28 29 // 10 11 14 15 | 26 27 30 31 // ------------------------- // 32 33 36 37 | 48 49 52 53 // 34 35 38 39 | 50 51 54 55 // 40 41 44 45 | 56 57 60 61 // 42 43 46 47 | 58 59 62 63 // see: https://en.wikipedia.org/wiki/Z-order_curve for (uint32_t i = 0; i < fb->pixels_per_slice; i++) { fb->backbuffer[i] = i; } framebuffer_pack_row_major(fb, 0, 0, w, h, pixelformat_r8g8b8a8_unorm, rowmajor_data); for (uint32_t y = 0; y < h; y++) { uint32_t tile_y = y / FRAMEBUFFER_TILE_WIDTH_IN_PIXELS; for (uint32_t x = 0; x < w; x++) { uint32_t tile_x = x / FRAMEBUFFER_TILE_WIDTH_IN_PIXELS; uint32_t tile_i = tile_y * (fb->pixels_per_row_of_tiles / FRAMEBUFFER_PIXELS_PER_TILE) + tile_x; uint32_t topleft_pixel_i = tile_i * FRAMEBUFFER_PIXELS_PER_TILE; uint32_t tile_relative_x = x - tile_x * FRAMEBUFFER_TILE_WIDTH_IN_PIXELS; uint32_t tile_relative_y = y - tile_y * FRAMEBUFFER_TILE_WIDTH_IN_PIXELS; uint32_t rowmajor_i = topleft_pixel_i + (tile_relative_y * FRAMEBUFFER_TILE_WIDTH_IN_PIXELS + tile_relative_x); uint32_t xmask = FRAMEBUFFER_TILE_X_SWIZZLE_MASK; uint32_t ymask = FRAMEBUFFER_TILE_Y_SWIZZLE_MASK; uint32_t xbits = pdep_u32(x, xmask); uint32_t ybits = pdep_u32(y, ymask); uint32_t swizzled_i = topleft_pixel_i + xbits + ybits; assert(rowmajor_data[rowmajor_i * 4 + 0] == ((fb->backbuffer[swizzled_i] & 0x00FF0000) >> 16)); assert(rowmajor_data[rowmajor_i * 4 + 1] == ((fb->backbuffer[swizzled_i] & 0x0000FF00) >> 8)); assert(rowmajor_data[rowmajor_i * 4 + 2] == ((fb->backbuffer[swizzled_i] & 0x000000FF) >> 0)); assert(rowmajor_data[rowmajor_i * 4 + 3] == ((fb->backbuffer[swizzled_i] & 0xFF000000) >> 24)); } } delete[] rowmajor_data; delete_framebuffer(fb); } } #endif<|endoftext|>
<commit_before>// Copyright 2013 Sean McKenna // // 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. // // a ray tracer in C++ // libraries, namespace #include <thread> #include <fstream> #include <iostream> #include <sstream> #include <string> #include <cmath> #include <random> #include "library/loadXML.cpp" #include "library/scene.cpp" using namespace std; // scene to load (project #) + all ray tracing options & settings string xml = "scenes/prj11-1.xml"; bool printXML = false; bool zBuffer = false; bool sampleCount = false; int bounceCount = 5; int sampleMin = 4; int sampleMax = 32; float sampleThreshold = 0.001; int shadowMin = 8; int shadowMax = 32; bool gammaCorr = true; bool globalIllum = true; bool irradCache = true; int samplesGI = 16; // variables for ray tracing int w; int h; int size; Color24* img; float* zImg; float* sampleImg; IrradianceMap im; // variables for anti-aliasing brightness calculations (XYZ, Lab) float perR = 0.2126; float perG = 0.7152; float perB = 0.0722; float Ycutoff = pow(6.0 / 29.0, 3.0); float Yprecalc = (1.0 / 3.0) * pow(29.0 / 6.0, 2.0); // setup threading static const int numThreads = 8; void rayTracing(int i); // for camera ray generation void cameraRayVars(); float imageDistance = 1.0; Point *imageTopLeftV; Point *dXV; Point *dYV; Point *dVx; Point *dVy; Point firstPixel; Transformation* c; Point cameraRay(float pX, float pY, Point offset); // ray tracer int main(){ // load scene: root node, camera, image (and set shadow casting variables) loadScene(xml, printXML, shadowMin, shadowMax, globalIllum, irradCache, samplesGI); // set the scene as the root node setScene(rootNode); // set variables for ray tracing w = render.getWidth(); h = render.getHeight(); size = render.getSize(); img = render.getRender(); zImg = render.getZBuffer(); sampleImg = render.getSample(); if(globalIllum && irradCache) im.Initialize(w, h); // set variables for generating camera rays cameraRayVars(); // compute an irradiance cache for global illumination if(globalIllum && irradCache){ // subdivide our image to compute indirect illumination bool subdivide = true; while(subdivide){ // check if we are on final subdivide if(im.GetSubdivLevel() == 0) subdivide = false; // calculate indirect illumination // subdivide (if necessary) if(subdivide) im.Subdivide(); } } // sample test output (know irrad map done) cout << "onto ray tracing!" << endl; // start ray tracing loop (in parallel with threads) thread t[numThreads]; for(int i = 0; i < numThreads; i++) t[i] = thread(rayTracing, i); // when finished, join all threads back to main for(int i = 0; i < numThreads; i++) t[i].join(); // output ray-traced image & z-buffer & sample count image (if set) render.save("images/image.ppm"); if(zBuffer){ render.computeZImage(); render.saveZImage("images/imageZ.ppm"); } if(sampleCount){ render.computeSampleImage(); render.saveSampleImage("images/imageSample.ppm"); } } // ray tracing loop (for an individual pixel) void rayTracing(int i){ // initial starting pixel int pixel = i; // setup random generator for anti-aliasing & depth-of-field mt19937 rnd; uniform_real_distribution<float> dist{0.0, 1.0}; // thread continuation condition while(pixel < size){ // number of samples int s = 0; // establish pixel location (center) float pX = pixel % w; float pY = pixel / w; // color values to store across samples Color col; Color colAvg; float zAvg = 0.0; float rVar = 0.0; float gVar = 0.0; float bVar = 0.0; float var = sampleThreshold; float brightness = 0.0; // random rotation of Halton sequence on circle of confusion float dcR = dist(rnd) * 2.0 * M_PI; // compute multi-adaptive sampling for each pixel (anti-aliasing) while(s < sampleMin || (s != sampleMax && (rVar * perR > var + brightness * var || gVar * perG > var + brightness * var || bVar * perB > var + brightness * var))){ // grab Halton sequence to shift point by on image plane float dpX = centerHalton(Halton(s, 3)); float dpY = centerHalton(Halton(s, 2)); // grab Halton sequence to shift point along circle of confusion float dcS = sqrt(Halton(s, 2)) * camera.dof; // grab Halton sequence to shift point around circle of confusion float dcT = Halton(s, 3) * 2.0 * M_PI; // compute the offset for depth of field sampling Point posOffset = (*dVx * cos(dcR + dcT) + *dVy * sin(dcR + dcT)) * dcS; // transform ray into world space (offset by Halton seqeunce for sampling) Point rayDir = cameraRay(pX + dpX, pY + dpY, posOffset); Cone *ray = new Cone(); ray->pos = camera.pos + c->transformFrom(posOffset); ray->dir = c->transformFrom(rayDir); ray->radius = 0.0; ray->tan = dXV->x / (2.0 * imageDistance); // traverse through scene DOM // transform rays into model space // detect ray intersections and get back HitInfo HitInfo hi = HitInfo(); bool hit = traceRay(*ray, hi); // update z-buffer, if necessary if(zBuffer) zAvg = (zAvg * s + hi.z) / (float) (s + 1); // if hit, get the node's material if(hit){ Node *n = hi.node; Material *m; if(n) m = n->getMaterial(); // if there is a material, shade the pixel // 5-passes for reflections and refractions if(m) col = m->shade(*ray, hi, lights, bounceCount); // otherwise color it white (as a hit) else col.Set(0.929, 0.929, 0.929); // if we hit nothing, draw the background }else{ Point p = Point((float) pX / w, (float) pY / h, 0.0); Color b = background.sample(p); col = b; } // compute average color float rAvg = (colAvg.r * s + col.r) / (float) (s + 1); float gAvg = (colAvg.g * s + col.g) / (float) (s + 1); float bAvg = (colAvg.b * s + col.b) / (float) (s + 1); colAvg.Set(rAvg, gAvg, bAvg); // compute color variances rVar = (rVar * s + (col.r - rAvg) * (col.r - rAvg)) / (float) (s + 1); gVar = (gVar * s + (col.g - gAvg) * (col.g - gAvg)) / (float) (s + 1); bVar = (bVar * s + (col.b - bAvg) * (col.b - bAvg)) / (float) (s + 1); // calculate and update brightness average using XYZ and Lab space float Y = perR * rAvg + perG * gAvg + perB * bAvg; float Y13 = Y; if(Y13 > Ycutoff) Y13 = pow(Y13, 1.0 / 3.0); else Y13 = Yprecalc * Y13 + (4.0 / 29.0); brightness = (116.0 * Y13 - 16.0) / 100.0; // increment sample count s++; // watch for errors at any individual sample, terminate thread if so if(colAvg[0] != colAvg[0] || colAvg[1] != colAvg[1] || colAvg[2] != colAvg[2]){ cout << "ERROR - pixel " << pixel << " & sample " << s << endl; s = sampleMax; pixel = size; } } // gamma correction if(gammaCorr){ colAvg.r = pow(colAvg.r, 1.0 / 2.2); colAvg.g = pow(colAvg.g, 1.0 / 2.2); colAvg.b = pow(colAvg.b, 1.0 / 2.2); } // color the pixel image img[pixel] = Color24(colAvg); // update the z-buffer image, if necessary if(zBuffer) zImg[pixel] = zAvg; // update the sample count image, if necessary if(sampleCount) sampleImg[pixel] = s; // re-assign next pixel (naive, but works) pixel += numThreads; } } // create variables for camera ray generation void cameraRayVars(){ float fov = camera.fov * M_PI / 180.0; float aspectRatio = (float) w / (float) h; imageDistance = camera.focalDist; float imageTipY = imageDistance * tan(fov / 2.0); float imageTipX = imageTipY * aspectRatio; float dX = (2.0 * imageTipX) / (float) w; float dY = (2.0 * imageTipY) / (float) h; imageTopLeftV = new Point(-imageTipX, imageTipY, -imageDistance); dXV = new Point(dX, 0.0, 0.0); dYV = new Point(0.0, -dY, 0.0); firstPixel = *imageTopLeftV + (*dXV * 0.5) + (*dYV * 0.5); // set up camera transformation (only need to rotate coordinates) c = new Transformation(); Matrix *rotate = new cyMatrix3f(); rotate->Set(camera.cross, camera.up, -camera.dir); c->transform(*rotate); // get normalized rays on the focal plane dVx = new Point(1.0, 0.0, 0.0); dVy = new Point(0.0, 1.0, 0.0); } // compute camera ray direction Point cameraRay(float pX, float pY, Point offset){ Point ray = firstPixel + (*dXV * pX) + (*dYV * pY) - offset; ray.Normalize(); return ray; } <commit_msg>add test of the irradiance map variables and prepping the indirect light for ray caching<commit_after>// Copyright 2013 Sean McKenna // // 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. // // a ray tracer in C++ // libraries, namespace #include <thread> #include <fstream> #include <iostream> #include <sstream> #include <string> #include <cmath> #include <random> #include "library/loadXML.cpp" #include "library/scene.cpp" using namespace std; // scene to load (project #) + all ray tracing options & settings string xml = "scenes/prj11-1.xml"; bool printXML = false; bool zBuffer = false; bool sampleCount = false; int bounceCount = 5; int sampleMin = 4; int sampleMax = 32; float sampleThreshold = 0.001; int shadowMin = 8; int shadowMax = 32; bool gammaCorr = true; bool globalIllum = true; bool irradCache = true; int samplesGI = 16; // variables for ray tracing int w; int h; int size; Color24* img; float* zImg; float* sampleImg; IrradianceMap im; // variables for anti-aliasing brightness calculations (XYZ, Lab) float perR = 0.2126; float perG = 0.7152; float perB = 0.0722; float Ycutoff = pow(6.0 / 29.0, 3.0); float Yprecalc = (1.0 / 3.0) * pow(29.0 / 6.0, 2.0); // setup threading static const int numThreads = 8; void rayTracing(int i); void rayTracingCache(int i); // for camera ray generation void cameraRayVars(); float imageDistance = 1.0; Point *imageTopLeftV; Point *dXV; Point *dYV; Point *dVx; Point *dVy; Point firstPixel; Transformation* c; Point cameraRay(float pX, float pY, Point offset); // ray tracer int main(){ // load scene: root node, camera, image (and set shadow casting variables) loadScene(xml, printXML, shadowMin, shadowMax, globalIllum, irradCache, samplesGI); // set the scene as the root node setScene(rootNode); // set variables for ray tracing w = render.getWidth(); h = render.getHeight(); size = render.getSize(); img = render.getRender(); zImg = render.getZBuffer(); sampleImg = render.getSample(); if(globalIllum && irradCache) im.Initialize(w, h); // set variables for generating camera rays cameraRayVars(); // compute an irradiance cache for global illumination if(globalIllum && irradCache){ // caching light list LightList lightCache; lightCache.deleteAll(); string name = "indirect"; IndirectLight *l = new IndirectLight(); Light *light = NULL; l->setLightList(&lights); l->setEnvironment(environment); l->setSamples(samplesGI); light = l; light->setName(name); lightCache.push_back(light); // subdivide our image to compute indirect illumination bool subdivide = true; while(subdivide){ // check if we are on final subdivide if(im.GetSubdivLevel() == 0) subdivide = false; // calculate indirect illumination int cnt = 0; for(int i = 0; i < im.GetDataCount(); i++){ if(im.IsValid(i)) cnt++; } cout << "size: " << im.GetDataCount() << endl; cout << "valid: " << cnt << endl; float x; float y; im.GetPosition(32, x, y); cout << "(x, y): " << x << ", " << y << endl; int pix = x + y * w; cout << "pixel #" << pix << endl << endl; // subdivide (if necessary) if(subdivide) im.Subdivide(); } } // sample test output (know irrad map done) cout << "onto ray tracing!" << endl; // start ray tracing loop (in parallel with threads) thread t[numThreads]; for(int i = 0; i < numThreads; i++) t[i] = thread(rayTracing, i); // when finished, join all threads back to main for(int i = 0; i < numThreads; i++) t[i].join(); // output ray-traced image & z-buffer & sample count image (if set) render.save("images/image.ppm"); if(zBuffer){ render.computeZImage(); render.saveZImage("images/imageZ.ppm"); } if(sampleCount){ render.computeSampleImage(); render.saveSampleImage("images/imageSample.ppm"); } } // ray tracing loop (for an individual pixel) void rayTracing(int i){ // initial starting pixel int pixel = i; // setup random generator for anti-aliasing & depth-of-field mt19937 rnd; uniform_real_distribution<float> dist{0.0, 1.0}; // thread continuation condition while(pixel < size){ // number of samples int s = 0; // establish pixel location (center) float pX = pixel % w; float pY = pixel / w; // color values to store across samples Color col; Color colAvg; float zAvg = 0.0; float rVar = 0.0; float gVar = 0.0; float bVar = 0.0; float var = sampleThreshold; float brightness = 0.0; // random rotation of Halton sequence on circle of confusion float dcR = dist(rnd) * 2.0 * M_PI; // compute multi-adaptive sampling for each pixel (anti-aliasing) while(s < sampleMin || (s != sampleMax && (rVar * perR > var + brightness * var || gVar * perG > var + brightness * var || bVar * perB > var + brightness * var))){ // grab Halton sequence to shift point by on image plane float dpX = centerHalton(Halton(s, 3)); float dpY = centerHalton(Halton(s, 2)); // grab Halton sequence to shift point along circle of confusion float dcS = sqrt(Halton(s, 2)) * camera.dof; // grab Halton sequence to shift point around circle of confusion float dcT = Halton(s, 3) * 2.0 * M_PI; // compute the offset for depth of field sampling Point posOffset = (*dVx * cos(dcR + dcT) + *dVy * sin(dcR + dcT)) * dcS; // transform ray into world space (offset by Halton seqeunce for sampling) Point rayDir = cameraRay(pX + dpX, pY + dpY, posOffset); Cone *ray = new Cone(); ray->pos = camera.pos + c->transformFrom(posOffset); ray->dir = c->transformFrom(rayDir); ray->radius = 0.0; ray->tan = dXV->x / (2.0 * imageDistance); // traverse through scene DOM // transform rays into model space // detect ray intersections and get back HitInfo HitInfo hi = HitInfo(); bool hit = traceRay(*ray, hi); // update z-buffer, if necessary if(zBuffer) zAvg = (zAvg * s + hi.z) / (float) (s + 1); // if hit, get the node's material if(hit){ Node *n = hi.node; Material *m; if(n) m = n->getMaterial(); // if there is a material, shade the pixel // 5-passes for reflections and refractions if(m) col = m->shade(*ray, hi, lights, bounceCount); // otherwise color it white (as a hit) else col.Set(0.929, 0.929, 0.929); // if we hit nothing, draw the background }else{ Point p = Point((float) pX / w, (float) pY / h, 0.0); Color b = background.sample(p); col = b; } // compute average color float rAvg = (colAvg.r * s + col.r) / (float) (s + 1); float gAvg = (colAvg.g * s + col.g) / (float) (s + 1); float bAvg = (colAvg.b * s + col.b) / (float) (s + 1); colAvg.Set(rAvg, gAvg, bAvg); // compute color variances rVar = (rVar * s + (col.r - rAvg) * (col.r - rAvg)) / (float) (s + 1); gVar = (gVar * s + (col.g - gAvg) * (col.g - gAvg)) / (float) (s + 1); bVar = (bVar * s + (col.b - bAvg) * (col.b - bAvg)) / (float) (s + 1); // calculate and update brightness average using XYZ and Lab space float Y = perR * rAvg + perG * gAvg + perB * bAvg; float Y13 = Y; if(Y13 > Ycutoff) Y13 = pow(Y13, 1.0 / 3.0); else Y13 = Yprecalc * Y13 + (4.0 / 29.0); brightness = (116.0 * Y13 - 16.0) / 100.0; // increment sample count s++; // watch for errors at any individual sample, terminate thread if so if(colAvg[0] != colAvg[0] || colAvg[1] != colAvg[1] || colAvg[2] != colAvg[2]){ cout << "ERROR - pixel " << pixel << " & sample " << s << endl; s = sampleMax; pixel = size; } } // gamma correction if(gammaCorr){ colAvg.r = pow(colAvg.r, 1.0 / 2.2); colAvg.g = pow(colAvg.g, 1.0 / 2.2); colAvg.b = pow(colAvg.b, 1.0 / 2.2); } // color the pixel image img[pixel] = Color24(colAvg); // update the z-buffer image, if necessary if(zBuffer) zImg[pixel] = zAvg; // update the sample count image, if necessary if(sampleCount) sampleImg[pixel] = s; // re-assign next pixel (naive, but works) pixel += numThreads; } } // create variables for camera ray generation void cameraRayVars(){ float fov = camera.fov * M_PI / 180.0; float aspectRatio = (float) w / (float) h; imageDistance = camera.focalDist; float imageTipY = imageDistance * tan(fov / 2.0); float imageTipX = imageTipY * aspectRatio; float dX = (2.0 * imageTipX) / (float) w; float dY = (2.0 * imageTipY) / (float) h; imageTopLeftV = new Point(-imageTipX, imageTipY, -imageDistance); dXV = new Point(dX, 0.0, 0.0); dYV = new Point(0.0, -dY, 0.0); firstPixel = *imageTopLeftV + (*dXV * 0.5) + (*dYV * 0.5); // set up camera transformation (only need to rotate coordinates) c = new Transformation(); Matrix *rotate = new cyMatrix3f(); rotate->Set(camera.cross, camera.up, -camera.dir); c->transform(*rotate); // get normalized rays on the focal plane dVx = new Point(1.0, 0.0, 0.0); dVy = new Point(0.0, 1.0, 0.0); } // compute camera ray direction Point cameraRay(float pX, float pY, Point offset){ Point ray = firstPixel + (*dXV * pX) + (*dYV * pY) - offset; ray.Normalize(); return ray; } <|endoftext|>
<commit_before>/* Copyright (C) 2009 Adenilson Cavalcanti <[email protected]> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; by version 2 of the License or (at your * choice) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * */ #include "gcalresource.h" #include "settings.h" #include "settingsadaptor.h" #include <QtDBus/QDBusConnection> #include <kabc/addressee.h> #include <kabc/phonenumber.h> #include <kabc/key.h> #include <kabc/errorhandler.h> #include <kcal/event.h> #include <qstring.h> #include <KWindowSystem> #include <akonadi/changerecorder.h> #include <akonadi/itemfetchscope.h> #include <KUrl> extern "C" { #include <gcalendar.h> #include <gcal_status.h> } using namespace Akonadi; GCalResource::GCalResource( const QString &id ) : ResourceBase(id) { new SettingsAdaptor( Settings::self() ); QDBusConnection::sessionBus().registerObject( QLatin1String( "/Settings" ), Settings::self(), QDBusConnection::ExportAdaptors ); changeRecorder()->itemFetchScope().fetchFullPayload(); if (!(gcal = gcal_new(GCALENDAR))) exit(1); gcal_set_store_xml(gcal, 1); all_events.length = 0; all_events.entries = NULL; } GCalResource::~GCalResource() { gcal_cleanup_events(&all_events); pending.clear(); deleted.clear(); } void GCalResource::retrieveTimestamp(QString &timestamp) { timestamp = Settings::self()->timestamp(); } void GCalResource::saveTimestamp(QString &timestamp) { Settings::self()->setTimestamp(timestamp); Settings::self()->writeConfig(); } void GCalResource::retrieveCollections() { if(!authenticated) { kError() << "No authentication for Google Calendar available"; const QString message = i18nc("@info: status", "Not yet authenticated for " "use of Google Calendar"); emit error(message); emit status(Broken, message); return; } Collection c; c.setParent(Collection::root()); c.setRemoteId("google-calendar"); c.setName(name()); QStringList mimeTypes; mimeTypes << "text/calendar"; c.setContentMimeTypes(mimeTypes); Collection::List list; list << c; collectionsRetrieved(list); } void GCalResource::retrieveItems( const Akonadi::Collection &collection ) { Q_UNUSED(collection); Item::List items; int result; gcal_event_t event; QString timestamp; QByteArray t_byte; kError() << "\n............. retrieveItems ...........\n"; if (!authenticated) { kError() << "No authentication for Google calendar available"; const QString message = i18nc("@info:status", "Not yet authenticated for" " use of Google calendar"); emit error(message); emit status(Broken, message); return; } /* Query by updated */ retrieveTimestamp(timestamp); t_byte = timestamp.toLocal8Bit(); if (t_byte.length() > TIMESTAMP_SIZE) { //TODO: implement getUpdated //result = getUpdated(t_byte.data()); return; } kError() << "First retrieve"; if ((result = gcal_get_events(gcal, &all_events))) exit(1); /* GCalendar returns last updated entry as first element */ event = gcal_event_element(&all_events, 0); if (!event) { kError() << "Failed to retrieve last updated event."; const QString message = i18nc("@info:status", "Failed getting last updated" " event"); emit error(message); emit status(Broken, message); return; } timestamp = gcal_event_get_updated(event); saveTimestamp(timestamp); /* Each google entry has a unique ID and edit_url */ for (size_t i = 0; i < all_events.length; ++i) { Item item(QLatin1String("text/calendar")); KCal::Event kevent; QString temp; event = gcal_event_element(&all_events, i); temp = gcal_event_get_title(event); kevent.setSummary(temp); temp = gcal_event_get_where(event); kevent.setLocation(temp); temp = gcal_event_get_status(event); KCal::Incidence::Status status; if (gcal_event_is_deleted(event)) status = KCal::Incidence::StatusCanceled; else status = KCal::Incidence::StatusConfirmed; kevent.setStatus(status); temp = gcal_event_get_content(event); kevent.setDescription(temp); temp = gcal_event_get_start(event); temp = gcal_event_get_end(event); //TODO: create a KDateTime //kevent.set } } bool GCalResource::retrieveItem( const Akonadi::Item &item, const QSet<QByteArray> &parts ) { Q_UNUSED(parts); Q_UNUSED(item); return true; } void GCalResource::aboutToQuit() { // TODO: any cleanup you need to do while there is still an active // event loop. The resource will terminate after this method returns } void GCalResource::doSetOnline(bool online) { Q_UNUSED(online); } int GCalResource::getUpdated(char *timestamp) { Q_UNUSED(timestamp); return -1; } void GCalResource::configure( WId windowId ) { Q_UNUSED(windowId); } void GCalResource::itemAdded( const Akonadi::Item &item, const Akonadi::Collection &collection ) { Q_UNUSED(collection); Q_UNUSED(item); } void GCalResource::itemChanged( const Akonadi::Item &item, const QSet<QByteArray> &parts ) { Q_UNUSED(parts); Q_UNUSED(item); } void GCalResource::itemRemoved( const Akonadi::Item &item ) { Q_UNUSED(item); } AKONADI_RESOURCE_MAIN( GCalResource ) #include "gcalresource.moc" <commit_msg>Setting event duration (not happy with current code).<commit_after>/* Copyright (C) 2009 Adenilson Cavalcanti <[email protected]> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; by version 2 of the License or (at your * choice) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * */ #include "gcalresource.h" #include "settings.h" #include "settingsadaptor.h" #include <QtDBus/QDBusConnection> #include <QDate> #include <kabc/addressee.h> #include <kabc/phonenumber.h> #include <kabc/key.h> #include <kabc/errorhandler.h> #include <kcal/event.h> #include <kdatetime.h> #include <qstring.h> #include <KWindowSystem> #include <akonadi/changerecorder.h> #include <akonadi/itemfetchscope.h> #include <KUrl> extern "C" { #include <gcalendar.h> #include <gcal_status.h> } using namespace Akonadi; GCalResource::GCalResource( const QString &id ) : ResourceBase(id) { new SettingsAdaptor( Settings::self() ); QDBusConnection::sessionBus().registerObject( QLatin1String( "/Settings" ), Settings::self(), QDBusConnection::ExportAdaptors ); changeRecorder()->itemFetchScope().fetchFullPayload(); if (!(gcal = gcal_new(GCALENDAR))) exit(1); gcal_set_store_xml(gcal, 1); all_events.length = 0; all_events.entries = NULL; } GCalResource::~GCalResource() { gcal_cleanup_events(&all_events); pending.clear(); deleted.clear(); } void GCalResource::retrieveTimestamp(QString &timestamp) { timestamp = Settings::self()->timestamp(); } void GCalResource::saveTimestamp(QString &timestamp) { Settings::self()->setTimestamp(timestamp); Settings::self()->writeConfig(); } void GCalResource::retrieveCollections() { if(!authenticated) { kError() << "No authentication for Google Calendar available"; const QString message = i18nc("@info: status", "Not yet authenticated for " "use of Google Calendar"); emit error(message); emit status(Broken, message); return; } Collection c; c.setParent(Collection::root()); c.setRemoteId("google-calendar"); c.setName(name()); QStringList mimeTypes; mimeTypes << "text/calendar"; c.setContentMimeTypes(mimeTypes); Collection::List list; list << c; collectionsRetrieved(list); } void GCalResource::retrieveItems( const Akonadi::Collection &collection ) { Q_UNUSED(collection); Item::List items; int result; gcal_event_t event; QString timestamp; QByteArray t_byte; kError() << "\n............. retrieveItems ...........\n"; if (!authenticated) { kError() << "No authentication for Google calendar available"; const QString message = i18nc("@info:status", "Not yet authenticated for" " use of Google calendar"); emit error(message); emit status(Broken, message); return; } /* Query by updated */ retrieveTimestamp(timestamp); t_byte = timestamp.toLocal8Bit(); if (t_byte.length() > TIMESTAMP_SIZE) { //TODO: implement getUpdated //result = getUpdated(t_byte.data()); return; } kError() << "First retrieve"; if ((result = gcal_get_events(gcal, &all_events))) exit(1); /* GCalendar returns last updated entry as first element */ event = gcal_event_element(&all_events, 0); if (!event) { kError() << "Failed to retrieve last updated event."; const QString message = i18nc("@info:status", "Failed getting last updated" " event"); emit error(message); emit status(Broken, message); return; } timestamp = gcal_event_get_updated(event); saveTimestamp(timestamp); /* Each google entry has a unique ID and edit_url */ for (size_t i = 0; i < all_events.length; ++i) { Item item(QLatin1String("text/calendar")); KCal::Event kevent; QString temp; event = gcal_event_element(&all_events, i); temp = gcal_event_get_title(event); kevent.setSummary(temp); temp = gcal_event_get_where(event); kevent.setLocation(temp); temp = gcal_event_get_status(event); KCal::Incidence::Status status; if (gcal_event_is_deleted(event)) status = KCal::Incidence::StatusCanceled; else status = KCal::Incidence::StatusConfirmed; kevent.setStatus(status); temp = gcal_event_get_content(event); kevent.setDescription(temp); /* TODO: there must exit an easier way */ QDate start, end; temp = gcal_event_get_start(event); start.fromString(temp, Qt::ISODate); temp = gcal_event_get_end(event); end.fromString(temp, Qt::ISODate); KDateTime time_start(start), time_end(end); kevent.setDtStart(time_start); kevent.setDtEnd(time_end); } } bool GCalResource::retrieveItem( const Akonadi::Item &item, const QSet<QByteArray> &parts ) { Q_UNUSED(parts); Q_UNUSED(item); return true; } void GCalResource::aboutToQuit() { // TODO: any cleanup you need to do while there is still an active // event loop. The resource will terminate after this method returns } void GCalResource::doSetOnline(bool online) { Q_UNUSED(online); } int GCalResource::getUpdated(char *timestamp) { Q_UNUSED(timestamp); return -1; } void GCalResource::configure( WId windowId ) { Q_UNUSED(windowId); } void GCalResource::itemAdded( const Akonadi::Item &item, const Akonadi::Collection &collection ) { Q_UNUSED(collection); Q_UNUSED(item); } void GCalResource::itemChanged( const Akonadi::Item &item, const QSet<QByteArray> &parts ) { Q_UNUSED(parts); Q_UNUSED(item); } void GCalResource::itemRemoved( const Akonadi::Item &item ) { Q_UNUSED(item); } AKONADI_RESOURCE_MAIN( GCalResource ) #include "gcalresource.moc" <|endoftext|>
<commit_before>// This file is part of the dune-gdt project: // http://users.dune-project.org/projects/dune-gdt // Copyright holders: Felix Schindler // License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause) #ifndef DUNE_GDT_OPERATORS_BASE_HH #define DUNE_GDT_OPERATORS_BASE_HH #include <dune/stuff/la/solver.hh> #include "interfaces.hh" namespace Dune { namespace GDT { namespace Operators { template< class Traits > class MatrixBased : public AssemblableOperatorInterface< Traits > { typedef AssemblableOperatorInterface< Traits > BaseType; public: using typename BaseType::GridViewType; using typename BaseType::SourceSpaceType; using typename BaseType::RangeSpaceType; using typename BaseType::MatrixType; private: typedef Stuff::LA::Solver< MatrixType > LinearSolverType; public: MatrixBased(MatrixType& matrix, const SourceSpaceType& source_space, const RangeSpaceType& range_space, const GridViewType& grid_view) : matrix_(matrix) , source_space_(source_space) , range_space_(range_space) , grid_view_(grid_view) , assembled_(false) {} MatrixBased(MatrixType& matrix, const SourceSpaceType& source_space, const RangeSpaceType& range_space) : matrix_(matrix) , source_space_(source_space) , range_space_(range_space) , grid_view_(*(source_space_.grid_view())) , assembled_(false) {} MatrixBased(MatrixType& matrix, const SourceSpaceType& source_space) : matrix_(matrix) , source_space_(source_space) , range_space_(source_space_) , grid_view_(*(source_space_.grid_view())) , assembled_(false) {} const GridViewType& grid_view() const { return grid_view_; } const RangeSpaceType& range_space() const { return range_space_; } const SourceSpaceType& source_space() const { return source_space_; } MatrixType& matrix() { return matrix_; } const MatrixType& matrix() const { return matrix_; } virtual void assemble() = 0; template< class S, class R > void apply(const Stuff::LA::VectorInterface< S >& source, Stuff::LA::VectorInterface< R >& range) { assemble(); matrix_.mv(source.as_imp(), range.as_imp()); } // ... apply(...) static std::vector< std::string > invert_options() { return LinearSolverType::options(); } static Stuff::Common::ConfigTree invert_options(const std::string& type) { return LinearSolverType::options(type); } template< class R, class S > void apply_inverse(const Stuff::LA::VectorInterface< R >& range, Stuff::LA::VectorInterface< S >& source, const Stuff::Common::ConfigTree& opts) { assemble(); LinearSolverType(matrix).apply(range.as_imp(), source.as_imp(), opts); } // ... apply_inverse(...) private: MatrixType& matrix_; const SourceSpaceType& source_space_; const RangeSpaceType& range_space_; const GridViewType& grid_view_; bool assembled_; }; // class MatrixBased } // namespace Operators } // namespace GDT } // namespace Dune #endif // DUNE_GDT_OPERATORS_BASE_HH <commit_msg>[operators.base] added missing vortial dtor<commit_after>// This file is part of the dune-gdt project: // http://users.dune-project.org/projects/dune-gdt // Copyright holders: Felix Schindler // License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause) #ifndef DUNE_GDT_OPERATORS_BASE_HH #define DUNE_GDT_OPERATORS_BASE_HH #include <dune/stuff/la/solver.hh> #include "interfaces.hh" namespace Dune { namespace GDT { namespace Operators { template< class Traits > class MatrixBased : public AssemblableOperatorInterface< Traits > { typedef AssemblableOperatorInterface< Traits > BaseType; public: using typename BaseType::GridViewType; using typename BaseType::SourceSpaceType; using typename BaseType::RangeSpaceType; using typename BaseType::MatrixType; private: typedef Stuff::LA::Solver< MatrixType > LinearSolverType; public: MatrixBased(MatrixType& matrix, const SourceSpaceType& source_space, const RangeSpaceType& range_space, const GridViewType& grid_view) : matrix_(matrix) , source_space_(source_space) , range_space_(range_space) , grid_view_(grid_view) , assembled_(false) {} MatrixBased(MatrixType& matrix, const SourceSpaceType& source_space, const RangeSpaceType& range_space) : matrix_(matrix) , source_space_(source_space) , range_space_(range_space) , grid_view_(*(source_space_.grid_view())) , assembled_(false) {} MatrixBased(MatrixType& matrix, const SourceSpaceType& source_space) : matrix_(matrix) , source_space_(source_space) , range_space_(source_space_) , grid_view_(*(source_space_.grid_view())) , assembled_(false) {} virtual ~MatrixBased() {} const GridViewType& grid_view() const { return grid_view_; } const RangeSpaceType& range_space() const { return range_space_; } const SourceSpaceType& source_space() const { return source_space_; } MatrixType& matrix() { return matrix_; } const MatrixType& matrix() const { return matrix_; } virtual void assemble() = 0; template< class S, class R > void apply(const Stuff::LA::VectorInterface< S >& source, Stuff::LA::VectorInterface< R >& range) { assemble(); matrix_.mv(source.as_imp(), range.as_imp()); } // ... apply(...) static std::vector< std::string > invert_options() { return LinearSolverType::options(); } static Stuff::Common::ConfigTree invert_options(const std::string& type) { return LinearSolverType::options(type); } template< class R, class S > void apply_inverse(const Stuff::LA::VectorInterface< R >& range, Stuff::LA::VectorInterface< S >& source, const Stuff::Common::ConfigTree& opts) { assemble(); LinearSolverType(matrix).apply(range.as_imp(), source.as_imp(), opts); } // ... apply_inverse(...) private: MatrixType& matrix_; const SourceSpaceType& source_space_; const RangeSpaceType& range_space_; const GridViewType& grid_view_; bool assembled_; }; // class MatrixBased } // namespace Operators } // namespace GDT } // namespace Dune #endif // DUNE_GDT_OPERATORS_BASE_HH <|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/stringprintf.h" #include "base/utf_string_conversions.h" #include "chrome/browser/password_manager/password_form_data.h" #include "chrome/test/live_sync/live_passwords_sync_test.h" using webkit_glue::PasswordForm; IN_PROC_BROWSER_TEST_F(MultipleClientLivePasswordsSyncTest, Sanity) { ASSERT_TRUE(SetupSync()) << "SetupSync() failed."; for (int i = 0; i < num_clients(); ++i) { PasswordForm form = CreateTestPasswordForm(i); AddLogin(GetPasswordStore(i), form); } ASSERT_TRUE(AwaitQuiescence()); std::vector<PasswordForm> forms0; GetLogins(GetPasswordStore(0), forms0); ASSERT_EQ((size_t) num_clients(), forms0.size()); for (int i = 1; i < num_clients(); ++i) { std::vector<PasswordForm> forms; GetLogins(GetPasswordStore(i), forms); ASSERT_TRUE(ContainsSamePasswordForms(forms0, forms)); } } <commit_msg>Marking MultipleClientLivePasswordsSyncTest.Sanity as failing<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/stringprintf.h" #include "base/utf_string_conversions.h" #include "chrome/browser/password_manager/password_form_data.h" #include "chrome/test/live_sync/live_passwords_sync_test.h" using webkit_glue::PasswordForm; // TODO(rsimha): This test fails intermittently -- see http://crbug.com/77993. IN_PROC_BROWSER_TEST_F(MultipleClientLivePasswordsSyncTest, FAILS_Sanity) { ASSERT_TRUE(SetupSync()) << "SetupSync() failed."; for (int i = 0; i < num_clients(); ++i) { PasswordForm form = CreateTestPasswordForm(i); AddLogin(GetPasswordStore(i), form); } ASSERT_TRUE(AwaitQuiescence()); std::vector<PasswordForm> forms0; GetLogins(GetPasswordStore(0), forms0); ASSERT_EQ((size_t) num_clients(), forms0.size()); for (int i = 1; i < num_clients(); ++i) { std::vector<PasswordForm> forms; GetLogins(GetPasswordStore(i), forms); ASSERT_TRUE(ContainsSamePasswordForms(forms0, forms)); } } <|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. */ //--- c-modules used ----------------------------------------------------------- //--- standard modules used ---------------------------------------------------- #include "Anything.h" #include "Dbg.h" //--- test modules used -------------------------------------------------------- #include "TestSuite.h" //--- module under test -------------------------------------------------------- //--- interface include -------------------------------------------------------- #include "LDAPDAICachePolicyTest.h" #include "LDAPDAICachePolicyModule.h" #include "System.h" #include "StringStream.h" #include "Application.h" #include "Threads.h" //---- LDAPDAICachePolicyTest ---------------------------------------------------------------- LDAPDAICachePolicyTest::LDAPDAICachePolicyTest(TString name) : TestCase(name) { StartTrace(LDAPDAICachePolicyTest.Ctor); } LDAPDAICachePolicyTest::~LDAPDAICachePolicyTest() { StartTrace(LDAPDAICachePolicyTest.Dtor); } // setup for this TestCase void LDAPDAICachePolicyTest::setUp () { StartTrace(LDAPDAICachePolicyTest.setUp); t_assert(System::LoadConfigFile(fGlobalConfig, "Config")); t_assert(fGlobalConfig.IsDefined("Modules")); Application::InitializeGlobalConfig(fGlobalConfig); assertEqualm(0, WDModule::Install(fGlobalConfig), "WDModule::Install should have worked."); } void LDAPDAICachePolicyTest::setUp (const String &configName) { StartTrace(LDAPDAICachePolicyTest.setUp); t_assert(System::LoadConfigFile(fGlobalConfig, configName)); TraceAny(fGlobalConfig, "Global Config"); t_assert(fGlobalConfig.IsDefined("Modules")); Application::InitializeGlobalConfig(fGlobalConfig); // Will fail because of NoDataDA and LdapCachePolicyModule return // code check is mandatory assertEqualm(-1, WDModule::Install(fGlobalConfig), "WDModule::Install should have failed."); } void LDAPDAICachePolicyTest::tearDown () { StartTrace(LDAPDAICachePolicyTest.tearDown); t_assert(fGlobalConfig.IsDefined("Modules")); WDModule::Terminate(fGlobalConfig); } void LDAPDAICachePolicyTest::NoDataReadTest() { StartTrace(LDAPDAICachePolicyTest.NoDataReadTest); setUp(); tearDown(); setUp(String("NoDataQueryConfig")); // re-install "good" config tearDown(); setUp(); } void LDAPDAICachePolicyTest::ReInitTest() { StartTrace(LDAPDAICachePolicyTest.ReInitTest); for (int i = 0; i < 5; i++) { ROAnything result; t_assert(LDAPDAICacheGetter::Get(result, "TestDA1", ":0.name")); assertEqualm("ifs APPL. User Directory", result.AsString(), "Reset test failed."); t_assert(LDAPDAICacheGetter::Get(result, "TestDA2", ":0.pd-dn")); assertEqualm("cn=CH10601-tkgae,dc=tkfpd.hsr.ch", result.AsString(), "Reset test failed."); assertEqualm(0, WDModule::Reset(fGlobalConfig, fGlobalConfig), "WDModule::Reset should have worked"); break; } for (int i = 0; i < 5; i++) { ROAnything result; t_assert(LDAPDAICacheGetter::Get(result, "TestDA1Action", ":0.name")); assertEqualm("ifs APPL. User Directory", result.AsString(), "Reset test failed."); t_assert(LDAPDAICacheGetter::Get(result, "TestDA2Action", ":0.pd-dn")); assertEqualm("cn=CH10601-tkgae,dc=tkfpd.hsr.ch", result.AsString(), "Reset test failed."); assertEqualm(0, WDModule::Reset(fGlobalConfig, fGlobalConfig), "WDModule::Reset should have worked"); break; } } void LDAPDAICachePolicyTest::CallsInARow() { StartTrace(LDAPDAICachePolicyTest.ReInitTest); for (int i = 0; i < 5; i++) { ROAnything result; t_assert(LDAPDAICacheGetter::Get(result, "TestDA1", ":0.name")); assertEqualm("ifs APPL. User Directory", result.AsString(), "Reset test failed."); t_assert(LDAPDAICacheGetter::Get(result, "TestDA2", ":0.pd-dn")); assertEqualm("cn=CH10601-tkgae,dc=tkfpd.hsr.ch", result.AsString(), "Reset test failed."); } for (int i = 0; i < 5; i++) { ROAnything result; t_assert(LDAPDAICacheGetter::Get(result, "TestDA1Action", ":0.name")); assertEqualm("ifs APPL. User Directory", result.AsString(), "Reset test failed."); t_assert(LDAPDAICacheGetter::Get(result, "TestDA2Action", ":0.pd-dn")); assertEqualm("cn=CH10601-tkgae,dc=tkfpd.hsr.ch", result.AsString(), "Reset test failed."); } } void LDAPDAICachePolicyTest::testCase() { StartTrace(LDAPDAICachePolicyTest.testCase); // t_assert(false); } // builds up a suite of testcases, add a line for each testmethod Test *LDAPDAICachePolicyTest::suite () { StartTrace(LDAPDAICachePolicyTest.suite); TestSuite *testSuite = new TestSuite; testSuite->addTest (NEW_CASE(LDAPDAICachePolicyTest, NoDataReadTest)); testSuite->addTest (NEW_CASE(LDAPDAICachePolicyTest, CallsInARow)); testSuite->addTest (NEW_CASE(LDAPDAICachePolicyTest, ReInitTest)); return testSuite; } <commit_msg>corrected double defined/used variable<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. */ //--- c-modules used ----------------------------------------------------------- //--- standard modules used ---------------------------------------------------- #include "Anything.h" #include "Dbg.h" //--- test modules used -------------------------------------------------------- #include "TestSuite.h" //--- module under test -------------------------------------------------------- //--- interface include -------------------------------------------------------- #include "LDAPDAICachePolicyTest.h" #include "LDAPDAICachePolicyModule.h" #include "System.h" #include "StringStream.h" #include "Application.h" #include "Threads.h" //---- LDAPDAICachePolicyTest ---------------------------------------------------------------- LDAPDAICachePolicyTest::LDAPDAICachePolicyTest(TString name) : TestCase(name) { StartTrace(LDAPDAICachePolicyTest.Ctor); } LDAPDAICachePolicyTest::~LDAPDAICachePolicyTest() { StartTrace(LDAPDAICachePolicyTest.Dtor); } // setup for this TestCase void LDAPDAICachePolicyTest::setUp () { StartTrace(LDAPDAICachePolicyTest.setUp); t_assert(System::LoadConfigFile(fGlobalConfig, "Config")); t_assert(fGlobalConfig.IsDefined("Modules")); Application::InitializeGlobalConfig(fGlobalConfig); assertEqualm(0, WDModule::Install(fGlobalConfig), "WDModule::Install should have worked."); } void LDAPDAICachePolicyTest::setUp (const String &configName) { StartTrace(LDAPDAICachePolicyTest.setUp); t_assert(System::LoadConfigFile(fGlobalConfig, configName)); TraceAny(fGlobalConfig, "Global Config"); t_assert(fGlobalConfig.IsDefined("Modules")); Application::InitializeGlobalConfig(fGlobalConfig); // Will fail because of NoDataDA and LdapCachePolicyModule return // code check is mandatory assertEqualm(-1, WDModule::Install(fGlobalConfig), "WDModule::Install should have failed."); } void LDAPDAICachePolicyTest::tearDown () { StartTrace(LDAPDAICachePolicyTest.tearDown); t_assert(fGlobalConfig.IsDefined("Modules")); WDModule::Terminate(fGlobalConfig); } void LDAPDAICachePolicyTest::NoDataReadTest() { StartTrace(LDAPDAICachePolicyTest.NoDataReadTest); setUp(); tearDown(); setUp(String("NoDataQueryConfig")); // re-install "good" config tearDown(); setUp(); } void LDAPDAICachePolicyTest::ReInitTest() { StartTrace(LDAPDAICachePolicyTest.ReInitTest); int i; for (i = 0; i < 5; i++) { ROAnything result; t_assert(LDAPDAICacheGetter::Get(result, "TestDA1", ":0.name")); assertEqualm("ifs APPL. User Directory", result.AsString(), "Reset test failed."); t_assert(LDAPDAICacheGetter::Get(result, "TestDA2", ":0.pd-dn")); assertEqualm("cn=CH10601-tkgae,dc=tkfpd.hsr.ch", result.AsString(), "Reset test failed."); assertEqualm(0, WDModule::Reset(fGlobalConfig, fGlobalConfig), "WDModule::Reset should have worked"); break; } for (i = 0; i < 5; i++) { ROAnything result; t_assert(LDAPDAICacheGetter::Get(result, "TestDA1Action", ":0.name")); assertEqualm("ifs APPL. User Directory", result.AsString(), "Reset test failed."); t_assert(LDAPDAICacheGetter::Get(result, "TestDA2Action", ":0.pd-dn")); assertEqualm("cn=CH10601-tkgae,dc=tkfpd.hsr.ch", result.AsString(), "Reset test failed."); assertEqualm(0, WDModule::Reset(fGlobalConfig, fGlobalConfig), "WDModule::Reset should have worked"); break; } } void LDAPDAICachePolicyTest::CallsInARow() { StartTrace(LDAPDAICachePolicyTest.ReInitTest); int i; for (i = 0; i < 5; i++) { ROAnything result; t_assert(LDAPDAICacheGetter::Get(result, "TestDA1", ":0.name")); assertEqualm("ifs APPL. User Directory", result.AsString(), "Reset test failed."); t_assert(LDAPDAICacheGetter::Get(result, "TestDA2", ":0.pd-dn")); assertEqualm("cn=CH10601-tkgae,dc=tkfpd.hsr.ch", result.AsString(), "Reset test failed."); } for (i = 0; i < 5; i++) { ROAnything result; t_assert(LDAPDAICacheGetter::Get(result, "TestDA1Action", ":0.name")); assertEqualm("ifs APPL. User Directory", result.AsString(), "Reset test failed."); t_assert(LDAPDAICacheGetter::Get(result, "TestDA2Action", ":0.pd-dn")); assertEqualm("cn=CH10601-tkgae,dc=tkfpd.hsr.ch", result.AsString(), "Reset test failed."); } } void LDAPDAICachePolicyTest::testCase() { StartTrace(LDAPDAICachePolicyTest.testCase); // t_assert(false); } // builds up a suite of testcases, add a line for each testmethod Test *LDAPDAICachePolicyTest::suite () { StartTrace(LDAPDAICachePolicyTest.suite); TestSuite *testSuite = new TestSuite; testSuite->addTest (NEW_CASE(LDAPDAICachePolicyTest, NoDataReadTest)); testSuite->addTest (NEW_CASE(LDAPDAICachePolicyTest, CallsInARow)); testSuite->addTest (NEW_CASE(LDAPDAICachePolicyTest, ReInitTest)); return testSuite; } <|endoftext|>
<commit_before>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ /* * This file is part of the LibreOffice project. * * 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/. * * This file incorporates work covered by the following license notice: * * 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 . */ // must be first #include <canvas/debug.hxx> #include <canvas/verbosetrace.hxx> #include "basecontainernode.hxx" #include "eventqueue.hxx" #include "tools.hxx" #include "nodetools.hxx" #include "delayevent.hxx" #include <boost/bind.hpp> #include <boost/mem_fn.hpp> #include <algorithm> using namespace com::sun::star; namespace slideshow { namespace internal { BaseContainerNode::BaseContainerNode( const uno::Reference< animations::XAnimationNode >& xNode, const BaseContainerNodeSharedPtr& rParent, const NodeContext& rContext ) : BaseNode( xNode, rParent, rContext ), maChildren(), mnFinishedChildren(0), mbDurationIndefinite( isIndefiniteTiming( xNode->getEnd() ) && isIndefiniteTiming( xNode->getDuration() ) ) { } void BaseContainerNode::dispose() { forEachChildNode( boost::mem_fn(&Disposable::dispose) ); maChildren.clear(); BaseNode::dispose(); } bool BaseContainerNode::init_st() { if( !(getXAnimationNode()->getRepeatCount() >>= mnLeftIterations) ) mnLeftIterations = 1.0; return init_children(); } bool BaseContainerNode::init_children() { mnFinishedChildren = 0; // initialize all children return (std::count_if( maChildren.begin(), maChildren.end(), boost::mem_fn(&AnimationNode::init) ) == static_cast<VectorOfNodes::difference_type>(maChildren.size())); } void BaseContainerNode::deactivate_st( NodeState eDestState ) { mnLeftIterations = 0; // in order to make skip effect work correctly if (eDestState == FROZEN) { // deactivate all children that are not FROZEN or ENDED: forEachChildNode( boost::mem_fn(&AnimationNode::deactivate), ~(FROZEN | ENDED) ); } else { // end all children that are not ENDED: forEachChildNode( boost::mem_fn(&AnimationNode::end), ~ENDED ); } } bool BaseContainerNode::hasPendingAnimation() const { // does any of our children returns "true" on // AnimationNode::hasPendingAnimation()? // If yes, we, too, return true VectorOfNodes::const_iterator const iEnd( maChildren.end() ); return (std::find_if( maChildren.begin(), iEnd, boost::mem_fn(&AnimationNode::hasPendingAnimation) ) != iEnd); } void BaseContainerNode::appendChildNode( AnimationNodeSharedPtr const& pNode ) { if (! checkValidNode()) return; // register derived classes as end listeners at all children. // this is necessary to control the children animation // sequence, and to determine our own end event if (pNode->registerDeactivatingListener( getSelf() )) { maChildren.push_back( pNode ); } } bool BaseContainerNode::isChildNode( AnimationNodeSharedPtr const& pNode ) const { // find given notifier in child vector VectorOfNodes::const_iterator const iEnd( maChildren.end() ); VectorOfNodes::const_iterator const iFind( std::find( maChildren.begin(), iEnd, pNode ) ); return (iFind != iEnd); } bool BaseContainerNode::notifyDeactivatedChild( AnimationNodeSharedPtr const& pChildNode ) { OSL_ASSERT( pChildNode->getState() == FROZEN || pChildNode->getState() == ENDED ); // early exit on invalid nodes OSL_ASSERT( getState() != INVALID ); if( getState() == INVALID ) return false; if (! isChildNode(pChildNode)) { OSL_FAIL( "unknown notifier!" ); return false; } std::size_t const nSize = maChildren.size(); OSL_ASSERT( mnFinishedChildren < nSize ); ++mnFinishedChildren; bool bFinished = (mnFinishedChildren >= nSize); // all children finished, and we've got indefinite duration? // think of ParallelTimeContainer::notifyDeactivating() // if duration given, we will be deactivated by some end event // @see fillCommonParameters() if (bFinished && isDurationIndefinite()) { if( mnLeftIterations >= 1.0 ) { mnLeftIterations -= 1.0; } if( mnLeftIterations >= 1.0 ) { bFinished = false; EventSharedPtr aRepetitionEvent = makeDelay( boost::bind( &BaseContainerNode::repeat, this ), 0.0, "BaseContainerNode::repeat"); getContext().mrEventQueue.addEvent( aRepetitionEvent ); } else { deactivate(); } } return bFinished; } bool BaseContainerNode::repeat() { forEachChildNode( boost::mem_fn(&AnimationNode::end), ~ENDED ); sal_Bool bState = init_children(); if( bState ) activate_st(); return bState; } #if OSL_DEBUG_LEVEL >= 2 && defined(DBG_UTIL) void BaseContainerNode::showState() const { for( std::size_t i=0; i<maChildren.size(); ++i ) { BaseNodeSharedPtr pNode = boost::shared_dynamic_cast<BaseNode>(maChildren[i]); VERBOSE_TRACE( "Node connection: n0x%X -> n0x%X", (const char*)this+debugGetCurrentOffset(), (const char*)pNode.get()+debugGetCurrentOffset() ); pNode->showState(); } BaseNode::showState(); } #endif } // namespace internal } // namespace slideshow /* vim:set shiftwidth=4 softtabstop=4 expandtab: */ <commit_msg>boost::shared_dynamic_cast -> boost::dynamic_pointer_cast<commit_after>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ /* * This file is part of the LibreOffice project. * * 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/. * * This file incorporates work covered by the following license notice: * * 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 . */ // must be first #include <canvas/debug.hxx> #include <canvas/verbosetrace.hxx> #include "basecontainernode.hxx" #include "eventqueue.hxx" #include "tools.hxx" #include "nodetools.hxx" #include "delayevent.hxx" #include <boost/bind.hpp> #include <boost/mem_fn.hpp> #include <algorithm> using namespace com::sun::star; namespace slideshow { namespace internal { BaseContainerNode::BaseContainerNode( const uno::Reference< animations::XAnimationNode >& xNode, const BaseContainerNodeSharedPtr& rParent, const NodeContext& rContext ) : BaseNode( xNode, rParent, rContext ), maChildren(), mnFinishedChildren(0), mbDurationIndefinite( isIndefiniteTiming( xNode->getEnd() ) && isIndefiniteTiming( xNode->getDuration() ) ) { } void BaseContainerNode::dispose() { forEachChildNode( boost::mem_fn(&Disposable::dispose) ); maChildren.clear(); BaseNode::dispose(); } bool BaseContainerNode::init_st() { if( !(getXAnimationNode()->getRepeatCount() >>= mnLeftIterations) ) mnLeftIterations = 1.0; return init_children(); } bool BaseContainerNode::init_children() { mnFinishedChildren = 0; // initialize all children return (std::count_if( maChildren.begin(), maChildren.end(), boost::mem_fn(&AnimationNode::init) ) == static_cast<VectorOfNodes::difference_type>(maChildren.size())); } void BaseContainerNode::deactivate_st( NodeState eDestState ) { mnLeftIterations = 0; // in order to make skip effect work correctly if (eDestState == FROZEN) { // deactivate all children that are not FROZEN or ENDED: forEachChildNode( boost::mem_fn(&AnimationNode::deactivate), ~(FROZEN | ENDED) ); } else { // end all children that are not ENDED: forEachChildNode( boost::mem_fn(&AnimationNode::end), ~ENDED ); } } bool BaseContainerNode::hasPendingAnimation() const { // does any of our children returns "true" on // AnimationNode::hasPendingAnimation()? // If yes, we, too, return true VectorOfNodes::const_iterator const iEnd( maChildren.end() ); return (std::find_if( maChildren.begin(), iEnd, boost::mem_fn(&AnimationNode::hasPendingAnimation) ) != iEnd); } void BaseContainerNode::appendChildNode( AnimationNodeSharedPtr const& pNode ) { if (! checkValidNode()) return; // register derived classes as end listeners at all children. // this is necessary to control the children animation // sequence, and to determine our own end event if (pNode->registerDeactivatingListener( getSelf() )) { maChildren.push_back( pNode ); } } bool BaseContainerNode::isChildNode( AnimationNodeSharedPtr const& pNode ) const { // find given notifier in child vector VectorOfNodes::const_iterator const iEnd( maChildren.end() ); VectorOfNodes::const_iterator const iFind( std::find( maChildren.begin(), iEnd, pNode ) ); return (iFind != iEnd); } bool BaseContainerNode::notifyDeactivatedChild( AnimationNodeSharedPtr const& pChildNode ) { OSL_ASSERT( pChildNode->getState() == FROZEN || pChildNode->getState() == ENDED ); // early exit on invalid nodes OSL_ASSERT( getState() != INVALID ); if( getState() == INVALID ) return false; if (! isChildNode(pChildNode)) { OSL_FAIL( "unknown notifier!" ); return false; } std::size_t const nSize = maChildren.size(); OSL_ASSERT( mnFinishedChildren < nSize ); ++mnFinishedChildren; bool bFinished = (mnFinishedChildren >= nSize); // all children finished, and we've got indefinite duration? // think of ParallelTimeContainer::notifyDeactivating() // if duration given, we will be deactivated by some end event // @see fillCommonParameters() if (bFinished && isDurationIndefinite()) { if( mnLeftIterations >= 1.0 ) { mnLeftIterations -= 1.0; } if( mnLeftIterations >= 1.0 ) { bFinished = false; EventSharedPtr aRepetitionEvent = makeDelay( boost::bind( &BaseContainerNode::repeat, this ), 0.0, "BaseContainerNode::repeat"); getContext().mrEventQueue.addEvent( aRepetitionEvent ); } else { deactivate(); } } return bFinished; } bool BaseContainerNode::repeat() { forEachChildNode( boost::mem_fn(&AnimationNode::end), ~ENDED ); sal_Bool bState = init_children(); if( bState ) activate_st(); return bState; } #if OSL_DEBUG_LEVEL >= 2 && defined(DBG_UTIL) void BaseContainerNode::showState() const { for( std::size_t i=0; i<maChildren.size(); ++i ) { BaseNodeSharedPtr pNode = boost::dynamic_pointer_cast<BaseNode>(maChildren[i]); VERBOSE_TRACE( "Node connection: n0x%X -> n0x%X", (const char*)this+debugGetCurrentOffset(), (const char*)pNode.get()+debugGetCurrentOffset() ); pNode->showState(); } BaseNode::showState(); } #endif } // namespace internal } // namespace slideshow /* vim:set shiftwidth=4 softtabstop=4 expandtab: */ <|endoftext|>
<commit_before>/* Begin CVS Header $Source: /Volumes/Home/Users/shoops/cvs/copasi_dev/copasi/xml/CCopasiXMLInterface.cpp,v $ $Revision: 1.28 $ $Name: $ $Author: shoops $ $Date: 2005/06/24 20:07:55 $ End CVS Header */ /** * CCopasiXMLInterface class. * The class CCopasiXMLInterface is the interface to various XML document * containing Copasi relevant informtion. * * Created for Copasi by Stefan Hoops 2003 */ #include <fstream> #include <limits> #include "copasi.h" #include "CCopasiXMLInterface.h" #include "model/CModel.h" #include "report/CReportDefinition.h" #include "report/CReportDefinitionVector.h" #include "plot/COutputDefinitionVector.h" #include "plot/CPlotSpecification.h" #include "CCopasiXMLParser.h" #include "utilities/CCopasiVector.h" #include "utilities/CSlider.h" SCopasiXMLGUI::SCopasiXMLGUI(): pSliderList(new CCopasiVector<CSlider>) {} SCopasiXMLGUI::~SCopasiXMLGUI() { pdelete(pSliderList); } void encodeNONE(const char & chr, std::ostringstream & xml) { xml << chr; return; } void encodeSTD(const char & chr, std::ostringstream & xml) { switch (chr) { case '&': xml << "&amp;"; break; case '\'': xml << "&apos;"; break; case '<': xml << "&lt;"; break; case '>': xml << "&gt;"; break; case '\"': xml << "&quot;"; break; default: xml << chr; break; } return; } void encodeATTRIBUTE(const char & chr, std::ostringstream & xml) { switch (chr) { case '&': xml << "&amp;"; break; case '<': xml << "&lt;"; break; case '\"': xml << "&quot;"; break; case '\t': // Without this <tab> is converted to <space> xml << "&#x09;"; break; default: xml << chr; break; } return; } void encodeCHARACTER(const char & chr, std::ostringstream & xml) { switch (chr) { case '&': xml << "&amp;"; break; case '<': xml << "&lt;"; break; default: xml << chr; break; } return; } std::string CCopasiXMLInterface::encode(const std::string & str, const EncodingType & type) { /* All COPASI std::strings and char are already UTF-8 encoded.*/ std::string tmp = str; std::ostringstream xml; void (*encode)(const char & chr, std::ostringstream & xml); std::string::const_iterator it = str.begin(); std::string::const_iterator end = str.end(); switch (type) { case none: encode = encodeNONE; break; case std: encode = encodeSTD; break; case attribute: encode = encodeATTRIBUTE; break; case character: encode = encodeCHARACTER; break; } for (; it != end; ++it) encode(*it, xml); return xml.str(); } std::string CCopasiXMLInterface::encodeDBL(const C_FLOAT64 & dbl) { std::ostringstream value; if (dbl != dbl) // NaN != NaN value << "NaN"; else if (dbl == std::numeric_limits<C_FLOAT64>::infinity()) value << "INF"; else if (-dbl == std::numeric_limits<C_FLOAT64>::infinity()) value << "-INF"; else value << dbl; return value.str(); } std::string CCopasiXMLInterface::utf8(const std::string & str) { return str; std::ostringstream utf8; /* Based on RFC 2279. Since every string whithin COPASI is treated as latin1 and input is only optained through QT and Expat which will provide latin1 encoded strings the below should suffice. */ unsigned C_INT32 i, imax; for (i = 0, imax = str.length(); i < imax; i++) { if ((unsigned char) str[i] < 0x80) utf8 << str[i]; else { utf8 << 0xc0 + ((str[i] >> 6) & 0x03); utf8 << 0x80 + (str[i] & 0x3f); } } return utf8.str(); } CCopasiXMLInterface::CCopasiXMLInterface(): mpModel(NULL), mpFunctionList(NULL), mpTaskList(NULL), mpReportList(NULL), mpPlotList(NULL), mpGUI(NULL), mpIstream(NULL), mpOstream(NULL), mIndent() {} CCopasiXMLInterface::~CCopasiXMLInterface() {} bool CCopasiXMLInterface::load(const std::string & fileName) { std::ifstream is(fileName.c_str()); if (is.fail()) return false; else return load(is); } bool CCopasiXMLInterface::save(const std::string & fileName) { std::ofstream os(fileName.c_str()); if (os.fail()) return false; else return save(os); } bool CCopasiXMLInterface::setModel(const CModel & model) { mpModel = const_cast<CModel *>(&model); return true; } CModel * CCopasiXMLInterface::getModel() const {return mpModel;} bool CCopasiXMLInterface::haveModel() const {return mpModel != NULL;} bool CCopasiXMLInterface::freeModel() { pdelete(mpModel); return true; } bool CCopasiXMLInterface::setFunctionList(const CCopasiVectorN< CEvaluationTree > & functionList) { mpFunctionList = const_cast<CCopasiVectorN< CEvaluationTree > *>(&functionList); return true; } CCopasiVectorN< CEvaluationTree > * CCopasiXMLInterface::getFunctionList() const {return mpFunctionList;} bool CCopasiXMLInterface::haveFunctionList() const {return mpFunctionList != NULL;} bool CCopasiXMLInterface::freeFunctionList() { pdelete(mpFunctionList); return true; } bool CCopasiXMLInterface::setTaskList(const CCopasiVectorN< CCopasiTask > & taskList) { mpTaskList = const_cast<CCopasiVectorN< CCopasiTask > *>(&taskList); return true; } CCopasiVectorN< CCopasiTask > * CCopasiXMLInterface::getTaskList() const {return mpTaskList;} bool CCopasiXMLInterface::haveTaskList() const {return mpTaskList != NULL;} bool CCopasiXMLInterface::freeTaskList() { pdelete(mpTaskList); return true; } bool CCopasiXMLInterface::setPlotList(const COutputDefinitionVector & plotList) { mpPlotList = const_cast<COutputDefinitionVector *>(&plotList); return true; } COutputDefinitionVector * CCopasiXMLInterface::getPlotList() const {return mpPlotList;} bool CCopasiXMLInterface::havePlotList() const {return mpPlotList != NULL;} bool CCopasiXMLInterface::freePlotList() { pdelete(mpPlotList); return true; } bool CCopasiXMLInterface::setReportList(const CReportDefinitionVector & reportList) { mpReportList = const_cast<CReportDefinitionVector *>(&reportList); return true; } CReportDefinitionVector * CCopasiXMLInterface::getReportList() const {return mpReportList;} bool CCopasiXMLInterface::haveReportList() const {return mpReportList != NULL;} bool CCopasiXMLInterface::freeReportList() { pdelete(mpReportList); return true; } bool CCopasiXMLInterface::setGUI(const SCopasiXMLGUI & GUI) { mpGUI = const_cast<SCopasiXMLGUI *>(&GUI); return true; } SCopasiXMLGUI * CCopasiXMLInterface::getGUI() const {return mpGUI;} bool CCopasiXMLInterface::haveGUI() const {return mpGUI != NULL;} bool CCopasiXMLInterface::freeGUI() { pdelete(mpGUI); return true; } bool CCopasiXMLInterface::saveData(const std::string & data) { *mpOstream << mIndent << CCopasiXMLInterface::encode(data) << std::endl; return true; } bool CCopasiXMLInterface::saveElement(const std::string & name, CXMLAttributeList & attributeList) { *mpOstream << mIndent << "<" << name; unsigned C_INT32 i, imax; for (i = 0, imax = attributeList.size(); i < imax; i++) *mpOstream << attributeList.getAttribute(i); *mpOstream << "/>" << std::endl; return true; } bool CCopasiXMLInterface::startSaveElement(const std::string & name) { *mpOstream << mIndent << "<" << name << ">" << std::endl; mIndent += " "; return true; } bool CCopasiXMLInterface::startSaveElement(const std::string & name, CXMLAttributeList & attributeList) { *mpOstream << mIndent << "<" << name; unsigned C_INT32 i, imax; for (i = 0, imax = attributeList.size(); i < imax; i++) *mpOstream << attributeList.getAttribute(i); *mpOstream << ">" << std::endl; mIndent += " "; return true; } bool CCopasiXMLInterface::endSaveElement(const std::string & name) { mIndent = mIndent.substr(0, mIndent.length() - 2); *mpOstream << mIndent << "</" << name << ">" << std::endl; return true; } CXMLAttributeList::CXMLAttributeList(): mAttributeList(), mSaveList() {} CXMLAttributeList::CXMLAttributeList(const CXMLAttributeList & src): mAttributeList(src.mAttributeList), mSaveList(src.mSaveList) {} CXMLAttributeList::~CXMLAttributeList() {} bool CXMLAttributeList::erase() { mAttributeList.clear(); mSaveList.clear(); return true; } unsigned C_INT32 CXMLAttributeList::size() {return mAttributeList.size() / 2;} bool CXMLAttributeList::add(const std::string & name, const C_FLOAT64 & value) { return add(name, CCopasiXMLInterface::encodeDBL(value), CCopasiXMLInterface::attribute); } bool CXMLAttributeList::setName(const unsigned C_INT32 & index, const std::string & name) { mAttributeList[2 * index] = name; return true; } const std::string & CXMLAttributeList::getName(const unsigned C_INT32 & index) const {return mAttributeList[2 * index];} const std::string & CXMLAttributeList::getValue(const unsigned C_INT32 & index) const {return mAttributeList[2 * index + 1];} bool CXMLAttributeList::skip(const unsigned C_INT32 & index) { mSaveList[index] = false; return true; } std::string CXMLAttributeList::getAttribute(const unsigned C_INT32 & index) const { if (mSaveList[index]) return " " + mAttributeList[2 * index] + "=\"" + mAttributeList[2 * index + 1] + "\""; else return ""; } <commit_msg>Use _isnan in encodeDBL to detect NaN.<commit_after>/* Begin CVS Header $Source: /Volumes/Home/Users/shoops/cvs/copasi_dev/copasi/xml/CCopasiXMLInterface.cpp,v $ $Revision: 1.29 $ $Name: $ $Author: shoops $ $Date: 2005/06/28 14:27:14 $ End CVS Header */ /** * CCopasiXMLInterface class. * The class CCopasiXMLInterface is the interface to various XML document * containing Copasi relevant informtion. * * Created for Copasi by Stefan Hoops 2003 */ #include <fstream> #include <limits> #include <float.h> #include "copasi.h" #include "CCopasiXMLInterface.h" #include "model/CModel.h" #include "report/CReportDefinition.h" #include "report/CReportDefinitionVector.h" #include "plot/COutputDefinitionVector.h" #include "plot/CPlotSpecification.h" #include "CCopasiXMLParser.h" #include "utilities/CCopasiVector.h" #include "utilities/CSlider.h" SCopasiXMLGUI::SCopasiXMLGUI(): pSliderList(new CCopasiVector<CSlider>) {} SCopasiXMLGUI::~SCopasiXMLGUI() { pdelete(pSliderList); } void encodeNONE(const char & chr, std::ostringstream & xml) { xml << chr; return; } void encodeSTD(const char & chr, std::ostringstream & xml) { switch (chr) { case '&': xml << "&amp;"; break; case '\'': xml << "&apos;"; break; case '<': xml << "&lt;"; break; case '>': xml << "&gt;"; break; case '\"': xml << "&quot;"; break; default: xml << chr; break; } return; } void encodeATTRIBUTE(const char & chr, std::ostringstream & xml) { switch (chr) { case '&': xml << "&amp;"; break; case '<': xml << "&lt;"; break; case '\"': xml << "&quot;"; break; case '\t': // Without this <tab> is converted to <space> xml << "&#x09;"; break; default: xml << chr; break; } return; } void encodeCHARACTER(const char & chr, std::ostringstream & xml) { switch (chr) { case '&': xml << "&amp;"; break; case '<': xml << "&lt;"; break; default: xml << chr; break; } return; } std::string CCopasiXMLInterface::encode(const std::string & str, const EncodingType & type) { /* All COPASI std::strings and char are already UTF-8 encoded.*/ std::string tmp = str; std::ostringstream xml; void (*encode)(const char & chr, std::ostringstream & xml); std::string::const_iterator it = str.begin(); std::string::const_iterator end = str.end(); switch (type) { case none: encode = encodeNONE; break; case std: encode = encodeSTD; break; case attribute: encode = encodeATTRIBUTE; break; case character: encode = encodeCHARACTER; break; } for (; it != end; ++it) encode(*it, xml); return xml.str(); } std::string CCopasiXMLInterface::encodeDBL(const C_FLOAT64 & dbl) { std::ostringstream value; if (_isnan(dbl)) value << "NaN"; else if (dbl == std::numeric_limits<C_FLOAT64>::infinity()) value << "INF"; else if (-dbl == std::numeric_limits<C_FLOAT64>::infinity()) value << "-INF"; else value << dbl; return value.str(); } std::string CCopasiXMLInterface::utf8(const std::string & str) { return str; std::ostringstream utf8; /* Based on RFC 2279. Since every string whithin COPASI is treated as latin1 and input is only optained through QT and Expat which will provide latin1 encoded strings the below should suffice. */ unsigned C_INT32 i, imax; for (i = 0, imax = str.length(); i < imax; i++) { if ((unsigned char) str[i] < 0x80) utf8 << str[i]; else { utf8 << 0xc0 + ((str[i] >> 6) & 0x03); utf8 << 0x80 + (str[i] & 0x3f); } } return utf8.str(); } CCopasiXMLInterface::CCopasiXMLInterface(): mpModel(NULL), mpFunctionList(NULL), mpTaskList(NULL), mpReportList(NULL), mpPlotList(NULL), mpGUI(NULL), mpIstream(NULL), mpOstream(NULL), mIndent() {} CCopasiXMLInterface::~CCopasiXMLInterface() {} bool CCopasiXMLInterface::load(const std::string & fileName) { std::ifstream is(fileName.c_str()); if (is.fail()) return false; else return load(is); } bool CCopasiXMLInterface::save(const std::string & fileName) { std::ofstream os(fileName.c_str()); if (os.fail()) return false; else return save(os); } bool CCopasiXMLInterface::setModel(const CModel & model) { mpModel = const_cast<CModel *>(&model); return true; } CModel * CCopasiXMLInterface::getModel() const {return mpModel;} bool CCopasiXMLInterface::haveModel() const {return mpModel != NULL;} bool CCopasiXMLInterface::freeModel() { pdelete(mpModel); return true; } bool CCopasiXMLInterface::setFunctionList(const CCopasiVectorN< CEvaluationTree > & functionList) { mpFunctionList = const_cast<CCopasiVectorN< CEvaluationTree > *>(&functionList); return true; } CCopasiVectorN< CEvaluationTree > * CCopasiXMLInterface::getFunctionList() const {return mpFunctionList;} bool CCopasiXMLInterface::haveFunctionList() const {return mpFunctionList != NULL;} bool CCopasiXMLInterface::freeFunctionList() { pdelete(mpFunctionList); return true; } bool CCopasiXMLInterface::setTaskList(const CCopasiVectorN< CCopasiTask > & taskList) { mpTaskList = const_cast<CCopasiVectorN< CCopasiTask > *>(&taskList); return true; } CCopasiVectorN< CCopasiTask > * CCopasiXMLInterface::getTaskList() const {return mpTaskList;} bool CCopasiXMLInterface::haveTaskList() const {return mpTaskList != NULL;} bool CCopasiXMLInterface::freeTaskList() { pdelete(mpTaskList); return true; } bool CCopasiXMLInterface::setPlotList(const COutputDefinitionVector & plotList) { mpPlotList = const_cast<COutputDefinitionVector *>(&plotList); return true; } COutputDefinitionVector * CCopasiXMLInterface::getPlotList() const {return mpPlotList;} bool CCopasiXMLInterface::havePlotList() const {return mpPlotList != NULL;} bool CCopasiXMLInterface::freePlotList() { pdelete(mpPlotList); return true; } bool CCopasiXMLInterface::setReportList(const CReportDefinitionVector & reportList) { mpReportList = const_cast<CReportDefinitionVector *>(&reportList); return true; } CReportDefinitionVector * CCopasiXMLInterface::getReportList() const {return mpReportList;} bool CCopasiXMLInterface::haveReportList() const {return mpReportList != NULL;} bool CCopasiXMLInterface::freeReportList() { pdelete(mpReportList); return true; } bool CCopasiXMLInterface::setGUI(const SCopasiXMLGUI & GUI) { mpGUI = const_cast<SCopasiXMLGUI *>(&GUI); return true; } SCopasiXMLGUI * CCopasiXMLInterface::getGUI() const {return mpGUI;} bool CCopasiXMLInterface::haveGUI() const {return mpGUI != NULL;} bool CCopasiXMLInterface::freeGUI() { pdelete(mpGUI); return true; } bool CCopasiXMLInterface::saveData(const std::string & data) { *mpOstream << mIndent << CCopasiXMLInterface::encode(data) << std::endl; return true; } bool CCopasiXMLInterface::saveElement(const std::string & name, CXMLAttributeList & attributeList) { *mpOstream << mIndent << "<" << name; unsigned C_INT32 i, imax; for (i = 0, imax = attributeList.size(); i < imax; i++) *mpOstream << attributeList.getAttribute(i); *mpOstream << "/>" << std::endl; return true; } bool CCopasiXMLInterface::startSaveElement(const std::string & name) { *mpOstream << mIndent << "<" << name << ">" << std::endl; mIndent += " "; return true; } bool CCopasiXMLInterface::startSaveElement(const std::string & name, CXMLAttributeList & attributeList) { *mpOstream << mIndent << "<" << name; unsigned C_INT32 i, imax; for (i = 0, imax = attributeList.size(); i < imax; i++) *mpOstream << attributeList.getAttribute(i); *mpOstream << ">" << std::endl; mIndent += " "; return true; } bool CCopasiXMLInterface::endSaveElement(const std::string & name) { mIndent = mIndent.substr(0, mIndent.length() - 2); *mpOstream << mIndent << "</" << name << ">" << std::endl; return true; } CXMLAttributeList::CXMLAttributeList(): mAttributeList(), mSaveList() {} CXMLAttributeList::CXMLAttributeList(const CXMLAttributeList & src): mAttributeList(src.mAttributeList), mSaveList(src.mSaveList) {} CXMLAttributeList::~CXMLAttributeList() {} bool CXMLAttributeList::erase() { mAttributeList.clear(); mSaveList.clear(); return true; } unsigned C_INT32 CXMLAttributeList::size() {return mAttributeList.size() / 2;} bool CXMLAttributeList::add(const std::string & name, const C_FLOAT64 & value) { return add(name, CCopasiXMLInterface::encodeDBL(value), CCopasiXMLInterface::attribute); } bool CXMLAttributeList::setName(const unsigned C_INT32 & index, const std::string & name) { mAttributeList[2 * index] = name; return true; } const std::string & CXMLAttributeList::getName(const unsigned C_INT32 & index) const {return mAttributeList[2 * index];} const std::string & CXMLAttributeList::getValue(const unsigned C_INT32 & index) const {return mAttributeList[2 * index + 1];} bool CXMLAttributeList::skip(const unsigned C_INT32 & index) { mSaveList[index] = false; return true; } std::string CXMLAttributeList::getAttribute(const unsigned C_INT32 & index) const { if (mSaveList[index]) return " " + mAttributeList[2 * index] + "=\"" + mAttributeList[2 * index + 1] + "\""; else return ""; } <|endoftext|>
<commit_before>// Copyright 2014 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/basictypes.h" #include "base/run_loop.h" #include "content/browser/service_worker/embedded_worker_registry.h" #include "content/browser/service_worker/embedded_worker_test_helper.h" #include "content/browser/service_worker/service_worker_context_core.h" #include "content/browser/service_worker/service_worker_registration.h" #include "content/browser/service_worker/service_worker_test_utils.h" #include "content/browser/service_worker/service_worker_version.h" #include "content/public/test/test_browser_thread_bundle.h" #include "testing/gtest/include/gtest/gtest.h" // IPC messages for testing --------------------------------------------------- #define IPC_MESSAGE_IMPL #include "ipc/ipc_message_macros.h" #define IPC_MESSAGE_START TestMsgStart IPC_MESSAGE_CONTROL0(TestMsg_Message); IPC_MESSAGE_CONTROL1(TestMsg_Request, int); IPC_MESSAGE_CONTROL1(TestMsg_Response, int); // --------------------------------------------------------------------------- namespace content { namespace { static const int kRenderProcessId = 1; class MessageReceiver : public EmbeddedWorkerTestHelper { public: MessageReceiver(ServiceWorkerContextCore* context) : EmbeddedWorkerTestHelper(context, kRenderProcessId), current_embedded_worker_id_(0), current_request_id_(0) {} virtual ~MessageReceiver() {} virtual bool OnSendMessageToWorker(int thread_id, int embedded_worker_id, int request_id, const IPC::Message& message) OVERRIDE { if (EmbeddedWorkerTestHelper::OnSendMessageToWorker( thread_id, embedded_worker_id, request_id, message)) { return true; } current_embedded_worker_id_ = embedded_worker_id; current_request_id_ = request_id; bool handled = true; IPC_BEGIN_MESSAGE_MAP(MessageReceiver, message) IPC_MESSAGE_HANDLER(TestMsg_Message, OnMessage) IPC_MESSAGE_HANDLER(TestMsg_Request, OnRequest) IPC_MESSAGE_UNHANDLED(handled = false) IPC_END_MESSAGE_MAP() return handled; } private: void OnMessage() { // Do nothing. } void OnRequest(int value) { // Double the given value and send back the response. SimulateSendMessageToBrowser(current_embedded_worker_id_, current_request_id_, TestMsg_Response(value * 2)); } int current_embedded_worker_id_; int current_request_id_; DISALLOW_COPY_AND_ASSIGN(MessageReceiver); }; void ReceiveResponse(ServiceWorkerStatusCode* status_out, int* value_out, ServiceWorkerStatusCode status, const IPC::Message& message) { Tuple1<int> param; ASSERT_TRUE(TestMsg_Response::Read(&message, &param)); *status_out = status; *value_out = param.a; } void VerifyCalled(bool* called) { *called = true; } void ObserveStatusChanges(ServiceWorkerVersion* version, std::vector<ServiceWorkerVersion::Status>* statuses) { statuses->push_back(version->status()); version->RegisterStatusChangeCallback( base::Bind(&ObserveStatusChanges, make_scoped_refptr(version), statuses)); } } // namespace class ServiceWorkerVersionTest : public testing::Test { protected: ServiceWorkerVersionTest() : thread_bundle_(TestBrowserThreadBundle::IO_MAINLOOP) {} virtual void SetUp() OVERRIDE { context_.reset(new ServiceWorkerContextCore(base::FilePath(), NULL)); helper_.reset(new MessageReceiver(context_.get())); registration_ = new ServiceWorkerRegistration( GURL("http://www.example.com/*"), GURL("http://www.example.com/service_worker.js"), 1L, context_->AsWeakPtr()); version_ = new ServiceWorkerVersion( registration_, 1L, context_->AsWeakPtr()); // Simulate adding one process to the worker. int embedded_worker_id = version_->embedded_worker()->embedded_worker_id(); helper_->SimulateAddProcessToWorker(embedded_worker_id, kRenderProcessId); } virtual void TearDown() OVERRIDE { version_ = 0; registration_ = 0; helper_.reset(); context_.reset(); } TestBrowserThreadBundle thread_bundle_; scoped_ptr<ServiceWorkerContextCore> context_; scoped_ptr<EmbeddedWorkerTestHelper> helper_; scoped_refptr<ServiceWorkerRegistration> registration_; scoped_refptr<ServiceWorkerVersion> version_; DISALLOW_COPY_AND_ASSIGN(ServiceWorkerVersionTest); }; TEST_F(ServiceWorkerVersionTest, ConcurrentStartAndStop) { // Call StartWorker() multiple times. ServiceWorkerStatusCode status1 = SERVICE_WORKER_ERROR_FAILED; ServiceWorkerStatusCode status2 = SERVICE_WORKER_ERROR_FAILED; ServiceWorkerStatusCode status3 = SERVICE_WORKER_ERROR_FAILED; version_->StartWorker(CreateReceiverOnCurrentThread(&status1)); version_->StartWorker(CreateReceiverOnCurrentThread(&status2)); EXPECT_EQ(ServiceWorkerVersion::STARTING, version_->running_status()); base::RunLoop().RunUntilIdle(); EXPECT_EQ(ServiceWorkerVersion::RUNNING, version_->running_status()); // Call StartWorker() after it's started. version_->StartWorker(CreateReceiverOnCurrentThread(&status3)); base::RunLoop().RunUntilIdle(); // All should just succeed. EXPECT_EQ(SERVICE_WORKER_OK, status1); EXPECT_EQ(SERVICE_WORKER_OK, status2); EXPECT_EQ(SERVICE_WORKER_OK, status3); // Call StopWorker() multiple times. status1 = SERVICE_WORKER_ERROR_FAILED; status2 = SERVICE_WORKER_ERROR_FAILED; status3 = SERVICE_WORKER_ERROR_FAILED; version_->StopWorker(CreateReceiverOnCurrentThread(&status1)); version_->StopWorker(CreateReceiverOnCurrentThread(&status2)); // Also try calling StartWorker while StopWorker is in queue. version_->StartWorker(CreateReceiverOnCurrentThread(&status3)); EXPECT_EQ(ServiceWorkerVersion::STOPPING, version_->running_status()); base::RunLoop().RunUntilIdle(); EXPECT_EQ(ServiceWorkerVersion::STOPPED, version_->running_status()); // All StopWorker should just succeed, while StartWorker fails. EXPECT_EQ(SERVICE_WORKER_OK, status1); EXPECT_EQ(SERVICE_WORKER_OK, status2); EXPECT_EQ(SERVICE_WORKER_ERROR_START_WORKER_FAILED, status3); } TEST_F(ServiceWorkerVersionTest, SendMessage) { EXPECT_EQ(ServiceWorkerVersion::STOPPED, version_->running_status()); // Send a message without starting the worker. ServiceWorkerStatusCode status = SERVICE_WORKER_ERROR_FAILED; version_->SendMessage(TestMsg_Message(), CreateReceiverOnCurrentThread(&status)); base::RunLoop().RunUntilIdle(); EXPECT_EQ(SERVICE_WORKER_OK, status); // The worker should be now started. EXPECT_EQ(ServiceWorkerVersion::RUNNING, version_->running_status()); // Stop the worker, and then send the message immediately. ServiceWorkerStatusCode msg_status = SERVICE_WORKER_ERROR_FAILED; ServiceWorkerStatusCode stop_status = SERVICE_WORKER_ERROR_FAILED; version_->StopWorker(CreateReceiverOnCurrentThread(&stop_status)); version_->SendMessage(TestMsg_Message(), CreateReceiverOnCurrentThread(&msg_status)); base::RunLoop().RunUntilIdle(); EXPECT_EQ(SERVICE_WORKER_OK, stop_status); // SendMessage should return START_WORKER_FAILED error since it tried to // start a worker while it was stopping. EXPECT_EQ(SERVICE_WORKER_ERROR_START_WORKER_FAILED, msg_status); } TEST_F(ServiceWorkerVersionTest, ReSendMessageAfterStop) { EXPECT_EQ(ServiceWorkerVersion::STOPPED, version_->running_status()); // Start the worker. ServiceWorkerStatusCode start_status = SERVICE_WORKER_ERROR_FAILED; version_->StartWorker(CreateReceiverOnCurrentThread(&start_status)); base::RunLoop().RunUntilIdle(); EXPECT_EQ(SERVICE_WORKER_OK, start_status); EXPECT_EQ(ServiceWorkerVersion::RUNNING, version_->running_status()); // Stop the worker, and then send the message immediately. ServiceWorkerStatusCode msg_status = SERVICE_WORKER_ERROR_FAILED; ServiceWorkerStatusCode stop_status = SERVICE_WORKER_ERROR_FAILED; version_->StopWorker(CreateReceiverOnCurrentThread(&stop_status)); version_->SendMessage(TestMsg_Message(), CreateReceiverOnCurrentThread(&msg_status)); base::RunLoop().RunUntilIdle(); EXPECT_EQ(SERVICE_WORKER_OK, stop_status); // SendMessage should return START_WORKER_FAILED error since it tried to // start a worker while it was stopping. EXPECT_EQ(SERVICE_WORKER_ERROR_START_WORKER_FAILED, msg_status); // Resend the message, which should succeed and restart the worker. version_->SendMessage(TestMsg_Message(), CreateReceiverOnCurrentThread(&msg_status)); base::RunLoop().RunUntilIdle(); EXPECT_EQ(SERVICE_WORKER_OK, msg_status); EXPECT_EQ(ServiceWorkerVersion::RUNNING, version_->running_status()); } TEST_F(ServiceWorkerVersionTest, SendMessageAndRegisterCallback) { // Send multiple messages and verify responses. ServiceWorkerStatusCode status1 = SERVICE_WORKER_ERROR_FAILED; ServiceWorkerStatusCode status2 = SERVICE_WORKER_ERROR_FAILED; int value1 = -1, value2 = -1; version_->SendMessageAndRegisterCallback( TestMsg_Request(111), base::Bind(&ReceiveResponse, &status1, &value1)); version_->SendMessageAndRegisterCallback( TestMsg_Request(333), base::Bind(&ReceiveResponse, &status2, &value2)); base::RunLoop().RunUntilIdle(); EXPECT_EQ(SERVICE_WORKER_OK, status1); EXPECT_EQ(SERVICE_WORKER_OK, status2); EXPECT_EQ(111 * 2, value1); EXPECT_EQ(333 * 2, value2); } TEST_F(ServiceWorkerVersionTest, InstallAndWaitCompletion) { EXPECT_EQ(ServiceWorkerVersion::NEW, version_->status()); // Dispatch an install event. ServiceWorkerStatusCode status = SERVICE_WORKER_ERROR_FAILED; version_->DispatchInstallEvent(-1, CreateReceiverOnCurrentThread(&status)); EXPECT_EQ(ServiceWorkerVersion::INSTALLING, version_->status()); // Wait for the completion. bool status_change_called = false; version_->RegisterStatusChangeCallback( base::Bind(&VerifyCalled, &status_change_called)); base::RunLoop().RunUntilIdle(); // After successful completion, version's status must be changed to // INSTALLED, and status change callback must have been fired. EXPECT_EQ(SERVICE_WORKER_OK, status); EXPECT_TRUE(status_change_called); EXPECT_EQ(ServiceWorkerVersion::INSTALLED, version_->status()); } TEST_F(ServiceWorkerVersionTest, ActivateAndWaitCompletion) { version_->SetStatus(ServiceWorkerVersion::INSTALLED); EXPECT_EQ(ServiceWorkerVersion::INSTALLED, version_->status()); // Dispatch an activate event. ServiceWorkerStatusCode status = SERVICE_WORKER_ERROR_FAILED; version_->DispatchActivateEvent(CreateReceiverOnCurrentThread(&status)); EXPECT_EQ(ServiceWorkerVersion::ACTIVATING, version_->status()); // Wait for the completion. bool status_change_called = false; version_->RegisterStatusChangeCallback( base::Bind(&VerifyCalled, &status_change_called)); base::RunLoop().RunUntilIdle(); // After successful completion, version's status must be changed to // ACTIVE, and status change callback must have been fired. EXPECT_EQ(SERVICE_WORKER_OK, status); EXPECT_TRUE(status_change_called); EXPECT_EQ(ServiceWorkerVersion::ACTIVE, version_->status()); } TEST_F(ServiceWorkerVersionTest, RepeatedlyObserveStatusChanges) { EXPECT_EQ(ServiceWorkerVersion::NEW, version_->status()); // Repeatedly observe status changes (the callback re-registers itself). std::vector<ServiceWorkerVersion::Status> statuses; version_->RegisterStatusChangeCallback( base::Bind(&ObserveStatusChanges, version_, &statuses)); // Dispatch some events. ServiceWorkerStatusCode status = SERVICE_WORKER_ERROR_FAILED; version_->DispatchInstallEvent(-1, CreateReceiverOnCurrentThread(&status)); base::RunLoop().RunUntilIdle(); EXPECT_EQ(SERVICE_WORKER_OK, status); status = SERVICE_WORKER_ERROR_FAILED; version_->DispatchActivateEvent(CreateReceiverOnCurrentThread(&status)); base::RunLoop().RunUntilIdle(); EXPECT_EQ(SERVICE_WORKER_OK, status); // Verify that we could successfully observe repeated status changes. ASSERT_EQ(4U, statuses.size()); ASSERT_EQ(ServiceWorkerVersion::INSTALLING, statuses[0]); ASSERT_EQ(ServiceWorkerVersion::INSTALLED, statuses[1]); ASSERT_EQ(ServiceWorkerVersion::ACTIVATING, statuses[2]); ASSERT_EQ(ServiceWorkerVersion::ACTIVE, statuses[3]); } } // namespace content <commit_msg>Disable ServiceWorkerVersionTest.RepeatedlyObserveStatusChanges<commit_after>// Copyright 2014 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/basictypes.h" #include "base/run_loop.h" #include "content/browser/service_worker/embedded_worker_registry.h" #include "content/browser/service_worker/embedded_worker_test_helper.h" #include "content/browser/service_worker/service_worker_context_core.h" #include "content/browser/service_worker/service_worker_registration.h" #include "content/browser/service_worker/service_worker_test_utils.h" #include "content/browser/service_worker/service_worker_version.h" #include "content/public/test/test_browser_thread_bundle.h" #include "testing/gtest/include/gtest/gtest.h" // IPC messages for testing --------------------------------------------------- #define IPC_MESSAGE_IMPL #include "ipc/ipc_message_macros.h" #define IPC_MESSAGE_START TestMsgStart IPC_MESSAGE_CONTROL0(TestMsg_Message); IPC_MESSAGE_CONTROL1(TestMsg_Request, int); IPC_MESSAGE_CONTROL1(TestMsg_Response, int); // --------------------------------------------------------------------------- namespace content { namespace { static const int kRenderProcessId = 1; class MessageReceiver : public EmbeddedWorkerTestHelper { public: MessageReceiver(ServiceWorkerContextCore* context) : EmbeddedWorkerTestHelper(context, kRenderProcessId), current_embedded_worker_id_(0), current_request_id_(0) {} virtual ~MessageReceiver() {} virtual bool OnSendMessageToWorker(int thread_id, int embedded_worker_id, int request_id, const IPC::Message& message) OVERRIDE { if (EmbeddedWorkerTestHelper::OnSendMessageToWorker( thread_id, embedded_worker_id, request_id, message)) { return true; } current_embedded_worker_id_ = embedded_worker_id; current_request_id_ = request_id; bool handled = true; IPC_BEGIN_MESSAGE_MAP(MessageReceiver, message) IPC_MESSAGE_HANDLER(TestMsg_Message, OnMessage) IPC_MESSAGE_HANDLER(TestMsg_Request, OnRequest) IPC_MESSAGE_UNHANDLED(handled = false) IPC_END_MESSAGE_MAP() return handled; } private: void OnMessage() { // Do nothing. } void OnRequest(int value) { // Double the given value and send back the response. SimulateSendMessageToBrowser(current_embedded_worker_id_, current_request_id_, TestMsg_Response(value * 2)); } int current_embedded_worker_id_; int current_request_id_; DISALLOW_COPY_AND_ASSIGN(MessageReceiver); }; void ReceiveResponse(ServiceWorkerStatusCode* status_out, int* value_out, ServiceWorkerStatusCode status, const IPC::Message& message) { Tuple1<int> param; ASSERT_TRUE(TestMsg_Response::Read(&message, &param)); *status_out = status; *value_out = param.a; } void VerifyCalled(bool* called) { *called = true; } void ObserveStatusChanges(ServiceWorkerVersion* version, std::vector<ServiceWorkerVersion::Status>* statuses) { statuses->push_back(version->status()); version->RegisterStatusChangeCallback( base::Bind(&ObserveStatusChanges, make_scoped_refptr(version), statuses)); } } // namespace class ServiceWorkerVersionTest : public testing::Test { protected: ServiceWorkerVersionTest() : thread_bundle_(TestBrowserThreadBundle::IO_MAINLOOP) {} virtual void SetUp() OVERRIDE { context_.reset(new ServiceWorkerContextCore(base::FilePath(), NULL)); helper_.reset(new MessageReceiver(context_.get())); registration_ = new ServiceWorkerRegistration( GURL("http://www.example.com/*"), GURL("http://www.example.com/service_worker.js"), 1L, context_->AsWeakPtr()); version_ = new ServiceWorkerVersion( registration_, 1L, context_->AsWeakPtr()); // Simulate adding one process to the worker. int embedded_worker_id = version_->embedded_worker()->embedded_worker_id(); helper_->SimulateAddProcessToWorker(embedded_worker_id, kRenderProcessId); } virtual void TearDown() OVERRIDE { version_ = 0; registration_ = 0; helper_.reset(); context_.reset(); } TestBrowserThreadBundle thread_bundle_; scoped_ptr<ServiceWorkerContextCore> context_; scoped_ptr<EmbeddedWorkerTestHelper> helper_; scoped_refptr<ServiceWorkerRegistration> registration_; scoped_refptr<ServiceWorkerVersion> version_; DISALLOW_COPY_AND_ASSIGN(ServiceWorkerVersionTest); }; TEST_F(ServiceWorkerVersionTest, ConcurrentStartAndStop) { // Call StartWorker() multiple times. ServiceWorkerStatusCode status1 = SERVICE_WORKER_ERROR_FAILED; ServiceWorkerStatusCode status2 = SERVICE_WORKER_ERROR_FAILED; ServiceWorkerStatusCode status3 = SERVICE_WORKER_ERROR_FAILED; version_->StartWorker(CreateReceiverOnCurrentThread(&status1)); version_->StartWorker(CreateReceiverOnCurrentThread(&status2)); EXPECT_EQ(ServiceWorkerVersion::STARTING, version_->running_status()); base::RunLoop().RunUntilIdle(); EXPECT_EQ(ServiceWorkerVersion::RUNNING, version_->running_status()); // Call StartWorker() after it's started. version_->StartWorker(CreateReceiverOnCurrentThread(&status3)); base::RunLoop().RunUntilIdle(); // All should just succeed. EXPECT_EQ(SERVICE_WORKER_OK, status1); EXPECT_EQ(SERVICE_WORKER_OK, status2); EXPECT_EQ(SERVICE_WORKER_OK, status3); // Call StopWorker() multiple times. status1 = SERVICE_WORKER_ERROR_FAILED; status2 = SERVICE_WORKER_ERROR_FAILED; status3 = SERVICE_WORKER_ERROR_FAILED; version_->StopWorker(CreateReceiverOnCurrentThread(&status1)); version_->StopWorker(CreateReceiverOnCurrentThread(&status2)); // Also try calling StartWorker while StopWorker is in queue. version_->StartWorker(CreateReceiverOnCurrentThread(&status3)); EXPECT_EQ(ServiceWorkerVersion::STOPPING, version_->running_status()); base::RunLoop().RunUntilIdle(); EXPECT_EQ(ServiceWorkerVersion::STOPPED, version_->running_status()); // All StopWorker should just succeed, while StartWorker fails. EXPECT_EQ(SERVICE_WORKER_OK, status1); EXPECT_EQ(SERVICE_WORKER_OK, status2); EXPECT_EQ(SERVICE_WORKER_ERROR_START_WORKER_FAILED, status3); } TEST_F(ServiceWorkerVersionTest, SendMessage) { EXPECT_EQ(ServiceWorkerVersion::STOPPED, version_->running_status()); // Send a message without starting the worker. ServiceWorkerStatusCode status = SERVICE_WORKER_ERROR_FAILED; version_->SendMessage(TestMsg_Message(), CreateReceiverOnCurrentThread(&status)); base::RunLoop().RunUntilIdle(); EXPECT_EQ(SERVICE_WORKER_OK, status); // The worker should be now started. EXPECT_EQ(ServiceWorkerVersion::RUNNING, version_->running_status()); // Stop the worker, and then send the message immediately. ServiceWorkerStatusCode msg_status = SERVICE_WORKER_ERROR_FAILED; ServiceWorkerStatusCode stop_status = SERVICE_WORKER_ERROR_FAILED; version_->StopWorker(CreateReceiverOnCurrentThread(&stop_status)); version_->SendMessage(TestMsg_Message(), CreateReceiverOnCurrentThread(&msg_status)); base::RunLoop().RunUntilIdle(); EXPECT_EQ(SERVICE_WORKER_OK, stop_status); // SendMessage should return START_WORKER_FAILED error since it tried to // start a worker while it was stopping. EXPECT_EQ(SERVICE_WORKER_ERROR_START_WORKER_FAILED, msg_status); } TEST_F(ServiceWorkerVersionTest, ReSendMessageAfterStop) { EXPECT_EQ(ServiceWorkerVersion::STOPPED, version_->running_status()); // Start the worker. ServiceWorkerStatusCode start_status = SERVICE_WORKER_ERROR_FAILED; version_->StartWorker(CreateReceiverOnCurrentThread(&start_status)); base::RunLoop().RunUntilIdle(); EXPECT_EQ(SERVICE_WORKER_OK, start_status); EXPECT_EQ(ServiceWorkerVersion::RUNNING, version_->running_status()); // Stop the worker, and then send the message immediately. ServiceWorkerStatusCode msg_status = SERVICE_WORKER_ERROR_FAILED; ServiceWorkerStatusCode stop_status = SERVICE_WORKER_ERROR_FAILED; version_->StopWorker(CreateReceiverOnCurrentThread(&stop_status)); version_->SendMessage(TestMsg_Message(), CreateReceiverOnCurrentThread(&msg_status)); base::RunLoop().RunUntilIdle(); EXPECT_EQ(SERVICE_WORKER_OK, stop_status); // SendMessage should return START_WORKER_FAILED error since it tried to // start a worker while it was stopping. EXPECT_EQ(SERVICE_WORKER_ERROR_START_WORKER_FAILED, msg_status); // Resend the message, which should succeed and restart the worker. version_->SendMessage(TestMsg_Message(), CreateReceiverOnCurrentThread(&msg_status)); base::RunLoop().RunUntilIdle(); EXPECT_EQ(SERVICE_WORKER_OK, msg_status); EXPECT_EQ(ServiceWorkerVersion::RUNNING, version_->running_status()); } TEST_F(ServiceWorkerVersionTest, SendMessageAndRegisterCallback) { // Send multiple messages and verify responses. ServiceWorkerStatusCode status1 = SERVICE_WORKER_ERROR_FAILED; ServiceWorkerStatusCode status2 = SERVICE_WORKER_ERROR_FAILED; int value1 = -1, value2 = -1; version_->SendMessageAndRegisterCallback( TestMsg_Request(111), base::Bind(&ReceiveResponse, &status1, &value1)); version_->SendMessageAndRegisterCallback( TestMsg_Request(333), base::Bind(&ReceiveResponse, &status2, &value2)); base::RunLoop().RunUntilIdle(); EXPECT_EQ(SERVICE_WORKER_OK, status1); EXPECT_EQ(SERVICE_WORKER_OK, status2); EXPECT_EQ(111 * 2, value1); EXPECT_EQ(333 * 2, value2); } TEST_F(ServiceWorkerVersionTest, InstallAndWaitCompletion) { EXPECT_EQ(ServiceWorkerVersion::NEW, version_->status()); // Dispatch an install event. ServiceWorkerStatusCode status = SERVICE_WORKER_ERROR_FAILED; version_->DispatchInstallEvent(-1, CreateReceiverOnCurrentThread(&status)); EXPECT_EQ(ServiceWorkerVersion::INSTALLING, version_->status()); // Wait for the completion. bool status_change_called = false; version_->RegisterStatusChangeCallback( base::Bind(&VerifyCalled, &status_change_called)); base::RunLoop().RunUntilIdle(); // After successful completion, version's status must be changed to // INSTALLED, and status change callback must have been fired. EXPECT_EQ(SERVICE_WORKER_OK, status); EXPECT_TRUE(status_change_called); EXPECT_EQ(ServiceWorkerVersion::INSTALLED, version_->status()); } TEST_F(ServiceWorkerVersionTest, ActivateAndWaitCompletion) { version_->SetStatus(ServiceWorkerVersion::INSTALLED); EXPECT_EQ(ServiceWorkerVersion::INSTALLED, version_->status()); // Dispatch an activate event. ServiceWorkerStatusCode status = SERVICE_WORKER_ERROR_FAILED; version_->DispatchActivateEvent(CreateReceiverOnCurrentThread(&status)); EXPECT_EQ(ServiceWorkerVersion::ACTIVATING, version_->status()); // Wait for the completion. bool status_change_called = false; version_->RegisterStatusChangeCallback( base::Bind(&VerifyCalled, &status_change_called)); base::RunLoop().RunUntilIdle(); // After successful completion, version's status must be changed to // ACTIVE, and status change callback must have been fired. EXPECT_EQ(SERVICE_WORKER_OK, status); EXPECT_TRUE(status_change_called); EXPECT_EQ(ServiceWorkerVersion::ACTIVE, version_->status()); } TEST_F(ServiceWorkerVersionTest, DISABLED_RepeatedlyObserveStatusChanges) { EXPECT_EQ(ServiceWorkerVersion::NEW, version_->status()); // Repeatedly observe status changes (the callback re-registers itself). std::vector<ServiceWorkerVersion::Status> statuses; version_->RegisterStatusChangeCallback( base::Bind(&ObserveStatusChanges, version_, &statuses)); // Dispatch some events. ServiceWorkerStatusCode status = SERVICE_WORKER_ERROR_FAILED; version_->DispatchInstallEvent(-1, CreateReceiverOnCurrentThread(&status)); base::RunLoop().RunUntilIdle(); EXPECT_EQ(SERVICE_WORKER_OK, status); status = SERVICE_WORKER_ERROR_FAILED; version_->DispatchActivateEvent(CreateReceiverOnCurrentThread(&status)); base::RunLoop().RunUntilIdle(); EXPECT_EQ(SERVICE_WORKER_OK, status); // Verify that we could successfully observe repeated status changes. ASSERT_EQ(4U, statuses.size()); ASSERT_EQ(ServiceWorkerVersion::INSTALLING, statuses[0]); ASSERT_EQ(ServiceWorkerVersion::INSTALLED, statuses[1]); ASSERT_EQ(ServiceWorkerVersion::ACTIVATING, statuses[2]); ASSERT_EQ(ServiceWorkerVersion::ACTIVE, statuses[3]); } } // namespace content <|endoftext|>
<commit_before>#pragma once #include <complex> #include <string> #include <type_traits> #include <limits> namespace tbm { namespace num { namespace detail { template<class scalar_t> struct complex_traits { using real_t = scalar_t; using complex_t = std::complex<scalar_t>; static constexpr bool is_complex = false; }; template<class scalar_t> struct complex_traits<std::complex<scalar_t>> { using real_t = scalar_t; using complex_t = std::complex<scalar_t>; static constexpr bool is_complex = true; }; } // namespace detail template<class scalar_t> using get_real_t = typename detail::complex_traits<scalar_t>::real_t; template<class scalar_t> using get_complex_t = typename detail::complex_traits<scalar_t>::complex_t; template<class scalar_t> inline constexpr bool is_complex() { return detail::complex_traits<scalar_t>::is_complex; } template<class scalar_t> inline scalar_t conjugate(scalar_t value) { return value; } template<class scalar_t> inline std::complex<scalar_t> conjugate(std::complex<scalar_t> value) { return std::conj(value); } template<class scalar_t> inline scalar_t complex_cast(std::complex<double> v) { return v; } template<> inline std::complex<float> complex_cast(std::complex<double> v) { return {static_cast<float>(v.real()), static_cast<float>(v.imag())}; } template<> inline double complex_cast<double>(std::complex<double> v) { return v.real(); } template<> inline float complex_cast<float>(std::complex<double> v) { return static_cast<float>(v.real()); } template<class scalar_t> inline std::string scalar_name() { return ""; } template<> inline std::string scalar_name<float>() { return "float"; } template<> inline std::string scalar_name<double>() { return "double"; } template<> inline std::string scalar_name<std::complex<float>>() { return "complex<float>"; } template<> inline std::string scalar_name<std::complex<double>>() { return "complex<double>"; } /** Floating-point equality with precision in ULP (units in the last place) */ template<class T, class = typename std::enable_if<std::is_floating_point<T>::value, void>::type> bool approx_equal(T x, T y, int ulp = 1) { auto const diff = std::abs(x - y); auto const scale = std::abs(x + y); return diff <= std::numeric_limits<T>::epsilon() * scale * ulp || diff <= std::numeric_limits<T>::min(); // subnormal case } }} // namespace tbm::num <commit_msg>Document numeric traits<commit_after>#pragma once #include <complex> #include <string> #include <type_traits> #include <limits> namespace tbm { namespace num { namespace detail { template<class T> struct complex_traits { static_assert(std::is_arithmetic<T>::value, ""); using real_t = T; using complex_t = std::complex<T>; static constexpr bool is_complex = false; }; template<class T> struct complex_traits<std::complex<T>> { using real_t = T; using complex_t = std::complex<T>; static constexpr bool is_complex = true; }; } // namespace detail /** Return the real type corresponding to the given scalar type For example: std::complex<float> -> float float -> float */ template<class scalar_t> using get_real_t = typename detail::complex_traits<scalar_t>::real_t; /** Return the complex type corresponding to the given scalar type For example: std::complex<float> -> std::complex<float> float -> std::complex<float> */ template<class scalar_t> using get_complex_t = typename detail::complex_traits<scalar_t>::complex_t; /** Is the given scalar type complex? */ template<class scalar_t> inline constexpr bool is_complex() { return detail::complex_traits<scalar_t>::is_complex; } /** Return the complex conjugate in the same scalar type as the input The standard `conj` function always returns `std::complex<T>` which is not convenient for generic algorithms. */ template<class scalar_t> inline scalar_t conjugate(scalar_t value) { return value; } template<class scalar_t> inline std::complex<scalar_t> conjugate(std::complex<scalar_t> value) { return std::conj(value); } /** Cast a `std::complex<double>` to another scalar The conversion loses precision and/or the imaginary part, as intended. */ template<class scalar_t> inline scalar_t complex_cast(std::complex<double> v) { return v; } template<> inline std::complex<float> complex_cast<std::complex<float>>(std::complex<double> v) { return {static_cast<float>(v.real()), static_cast<float>(v.imag())}; } template<> inline double complex_cast<double>(std::complex<double> v) { return v.real(); } template<> inline float complex_cast<float>(std::complex<double> v) { return static_cast<float>(v.real()); } /** Return a human readable name of the scalar type */ template<class scalar_t> inline std::string scalar_name(); template<> inline std::string scalar_name<float>() { return "float"; } template<> inline std::string scalar_name<double>() { return "double"; } template<> inline std::string scalar_name<std::complex<float>>() { return "complex<float>"; } template<> inline std::string scalar_name<std::complex<double>>() { return "complex<double>"; } /** Floating-point equality with precision in ULP (units in the last place) */ template<class T, class = typename std::enable_if<std::is_floating_point<T>::value, void>::type> bool approx_equal(T x, T y, int ulp = 1) { auto const diff = std::abs(x - y); auto const scale = std::abs(x + y); return diff <= std::numeric_limits<T>::epsilon() * scale * ulp || diff <= std::numeric_limits<T>::min(); // subnormal case } }} // namespace tbm::num <|endoftext|>
<commit_before>#include "xchainer/testing/routines.h" #include <functional> #include <iostream> #include <sstream> #include <vector> #include <gsl/gsl> #include "xchainer/array.h" #include "xchainer/context.h" #include "xchainer/numeric.h" #include "xchainer/testing/threading.h" namespace xchainer { namespace testing { namespace { void CheckArraysEqual(const std::vector<Array>& expected, const std::vector<Array>& actual, double atol, double rtol) { // Number of outputs if (expected.size() != actual.size()) { throw RoutinesCheckError{"Number of arrays does not match."}; } // Output array properties for (size_t i = 0; i < expected.size(); ++i) { const Array& e = expected[i]; const Array& a = actual[i]; if (e.shape() != a.shape()) { throw RoutinesCheckError{"Shape of output array ", i, " of ", expected.size(), " is incorrect. Actual ", a.shape(), " != Expected ", e.shape(), "."}; } if (e.dtype() != a.dtype()) { throw RoutinesCheckError{"Dtype of output array ", i, " of ", expected.size(), " is incorrect. Actual ", GetDtypeName(a.dtype()), " != Expected ", GetDtypeName(e.dtype()), "."}; } if (&e.device() != &a.device()) { throw RoutinesCheckError{"Device of output array ", i, " of ", expected.size(), " is incorrect. Actual ", a.device().name(), " != Expected ", e.device().name(), "."}; } } // Numerical check std::vector<size_t> failed_input_indices; for (size_t i = 0; i < expected.size(); ++i) { const Array& e = expected[i]; const Array& a = actual[i]; if (!AllClose(e, a, atol, rtol)) { failed_input_indices.emplace_back(i); } } if (!failed_input_indices.empty()) { std::ostringstream os; os << "Numerical error in forward outputs (out of " << expected.size() << "): "; for (size_t i : failed_input_indices) { if (i != 0) { os << ", "; } os << i; } os << std::endl; os << "Atol: " << atol << " Rtol: " << rtol << std::endl; for (size_t i : failed_input_indices) { const Array& e = expected[i]; const Array& a = actual[i]; os << "Error[" << i << "]:" << std::endl << e - a << std::endl // TODO(niboshi): Use abs << "Actual output[" << i << "]:" << std::endl << a << std::endl << "Expected output[" << i << "]:" << std ::endl << e << std::endl; } throw RoutinesCheckError{os.str()}; } } } // namespace // TODO(niboshi): Check array nodes of output arrays to ensure the implementation takes backprop mode into account void CheckForward( const std::function<std::vector<Array>(const std::vector<Array>&)>& func, const std::vector<Array>& inputs, const std::vector<Array>& expected_outputs, size_t concurrent_check_repeat_count, size_t concurrent_check_thread_count, double atol, double rtol) { // Run single-shot test std::vector<Array> outputs = func(inputs); CheckArraysEqual(expected_outputs, outputs, atol, rtol); // Run thread safety check if (concurrent_check_repeat_count > 0) { Context& context = xchainer::GetDefaultContext(); CheckThreadSafety( concurrent_check_repeat_count, concurrent_check_thread_count, [](size_t /*repeat_index*/) { return nullptr; }, [&func, &inputs, &expected_outputs, &atol, &rtol, &context](size_t /*thread_index*/, std::nullptr_t) { xchainer::SetDefaultContext(&context); std::vector<Array> outputs = func(inputs); CheckArraysEqual(expected_outputs, outputs, atol, rtol); return nullptr; }, [](const std::vector<std::nullptr_t>&) {}); } } } // namespace testing } // namespace xchainer <commit_msg>CheckArraysEqual -> CheckOutputArraysEqual<commit_after>#include "xchainer/testing/routines.h" #include <functional> #include <iostream> #include <sstream> #include <vector> #include <gsl/gsl> #include "xchainer/array.h" #include "xchainer/context.h" #include "xchainer/numeric.h" #include "xchainer/testing/threading.h" namespace xchainer { namespace testing { namespace { void CheckOutputArraysEqual(const std::vector<Array>& expected, const std::vector<Array>& actual, double atol, double rtol) { // Number of outputs if (expected.size() != actual.size()) { throw RoutinesCheckError{"Number of output arrays does not match."}; } // Output array properties for (size_t i = 0; i < expected.size(); ++i) { const Array& e = expected[i]; const Array& a = actual[i]; if (e.shape() != a.shape()) { throw RoutinesCheckError{"Shape of output array ", i, " of ", expected.size(), " is incorrect. Actual ", a.shape(), " != Expected ", e.shape(), "."}; } if (e.dtype() != a.dtype()) { throw RoutinesCheckError{"Dtype of output array ", i, " of ", expected.size(), " is incorrect. Actual ", GetDtypeName(a.dtype()), " != Expected ", GetDtypeName(e.dtype()), "."}; } if (&e.device() != &a.device()) { throw RoutinesCheckError{"Device of output array ", i, " of ", expected.size(), " is incorrect. Actual ", a.device().name(), " != Expected ", e.device().name(), "."}; } } // Numerical check std::vector<size_t> failed_input_indices; for (size_t i = 0; i < expected.size(); ++i) { const Array& e = expected[i]; const Array& a = actual[i]; if (!AllClose(e, a, atol, rtol)) { failed_input_indices.emplace_back(i); } } if (!failed_input_indices.empty()) { std::ostringstream os; os << "Numerical error in forward outputs (out of " << expected.size() << "): "; for (size_t i : failed_input_indices) { if (i != 0) { os << ", "; } os << i; } os << std::endl; os << "Atol: " << atol << " Rtol: " << rtol << std::endl; for (size_t i : failed_input_indices) { const Array& e = expected[i]; const Array& a = actual[i]; os << "Error[" << i << "]:" << std::endl << e - a << std::endl // TODO(niboshi): Use abs << "Actual output[" << i << "]:" << std::endl << a << std::endl << "Expected output[" << i << "]:" << std ::endl << e << std::endl; } throw RoutinesCheckError{os.str()}; } } } // namespace // TODO(niboshi): Check array nodes of output arrays to ensure the implementation takes backprop mode into account void CheckForward( const std::function<std::vector<Array>(const std::vector<Array>&)>& func, const std::vector<Array>& inputs, const std::vector<Array>& expected_outputs, size_t concurrent_check_repeat_count, size_t concurrent_check_thread_count, double atol, double rtol) { // Run single-shot test std::vector<Array> outputs = func(inputs); CheckOutputArraysEqual(expected_outputs, outputs, atol, rtol); // Run thread safety check if (concurrent_check_repeat_count > 0) { Context& context = xchainer::GetDefaultContext(); CheckThreadSafety( concurrent_check_repeat_count, concurrent_check_thread_count, [](size_t /*repeat_index*/) { return nullptr; }, [&func, &inputs, &expected_outputs, &atol, &rtol, &context](size_t /*thread_index*/, std::nullptr_t) { xchainer::SetDefaultContext(&context); std::vector<Array> outputs = func(inputs); CheckOutputArraysEqual(expected_outputs, outputs, atol, rtol); return nullptr; }, [](const std::vector<std::nullptr_t>&) {}); } } } // namespace testing } // namespace xchainer <|endoftext|>
<commit_before>// Copyright (c) 2020 by Apex.AI Inc. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include "test.hpp" #include "iceoryx_utils/concurrent/resizeable_lockfree_queue.hpp" using namespace ::testing; //********************************************************* // Test the added functionaility of ResizeableLockFreeQueue // to change the capacity (setCapacity). // The remaining functionality is identical to LockFreeQueue // and tested in test_lockfree_queue.cpp (as a typed test). //********************************************************* namespace { // use a non-POD type for testing (just a boxed version of int) struct Integer { Integer(int value = 0) : value(value) { } int value{0}; // so that it behaves like an int for comparison purposes operator int() const { return value; } }; template <typename T> class ResizeableLockFreeQueueTest : public ::testing::Test { protected: ResizeableLockFreeQueueTest() { } ~ResizeableLockFreeQueueTest() { } void SetUp() { } void TearDown() { } void fillQueue(int start = 0) { int element{start}; for (uint64_t i = 0; i < queue.capacity(); ++i) { queue.tryPush(element); element++; } } using Queue = T; Queue queue; }; template <size_t Capacity> using IntegerQueue = iox::concurrent::ResizeableLockFreeQueue<Integer, Capacity>; template <size_t Capacity> using IntQueue = iox::concurrent::ResizeableLockFreeQueue<int, Capacity>; typedef ::testing::Types<IntegerQueue<1>, IntegerQueue<10>, IntQueue<10>> TestQueues; /// we require TYPED_TEST since we support gtest 1.8 for our safety targets #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wdeprecated-declarations" TYPED_TEST_CASE(ResizeableLockFreeQueueTest, TestQueues); #pragma GCC diagnostic pop TEST(ResizeableLockFreeQueueTest, maxCapacityIsConsistent) { using Queue = IntegerQueue<37>; EXPECT_EQ(Queue::maxCapacity(), 37); } TYPED_TEST(ResizeableLockFreeQueueTest, initialCapacityIsMaximalbyDefault) { using Queue = typename TestFixture::Queue; auto& q = this->queue; EXPECT_EQ(q.capacity(), q.maxCapacity()); EXPECT_EQ(q.capacity(), Queue::maxCapacity()); } TYPED_TEST(ResizeableLockFreeQueueTest, constructWithMaxCapacity) { constexpr auto MAX_CAP = TestFixture::Queue::MAX_CAPACITY; typename TestFixture::Queue q(MAX_CAP); EXPECT_EQ(q.capacity(), q.maxCapacity()); } TYPED_TEST(ResizeableLockFreeQueueTest, constructWithMoreThanMaxCapacitySaturatesAtMaxCapacity) { constexpr auto MAX_CAP = TestFixture::Queue::MAX_CAPACITY; typename TestFixture::Queue q(MAX_CAP + 1); EXPECT_EQ(q.capacity(), q.maxCapacity()); } TYPED_TEST(ResizeableLockFreeQueueTest, constructWithNoCapacity) { typename TestFixture::Queue q(0); EXPECT_EQ(q.capacity(), 0); } TYPED_TEST(ResizeableLockFreeQueueTest, constructWithHalfOfMaxCapacity) { constexpr auto cap = TestFixture::Queue::MAX_CAPACITY / 2; typename TestFixture::Queue q(cap); EXPECT_EQ(q.capacity(), cap); } TYPED_TEST(ResizeableLockFreeQueueTest, decreaseCapacityToZeroOneByOne) { auto& q = this->queue; constexpr auto MAX_CAP = TestFixture::Queue::MAX_CAPACITY; auto i = MAX_CAP; while (i > 0) { EXPECT_TRUE(q.setCapacity(--i)); ASSERT_EQ(q.capacity(), i); } } TYPED_TEST(ResizeableLockFreeQueueTest, increaseToMaxCapacity) { typename TestFixture::Queue q(0); constexpr auto MAX_CAP = TestFixture::Queue::MAX_CAPACITY; EXPECT_EQ(q.capacity(), 0); EXPECT_TRUE(q.setCapacity(MAX_CAP)); EXPECT_EQ(q.capacity(), MAX_CAP); } TYPED_TEST(ResizeableLockFreeQueueTest, increaseToMaxCapacityOneByOne) { typename TestFixture::Queue q(0); constexpr auto MAX_CAP = TestFixture::Queue::MAX_CAPACITY; EXPECT_EQ(q.capacity(), 0); for (uint64_t i = 0; i < MAX_CAP;) { EXPECT_TRUE(q.setCapacity(++i)); ASSERT_EQ(q.capacity(), i); } } TYPED_TEST(ResizeableLockFreeQueueTest, setCapacityToZero) { auto& q = this->queue; EXPECT_TRUE(q.setCapacity(0)); EXPECT_EQ(q.capacity(), 0); } TYPED_TEST(ResizeableLockFreeQueueTest, setCapacityToOne) { auto& q = this->queue; EXPECT_TRUE(q.setCapacity(1)); EXPECT_EQ(q.capacity(), 1); } TYPED_TEST(ResizeableLockFreeQueueTest, setCapacityToMaxCapacity) { typename TestFixture::Queue q(0); constexpr auto MAX_CAP = TestFixture::Queue::MAX_CAPACITY; EXPECT_TRUE(q.setCapacity(MAX_CAP)); EXPECT_EQ(q.capacity(), MAX_CAP); } TYPED_TEST(ResizeableLockFreeQueueTest, setCapacityToHalfOfMaxCapacityAndFillIt) { auto& q = this->queue; constexpr auto MAX_CAP = TestFixture::Queue::MAX_CAPACITY; uint64_t newCap = MAX_CAP / 2; EXPECT_EQ(q.setCapacity(newCap), true); EXPECT_EQ(q.capacity(), newCap); uint element = 0; while (q.tryPush(element++)) ; EXPECT_EQ(q.capacity(), newCap); EXPECT_EQ(q.size(), newCap); EXPECT_EQ(element, newCap + 1); } TYPED_TEST(ResizeableLockFreeQueueTest, setCapacityFromHalfOfMaxCapacityToMaxCapacity) { auto& q = this->queue; constexpr auto MAX_CAP = TestFixture::Queue::MAX_CAPACITY; uint64_t cap = MAX_CAP / 2; EXPECT_EQ(q.setCapacity(cap), true); EXPECT_EQ(q.capacity(), cap); uint64_t element = 0; while (q.tryPush(element++)) ; EXPECT_EQ(q.capacity(), cap); EXPECT_EQ(q.size(), cap); EXPECT_EQ(element, cap + 1); EXPECT_EQ(q.setCapacity(MAX_CAP), true); EXPECT_EQ(q.capacity(), MAX_CAP); EXPECT_EQ(q.size(), cap); --element; // compensate the last failed tryPush while (q.tryPush(element++)) ; // we want to find all elements we pushed for (element = 0; element < MAX_CAP; ++element) { auto result = q.pop(); ASSERT_TRUE(result.has_value()); EXPECT_EQ(result.value(), element); } } TYPED_TEST(ResizeableLockFreeQueueTest, setCapacityOfFullQueueToHalfOfMaxCapacity) { auto& q = this->queue; constexpr auto MAX_CAP = TestFixture::Queue::MAX_CAPACITY; uint64_t cap = MAX_CAP / 2; uint64_t element = 0; while (q.tryPush(element++)) ; EXPECT_EQ(q.capacity(), MAX_CAP); EXPECT_EQ(q.size(), MAX_CAP); EXPECT_TRUE(q.setCapacity(cap)); EXPECT_EQ(q.capacity(), cap); EXPECT_EQ(q.size(), cap); if (cap == 0) { return; } // the least recent values are removed due to the capacity being decreased for (element = cap; element < MAX_CAP; ++element) { auto result = q.pop(); ASSERT_TRUE(result.has_value()); EXPECT_EQ(result.value(), element); } } // note this is one of the most general cases and necessary to test: // decreasing the capacity starting with a partially filled queue and checking whether the last values // remain (and the others are removed) TYPED_TEST(ResizeableLockFreeQueueTest, DecreaseCapacityOfAPartiallyFilledQueue) { auto& q = this->queue; constexpr auto MAX_CAP = TestFixture::Queue::MAX_CAPACITY; iox::cxx::vector<int, MAX_CAP> removedElements; uint64_t cap = MAX_CAP / 2; EXPECT_TRUE(q.setCapacity(cap)); EXPECT_EQ(q.capacity(), cap); uint64_t element = 0; while (q.tryPush(element++)) ; EXPECT_EQ(q.capacity(), cap); EXPECT_EQ(q.size(), cap); auto cap2 = cap + MAX_CAP / 4; // roughly 3 quarters of max (integer division) EXPECT_TRUE(q.setCapacity(cap2)); EXPECT_EQ(q.capacity(), cap2); EXPECT_EQ(q.size(), cap); auto cap3 = cap2 - cap; // roughly a quarter of max EXPECT_TRUE(q.setCapacity(cap3, removedElements)); EXPECT_EQ(q.capacity(), cap3); EXPECT_EQ(q.size(), cap3); // cap3 elements remain, the first cap - cap3 elements are removed // were the least recent elements removed? EXPECT_EQ(removedElements.size(), cap - cap3); element = 0; for (auto& removedElement : removedElements) { EXPECT_EQ(removedElement, element++); } // are the remaining elements correct? (i.e. we did not remove too many elements) for (element = cap - cap3; element < cap; ++element) { auto result = q.pop(); ASSERT_TRUE(result.has_value()); EXPECT_EQ(result.value(), element); } // refill to verify the capacity can really be used element = 0; while (q.tryPush(element++)) ; for (element = 0; element < cap3; ++element) { auto result = q.pop(); ASSERT_TRUE(result.has_value()); EXPECT_EQ(result.value(), element); } } TYPED_TEST(ResizeableLockFreeQueueTest, DecreaseCapacityOfAPartiallyFilledQueueWithRemoveHandler) { using element_t = typename TestFixture::Queue::element_t; auto& q = this->queue; constexpr auto MAX_CAP = TestFixture::Queue::MAX_CAPACITY; iox::cxx::vector<int, MAX_CAP> removedElements; auto removeHandler = [&](const element_t& value) { removedElements.push_back(std::move(value)); }; uint64_t cap = MAX_CAP / 2; EXPECT_TRUE(q.setCapacity(cap)); EXPECT_EQ(q.capacity(), cap); uint64_t element = 0; while (q.tryPush(element++)) ; EXPECT_EQ(q.capacity(), cap); EXPECT_EQ(q.size(), cap); auto cap2 = cap + MAX_CAP / 4; // roughly 3 quarters of max (integer division) EXPECT_TRUE(q.setCapacity(cap2)); EXPECT_EQ(q.capacity(), cap2); EXPECT_EQ(q.size(), cap); auto cap3 = cap2 - cap; // roughly a quarter of max EXPECT_TRUE(q.setCapacity(cap3, removeHandler)); EXPECT_EQ(q.capacity(), cap3); EXPECT_EQ(q.size(), cap3); // cap3 elements remain, the first cap - cap3 elements are removed // were the least recent elements removed? EXPECT_EQ(removedElements.size(), cap - cap3); element = 0; for (auto& removedElement : removedElements) { EXPECT_EQ(removedElement, element++); } // are the remaining elements correct? (i.e. we did not remove too many elements) for (element = cap - cap3; element < cap; ++element) { auto result = q.pop(); ASSERT_TRUE(result.has_value()); EXPECT_EQ(result.value(), element); } // refill to verify the capacity can really be used element = 0; while (q.tryPush(element++)) ; for (element = 0; element < cap3; ++element) { auto result = q.pop(); ASSERT_TRUE(result.has_value()); EXPECT_EQ(result.value(), element); } } } // namespace<commit_msg>iox-#216 fix type conversion in test<commit_after>// Copyright (c) 2020 by Apex.AI Inc. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include "test.hpp" #include "iceoryx_utils/concurrent/resizeable_lockfree_queue.hpp" using namespace ::testing; //********************************************************* // Test the added functionaility of ResizeableLockFreeQueue // to change the capacity (setCapacity). // The remaining functionality is identical to LockFreeQueue // and tested in test_lockfree_queue.cpp (as a typed test). //********************************************************* namespace { // use a non-POD type for testing (just a boxed version of int) struct Integer { Integer(int value = 0) : value(value) { } int value{0}; // so that it behaves like an int for comparison purposes operator int() const { return value; } }; template <typename T> class ResizeableLockFreeQueueTest : public ::testing::Test { protected: ResizeableLockFreeQueueTest() { } ~ResizeableLockFreeQueueTest() { } void SetUp() { } void TearDown() { } void fillQueue(int start = 0) { int element{start}; for (uint64_t i = 0; i < queue.capacity(); ++i) { queue.tryPush(element); element++; } } using Queue = T; Queue queue; }; template <size_t Capacity> using IntegerQueue = iox::concurrent::ResizeableLockFreeQueue<Integer, Capacity>; template <size_t Capacity> using IntQueue = iox::concurrent::ResizeableLockFreeQueue<int, Capacity>; typedef ::testing::Types<IntegerQueue<1>, IntegerQueue<10>, IntQueue<10>> TestQueues; /// we require TYPED_TEST since we support gtest 1.8 for our safety targets #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wdeprecated-declarations" TYPED_TEST_CASE(ResizeableLockFreeQueueTest, TestQueues); #pragma GCC diagnostic pop TEST(ResizeableLockFreeQueueTest, maxCapacityIsConsistent) { using Queue = IntegerQueue<37>; EXPECT_EQ(Queue::maxCapacity(), 37); } TYPED_TEST(ResizeableLockFreeQueueTest, initialCapacityIsMaximalbyDefault) { using Queue = typename TestFixture::Queue; auto& q = this->queue; EXPECT_EQ(q.capacity(), q.maxCapacity()); EXPECT_EQ(q.capacity(), Queue::maxCapacity()); } TYPED_TEST(ResizeableLockFreeQueueTest, constructWithMaxCapacity) { constexpr auto MAX_CAP = TestFixture::Queue::MAX_CAPACITY; typename TestFixture::Queue q(MAX_CAP); EXPECT_EQ(q.capacity(), q.maxCapacity()); } TYPED_TEST(ResizeableLockFreeQueueTest, constructWithMoreThanMaxCapacitySaturatesAtMaxCapacity) { constexpr auto MAX_CAP = TestFixture::Queue::MAX_CAPACITY; typename TestFixture::Queue q(MAX_CAP + 1); EXPECT_EQ(q.capacity(), q.maxCapacity()); } TYPED_TEST(ResizeableLockFreeQueueTest, constructWithNoCapacity) { typename TestFixture::Queue q(0); EXPECT_EQ(q.capacity(), 0); } TYPED_TEST(ResizeableLockFreeQueueTest, constructWithHalfOfMaxCapacity) { constexpr auto cap = TestFixture::Queue::MAX_CAPACITY / 2; typename TestFixture::Queue q(cap); EXPECT_EQ(q.capacity(), cap); } TYPED_TEST(ResizeableLockFreeQueueTest, decreaseCapacityToZeroOneByOne) { auto& q = this->queue; constexpr auto MAX_CAP = TestFixture::Queue::MAX_CAPACITY; auto i = MAX_CAP; while (i > 0) { EXPECT_TRUE(q.setCapacity(--i)); ASSERT_EQ(q.capacity(), i); } } TYPED_TEST(ResizeableLockFreeQueueTest, increaseToMaxCapacity) { typename TestFixture::Queue q(0); constexpr auto MAX_CAP = TestFixture::Queue::MAX_CAPACITY; EXPECT_EQ(q.capacity(), 0); EXPECT_TRUE(q.setCapacity(MAX_CAP)); EXPECT_EQ(q.capacity(), MAX_CAP); } TYPED_TEST(ResizeableLockFreeQueueTest, increaseToMaxCapacityOneByOne) { typename TestFixture::Queue q(0); constexpr auto MAX_CAP = TestFixture::Queue::MAX_CAPACITY; EXPECT_EQ(q.capacity(), 0); for (uint64_t i = 0; i < MAX_CAP;) { EXPECT_TRUE(q.setCapacity(++i)); ASSERT_EQ(q.capacity(), i); } } TYPED_TEST(ResizeableLockFreeQueueTest, setCapacityToZero) { auto& q = this->queue; EXPECT_TRUE(q.setCapacity(0)); EXPECT_EQ(q.capacity(), 0); } TYPED_TEST(ResizeableLockFreeQueueTest, setCapacityToOne) { auto& q = this->queue; EXPECT_TRUE(q.setCapacity(1)); EXPECT_EQ(q.capacity(), 1); } TYPED_TEST(ResizeableLockFreeQueueTest, setCapacityToMaxCapacity) { typename TestFixture::Queue q(0); constexpr auto MAX_CAP = TestFixture::Queue::MAX_CAPACITY; EXPECT_TRUE(q.setCapacity(MAX_CAP)); EXPECT_EQ(q.capacity(), MAX_CAP); } TYPED_TEST(ResizeableLockFreeQueueTest, setCapacityToHalfOfMaxCapacityAndFillIt) { auto& q = this->queue; constexpr auto MAX_CAP = TestFixture::Queue::MAX_CAPACITY; uint64_t newCap = MAX_CAP / 2; EXPECT_EQ(q.setCapacity(newCap), true); EXPECT_EQ(q.capacity(), newCap); int element = 0; while (q.tryPush(element++)) ; EXPECT_EQ(q.capacity(), newCap); EXPECT_EQ(q.size(), newCap); EXPECT_EQ(element, newCap + 1); } TYPED_TEST(ResizeableLockFreeQueueTest, setCapacityFromHalfOfMaxCapacityToMaxCapacity) { auto& q = this->queue; constexpr auto MAX_CAP = TestFixture::Queue::MAX_CAPACITY; uint64_t cap = MAX_CAP / 2; EXPECT_EQ(q.setCapacity(cap), true); EXPECT_EQ(q.capacity(), cap); int element = 0; while (q.tryPush(element++)) ; EXPECT_EQ(q.capacity(), cap); EXPECT_EQ(q.size(), cap); EXPECT_EQ(element, cap + 1); EXPECT_EQ(q.setCapacity(MAX_CAP), true); EXPECT_EQ(q.capacity(), MAX_CAP); EXPECT_EQ(q.size(), cap); --element; // compensate the last failed tryPush while (q.tryPush(element++)) ; // we want to find all elements we pushed for (element = 0; element < MAX_CAP; ++element) { auto result = q.pop(); ASSERT_TRUE(result.has_value()); EXPECT_EQ(result.value(), element); } } TYPED_TEST(ResizeableLockFreeQueueTest, setCapacityOfFullQueueToHalfOfMaxCapacity) { auto& q = this->queue; constexpr auto MAX_CAP = TestFixture::Queue::MAX_CAPACITY; uint64_t cap = MAX_CAP / 2; int element = 0; while (q.tryPush(element++)) ; EXPECT_EQ(q.capacity(), MAX_CAP); EXPECT_EQ(q.size(), MAX_CAP); EXPECT_TRUE(q.setCapacity(cap)); EXPECT_EQ(q.capacity(), cap); EXPECT_EQ(q.size(), cap); if (cap == 0) { return; } // the least recent values are removed due to the capacity being decreased for (element = cap; element < MAX_CAP; ++element) { auto result = q.pop(); ASSERT_TRUE(result.has_value()); EXPECT_EQ(result.value(), element); } } // note this is one of the most general cases and necessary to test: // decreasing the capacity starting with a partially filled queue and checking whether the last values // remain (and the others are removed) TYPED_TEST(ResizeableLockFreeQueueTest, DecreaseCapacityOfAPartiallyFilledQueue) { auto& q = this->queue; constexpr auto MAX_CAP = TestFixture::Queue::MAX_CAPACITY; iox::cxx::vector<int, MAX_CAP> removedElements; uint64_t cap = MAX_CAP / 2; EXPECT_TRUE(q.setCapacity(cap)); EXPECT_EQ(q.capacity(), cap); int element = 0; while (q.tryPush(element++)) ; EXPECT_EQ(q.capacity(), cap); EXPECT_EQ(q.size(), cap); auto cap2 = cap + MAX_CAP / 4; // roughly 3 quarters of max (integer division) EXPECT_TRUE(q.setCapacity(cap2)); EXPECT_EQ(q.capacity(), cap2); EXPECT_EQ(q.size(), cap); auto cap3 = cap2 - cap; // roughly a quarter of max EXPECT_TRUE(q.setCapacity(cap3, removedElements)); EXPECT_EQ(q.capacity(), cap3); EXPECT_EQ(q.size(), cap3); // cap3 elements remain, the first cap - cap3 elements are removed // were the least recent elements removed? EXPECT_EQ(removedElements.size(), cap - cap3); element = 0; for (auto& removedElement : removedElements) { EXPECT_EQ(removedElement, element++); } // are the remaining elements correct? (i.e. we did not remove too many elements) for (element = cap - cap3; element < cap; ++element) { auto result = q.pop(); ASSERT_TRUE(result.has_value()); EXPECT_EQ(result.value(), element); } // refill to verify the capacity can really be used element = 0; while (q.tryPush(element++)) ; for (element = 0; element < cap3; ++element) { auto result = q.pop(); ASSERT_TRUE(result.has_value()); EXPECT_EQ(result.value(), element); } } TYPED_TEST(ResizeableLockFreeQueueTest, DecreaseCapacityOfAPartiallyFilledQueueWithRemoveHandler) { using element_t = typename TestFixture::Queue::element_t; auto& q = this->queue; constexpr auto MAX_CAP = TestFixture::Queue::MAX_CAPACITY; iox::cxx::vector<int, MAX_CAP> removedElements; auto removeHandler = [&](const element_t& value) { removedElements.push_back(std::move(value)); }; uint64_t cap = MAX_CAP / 2; EXPECT_TRUE(q.setCapacity(cap)); EXPECT_EQ(q.capacity(), cap); int element = 0; while (q.tryPush(element++)) ; EXPECT_EQ(q.capacity(), cap); EXPECT_EQ(q.size(), cap); auto cap2 = cap + MAX_CAP / 4; // roughly 3 quarters of max (integer division) EXPECT_TRUE(q.setCapacity(cap2)); EXPECT_EQ(q.capacity(), cap2); EXPECT_EQ(q.size(), cap); auto cap3 = cap2 - cap; // roughly a quarter of max EXPECT_TRUE(q.setCapacity(cap3, removeHandler)); EXPECT_EQ(q.capacity(), cap3); EXPECT_EQ(q.size(), cap3); // cap3 elements remain, the first cap - cap3 elements are removed // were the least recent elements removed? EXPECT_EQ(removedElements.size(), cap - cap3); element = 0; for (auto& removedElement : removedElements) { EXPECT_EQ(removedElement, element++); } // are the remaining elements correct? (i.e. we did not remove too many elements) for (element = cap - cap3; element < cap; ++element) { auto result = q.pop(); ASSERT_TRUE(result.has_value()); EXPECT_EQ(result.value(), element); } // refill to verify the capacity can really be used element = 0; while (q.tryPush(element++)) ; for (element = 0; element < cap3; ++element) { auto result = q.pop(); ASSERT_TRUE(result.has_value()); EXPECT_EQ(result.value(), element); } } } // namespace<|endoftext|>
<commit_before>/************************************************ * Copyright (c) IBM Corp. 2014 * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html *************************************************/ /* * Contributors: * arayshu, lschneid - initial implementation */ #ifndef __SKV_SERVER_RETRIEVE_N_KEYS_COMMAND_SM_HPP__ #define __SKV_SERVER_RETRIEVE_N_KEYS_COMMAND_SM_HPP__ #ifndef SKV_SERVER_RETRIEVE_N_KEYS_COMMAND_SM_LOG #define SKV_SERVER_RETRIEVE_N_KEYS_COMMAND_SM_LOG ( 0 | SKV_LOGGING_ALL ) #endif #ifndef SKV_SERVER_RETRIEVE_N_KEYS_DATA_LOG #define SKV_SERVER_RETRIEVE_N_KEYS_DATA_LOG ( 0 ) #endif class skv_server_retrieve_n_keys_command_sm { static inline skv_status_t create_multi_stage( skv_server_ep_state_t *aEPState, skv_local_kv_t *aLocalKV, skv_server_ccb_t *aCommand, int aCommandOrdinal ) { skv_status_t status = SKV_SUCCESS; BegLogLine( SKV_SERVER_RETRIEVE_N_KEYS_COMMAND_SM_LOG ) << "skv_server_retrieve_n_keys_command_sm:: " << " Command requires async operation (async storage or data transfer)..." << EndLogLine; // check if we're already multi-stage class command if ( aCommand->GetCommandClass() == SKV_COMMAND_CLASS_MULTI_STAGE ) return status; // \todo check if we need locking when going multi-stage! (retreive-side locking isn't considered yet) // To be ready, we have the aLocalKV as a function arguments aEPState->ReplaceAndInitCommandBuffer( aCommand, aCommandOrdinal ); return status; } static inline skv_status_t retrieve_n_start( skv_server_ep_state_t *aEPState, skv_local_kv_t *aLocalKV, skv_server_ccb_t *aCommand, int aCommandOrdinal, skv_cmd_retrieve_n_keys_req_t* aReq, int *aRetrievedKeysCount, skv_lmr_triplet_t *aRetrievedKeysSizesSegs, int *aRetrievedKeysSizesSegsCount ) { // Check if the key is in the buffer if( ! aReq->mIsKeyInCtrlMsg ) return SKV_ERRNO_KEY_TOO_LARGE; AssertLogLine( SKV_CLIENT_MAX_CURSOR_KEYS_TO_CACHE == aReq->mKeysDataListMaxCount ) << "skv_server_retrieve_n_keys_command_sm:: ERROR: " << " aRemoteMemKeysMaxCount: " << aReq->mKeysDataListMaxCount << " SKV_CLIENT_MAX_CURSOR_KEYS_TO_CACHE: " << SKV_CLIENT_MAX_CURSOR_KEYS_TO_CACHE << EndLogLine; // Check if the key exists skv_local_kv_cookie_t *cookie = &aCommand->mLocalKVCookie; cookie->Set( aCommandOrdinal, aEPState ); skv_status_t status = aLocalKV->RetrieveNKeys( aReq->mPDSId, aReq->mStartingKeyData, aReq->mStartingKeySize, aRetrievedKeysSizesSegs, aRetrievedKeysCount, aRetrievedKeysSizesSegsCount, aReq->mKeysDataListMaxCount, aReq->mFlags, cookie ); BegLogLine( SKV_SERVER_RETRIEVE_N_KEYS_COMMAND_SM_LOG ) << "skv_server_retrieve_n_keys_command_sm:: Results of local call to RetrieveNKeys: " << " RetrievedKeysCount: " << *aRetrievedKeysCount << " RetrievedKeysSizesSegsCount: " << aRetrievedKeysSizesSegsCount << " aRemoteMemKeysMaxCount: " << aReq->mKeysDataListMaxCount << " first Key: " << aRetrievedKeysSizesSegs[0].GetAddr() << " status: " << skv_status_to_string( status ) << EndLogLine; return status; } static inline skv_status_t post_rdma_write( skv_server_ep_state_t *aEPState, skv_lmr_triplet_t *aRetrievedKeysSizesSegs, int aRetrievedKeysSizesSegsCount, skv_cmd_retrieve_n_keys_req_t* aReq ) { it_status_t itstatus = IT_SUCCESS; skv_server_rdma_write_cmpl_cookie_t Cookie; Cookie.Init( NULL, NULL ); // it_dto_flags_t dto_flags = (it_dto_flags_t) ( IT_COMPLETION_FLAG | IT_NOTIFY_FLAG ); it_dto_flags_t dto_flags = (it_dto_flags_t) ( 0 ); BegLogLine( SKV_SERVER_RETRIEVE_N_KEYS_DATA_LOG ) << "skv_server_retrieve_n_keys_command_sm::post_rdma_write(): LMRs: " << " " << aRetrievedKeysSizesSegs[0] << " " << aRetrievedKeysSizesSegs[1] << " " << aRetrievedKeysSizesSegs[2] << " " << aRetrievedKeysSizesSegs[3] << EndLogLine; BegLogLine( SKV_SERVER_RETRIEVE_N_KEYS_DATA_LOG ) << "skv_server_retrieve_n_keys_command_sm::post_rdma_write(): first keysize: " << *(int*)(aRetrievedKeysSizesSegs[0].GetAddr()) << " writeTo: " << aReq->mKeysDataList << " KeyData: " << HexDump( (void*)aRetrievedKeysSizesSegs[0].GetAddr(), aRetrievedKeysSizesSegs[0].GetLen() ) << " " << HexDump( (void*)aRetrievedKeysSizesSegs[1].GetAddr(), aRetrievedKeysSizesSegs[1].GetLen() ) << " " << HexDump( (void*)aRetrievedKeysSizesSegs[2].GetAddr(), aRetrievedKeysSizesSegs[2].GetLen() ) << " " << HexDump( (void*)aRetrievedKeysSizesSegs[3].GetAddr(), aRetrievedKeysSizesSegs[3].GetLen() ) << EndLogLine; // rdma_write the value itstatus = it_post_rdma_write( aEPState->mEPHdl, (it_lmr_triplet_t *) aRetrievedKeysSizesSegs, aRetrievedKeysSizesSegsCount, Cookie.GetCookie(), dto_flags, (it_rdma_addr_t) aReq->mKeysDataList, aReq->mKeyDataCacheMemReg.mKeysDataCacheRMR ); AssertLogLine( itstatus == IT_SUCCESS ) << "skv_server_retrieve_n_keys_command_sm:: ERROR: " << " itstatus: " << itstatus << EndLogLine; return SKV_SUCCESS; } static inline skv_status_t command_completion( skv_status_t aRC, skv_server_ep_state_t *aEPState, skv_server_ccb_t *aCommand, int aRetrievedKeysCount, skv_lmr_triplet_t *aRetrievedKeysSizesSegs, skv_cmd_retrieve_n_keys_rdma_write_ack_t *aCmpl, int aCommandOrdinal, int *aSeqNo ) { skv_status_t status; if( (aRC == SKV_SUCCESS) || (aRC == SKV_ERRNO_END_OF_RECORDS) ) { aCmpl->mHdr.mEvent = SKV_CLIENT_EVENT_RDMA_WRITE_VALUE_ACK; aCmpl->mCachedKeysCount = aRetrievedKeysCount; } else { aCmpl->mHdr.mEvent = SKV_CLIENT_EVENT_ERROR; aCmpl->mCachedKeysCount = 0; } aCmpl->mStatus = aRC; BegLogLine( SKV_SERVER_RETRIEVE_N_KEYS_COMMAND_SM_LOG ) << "skv_server_retrieve_n_keys_command_sm:: " << " About to Dispatch(): " << " status: " << skv_status_to_string( aCmpl->mStatus ) << " mCachedKeysCount: " << aCmpl->mCachedKeysCount << EndLogLine; status = aEPState->Dispatch( aCommand, aSeqNo, aCommandOrdinal ); AssertLogLine( status == SKV_SUCCESS ) << "skv_server_retrieve_n_keys_command_sm:: ERROR: " << " status: " << skv_status_to_string( status ) << EndLogLine; delete aRetrievedKeysSizesSegs; return status; } public: static skv_status_t Execute( skv_local_kv_t *aLocalKV, skv_server_ep_state_t *aEPState, int aCommandOrdinal, skv_server_event_t *aEvent, int *aSeqNo, it_pz_handle_t aPZHdl ) { skv_status_t status = SKV_SUCCESS; skv_server_ccb_t* Command = aEPState->GetCommandForOrdinal( aCommandOrdinal ); skv_server_command_state_t State = Command->mState; skv_server_event_type_t EventType = aEvent->mCmdEventType; switch( State ) { case SKV_SERVER_COMMAND_STATE_INIT: { switch( EventType ) { case SKV_SERVER_EVENT_TYPE_IT_DTO_RETRIEVE_N_KEYS_CMD: { int RetrievedKeysCount = 0; int RetrievedKeysSizesSegsCount = 0; // NEED NEED NEED:: This will live on the stack for now. Think about how to allocate this memory based // on aRemoteMemKeysMaxCount. Need a better place to put this. // #define SKV_CLIENT_MAX_CURSOR_KEYS_TO_CACHE_SEND_VEC ( 2 * SKV_CLIENT_MAX_CURSOR_KEYS_TO_CACHE ) // skv_lmr_triplet_t RetrievedKeysSizesSegs[ SKV_CLIENT_MAX_CURSOR_KEYS_TO_CACHE_SEND_VEC ]; skv_lmr_triplet_t *RetrievedKeysSizesSegs = (skv_lmr_triplet_t*)new char( SKV_CLIENT_MAX_CURSOR_KEYS_TO_CACHE_SEND_VEC * sizeof(skv_lmr_triplet_t) ); status = retrieve_n_start( aEPState, aLocalKV, Command, aCommandOrdinal, (skv_cmd_retrieve_n_keys_req_t*) Command->GetSendBuff(), & RetrievedKeysCount, RetrievedKeysSizesSegs, & RetrievedKeysSizesSegsCount ); switch( status ) { case SKV_ERRNO_END_OF_RECORDS: // skip the rdma_write only if there was no key retrieved, otherwise rdma the remaining keys if( RetrievedKeysSizesSegsCount == 0 ) break; case SKV_SUCCESS: { post_rdma_write( aEPState, RetrievedKeysSizesSegs, RetrievedKeysSizesSegsCount, (skv_cmd_retrieve_n_keys_req_t*) Command->GetSendBuff() ); break; } case SKV_ERRNO_LOCAL_KV_EVENT: create_multi_stage( aEPState, aLocalKV, Command, aCommandOrdinal ); Command->Transit( SKV_SERVER_COMMAND_STATE_LOCAL_KV_DATA_OP ); return SKV_SUCCESS; default: break; } status = command_completion( status, aEPState, Command, RetrievedKeysCount, RetrievedKeysSizesSegs, (skv_cmd_retrieve_n_keys_rdma_write_ack_t*)Command->GetSendBuff(), aCommandOrdinal, aSeqNo ); Command->Transit( SKV_SERVER_COMMAND_STATE_INIT ); break; } default: { StrongAssertLogLine( 0 ) << "skv_server_retrieve_n_keys_command_sm:: Execute():: ERROR: State not recognized" << " State: " << State << " EventType: " << EventType << EndLogLine; break; } } break; } case SKV_SERVER_COMMAND_STATE_LOCAL_KV_DATA_OP: { switch( EventType ) { case SKV_SERVER_EVENT_TYPE_LOCAL_KV_CMPL: { status = Command->mLocalKVrc; switch( status ) { case SKV_ERRNO_END_OF_RECORDS: // skip the rdma_write only if there was no key retrieved if( Command->mLocalKVData.mRetrieveNKeys.mKeysCount == 0 ) break; // no break on purpose: EOR might be signaled even if there were a few keys available? case SKV_SUCCESS: post_rdma_write( aEPState, Command->mLocalKVData.mRetrieveNKeys.mKeysSizesSegs, Command->mLocalKVData.mRetrieveNKeys.mKeysSizesSegsCount, (skv_cmd_retrieve_n_keys_req_t*) Command->GetSendBuff() ); break; } status = command_completion( status, aEPState, Command, Command->mLocalKVData.mRetrieveNKeys.mKeysCount, Command->mLocalKVData.mRetrieveNKeys.mKeysSizesSegs, (skv_cmd_retrieve_n_keys_rdma_write_ack_t*)Command->GetSendBuff(), aCommandOrdinal, aSeqNo ); Command->Transit( SKV_SERVER_COMMAND_STATE_INIT ); break; } default: status = SKV_ERRNO_STATE_MACHINE_ERROR; } break; } default: { StrongAssertLogLine( 0 ) << "skv_server_retrieve_n_keys_command_sm:: Execute():: ERROR: State not recognized" << " State: " << State << EndLogLine; break; } } return status; } }; #endif <commit_msg>fix memory allocation issue<commit_after>/************************************************ * Copyright (c) IBM Corp. 2014 * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html *************************************************/ /* * Contributors: * arayshu, lschneid - initial implementation */ #ifndef __SKV_SERVER_RETRIEVE_N_KEYS_COMMAND_SM_HPP__ #define __SKV_SERVER_RETRIEVE_N_KEYS_COMMAND_SM_HPP__ #ifndef SKV_SERVER_RETRIEVE_N_KEYS_COMMAND_SM_LOG #define SKV_SERVER_RETRIEVE_N_KEYS_COMMAND_SM_LOG ( 0 | SKV_LOGGING_ALL ) #endif #ifndef SKV_SERVER_RETRIEVE_N_KEYS_DATA_LOG #define SKV_SERVER_RETRIEVE_N_KEYS_DATA_LOG ( 0 ) #endif class skv_server_retrieve_n_keys_command_sm { static inline skv_status_t create_multi_stage( skv_server_ep_state_t *aEPState, skv_local_kv_t *aLocalKV, skv_server_ccb_t *aCommand, int aCommandOrdinal ) { skv_status_t status = SKV_SUCCESS; BegLogLine( SKV_SERVER_RETRIEVE_N_KEYS_COMMAND_SM_LOG ) << "skv_server_retrieve_n_keys_command_sm:: " << " Command requires async operation (async storage or data transfer)..." << EndLogLine; // check if we're already multi-stage class command if ( aCommand->GetCommandClass() == SKV_COMMAND_CLASS_MULTI_STAGE ) return status; // \todo check if we need locking when going multi-stage! (retreive-side locking isn't considered yet) // To be ready, we have the aLocalKV as a function arguments aEPState->ReplaceAndInitCommandBuffer( aCommand, aCommandOrdinal ); return status; } static inline skv_status_t retrieve_n_start( skv_server_ep_state_t *aEPState, skv_local_kv_t *aLocalKV, skv_server_ccb_t *aCommand, int aCommandOrdinal, skv_cmd_retrieve_n_keys_req_t* aReq, int *aRetrievedKeysCount, skv_lmr_triplet_t *aRetrievedKeysSizesSegs, int *aRetrievedKeysSizesSegsCount ) { // Check if the key is in the buffer if( ! aReq->mIsKeyInCtrlMsg ) return SKV_ERRNO_KEY_TOO_LARGE; AssertLogLine( SKV_CLIENT_MAX_CURSOR_KEYS_TO_CACHE == aReq->mKeysDataListMaxCount ) << "skv_server_retrieve_n_keys_command_sm:: ERROR: " << " aRemoteMemKeysMaxCount: " << aReq->mKeysDataListMaxCount << " SKV_CLIENT_MAX_CURSOR_KEYS_TO_CACHE: " << SKV_CLIENT_MAX_CURSOR_KEYS_TO_CACHE << EndLogLine; // Check if the key exists skv_local_kv_cookie_t *cookie = &aCommand->mLocalKVCookie; cookie->Set( aCommandOrdinal, aEPState ); skv_status_t status = aLocalKV->RetrieveNKeys( aReq->mPDSId, aReq->mStartingKeyData, aReq->mStartingKeySize, aRetrievedKeysSizesSegs, aRetrievedKeysCount, aRetrievedKeysSizesSegsCount, aReq->mKeysDataListMaxCount, aReq->mFlags, cookie ); BegLogLine( SKV_SERVER_RETRIEVE_N_KEYS_COMMAND_SM_LOG ) << "skv_server_retrieve_n_keys_command_sm:: Results of local call to RetrieveNKeys: " << " RetrievedKeysCount: " << *aRetrievedKeysCount << " RetrievedKeysSizesSegsCount: " << aRetrievedKeysSizesSegsCount << " aRemoteMemKeysMaxCount: " << aReq->mKeysDataListMaxCount << " first Key: " << aRetrievedKeysSizesSegs[0].GetAddr() << " status: " << skv_status_to_string( status ) << EndLogLine; return status; } static inline skv_status_t post_rdma_write( skv_server_ep_state_t *aEPState, skv_lmr_triplet_t *aRetrievedKeysSizesSegs, int aRetrievedKeysSizesSegsCount, skv_cmd_retrieve_n_keys_req_t* aReq ) { it_status_t itstatus = IT_SUCCESS; skv_server_rdma_write_cmpl_cookie_t Cookie; Cookie.Init( NULL, NULL ); // it_dto_flags_t dto_flags = (it_dto_flags_t) ( IT_COMPLETION_FLAG | IT_NOTIFY_FLAG ); it_dto_flags_t dto_flags = (it_dto_flags_t) ( 0 ); BegLogLine( SKV_SERVER_RETRIEVE_N_KEYS_DATA_LOG ) << "skv_server_retrieve_n_keys_command_sm::post_rdma_write(): " << aRetrievedKeysSizesSegsCount << " LMRs: " << " " << aRetrievedKeysSizesSegs[0] << " " << aRetrievedKeysSizesSegs[1] << " " << aRetrievedKeysSizesSegs[2] << " " << aRetrievedKeysSizesSegs[3] << EndLogLine; BegLogLine( SKV_SERVER_RETRIEVE_N_KEYS_DATA_LOG ) << "skv_server_retrieve_n_keys_command_sm::post_rdma_write(): first keysize: " << *(int*)(aRetrievedKeysSizesSegs[0].GetAddr()) << " writeTo: " << aReq->mKeysDataList << " KeyData: " << HexDump( (void*)aRetrievedKeysSizesSegs[0].GetAddr(), aRetrievedKeysSizesSegs[0].GetLen() ) << " " << HexDump( (void*)aRetrievedKeysSizesSegs[1].GetAddr(), aRetrievedKeysSizesSegs[1].GetLen() ) << " " << HexDump( (void*)aRetrievedKeysSizesSegs[2].GetAddr(), aRetrievedKeysSizesSegs[2].GetLen() ) << " " << HexDump( (void*)aRetrievedKeysSizesSegs[3].GetAddr(), aRetrievedKeysSizesSegs[3].GetLen() ) << EndLogLine; // rdma_write the value itstatus = it_post_rdma_write( aEPState->mEPHdl, (it_lmr_triplet_t *) aRetrievedKeysSizesSegs, aRetrievedKeysSizesSegsCount, Cookie.GetCookie(), dto_flags, (it_rdma_addr_t) aReq->mKeysDataList, aReq->mKeyDataCacheMemReg.mKeysDataCacheRMR ); AssertLogLine( itstatus == IT_SUCCESS ) << "skv_server_retrieve_n_keys_command_sm:: ERROR: " << " itstatus: " << itstatus << EndLogLine; return SKV_SUCCESS; } static inline skv_status_t command_completion( skv_status_t aRC, skv_server_ep_state_t *aEPState, skv_server_ccb_t *aCommand, int aRetrievedKeysCount, skv_lmr_triplet_t *aRetrievedKeysSizesSegs, skv_cmd_retrieve_n_keys_rdma_write_ack_t *aCmpl, int aCommandOrdinal, int *aSeqNo ) { skv_status_t status; if( (aRC == SKV_SUCCESS) || (aRC == SKV_ERRNO_END_OF_RECORDS) ) { aCmpl->mHdr.mEvent = SKV_CLIENT_EVENT_RDMA_WRITE_VALUE_ACK; aCmpl->mCachedKeysCount = aRetrievedKeysCount; } else { aCmpl->mHdr.mEvent = SKV_CLIENT_EVENT_ERROR; aCmpl->mCachedKeysCount = 0; } aCmpl->mStatus = aRC; BegLogLine( SKV_SERVER_RETRIEVE_N_KEYS_COMMAND_SM_LOG ) << "skv_server_retrieve_n_keys_command_sm:: " << " About to Dispatch(): " << " status: " << skv_status_to_string( aCmpl->mStatus ) << " mCachedKeysCount: " << aCmpl->mCachedKeysCount << EndLogLine; status = aEPState->Dispatch( aCommand, aSeqNo, aCommandOrdinal ); AssertLogLine( status == SKV_SUCCESS ) << "skv_server_retrieve_n_keys_command_sm:: ERROR: " << " status: " << skv_status_to_string( status ) << EndLogLine; delete [] aRetrievedKeysSizesSegs; return status; } public: static skv_status_t Execute( skv_local_kv_t *aLocalKV, skv_server_ep_state_t *aEPState, int aCommandOrdinal, skv_server_event_t *aEvent, int *aSeqNo, it_pz_handle_t aPZHdl ) { skv_status_t status = SKV_SUCCESS; skv_server_ccb_t* Command = aEPState->GetCommandForOrdinal( aCommandOrdinal ); skv_server_command_state_t State = Command->mState; skv_server_event_type_t EventType = aEvent->mCmdEventType; switch( State ) { case SKV_SERVER_COMMAND_STATE_INIT: { switch( EventType ) { case SKV_SERVER_EVENT_TYPE_IT_DTO_RETRIEVE_N_KEYS_CMD: { int RetrievedKeysCount = 0; int RetrievedKeysSizesSegsCount = 0; #define SKV_CLIENT_MAX_CURSOR_KEYS_TO_CACHE_SEND_VEC ( 2 * SKV_CLIENT_MAX_CURSOR_KEYS_TO_CACHE ) skv_lmr_triplet_t *RetrievedKeysSizesSegs = new skv_lmr_triplet_t[ SKV_CLIENT_MAX_CURSOR_KEYS_TO_CACHE_SEND_VEC ]; BegLogLine( SKV_SERVER_RETRIEVE_N_KEYS_COMMAND_SM_LOG ) << "skv_server_retrieve_n_keys_command_sm: allocated " << SKV_CLIENT_MAX_CURSOR_KEYS_TO_CACHE_SEND_VEC << " KeysSegs@" << (void*)RetrievedKeysSizesSegs << EndLogLine; status = retrieve_n_start( aEPState, aLocalKV, Command, aCommandOrdinal, (skv_cmd_retrieve_n_keys_req_t*) Command->GetSendBuff(), & RetrievedKeysCount, RetrievedKeysSizesSegs, & RetrievedKeysSizesSegsCount ); switch( status ) { case SKV_ERRNO_END_OF_RECORDS: // skip the rdma_write only if there was no key retrieved, otherwise rdma the remaining keys if( RetrievedKeysSizesSegsCount == 0 ) break; case SKV_SUCCESS: { post_rdma_write( aEPState, RetrievedKeysSizesSegs, RetrievedKeysSizesSegsCount, (skv_cmd_retrieve_n_keys_req_t*) Command->GetSendBuff() ); break; } case SKV_ERRNO_LOCAL_KV_EVENT: create_multi_stage( aEPState, aLocalKV, Command, aCommandOrdinal ); Command->Transit( SKV_SERVER_COMMAND_STATE_LOCAL_KV_DATA_OP ); return SKV_SUCCESS; default: break; } status = command_completion( status, aEPState, Command, RetrievedKeysCount, RetrievedKeysSizesSegs, (skv_cmd_retrieve_n_keys_rdma_write_ack_t*)Command->GetSendBuff(), aCommandOrdinal, aSeqNo ); Command->Transit( SKV_SERVER_COMMAND_STATE_INIT ); break; } default: { StrongAssertLogLine( 0 ) << "skv_server_retrieve_n_keys_command_sm:: Execute():: ERROR: State not recognized" << " State: " << State << " EventType: " << EventType << EndLogLine; break; } } break; } case SKV_SERVER_COMMAND_STATE_LOCAL_KV_DATA_OP: { switch( EventType ) { case SKV_SERVER_EVENT_TYPE_LOCAL_KV_CMPL: { status = Command->mLocalKVrc; switch( status ) { case SKV_ERRNO_END_OF_RECORDS: // skip the rdma_write only if there was no key retrieved if( Command->mLocalKVData.mRetrieveNKeys.mKeysCount == 0 ) break; // no break on purpose: EOR might be signaled even if there were a few keys available? case SKV_SUCCESS: post_rdma_write( aEPState, Command->mLocalKVData.mRetrieveNKeys.mKeysSizesSegs, Command->mLocalKVData.mRetrieveNKeys.mKeysSizesSegsCount, (skv_cmd_retrieve_n_keys_req_t*) Command->GetSendBuff() ); break; } status = command_completion( status, aEPState, Command, Command->mLocalKVData.mRetrieveNKeys.mKeysCount, Command->mLocalKVData.mRetrieveNKeys.mKeysSizesSegs, (skv_cmd_retrieve_n_keys_rdma_write_ack_t*)Command->GetSendBuff(), aCommandOrdinal, aSeqNo ); Command->Transit( SKV_SERVER_COMMAND_STATE_INIT ); break; } default: status = SKV_ERRNO_STATE_MACHINE_ERROR; } break; } default: { StrongAssertLogLine( 0 ) << "skv_server_retrieve_n_keys_command_sm:: Execute():: ERROR: State not recognized" << " State: " << State << EndLogLine; break; } } return status; } }; #endif <|endoftext|>
<commit_before>//****************************************************************** // // Copyright 2016 Samsung Electronics All Rights Reserved. // //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= #include <gtest/gtest.h> #include <HippoMocks/hippomocks.h> #include <atomic> #include <functional> #include <condition_variable> #include <mutex> #include <chrono> #include "ESEnrolleeSimulator.h" #include "escommon.h" #include "ESRichCommon.h" #include "EasySetup.hpp" #include "RemoteEnrollee.h" #include "ESEnrolleeCommon.h" #include "easysetup.h" #include "ocrandom.h" #include "cainterface.h" #include "OCPlatform.h" using namespace OC; using namespace OIC::Service; namespace { std::atomic_bool g_isStartedStack(false); std::chrono::milliseconds g_waitForResponse(1000); std::condition_variable responseCon; std::mutex mutexForCondition; ESEnrolleeSimulator g_enrolleeSimul; std::shared_ptr<RemoteEnrollee> g_remoteEnrollee; } class TestWithMock: public testing::Test { public: MockRepository mocks; protected: virtual ~TestWithMock() noexcept(noexcept(std::declval<Test>().~Test())) { } virtual void TearDown() { try { mocks.VerifyAll(); } catch (...) { mocks.reset(); throw; } } }; class EasysetupMediatorTest : public TestWithMock { public: std::shared_ptr<OC::OCResource> m_enrolleeResource; public: EasysetupMediatorTest() = default; ~EasysetupMediatorTest() = default; std::shared_ptr<OC::OCResource> CreateNotEasySetupResource() { OCConnectivityType connectivityType = CT_DEFAULT; std::vector<std::string> types = {"oic.r.noteasysetup"}; std::vector<std::string> ifaces = {DEFAULT_INTERFACE}; return OCPlatform::constructResourceObject("coap://192.168.1.2:5000", "/NotEasySetupResURI", connectivityType, false, types, ifaces); } void discoverRemoteEnrollee() { std::string uri = std::string("/oic/res?rt=") + OC_RSRVD_ES_RES_TYPE_EASYSETUP; OC::OCPlatform::findResource("", uri, OCConnectivityType::CT_DEFAULT, std::bind(&EasysetupMediatorTest::discoverRemoteEnrolleeCb, this, std::placeholders::_1)); std::unique_lock< std::mutex > lock{ mutexForCondition }; responseCon.wait_for(lock, g_waitForResponse); } protected: void SetUp() { TestWithMock::SetUp(); if (g_isStartedStack == false) { if (OCInit(NULL, 0, OC_CLIENT_SERVER) != OC_STACK_OK) { printf("OCStack init error!!\n"); return; } g_enrolleeSimul.initEnrollee(); g_isStartedStack = true; } } void TearDown() { TestWithMock::TearDown(); } private: bool isValidResourceToTest(std::shared_ptr<OC::OCResource> resource) { if((resource->connectivityType() & CT_ADAPTER_TCP) == CT_ADAPTER_TCP) { return false; } CAEndpoint_t *tempInfo = NULL; size_t tempSize = 0; CAResult_t res = CAGetNetworkInformation(&tempInfo, &tempSize); if (CA_STATUS_OK != res || NULL == tempInfo || 0 == tempSize) { free(tempInfo); return false; } for (size_t index = 0; index < tempSize; index++) { if (CA_ADAPTER_IP == tempInfo[index].adapter) { if(resource->host().find(tempInfo[index].addr) != std::string::npos && resource->host().find(std::to_string(tempInfo[index].port).c_str()) != std::string::npos) { return true; } } } return false; } void discoverRemoteEnrolleeCb(std::shared_ptr<OC::OCResource> resource) { if(!isValidResourceToTest(resource)) { return ; } if(!resource->getResourceTypes().at(0).compare(OC_RSRVD_ES_RES_TYPE_EASYSETUP)) { m_enrolleeResource = resource; } } }; TEST_F(EasysetupMediatorTest, createremoteenrolleeFailedWithNotEasySetupResource) { auto remoteEnrollee = EasySetup::getInstance()->createRemoteEnrollee(CreateNotEasySetupResource()); EXPECT_EQ(nullptr, remoteEnrollee); } TEST_F(EasysetupMediatorTest, createremoteenrolleeSucceedWithEasySetupResource) { discoverRemoteEnrollee(); g_remoteEnrollee = EasySetup::getInstance()->createRemoteEnrollee(m_enrolleeResource); ASSERT_NE(nullptr, g_remoteEnrollee); } class GetConfigurationTest : public EasysetupMediatorTest { public: GetConfigurationTest() = default; ~GetConfigurationTest() = default; static void onGetConfigurationCb(shared_ptr< GetConfigurationStatus > /*status*/) { } protected: void SetUp() { TestWithMock::SetUp(); } void TearDown() { TestWithMock::TearDown(); } }; TEST_F(GetConfigurationTest, ThrowExceptionWhenGetConfigurationFailedByCallbackIsNull) { EXPECT_ANY_THROW(g_remoteEnrollee->getConfiguration(nullptr)); } TEST_F(GetConfigurationTest, GetConfigurationSucceed) { bool isWellConstructed = false; g_enrolleeSimul.setDeviceProperty(); mocks.ExpectCallFunc(onGetConfigurationCb).Do( [&isWellConstructed](std::shared_ptr< GetConfigurationStatus > status) { if(status->getESResult() == ES_OK) { EnrolleeConf conf = status->getEnrolleeConf(); if(!conf.getWiFiModes().empty()) { if(conf.getWiFiModes().at(0) == WIFI_11G && conf.getWiFiFreq() == WIFI_5G && !strcmp(conf.getDeviceName().c_str(), "Test Device") && !strcmp(conf.getModelNumber().c_str(), "Test Model Number")) { isWellConstructed = true; } cout << "getDeviceName : " << conf.getDeviceName().c_str() << endl; cout << "getModelNumber : " << conf.getModelNumber().c_str() << endl; } } }); g_remoteEnrollee->getConfiguration(onGetConfigurationCb); std::unique_lock< std::mutex > lock{ mutexForCondition }; responseCon.wait_for(lock, g_waitForResponse); EXPECT_TRUE(isWellConstructed); } class GetStatusTest : public EasysetupMediatorTest { public: GetStatusTest() = default; ~GetStatusTest() = default; static void onGetStatusCb(shared_ptr< GetEnrolleeStatus > /*status*/) { } protected: void SetUp() { TestWithMock::SetUp(); } void TearDown() { TestWithMock::TearDown(); } }; TEST_F(GetStatusTest, ThrowExceptionWhenGetStatusFailedByCallbackIsNull) { EXPECT_ANY_THROW(g_remoteEnrollee->getStatus(nullptr)); } TEST_F(GetStatusTest, GetStatusSucceed) { g_enrolleeSimul.setESState(); g_enrolleeSimul.setESErrorCode(); bool isWellConstructed = false; mocks.ExpectCallFunc(onGetStatusCb).Do( [&isWellConstructed](std::shared_ptr< GetEnrolleeStatus > status) { if(status->getESResult() == ES_OK) { EnrolleeStatus enrolleeStatus = status->getEnrolleeStatus(); if(enrolleeStatus.getProvStatus() == ES_STATE_CONNECTED_TO_ENROLLER && enrolleeStatus.getLastErrCode() == ES_ERRCODE_NO_INTERNETCONNECTION) { isWellConstructed = true; } } }); g_remoteEnrollee->getStatus(onGetStatusCb); std::unique_lock< std::mutex > lock{ mutexForCondition }; responseCon.wait_for(lock, g_waitForResponse); EXPECT_TRUE(isWellConstructed); } class ProvisionDevicePropertiesTest : public EasysetupMediatorTest { public: ProvisionDevicePropertiesTest() = default; ~ProvisionDevicePropertiesTest() = default; static void deviceProvisioningStatusCb( shared_ptr< DevicePropProvisioningStatus > /*status*/) { } protected: void SetUp() { TestWithMock::SetUp(); } void TearDown() { TestWithMock::TearDown(); } }; TEST_F(ProvisionDevicePropertiesTest, ThrowExceptionWhenProvisionDeviceProperiesFailedByCallbackIsNull) { DeviceProp devProp; devProp.setWiFiProp("Iotivity_SSID", "Iotivity_PWD", WPA2_PSK, TKIP_AES); devProp.setDevConfProp("korean", "Korea", "Location"); EXPECT_ANY_THROW(g_remoteEnrollee->provisionDeviceProperties(devProp, nullptr)); } TEST_F(ProvisionDevicePropertiesTest, ThrowExceptionWhenProvisionDeviceProperiesFailedWithoutSSID) { DeviceProp devProp; devProp.setWiFiProp("", "Iotivity_PWD", WPA2_PSK, TKIP_AES); devProp.setDevConfProp("korean", "Korea", "Location"); EXPECT_ANY_THROW(g_remoteEnrollee->provisionDeviceProperties(devProp, deviceProvisioningStatusCb)); } TEST_F(ProvisionDevicePropertiesTest, ProvisionDeviceProperiesSucceed) { DeviceProp devProp; devProp.setWiFiProp("Iotivity_SSID", "Iotivity_PWD", WPA2_PSK, TKIP_AES); devProp.setDevConfProp("korean", "Korea", "Location"); int cntForReceivedCallbackWithSuccess = 0; mocks.OnCallFunc(deviceProvisioningStatusCb).Do( [&cntForReceivedCallbackWithSuccess] (std::shared_ptr< DevicePropProvisioningStatus > status) { if(status->getESResult() == ES_OK) { cntForReceivedCallbackWithSuccess++; } }); g_remoteEnrollee->provisionDeviceProperties(devProp, deviceProvisioningStatusCb); std::unique_lock< std::mutex > lock{ mutexForCondition }; responseCon.wait_for(lock, g_waitForResponse); EXPECT_EQ(cntForReceivedCallbackWithSuccess, 1); } class ProvisionCloudPropertiesTest : public EasysetupMediatorTest { public: ProvisionCloudPropertiesTest() = default; ~ProvisionCloudPropertiesTest() = default; static void cloudPropProvStatusCb(shared_ptr< CloudPropProvisioningStatus > /*status*/) { } protected: void SetUp() { TestWithMock::SetUp(); } void TearDown() { TestWithMock::TearDown(); } }; TEST_F(ProvisionCloudPropertiesTest, ThrowExceptionWhenProvisionCloudPropertiesFailedByCallbackIsNull) { CloudProp cloudProp; cloudProp.setCloudProp("authCode", "authProvider", "ciServer"); cloudProp.setCloudID("f002ae8b-c42c-40d3-8b8d-1927c17bd1b3"); EXPECT_ANY_THROW(g_remoteEnrollee->provisionCloudProperties(cloudProp, nullptr)); } TEST_F(ProvisionCloudPropertiesTest, ThrowExceptionWhenProvisionCloudPropertiesFailedWithoutAuthCode) { CloudProp cloudProp; cloudProp.setCloudProp("", "authProvider", "ciServer"); cloudProp.setCloudID("f002ae8b-c42c-40d3-8b8d-1927c17bd1b3"); EXPECT_ANY_THROW(g_remoteEnrollee->provisionCloudProperties(cloudProp, cloudPropProvStatusCb)); } TEST_F(ProvisionCloudPropertiesTest, ThrowExceptionWhenProvisionCloudPropertiesFailedWithoutAuthProvider) { CloudProp cloudProp; cloudProp.setCloudProp("authCode", "", "ciServer"); cloudProp.setCloudID("f002ae8b-c42c-40d3-8b8d-1927c17bd1b3"); EXPECT_ANY_THROW(g_remoteEnrollee->provisionCloudProperties(cloudProp, cloudPropProvStatusCb)); } TEST_F(ProvisionCloudPropertiesTest, ThrowExceptionWhenProvisionCloudPropertiesFailedWithoutCIServer) { CloudProp cloudProp; cloudProp.setCloudProp("authCode", "authProvider", ""); cloudProp.setCloudID("f002ae8b-c42c-40d3-8b8d-1927c17bd1b3"); EXPECT_ANY_THROW(g_remoteEnrollee->provisionCloudProperties(cloudProp, cloudPropProvStatusCb)); } TEST_F(ProvisionCloudPropertiesTest, ProvisionCloudPropertiesSucceed) { CloudProp cloudProp; cloudProp.setCloudProp("authCode", "authProvider", "ciServer"); cloudProp.setCloudID("f002ae8b-c42c-40d3-8b8d-1927c17bd1b3"); int cntForReceivedCallbackWithSuccess = 0; mocks.OnCallFunc(cloudPropProvStatusCb).Do( [& cntForReceivedCallbackWithSuccess](std::shared_ptr< CloudPropProvisioningStatus > status) { if(status->getESResult() == ES_OK) { cntForReceivedCallbackWithSuccess++; } }); g_remoteEnrollee->provisionCloudProperties(cloudProp, cloudPropProvStatusCb); std::unique_lock< std::mutex > lock{ mutexForCondition }; responseCon.wait_for(lock, g_waitForResponse); EXPECT_EQ(cntForReceivedCallbackWithSuccess, 1); ESTerminateEnrollee(); } <commit_msg>Removed easy-setup TC associated with https://gerrit.iotivity.org/gerrit/#/c/17995/<commit_after>//****************************************************************** // // Copyright 2016 Samsung Electronics All Rights Reserved. // //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= #include <gtest/gtest.h> #include <HippoMocks/hippomocks.h> #include <atomic> #include <functional> #include <condition_variable> #include <mutex> #include <chrono> #include "ESEnrolleeSimulator.h" #include "escommon.h" #include "ESRichCommon.h" #include "EasySetup.hpp" #include "RemoteEnrollee.h" #include "ESEnrolleeCommon.h" #include "easysetup.h" #include "ocrandom.h" #include "cainterface.h" #include "OCPlatform.h" using namespace OC; using namespace OIC::Service; namespace { std::atomic_bool g_isStartedStack(false); std::chrono::milliseconds g_waitForResponse(1000); std::condition_variable responseCon; std::mutex mutexForCondition; ESEnrolleeSimulator g_enrolleeSimul; std::shared_ptr<RemoteEnrollee> g_remoteEnrollee; } class TestWithMock: public testing::Test { public: MockRepository mocks; protected: virtual ~TestWithMock() noexcept(noexcept(std::declval<Test>().~Test())) { } virtual void TearDown() { try { mocks.VerifyAll(); } catch (...) { mocks.reset(); throw; } } }; class EasysetupMediatorTest : public TestWithMock { public: std::shared_ptr<OC::OCResource> m_enrolleeResource; public: EasysetupMediatorTest() = default; ~EasysetupMediatorTest() = default; std::shared_ptr<OC::OCResource> CreateNotEasySetupResource() { OCConnectivityType connectivityType = CT_DEFAULT; std::vector<std::string> types = {"oic.r.noteasysetup"}; std::vector<std::string> ifaces = {DEFAULT_INTERFACE}; return OCPlatform::constructResourceObject("coap://192.168.1.2:5000", "/NotEasySetupResURI", connectivityType, false, types, ifaces); } void discoverRemoteEnrollee() { std::string uri = std::string("/oic/res?rt=") + OC_RSRVD_ES_RES_TYPE_EASYSETUP; OC::OCPlatform::findResource("", uri, OCConnectivityType::CT_DEFAULT, std::bind(&EasysetupMediatorTest::discoverRemoteEnrolleeCb, this, std::placeholders::_1)); std::unique_lock< std::mutex > lock{ mutexForCondition }; responseCon.wait_for(lock, g_waitForResponse); } protected: void SetUp() { TestWithMock::SetUp(); if (g_isStartedStack == false) { if (OCInit(NULL, 0, OC_CLIENT_SERVER) != OC_STACK_OK) { printf("OCStack init error!!\n"); return; } g_enrolleeSimul.initEnrollee(); g_isStartedStack = true; } } void TearDown() { TestWithMock::TearDown(); } private: bool isValidResourceToTest(std::shared_ptr<OC::OCResource> resource) { if((resource->connectivityType() & CT_ADAPTER_TCP) == CT_ADAPTER_TCP) { return false; } CAEndpoint_t *tempInfo = NULL; size_t tempSize = 0; CAResult_t res = CAGetNetworkInformation(&tempInfo, &tempSize); if (CA_STATUS_OK != res || NULL == tempInfo || 0 == tempSize) { free(tempInfo); return false; } for (size_t index = 0; index < tempSize; index++) { if (CA_ADAPTER_IP == tempInfo[index].adapter) { if(resource->host().find(tempInfo[index].addr) != std::string::npos && resource->host().find(std::to_string(tempInfo[index].port).c_str()) != std::string::npos) { return true; } } } return false; } void discoverRemoteEnrolleeCb(std::shared_ptr<OC::OCResource> resource) { if(!isValidResourceToTest(resource)) { return ; } if(!resource->getResourceTypes().at(0).compare(OC_RSRVD_ES_RES_TYPE_EASYSETUP)) { m_enrolleeResource = resource; } } }; TEST_F(EasysetupMediatorTest, createremoteenrolleeFailedWithNotEasySetupResource) { auto remoteEnrollee = EasySetup::getInstance()->createRemoteEnrollee(CreateNotEasySetupResource()); EXPECT_EQ(nullptr, remoteEnrollee); } TEST_F(EasysetupMediatorTest, createremoteenrolleeSucceedWithEasySetupResource) { discoverRemoteEnrollee(); g_remoteEnrollee = EasySetup::getInstance()->createRemoteEnrollee(m_enrolleeResource); ASSERT_NE(nullptr, g_remoteEnrollee); } class GetConfigurationTest : public EasysetupMediatorTest { public: GetConfigurationTest() = default; ~GetConfigurationTest() = default; static void onGetConfigurationCb(shared_ptr< GetConfigurationStatus > /*status*/) { } protected: void SetUp() { TestWithMock::SetUp(); } void TearDown() { TestWithMock::TearDown(); } }; TEST_F(GetConfigurationTest, ThrowExceptionWhenGetConfigurationFailedByCallbackIsNull) { EXPECT_ANY_THROW(g_remoteEnrollee->getConfiguration(nullptr)); } TEST_F(GetConfigurationTest, GetConfigurationSucceed) { bool isWellConstructed = false; g_enrolleeSimul.setDeviceProperty(); mocks.ExpectCallFunc(onGetConfigurationCb).Do( [&isWellConstructed](std::shared_ptr< GetConfigurationStatus > status) { if(status->getESResult() == ES_OK) { EnrolleeConf conf = status->getEnrolleeConf(); if(!conf.getWiFiModes().empty()) { if(conf.getWiFiModes().at(0) == WIFI_11G && conf.getWiFiFreq() == WIFI_5G && !strcmp(conf.getDeviceName().c_str(), "Test Device") && !strcmp(conf.getModelNumber().c_str(), "Test Model Number")) { isWellConstructed = true; } cout << "getDeviceName : " << conf.getDeviceName().c_str() << endl; cout << "getModelNumber : " << conf.getModelNumber().c_str() << endl; } } }); g_remoteEnrollee->getConfiguration(onGetConfigurationCb); std::unique_lock< std::mutex > lock{ mutexForCondition }; responseCon.wait_for(lock, g_waitForResponse); EXPECT_TRUE(isWellConstructed); } class GetStatusTest : public EasysetupMediatorTest { public: GetStatusTest() = default; ~GetStatusTest() = default; static void onGetStatusCb(shared_ptr< GetEnrolleeStatus > /*status*/) { } protected: void SetUp() { TestWithMock::SetUp(); } void TearDown() { TestWithMock::TearDown(); } }; TEST_F(GetStatusTest, ThrowExceptionWhenGetStatusFailedByCallbackIsNull) { EXPECT_ANY_THROW(g_remoteEnrollee->getStatus(nullptr)); } TEST_F(GetStatusTest, GetStatusSucceed) { g_enrolleeSimul.setESState(); g_enrolleeSimul.setESErrorCode(); bool isWellConstructed = false; mocks.ExpectCallFunc(onGetStatusCb).Do( [&isWellConstructed](std::shared_ptr< GetEnrolleeStatus > status) { if(status->getESResult() == ES_OK) { EnrolleeStatus enrolleeStatus = status->getEnrolleeStatus(); if(enrolleeStatus.getProvStatus() == ES_STATE_CONNECTED_TO_ENROLLER && enrolleeStatus.getLastErrCode() == ES_ERRCODE_NO_INTERNETCONNECTION) { isWellConstructed = true; } } }); g_remoteEnrollee->getStatus(onGetStatusCb); std::unique_lock< std::mutex > lock{ mutexForCondition }; responseCon.wait_for(lock, g_waitForResponse); EXPECT_TRUE(isWellConstructed); } class ProvisionDevicePropertiesTest : public EasysetupMediatorTest { public: ProvisionDevicePropertiesTest() = default; ~ProvisionDevicePropertiesTest() = default; static void deviceProvisioningStatusCb( shared_ptr< DevicePropProvisioningStatus > /*status*/) { } protected: void SetUp() { TestWithMock::SetUp(); } void TearDown() { TestWithMock::TearDown(); } }; TEST_F(ProvisionDevicePropertiesTest, ThrowExceptionWhenProvisionDeviceProperiesFailedByCallbackIsNull) { DeviceProp devProp; devProp.setWiFiProp("Iotivity_SSID", "Iotivity_PWD", WPA2_PSK, TKIP_AES); devProp.setDevConfProp("korean", "Korea", "Location"); EXPECT_ANY_THROW(g_remoteEnrollee->provisionDeviceProperties(devProp, nullptr)); } TEST_F(ProvisionDevicePropertiesTest, ProvisionDeviceProperiesSucceed) { DeviceProp devProp; devProp.setWiFiProp("Iotivity_SSID", "Iotivity_PWD", WPA2_PSK, TKIP_AES); devProp.setDevConfProp("korean", "Korea", "Location"); int cntForReceivedCallbackWithSuccess = 0; mocks.OnCallFunc(deviceProvisioningStatusCb).Do( [&cntForReceivedCallbackWithSuccess] (std::shared_ptr< DevicePropProvisioningStatus > status) { if(status->getESResult() == ES_OK) { cntForReceivedCallbackWithSuccess++; } }); g_remoteEnrollee->provisionDeviceProperties(devProp, deviceProvisioningStatusCb); std::unique_lock< std::mutex > lock{ mutexForCondition }; responseCon.wait_for(lock, g_waitForResponse); EXPECT_EQ(cntForReceivedCallbackWithSuccess, 1); } class ProvisionCloudPropertiesTest : public EasysetupMediatorTest { public: ProvisionCloudPropertiesTest() = default; ~ProvisionCloudPropertiesTest() = default; static void cloudPropProvStatusCb(shared_ptr< CloudPropProvisioningStatus > /*status*/) { } protected: void SetUp() { TestWithMock::SetUp(); } void TearDown() { TestWithMock::TearDown(); } }; TEST_F(ProvisionCloudPropertiesTest, ThrowExceptionWhenProvisionCloudPropertiesFailedByCallbackIsNull) { CloudProp cloudProp; cloudProp.setCloudProp("authCode", "authProvider", "ciServer"); cloudProp.setCloudID("f002ae8b-c42c-40d3-8b8d-1927c17bd1b3"); EXPECT_ANY_THROW(g_remoteEnrollee->provisionCloudProperties(cloudProp, nullptr)); } TEST_F(ProvisionCloudPropertiesTest, ThrowExceptionWhenProvisionCloudPropertiesFailedWithoutAuthCode) { CloudProp cloudProp; cloudProp.setCloudProp("", "authProvider", "ciServer"); cloudProp.setCloudID("f002ae8b-c42c-40d3-8b8d-1927c17bd1b3"); EXPECT_ANY_THROW(g_remoteEnrollee->provisionCloudProperties(cloudProp, cloudPropProvStatusCb)); } TEST_F(ProvisionCloudPropertiesTest, ThrowExceptionWhenProvisionCloudPropertiesFailedWithoutAuthProvider) { CloudProp cloudProp; cloudProp.setCloudProp("authCode", "", "ciServer"); cloudProp.setCloudID("f002ae8b-c42c-40d3-8b8d-1927c17bd1b3"); EXPECT_ANY_THROW(g_remoteEnrollee->provisionCloudProperties(cloudProp, cloudPropProvStatusCb)); } TEST_F(ProvisionCloudPropertiesTest, ThrowExceptionWhenProvisionCloudPropertiesFailedWithoutCIServer) { CloudProp cloudProp; cloudProp.setCloudProp("authCode", "authProvider", ""); cloudProp.setCloudID("f002ae8b-c42c-40d3-8b8d-1927c17bd1b3"); EXPECT_ANY_THROW(g_remoteEnrollee->provisionCloudProperties(cloudProp, cloudPropProvStatusCb)); } TEST_F(ProvisionCloudPropertiesTest, ProvisionCloudPropertiesSucceed) { CloudProp cloudProp; cloudProp.setCloudProp("authCode", "authProvider", "ciServer"); cloudProp.setCloudID("f002ae8b-c42c-40d3-8b8d-1927c17bd1b3"); int cntForReceivedCallbackWithSuccess = 0; mocks.OnCallFunc(cloudPropProvStatusCb).Do( [& cntForReceivedCallbackWithSuccess](std::shared_ptr< CloudPropProvisioningStatus > status) { if(status->getESResult() == ES_OK) { cntForReceivedCallbackWithSuccess++; } }); g_remoteEnrollee->provisionCloudProperties(cloudProp, cloudPropProvStatusCb); std::unique_lock< std::mutex > lock{ mutexForCondition }; responseCon.wait_for(lock, g_waitForResponse); EXPECT_EQ(cntForReceivedCallbackWithSuccess, 1); ESTerminateEnrollee(); } <|endoftext|>
<commit_before>/* * Copyright (c) 2015 Samsung Electronics Co., Ltd. * * 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. */ // CLASS HEADERS #include <dali/internal/render/renderers/render-renderer-property-buffer.h> // INTERNAL INCLUDES #include <dali/internal/render/gl-resources/gpu-buffer.h> #include <dali/internal/render/shaders/program.h> namespace Dali { namespace Internal { namespace SceneGraph { RenderPropertyBuffer::RenderPropertyBuffer( const PropertyBufferDataProvider& propertyBufferDataProvider, GpuBuffer::Target gpuBufferTarget, GpuBuffer::Usage gpuBufferUsage ) : mDataProvider( propertyBufferDataProvider ), mGpuBuffer( NULL ), mGpuBufferTarget( gpuBufferTarget ), mGpuBufferUsage( gpuBufferUsage ) { } RenderPropertyBuffer::~RenderPropertyBuffer() { } void RenderPropertyBuffer::Upload( Context& context, BufferIndex bufferIndex ) { bool hasGpuBuffer = NULL != mGpuBuffer; // Check if we have a gpu-buffer unsigned int gpuBufferId = 0; // TODO: MESH_REWORK FIX THIS mDataProvider.GetGpuBufferId( bufferIndex ); if ( ! hasGpuBuffer ) { // TODO: MESH_REWORK // mGpuBuffer /*= gpuBufferCache.GetGpuBuffer( gpuBufferId ) */; (void )gpuBufferId; mGpuBuffer = new GpuBuffer( context, mGpuBufferTarget, mGpuBufferUsage ); } // Update the GpuBuffer if ( ! hasGpuBuffer || mDataProvider.HasDataChanged( bufferIndex ) ) { std::size_t dataSize = mDataProvider.GetDataSize( bufferIndex ); const void *data = &(mDataProvider.GetData( bufferIndex )[0]); // Index buffer needs to be unsigned short which is not supported by the property system if( mGpuBufferTarget == GpuBuffer::ELEMENT_ARRAY_BUFFER ) { Vector<unsigned short> ushortData; ushortData.Resize( dataSize ); const unsigned int* unsignedData = static_cast<const unsigned int*>(data); for( unsigned int i = 0; i < dataSize; ++i ) { ushortData[i] = unsignedData[i]; } data = &(ushortData[0]); } mGpuBuffer->UpdateDataBuffer( dataSize, data ); mGpuBuffer->SetStride( mDataProvider.GetElementSize( bufferIndex ) ); } } void RenderPropertyBuffer::BindBuffer( Context& context, Program& progam ) { mGpuBuffer->Bind(); } void RenderPropertyBuffer::EnableVertexAttributes( Context& context, BufferIndex bufferIndex, Program& program ) { // Check if attribute locations are cached already if( mAttributesLocation.Size() == 0 ) { UpdateAttributeLocations( context, bufferIndex, program ); } unsigned int attributeCount = mDataProvider.GetAttributeCount( bufferIndex ); DALI_ASSERT_DEBUG( attributeCount == mAttributesLocation.Size() && "Incorrect number of attributes!" ); GLsizei elementSize = mDataProvider.GetElementSize( bufferIndex ); for( unsigned int i = 0; i < attributeCount; ++i ) { GLint attributeLocation = mAttributesLocation[i]; if( attributeLocation != -1 ) { context.EnableVertexAttributeArray( attributeLocation ); GLint attributeSize = mDataProvider.GetAttributeSize( bufferIndex, i ); size_t attributeOffset = mDataProvider.GetAttributeOffset( bufferIndex, i ); // TODO: MESH_REWORK Matrices need multiple calls to this function context.VertexAttribPointer( attributeLocation, attributeSize / sizeof(float), // TODO: MESH_REWORK get the correct type GL_FLOAT, // TODO: MESH_REWORK get the correct type GL_FALSE, // Not normalized elementSize, (void*)attributeOffset ); } } } void RenderPropertyBuffer::DisableVertexAttributes( Context& context, BufferIndex bufferIndex, Program& program ) { unsigned int attributeCount = mDataProvider.GetAttributeCount( bufferIndex ); for( unsigned int i = 0; i < attributeCount; ++i ) { GLint attributeLocation = mAttributesLocation[i]; if( attributeLocation != -1 ) { context.DisableVertexAttributeArray( attributeLocation ); } } } void RenderPropertyBuffer::UpdateAttributeLocations( Context& context, BufferIndex bufferIndex, Program& program ) { unsigned int attributeCount = mDataProvider.GetAttributeCount( bufferIndex ); mAttributesLocation.Resize( attributeCount ); for( unsigned int i = 0; i < attributeCount; ++i ) { const std::string& attributeName = mDataProvider.GetAttributeName( bufferIndex, i ); unsigned int index = program.RegisterCustomAttribute( attributeName ); GLint attributeLocation = program.GetCustomAttributeLocation( index ); if( -1 == attributeLocation ) { DALI_LOG_WARNING( "Attribute not found in the shader: %s\n", attributeName.c_str() ); } mAttributesLocation[i] = attributeLocation; } } } // namespace SceneGraph } // namespace Internal } // namespace Dali <commit_msg>Fix buffer used in the wrong scope.<commit_after>/* * Copyright (c) 2015 Samsung Electronics Co., Ltd. * * 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. */ // CLASS HEADERS #include <dali/internal/render/renderers/render-renderer-property-buffer.h> // INTERNAL INCLUDES #include <dali/internal/render/gl-resources/gpu-buffer.h> #include <dali/internal/render/shaders/program.h> namespace Dali { namespace Internal { namespace SceneGraph { RenderPropertyBuffer::RenderPropertyBuffer( const PropertyBufferDataProvider& propertyBufferDataProvider, GpuBuffer::Target gpuBufferTarget, GpuBuffer::Usage gpuBufferUsage ) : mDataProvider( propertyBufferDataProvider ), mGpuBuffer( NULL ), mGpuBufferTarget( gpuBufferTarget ), mGpuBufferUsage( gpuBufferUsage ) { } RenderPropertyBuffer::~RenderPropertyBuffer() { } void RenderPropertyBuffer::Upload( Context& context, BufferIndex bufferIndex ) { bool hasGpuBuffer = NULL != mGpuBuffer; // Check if we have a gpu-buffer unsigned int gpuBufferId = 0; // TODO: MESH_REWORK FIX THIS mDataProvider.GetGpuBufferId( bufferIndex ); if ( ! hasGpuBuffer ) { // TODO: MESH_REWORK // mGpuBuffer /*= gpuBufferCache.GetGpuBuffer( gpuBufferId ) */; (void )gpuBufferId; mGpuBuffer = new GpuBuffer( context, mGpuBufferTarget, mGpuBufferUsage ); } // Update the GpuBuffer if ( ! hasGpuBuffer || mDataProvider.HasDataChanged( bufferIndex ) ) { std::size_t dataSize = mDataProvider.GetDataSize( bufferIndex ); const void *data = &(mDataProvider.GetData( bufferIndex )[0]); Vector<unsigned short> ushortData; // Index buffer needs to be unsigned short which is not supported by the property system if( mGpuBufferTarget == GpuBuffer::ELEMENT_ARRAY_BUFFER ) { ushortData.Resize( dataSize ); const unsigned int* unsignedData = static_cast<const unsigned int*>(data); for( unsigned int i = 0; i < dataSize; ++i ) { ushortData[i] = unsignedData[i]; } data = &(ushortData[0]); } mGpuBuffer->UpdateDataBuffer( dataSize, data ); mGpuBuffer->SetStride( mDataProvider.GetElementSize( bufferIndex ) ); } } void RenderPropertyBuffer::BindBuffer( Context& context, Program& progam ) { mGpuBuffer->Bind(); } void RenderPropertyBuffer::EnableVertexAttributes( Context& context, BufferIndex bufferIndex, Program& program ) { // Check if attribute locations are cached already if( mAttributesLocation.Size() == 0 ) { UpdateAttributeLocations( context, bufferIndex, program ); } unsigned int attributeCount = mDataProvider.GetAttributeCount( bufferIndex ); DALI_ASSERT_DEBUG( attributeCount == mAttributesLocation.Size() && "Incorrect number of attributes!" ); GLsizei elementSize = mDataProvider.GetElementSize( bufferIndex ); for( unsigned int i = 0; i < attributeCount; ++i ) { GLint attributeLocation = mAttributesLocation[i]; if( attributeLocation != -1 ) { context.EnableVertexAttributeArray( attributeLocation ); GLint attributeSize = mDataProvider.GetAttributeSize( bufferIndex, i ); size_t attributeOffset = mDataProvider.GetAttributeOffset( bufferIndex, i ); // TODO: MESH_REWORK Matrices need multiple calls to this function context.VertexAttribPointer( attributeLocation, attributeSize / sizeof(float), // TODO: MESH_REWORK get the correct type GL_FLOAT, // TODO: MESH_REWORK get the correct type GL_FALSE, // Not normalized elementSize, (void*)attributeOffset ); } } } void RenderPropertyBuffer::DisableVertexAttributes( Context& context, BufferIndex bufferIndex, Program& program ) { unsigned int attributeCount = mDataProvider.GetAttributeCount( bufferIndex ); for( unsigned int i = 0; i < attributeCount; ++i ) { GLint attributeLocation = mAttributesLocation[i]; if( attributeLocation != -1 ) { context.DisableVertexAttributeArray( attributeLocation ); } } } void RenderPropertyBuffer::UpdateAttributeLocations( Context& context, BufferIndex bufferIndex, Program& program ) { unsigned int attributeCount = mDataProvider.GetAttributeCount( bufferIndex ); mAttributesLocation.Resize( attributeCount ); for( unsigned int i = 0; i < attributeCount; ++i ) { const std::string& attributeName = mDataProvider.GetAttributeName( bufferIndex, i ); unsigned int index = program.RegisterCustomAttribute( attributeName ); GLint attributeLocation = program.GetCustomAttributeLocation( index ); if( -1 == attributeLocation ) { DALI_LOG_WARNING( "Attribute not found in the shader: %s\n", attributeName.c_str() ); } mAttributesLocation[i] = attributeLocation; } } } // namespace SceneGraph } // namespace Internal } // namespace Dali <|endoftext|>