text
stringlengths
54
60.6k
<commit_before>/* This file is part of KOrganizer. Copyright (c) 2003 Cornelius Schumacher <schumacher@kde.org> This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) 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 Street, Fifth Floor, Boston, MA 02110-1301, USA. As a special exception, permission is given to link this program with any edition of Qt, and distribute the resulting executable, without including the source code for Qt in the source distribution. */ #include "alarmdockwindow.h" #include "koalarmclient.h" #include <kactioncollection.h> #include <kdebug.h> #include <kdeversion.h> #include <klocale.h> #include <kiconloader.h> #include <kiconeffect.h> #include <kconfig.h> #include <kconfiggroup.h> #include <kurl.h> #include <kstandarddirs.h> #include <kmenu.h> #include <kmessagebox.h> #include <kaction.h> #include <kstandardaction.h> #include <ktoolinvocation.h> #include <kglobal.h> #include <QFile> #include <QMouseEvent> #include <stdlib.h> AlarmDockWindow::AlarmDockWindow() : KSystemTrayIcon( 0 ) { // Read the autostart status from the config file KConfigGroup config( KGlobal::config(), "General" ); bool autostart = config.readEntry( "Autostart", true ); bool alarmsEnabled = config.readEntry( "Enabled", true ); mName = i18nc( "@title:window", "KOrganizer Reminder Daemon" ); setToolTip( mName ); // Set up icons KIconLoader::global()->addAppDir( "korgac" ); KIconLoader::global()->addAppDir( "kdepim" ); mIconEnabled = loadIcon( "korgac" ); if ( mIconEnabled.isNull() ) { KMessageBox::sorry( parentWidget(), i18nc( "@info", "Cannot load system tray icon." ) ); } else { KIconLoader loader; QImage iconDisabled = mIconEnabled.pixmap( loader.currentSize( KIconLoader::Panel ) ).toImage(); KIconEffect::toGray( iconDisabled, 1.0 ); mIconDisabled = QIcon( QPixmap::fromImage( iconDisabled ) ); } setIcon( alarmsEnabled ? mIconEnabled : mIconDisabled ); // Set up the context menu mSuspendAll = contextMenu()->addAction( i18nc( "@action:inmenu", "Suspend All" ), this, SLOT(slotSuspendAll()) ); mDismissAll = contextMenu()->addAction( i18nc( "@action:inmenu", "Dismiss All" ), this, SLOT(slotDismissAll()) ); mSuspendAll->setEnabled( false ); mDismissAll->setEnabled( false ); contextMenu()->addSeparator(); mAlarmsEnabled = contextMenu()->addAction( i18nc( "@action:inmenu", "Enable Reminders" ) ); connect( mAlarmsEnabled, SIGNAL(toggled(bool)), SLOT(toggleAlarmsEnabled(bool)) ); mAlarmsEnabled->setCheckable( true ); mAutostart = contextMenu()->addAction( i18nc( "@action:inmenu", "Start Reminder Daemon at Login" ) ); connect( mAutostart, SIGNAL(toggled(bool )), SLOT(toggleAutostart(bool)) ); mAutostart->setCheckable( true ); mAlarmsEnabled->setChecked( alarmsEnabled ); mAutostart->setChecked( autostart ); // Disable standard quit behaviour. We have to intercept the quit even, if the // main window is hidden. KActionCollection *ac = actionCollection(); const char *quitName = KStandardAction::name( KStandardAction::Quit ); QAction *quit = ac->action( quitName ); if ( !quit ) { kDebug() << "No Quit standard action."; } else { quit->disconnect( SIGNAL(triggered(bool)), this, SLOT(maybeQuit()) ); connect( quit, SIGNAL(activated()), SLOT(slotQuit()) ); } connect( this, SIGNAL(activated( QSystemTrayIcon::ActivationReason )), SLOT(slotActivated( QSystemTrayIcon::ActivationReason )) ); setToolTip( mName ); } AlarmDockWindow::~AlarmDockWindow() { } void AlarmDockWindow::slotUpdate( int reminders ) { mSuspendAll->setEnabled( reminders > 0 ); mDismissAll->setEnabled( reminders > 0 ); if ( reminders > 0 ) { setToolTip( i18ncp( "@info:tooltip", "There is 1 active reminder.", "There are %1 active reminders.", reminders ) ); } else { setToolTip( mName ); } } void AlarmDockWindow::toggleAlarmsEnabled( bool checked ) { kDebug(); setIcon( checked ? mIconEnabled : mIconDisabled ); KConfigGroup config( KGlobal::config(), "General" ); config.writeEntry( "Enabled", checked ); config.sync(); } void AlarmDockWindow::toggleAutostart( bool checked ) { kDebug(); enableAutostart( checked ); } void AlarmDockWindow::slotSuspendAll() { emit suspendAllSignal(); } void AlarmDockWindow::slotDismissAll() { emit dismissAllSignal(); } void AlarmDockWindow::enableAutostart( bool enable ) { KConfigGroup config( KGlobal::config(), "General" ); config.writeEntry( "Autostart", enable ); config.sync(); } void AlarmDockWindow::slotActivated( QSystemTrayIcon::ActivationReason reason ) { if ( reason == QSystemTrayIcon::Trigger ) { KToolInvocation::startServiceByDesktopName( "korganizer", QString() ); } } void AlarmDockWindow::slotQuit() { int result = KMessageBox::questionYesNoCancel( parentWidget(), i18nc( "@info", "Do you want to start the KOrganizer reminder daemon at login " "(note that you will not get reminders whilst the daemon is not running)?" ), i18nc( "@title:window", "Close KOrganizer Reminder Daemon" ), KGuiItem( i18nc( "@action:button start the reminder daemon", "Start" ) ), KGuiItem( i18nc( "@action:button do not start the reminder daemon", "Do Not Start" ) ), KStandardGuiItem::cancel(), QString::fromLatin1( "AskForStartAtLogin" ) ); bool autostart = true; if ( result == KMessageBox::No ) { autostart = false; } enableAutostart( autostart ); if ( result != KMessageBox::Cancel ) { emit quitSignal(); } } #include "alarmdockwindow.moc" <commit_msg>more explicit menu items strings<commit_after>/* This file is part of KOrganizer. Copyright (c) 2003 Cornelius Schumacher <schumacher@kde.org> This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) 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 Street, Fifth Floor, Boston, MA 02110-1301, USA. As a special exception, permission is given to link this program with any edition of Qt, and distribute the resulting executable, without including the source code for Qt in the source distribution. */ #include "alarmdockwindow.h" #include "koalarmclient.h" #include <kactioncollection.h> #include <kdebug.h> #include <kdeversion.h> #include <klocale.h> #include <kiconloader.h> #include <kiconeffect.h> #include <kconfig.h> #include <kconfiggroup.h> #include <kurl.h> #include <kstandarddirs.h> #include <kmenu.h> #include <kmessagebox.h> #include <kaction.h> #include <kstandardaction.h> #include <ktoolinvocation.h> #include <kglobal.h> #include <QFile> #include <QMouseEvent> #include <stdlib.h> AlarmDockWindow::AlarmDockWindow() : KSystemTrayIcon( 0 ) { // Read the autostart status from the config file KConfigGroup config( KGlobal::config(), "General" ); bool autostart = config.readEntry( "Autostart", true ); bool alarmsEnabled = config.readEntry( "Enabled", true ); mName = i18nc( "@title:window", "KOrganizer Reminder Daemon" ); setToolTip( mName ); // Set up icons KIconLoader::global()->addAppDir( "korgac" ); KIconLoader::global()->addAppDir( "kdepim" ); mIconEnabled = loadIcon( "korgac" ); if ( mIconEnabled.isNull() ) { KMessageBox::sorry( parentWidget(), i18nc( "@info", "Cannot load system tray icon." ) ); } else { KIconLoader loader; QImage iconDisabled = mIconEnabled.pixmap( loader.currentSize( KIconLoader::Panel ) ).toImage(); KIconEffect::toGray( iconDisabled, 1.0 ); mIconDisabled = QIcon( QPixmap::fromImage( iconDisabled ) ); } setIcon( alarmsEnabled ? mIconEnabled : mIconDisabled ); // Set up the context menu mSuspendAll = contextMenu()->addAction( i18nc( "@action:inmenu", "Suspend All Reminders" ), this, SLOT(slotSuspendAll()) ); mDismissAll = contextMenu()->addAction( i18nc( "@action:inmenu", "Dismiss All Reminders" ), this, SLOT(slotDismissAll()) ); mSuspendAll->setEnabled( false ); mDismissAll->setEnabled( false ); contextMenu()->addSeparator(); mAlarmsEnabled = contextMenu()->addAction( i18nc( "@action:inmenu", "Enable Reminders" ) ); connect( mAlarmsEnabled, SIGNAL(toggled(bool)), SLOT(toggleAlarmsEnabled(bool)) ); mAlarmsEnabled->setCheckable( true ); mAutostart = contextMenu()->addAction( i18nc( "@action:inmenu", "Start Reminder Daemon at Login" ) ); connect( mAutostart, SIGNAL(toggled(bool )), SLOT(toggleAutostart(bool)) ); mAutostart->setCheckable( true ); mAlarmsEnabled->setChecked( alarmsEnabled ); mAutostart->setChecked( autostart ); // Disable standard quit behaviour. We have to intercept the quit even, if the // main window is hidden. KActionCollection *ac = actionCollection(); const char *quitName = KStandardAction::name( KStandardAction::Quit ); QAction *quit = ac->action( quitName ); if ( !quit ) { kDebug() << "No Quit standard action."; } else { quit->disconnect( SIGNAL(triggered(bool)), this, SLOT(maybeQuit()) ); connect( quit, SIGNAL(activated()), SLOT(slotQuit()) ); } connect( this, SIGNAL(activated( QSystemTrayIcon::ActivationReason )), SLOT(slotActivated( QSystemTrayIcon::ActivationReason )) ); setToolTip( mName ); } AlarmDockWindow::~AlarmDockWindow() { } void AlarmDockWindow::slotUpdate( int reminders ) { mSuspendAll->setEnabled( reminders > 0 ); mDismissAll->setEnabled( reminders > 0 ); if ( reminders > 0 ) { setToolTip( i18ncp( "@info:tooltip", "There is 1 active reminder.", "There are %1 active reminders.", reminders ) ); } else { setToolTip( i18nc( "@info:tooltip", "No active reminders." ) ); } } void AlarmDockWindow::toggleAlarmsEnabled( bool checked ) { kDebug(); setIcon( checked ? mIconEnabled : mIconDisabled ); KConfigGroup config( KGlobal::config(), "General" ); config.writeEntry( "Enabled", checked ); config.sync(); } void AlarmDockWindow::toggleAutostart( bool checked ) { kDebug(); enableAutostart( checked ); } void AlarmDockWindow::slotSuspendAll() { emit suspendAllSignal(); } void AlarmDockWindow::slotDismissAll() { emit dismissAllSignal(); } void AlarmDockWindow::enableAutostart( bool enable ) { KConfigGroup config( KGlobal::config(), "General" ); config.writeEntry( "Autostart", enable ); config.sync(); } void AlarmDockWindow::slotActivated( QSystemTrayIcon::ActivationReason reason ) { if ( reason == QSystemTrayIcon::Trigger ) { KToolInvocation::startServiceByDesktopName( "korganizer", QString() ); } } void AlarmDockWindow::slotQuit() { int result = KMessageBox::questionYesNoCancel( parentWidget(), i18nc( "@info", "Do you want to start the KOrganizer reminder daemon at login " "(note that you will not get reminders whilst the daemon is not running)?" ), i18nc( "@title:window", "Close KOrganizer Reminder Daemon" ), KGuiItem( i18nc( "@action:button start the reminder daemon", "Start" ) ), KGuiItem( i18nc( "@action:button do not start the reminder daemon", "Do Not Start" ) ), KStandardGuiItem::cancel(), QString::fromLatin1( "AskForStartAtLogin" ) ); bool autostart = true; if ( result == KMessageBox::No ) { autostart = false; } enableAutostart( autostart ); if ( result != KMessageBox::Cancel ) { emit quitSignal(); } } #include "alarmdockwindow.moc" <|endoftext|>
<commit_before>/* This file is part of kdepim. Copyright (c) 2008 Kevin Ottens <ervin@kde.org> 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. 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 "folderselectdialog.h" #include <qlayout.h> #include <qlabel.h> #include <qevent.h> using namespace KPIM; FolderSelectDialog::FolderSelectDialog( const QString& caption, const QString& label, const QStringList& list ) : KDialog() { setModal(true); setCaption(caption); setButtons(Ok); setDefaultButton(Ok); showButtonSeparator(true); QWidget* frame = mainWidget(); QVBoxLayout* layout = new QVBoxLayout( frame, 0, spacingHint() ); QLabel* labelWidget = new QLabel( label, frame ); layout->addWidget( labelWidget ); mListBox = new K3ListBox( frame ); mListBox->insertStringList( list ); mListBox->setSelected( 0, true ); mListBox->ensureCurrentVisible(); layout->addWidget( mListBox, 10 ); connect( mListBox, SIGNAL( doubleClicked( QListBoxItem * ) ), SLOT( okClicked() ) ); connect( mListBox, SIGNAL( returnPressed( QListBoxItem * ) ), SLOT( okClicked() ) ); mListBox->setFocus(); layout->addStretch(); setMinimumWidth( 320 ); } QString FolderSelectDialog::getItem( const QString &caption, const QString &label, const QStringList& list ) { FolderSelectDialog dlg( caption, label, list ); QString result; if ( dlg.exec() == Accepted ) result = dlg.mListBox->currentText(); return result; } void FolderSelectDialog::closeEvent(QCloseEvent *event) { event->ignore(); } void FolderSelectDialog::reject() { } <commit_msg>Fix signal/slot connection.<commit_after>/* This file is part of kdepim. Copyright (c) 2008 Kevin Ottens <ervin@kde.org> 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. 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 "folderselectdialog.h" #include <qlayout.h> #include <qlabel.h> #include <qevent.h> using namespace KPIM; FolderSelectDialog::FolderSelectDialog( const QString& caption, const QString& label, const QStringList& list ) : KDialog() { setModal(true); setCaption(caption); setButtons(Ok); setDefaultButton(Ok); showButtonSeparator(true); QWidget* frame = mainWidget(); QVBoxLayout* layout = new QVBoxLayout( frame, 0, spacingHint() ); QLabel* labelWidget = new QLabel( label, frame ); layout->addWidget( labelWidget ); mListBox = new K3ListBox( frame ); mListBox->insertStringList( list ); mListBox->setSelected( 0, true ); mListBox->ensureCurrentVisible(); layout->addWidget( mListBox, 10 ); connect( mListBox, SIGNAL( doubleClicked( Q3ListBoxItem * ) ), SLOT( accept() ) ); connect( mListBox, SIGNAL( returnPressed( Q3ListBoxItem * ) ), SLOT( accept() ) ); mListBox->setFocus(); layout->addStretch(); setMinimumWidth( 320 ); } QString FolderSelectDialog::getItem( const QString &caption, const QString &label, const QStringList& list ) { FolderSelectDialog dlg( caption, label, list ); QString result; if ( dlg.exec() == Accepted ) result = dlg.mListBox->currentText(); return result; } void FolderSelectDialog::closeEvent(QCloseEvent *event) { event->ignore(); } void FolderSelectDialog::reject() { } <|endoftext|>
<commit_before>/** * Copyright (c) 2016 Los Alamos National Security, LLC * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * LA-CC 10-123 */ //@HEADER // *************************************************** // // HPCG: High Performance Conjugate Gradient Benchmark // // Contact: // Michael A. Heroux ( maherou@sandia.gov) // Jack Dongarra (dongarra@eecs.utk.edu) // Piotr Luszczek (luszczek@eecs.utk.edu) // // *************************************************** //@HEADER /*! @file SetupHalo_ref.cpp HPCG routine */ #pragma once #include "LegionMatrices.hpp" #include "hpcg.hpp" #include "mytimer.hpp" #include <map> #include <set> #include <cassert> /*! Reference version of SetupHalo that prepares system matrix data structure and creates data necessary for communication of boundary values of this process. @param[inout] A The known system matrix @see ExchangeHalo */ inline void SetupHalo( SparseMatrix &A, LegionRuntime::HighLevel::Context ctx, LegionRuntime::HighLevel::Runtime *runtime ) { using namespace std; // Extract Matrix pieces local_int_t localNumberOfRows = A.localNumberOfRows; char *nonzerosInRow = A.nonzerosInRow; // These have already been allocated, so just interpret at 2D array Array2D<global_int_t> mtxIndG( localNumberOfRows, A.maxNonzerosPerRow , A.mtxIndG ); Array2D<local_int_t> mtxIndL( localNumberOfRows, A.maxNonzerosPerRow , A.mtxIndL ); // Scan global IDs of the nonzeros in the matrix. Determine if the column // ID matches a row ID. If not: 1) We call the ComputeRankOfMatrixRow // function, which tells us the rank of the processor owning the row ID. We // need to receive this value of the x vector during the halo exchange. 2) // We record our row ID since we know that the other processor will need // this value from us, due to symmetry. std::map< int, std::set< global_int_t> > sendList, receiveList; typedef std::map< int, std::set< global_int_t> >::iterator map_iter; typedef std::set<global_int_t>::iterator set_iter; std::map< local_int_t, local_int_t > externalToLocalMap; for (local_int_t i = 0; i < localNumberOfRows; i++) { global_int_t currentGlobalRow = A.localToGlobalMap[i]; for (int j = 0; j<nonzerosInRow[i]; j++) { global_int_t curIndex = mtxIndG(i, j); int rankIdOfColumnEntry = ComputeRankOfMatrixRow( *(A.geom), curIndex ); // If column index is not a row index, then it comes from another // processor if (A.geom->rank != rankIdOfColumnEntry) { receiveList[rankIdOfColumnEntry].insert(curIndex); // Matrix symmetry means we know the neighbor process wants my // value sendList[rankIdOfColumnEntry].insert(currentGlobalRow); } } } // Count number of matrix entries to send and receive local_int_t totalToBeSent = 0; for (map_iter curNeighbor = sendList.begin(); curNeighbor != sendList.end(); ++curNeighbor) { totalToBeSent += (curNeighbor->second).size(); } local_int_t totalToBeReceived = 0; for (map_iter curNeighbor = receiveList.begin(); curNeighbor != receiveList.end(); ++curNeighbor) { totalToBeReceived += (curNeighbor->second).size(); } #ifdef HPCG_DETAILED_DEBUG // These are all attributes that should be true, due to symmetry HPCG_fout << "totalToBeSent = " << totalToBeSent << " totalToBeReceived = " << totalToBeReceived << endl; // Number of sent entry should equal number of received assert(totalToBeSent == totalToBeReceived); // Number of send-to neighbors should equal number of receive-from assert(sendList.size() == receiveList.size()); // Each receive-from neighbor should be a send-to neighbor, and send the // same number of entries for (map_iter curNeighbor = receiveList.begin(); curNeighbor != receiveList.end(); ++curNeighbor) { assert(sendList.find(curNeighbor->first)!=sendList.end()); assert(sendList[curNeighbor->first].size() == receiveList[curNeighbor->first].size()); } #endif // Build the arrays and lists needed by the ExchangeHalo function. //double * sendBuffer = new double[totalToBeSent]; // ArrayAllocator<local_int_t> *aaElementsToSend = nullptr; local_int_t *elementsToSend = nullptr; if (totalToBeSent != 0) { aaElementsToSend = new ArrayAllocator<local_int_t>( totalToBeSent, WO_E, ctx, runtime ); elementsToSend = aaElementsToSend->data(); assert(elementsToSend); } // ArrayAllocator<int> *aaNeighbors = nullptr; int *neighbors = nullptr; if (sendList.size() != 0) { aaNeighbors = new ArrayAllocator<int>( sendList.size(), WO_E, ctx, runtime ); neighbors = aaNeighbors->data(); assert(neighbors); } // ArrayAllocator<local_int_t> *aaReceiveLength = nullptr; local_int_t *receiveLength = nullptr; if (receiveList.size() != 0) { aaReceiveLength = new ArrayAllocator<local_int_t>( receiveList.size(), WO_E, ctx, runtime ); receiveLength = aaReceiveLength->data(); assert(receiveLength); } // ArrayAllocator<local_int_t> *aaSendLength = nullptr; local_int_t *sendLength = nullptr; if (sendList.size() != 0) { aaSendLength = new ArrayAllocator<local_int_t>( sendList.size(), WO_E, ctx, runtime ); sendLength = aaSendLength->data(); assert(sendLength); } int neighborCount = 0; local_int_t receiveEntryCount = 0; local_int_t sendEntryCount = 0; for (map_iter curNeighbor = receiveList.begin(); curNeighbor != receiveList.end(); ++curNeighbor, ++neighborCount) { // rank of current neighbor we are processing int neighborId = curNeighbor->first; // store rank ID of current neighbor neighbors[neighborCount] = neighborId; receiveLength[neighborCount] = receiveList[neighborId].size(); // Get count if sends/receives sendLength[neighborCount] = sendList[neighborId].size(); for (set_iter i = receiveList[neighborId].begin(); i != receiveList[neighborId].end(); ++i, ++receiveEntryCount) { // The remote columns are indexed at end of internals externalToLocalMap[*i] = localNumberOfRows + receiveEntryCount; } for (set_iter i = sendList[neighborId].begin(); i != sendList[neighborId].end(); ++i, ++sendEntryCount) { // store local ids of entry to send elementsToSend[sendEntryCount] = A.globalToLocalMap[*i]; } } // Convert matrix indices to local IDs for (local_int_t i = 0; i< localNumberOfRows; i++) { for (int j = 0; j < nonzerosInRow[i]; j++) { global_int_t curIndex = mtxIndG(i, j); int rankIdOfColumnEntry = ComputeRankOfMatrixRow(*(A.geom), curIndex); // My column index, so convert to local index if (A.geom->rank==rankIdOfColumnEntry) { mtxIndL(i, j) = A.globalToLocalMap[curIndex]; } // If column index is not a row index, then it comes from another // processor else { mtxIndL(i, j) = externalToLocalMap[curIndex]; } } } // Store contents in our matrix struct // Convenience pointer to A.localData auto *AlD = A.localData; // AlD->numberOfExternalValues = externalToLocalMap.size(); AlD->localNumberOfColumns = AlD->localNumberOfRows + AlD->numberOfExternalValues; AlD->numberOfSendNeighbors = sendList.size(); AlD->numberOfRecvNeighbors = receiveList.size(); AlD->totalToBeSent = totalToBeSent; // if (aaElementsToSend) { aaElementsToSend->bindToLogicalRegion(*(A.pic.elementsToSend.data())); delete aaElementsToSend; } if (aaNeighbors) { aaNeighbors->bindToLogicalRegion(*(A.pic.neighbors.data())); delete aaNeighbors; } if (aaReceiveLength) { aaReceiveLength->bindToLogicalRegion(*(A.pic.receiveLength.data())); delete aaReceiveLength; } if (aaSendLength) { aaSendLength->bindToLogicalRegion(*(A.pic.sendLength.data())); delete aaSendLength; } #if 0 cout << " For rank " << A.geom->rank << " of " << A.geom->size << ", number of neighbors = " << AlD->numberOfSendNeighbors << endl; for (int i = 0; i < AlD->numberOfSendNeighbors; i++) { cout << " rank " << A.geom->rank << " neighbor " << neighbors[i] << " send/recv length = " << sendLength[i] << "/" << receiveLength[i] << endl; for (local_int_t j = 0; j<sendLength[i]; ++j) cout << " rank " << A.geom->rank << " elementsToSend[" << j << "] = " << elementsToSend[j] << endl; } #endif } /** * */ inline void SetupHaloTopLevel( LogicalSparseMatrix &A, const Geometry &geom, LegionRuntime::HighLevel::Context ctx, LegionRuntime::HighLevel::Runtime *lrt ) { using namespace std; // cout << "*** Setting Up Structures for SPMD Exchanges..." << endl; const double startTime = mytimer(); const int nShards = geom.size; // Extract required info from logical structures. // cout << "--> Memory for SparseMatrixScalars=" << (sizeof(SparseMatrixScalars) * nShards) / 1024.0 << "kB" << endl; Array<SparseMatrixScalars> aSparseMatrixScalars( A.localData.mapRegion(RO_E, ctx, lrt), ctx, lrt ); SparseMatrixScalars *smScalars = aSparseMatrixScalars.data(); assert(smScalars); // Calculate the entire extent (including ghost cells) for a given halo'd // vector. This is simply the sum of all localNumberOfColumns. size_t totVecLen = 0; std::vector<size_t> vecPartLens; for (int s = 0; s < nShards; ++s) { const auto locLen = smScalars[s].localNumberOfColumns; totVecLen += locLen; vecPartLens.push_back(locLen); } cout << "--> Halo'd Vector Total Length=" << totVecLen << endl; // Array<LogicalRegion> alrNeighborss( A.lrNeighborss.mapRegion(RO_E, ctx, lrt), ctx, lrt ); LogicalRegion *lrpNeighbors = alrNeighborss.data(); assert(lrpNeighbors); // Determine total number of PhaseBarriers required for synchronization size_t totpb = 0; // Record number of PhaseBarriers required for each task and tally total // number of PhaseBarriers required for this calculation. std::vector<size_t> numPhaseBarriers; for (int shard = 0; shard < nShards; ++shard) { const size_t nrn = smScalars[shard].numberOfSendNeighbors; numPhaseBarriers.push_back(nrn); totpb += nrn; } // 2x for ready/done pairs cout << "--> Total Number of PhaseBarriers Created=" << 2 * totpb << endl; // Create and partition logical regions that will store PhaseBarriers LogicalArray<PhaseBarrier> lrReadyPhaseBarriers; LogicalArray<PhaseBarrier> lrDonePhaseBarriers; // lrReadyPhaseBarriers.allocate(totpb, ctx, lrt); lrDonePhaseBarriers.allocate(totpb, ctx, lrt); // lrReadyPhaseBarriers.partition(numPhaseBarriers, ctx, lrt); lrDonePhaseBarriers.partition(numPhaseBarriers, ctx, lrt); // Iterate over all shards for (int shard = 0; shard < nShards; ++shard) { LogicalItem<LogicalRegion> lrNeighbors(lrpNeighbors[shard], ctx, lrt); Array<int> aNeighbors(lrNeighbors.mapRegion(RO_E, ctx, lrt), ctx, lrt); int *neighbors = aNeighbors.data(); assert(neighbors); const int nNeighbors = smScalars[shard].numberOfSendNeighbors; cout << "Rank " << shard << " Has " << nNeighbors << " Send Neighbors " << endl; for (int i = 0; i < nNeighbors; ++i) { cout << neighbors[i] << " "; } cout << endl; lrNeighbors.unmapRegion(ctx, lrt); } // Unmap inline mapped structures. A.localData.unmapRegion(ctx, lrt); A.lrNeighborss.unmapRegion(ctx, lrt); // lrReadyPhaseBarriers.deallocate(ctx, lrt); lrDonePhaseBarriers.deallocate(ctx, lrt); // const double endTime = mytimer(); double time = endTime - startTime; cout << "--> Time=" << time << "s" << endl; } <commit_msg>Fix build and cleanup.<commit_after>/** * Copyright (c) 2016 Los Alamos National Security, LLC * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * LA-CC 10-123 */ //@HEADER // *************************************************** // // HPCG: High Performance Conjugate Gradient Benchmark // // Contact: // Michael A. Heroux ( maherou@sandia.gov) // Jack Dongarra (dongarra@eecs.utk.edu) // Piotr Luszczek (luszczek@eecs.utk.edu) // // *************************************************** //@HEADER /*! @file SetupHalo_ref.cpp HPCG routine */ #pragma once #include "LegionMatrices.hpp" #include "hpcg.hpp" #include "mytimer.hpp" #include <map> #include <set> #include <cassert> /*! Reference version of SetupHalo that prepares system matrix data structure and creates data necessary for communication of boundary values of this process. @param[inout] A The known system matrix @see ExchangeHalo */ inline void SetupHalo( SparseMatrix &A, LegionRuntime::HighLevel::Context ctx, LegionRuntime::HighLevel::Runtime *runtime ) { using namespace std; // Extract Matrix pieces local_int_t localNumberOfRows = A.localNumberOfRows; char *nonzerosInRow = A.nonzerosInRow; // These have already been allocated, so just interpret at 2D array Array2D<global_int_t> mtxIndG( localNumberOfRows, A.maxNonzerosPerRow , A.mtxIndG ); Array2D<local_int_t> mtxIndL( localNumberOfRows, A.maxNonzerosPerRow , A.mtxIndL ); // Scan global IDs of the nonzeros in the matrix. Determine if the column // ID matches a row ID. If not: 1) We call the ComputeRankOfMatrixRow // function, which tells us the rank of the processor owning the row ID. We // need to receive this value of the x vector during the halo exchange. 2) // We record our row ID since we know that the other processor will need // this value from us, due to symmetry. std::map< int, std::set< global_int_t> > sendList, receiveList; typedef std::map< int, std::set< global_int_t> >::iterator map_iter; typedef std::set<global_int_t>::iterator set_iter; std::map< local_int_t, local_int_t > externalToLocalMap; for (local_int_t i = 0; i < localNumberOfRows; i++) { global_int_t currentGlobalRow = A.localToGlobalMap[i]; for (int j = 0; j<nonzerosInRow[i]; j++) { global_int_t curIndex = mtxIndG(i, j); int rankIdOfColumnEntry = ComputeRankOfMatrixRow( *(A.geom), curIndex ); // If column index is not a row index, then it comes from another // processor if (A.geom->rank != rankIdOfColumnEntry) { receiveList[rankIdOfColumnEntry].insert(curIndex); // Matrix symmetry means we know the neighbor process wants my // value sendList[rankIdOfColumnEntry].insert(currentGlobalRow); } } } // Count number of matrix entries to send and receive local_int_t totalToBeSent = 0; for (map_iter curNeighbor = sendList.begin(); curNeighbor != sendList.end(); ++curNeighbor) { totalToBeSent += (curNeighbor->second).size(); } local_int_t totalToBeReceived = 0; for (map_iter curNeighbor = receiveList.begin(); curNeighbor != receiveList.end(); ++curNeighbor) { totalToBeReceived += (curNeighbor->second).size(); } #ifdef HPCG_DETAILED_DEBUG // These are all attributes that should be true, due to symmetry HPCG_fout << "totalToBeSent = " << totalToBeSent << " totalToBeReceived = " << totalToBeReceived << endl; // Number of sent entry should equal number of received assert(totalToBeSent == totalToBeReceived); // Number of send-to neighbors should equal number of receive-from assert(sendList.size() == receiveList.size()); // Each receive-from neighbor should be a send-to neighbor, and send the // same number of entries for (map_iter curNeighbor = receiveList.begin(); curNeighbor != receiveList.end(); ++curNeighbor) { assert(sendList.find(curNeighbor->first)!=sendList.end()); assert(sendList[curNeighbor->first].size() == receiveList[curNeighbor->first].size()); } #endif // Build the arrays and lists needed by the ExchangeHalo function. //double * sendBuffer = new double[totalToBeSent]; // ArrayAllocator<local_int_t> *aaElementsToSend = nullptr; local_int_t *elementsToSend = nullptr; if (totalToBeSent != 0) { aaElementsToSend = new ArrayAllocator<local_int_t>( totalToBeSent, WO_E, ctx, runtime ); elementsToSend = aaElementsToSend->data(); assert(elementsToSend); } // ArrayAllocator<int> *aaNeighbors = nullptr; int *neighbors = nullptr; if (sendList.size() != 0) { aaNeighbors = new ArrayAllocator<int>( sendList.size(), WO_E, ctx, runtime ); neighbors = aaNeighbors->data(); assert(neighbors); } // ArrayAllocator<local_int_t> *aaReceiveLength = nullptr; local_int_t *receiveLength = nullptr; if (receiveList.size() != 0) { aaReceiveLength = new ArrayAllocator<local_int_t>( receiveList.size(), WO_E, ctx, runtime ); receiveLength = aaReceiveLength->data(); assert(receiveLength); } // ArrayAllocator<local_int_t> *aaSendLength = nullptr; local_int_t *sendLength = nullptr; if (sendList.size() != 0) { aaSendLength = new ArrayAllocator<local_int_t>( sendList.size(), WO_E, ctx, runtime ); sendLength = aaSendLength->data(); assert(sendLength); } int neighborCount = 0; local_int_t receiveEntryCount = 0; local_int_t sendEntryCount = 0; for (map_iter curNeighbor = receiveList.begin(); curNeighbor != receiveList.end(); ++curNeighbor, ++neighborCount) { // rank of current neighbor we are processing int neighborId = curNeighbor->first; // store rank ID of current neighbor neighbors[neighborCount] = neighborId; receiveLength[neighborCount] = receiveList[neighborId].size(); // Get count if sends/receives sendLength[neighborCount] = sendList[neighborId].size(); for (set_iter i = receiveList[neighborId].begin(); i != receiveList[neighborId].end(); ++i, ++receiveEntryCount) { // The remote columns are indexed at end of internals externalToLocalMap[*i] = localNumberOfRows + receiveEntryCount; } for (set_iter i = sendList[neighborId].begin(); i != sendList[neighborId].end(); ++i, ++sendEntryCount) { // store local ids of entry to send elementsToSend[sendEntryCount] = A.globalToLocalMap[*i]; } } // Convert matrix indices to local IDs for (local_int_t i = 0; i< localNumberOfRows; i++) { for (int j = 0; j < nonzerosInRow[i]; j++) { global_int_t curIndex = mtxIndG(i, j); int rankIdOfColumnEntry = ComputeRankOfMatrixRow(*(A.geom), curIndex); // My column index, so convert to local index if (A.geom->rank==rankIdOfColumnEntry) { mtxIndL(i, j) = A.globalToLocalMap[curIndex]; } // If column index is not a row index, then it comes from another // processor else { mtxIndL(i, j) = externalToLocalMap[curIndex]; } } } // Store contents in our matrix struct // Convenience pointer to A.localData auto *AlD = A.localData; // AlD->numberOfExternalValues = externalToLocalMap.size(); AlD->localNumberOfColumns = AlD->localNumberOfRows + AlD->numberOfExternalValues; AlD->numberOfSendNeighbors = sendList.size(); AlD->numberOfRecvNeighbors = receiveList.size(); AlD->totalToBeSent = totalToBeSent; // if (aaElementsToSend) { aaElementsToSend->bindToLogicalRegion(*(A.pic.elementsToSend.data())); delete aaElementsToSend; } if (aaNeighbors) { aaNeighbors->bindToLogicalRegion(*(A.pic.neighbors.data())); delete aaNeighbors; } if (aaReceiveLength) { aaReceiveLength->bindToLogicalRegion(*(A.pic.receiveLength.data())); delete aaReceiveLength; } if (aaSendLength) { aaSendLength->bindToLogicalRegion(*(A.pic.sendLength.data())); delete aaSendLength; } #if 0 cout << " For rank " << A.geom->rank << " of " << A.geom->size << ", number of neighbors = " << AlD->numberOfSendNeighbors << endl; for (int i = 0; i < AlD->numberOfSendNeighbors; i++) { cout << " rank " << A.geom->rank << " neighbor " << neighbors[i] << " send/recv length = " << sendLength[i] << "/" << receiveLength[i] << endl; for (local_int_t j = 0; j<sendLength[i]; ++j) cout << " rank " << A.geom->rank << " elementsToSend[" << j << "] = " << elementsToSend[j] << endl; } #endif } /** * */ inline void SetupHaloTopLevel( LogicalSparseMatrix &A, const Geometry &geom, LegionRuntime::HighLevel::Context ctx, LegionRuntime::HighLevel::Runtime *lrt ) { using namespace std; // cout << "*** Setting Up Structures for SPMD Exchanges..." << endl; const double startTime = mytimer(); const int nShards = geom.size; // Extract required info from logical structures. // cout << "--> Memory for SparseMatrixScalars=" << (sizeof(SparseMatrixScalars) * nShards) / 1024.0 << "kB" << endl; Array<SparseMatrixScalars> aSparseMatrixScalars( A.localData.mapRegion(RO_E, ctx, lrt), ctx, lrt ); SparseMatrixScalars *smScalars = aSparseMatrixScalars.data(); assert(smScalars); // Calculate the entire extent (including ghost cells) for a given halo'd // vector. This is simply the sum of all localNumberOfColumns. size_t totVecLen = 0; std::vector<size_t> vecPartLens; for (int s = 0; s < nShards; ++s) { const auto locLen = smScalars[s].localNumberOfColumns; totVecLen += locLen; vecPartLens.push_back(locLen); } cout << "--> Halo'd Vector Total Length=" << totVecLen << endl; // Array<LogicalRegion> alrNeighborss( A.lrNeighbors.mapRegion(RO_E, ctx, lrt), ctx, lrt ); LogicalRegion *lrpNeighbors = alrNeighborss.data(); assert(lrpNeighbors); // Determine total number of PhaseBarriers required for synchronization. // Each shard will create two PhaseBarriers that it owns. A ready // PhaseBarrier to notify its consumers and a done PhaseBarrier to receive // notifications from its consumers. // 2x for ready/done pairs size_t totpb = 2 * nShards; cout << "--> Total Number of PhaseBarriers Created=" << totpb << endl; // Iterate over all shards for (int shard = 0; shard < nShards; ++shard) { LogicalItem<LogicalRegion> lrNeighbors(lrpNeighbors[shard], ctx, lrt); Array<int> aNeighbors(lrNeighbors.mapRegion(RO_E, ctx, lrt), ctx, lrt); int *neighbors = aNeighbors.data(); assert(neighbors); const int nNeighbors = smScalars[shard].numberOfSendNeighbors; cout << "Rank " << shard << " Has " << nNeighbors << " Send Neighbors " << endl; for (int i = 0; i < nNeighbors; ++i) { cout << neighbors[i] << " "; } cout << endl; lrNeighbors.unmapRegion(ctx, lrt); } // Unmap inline mapped structures. A.localData.unmapRegion(ctx, lrt); A.lrNeighbors.unmapRegion(ctx, lrt); // const double endTime = mytimer(); double time = endTime - startTime; cout << "--> Time=" << time << "s" << endl; } <|endoftext|>
<commit_before>/* * * Copyright (c) 2021 Project CHIP Authors * * 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 <lib/support/CodeUtils.h> #include <lib/support/DefaultStorageKeyAllocator.h> #include <lib/support/SafeInt.h> #include <lib/support/logging/CHIPLogging.h> #include <platform/CHIPDeviceLayer.h> #include <platform/KeyValueStoreManager.h> #include <platform/NetworkCommissioning.h> #include <platform/OpenThread/GenericNetworkCommissioningThreadDriver.h> #include <platform/OpenThread/GenericThreadStackManagerImpl_OpenThread.h> #include <platform/ThreadStackManager.h> #include <limits> using namespace chip; using namespace chip::Thread; using namespace chip::DeviceLayer::PersistedStorage; namespace chip { namespace DeviceLayer { namespace NetworkCommissioning { // NOTE: For GenericThreadDriver, we assume that the network configuration is persisted by // the OpenThread stack after ConnectNetwork command is called, and before that, all the changes // are made to a local copy of the dataset stored in mStagingNetwork. // Also, in order to support the fail-safe mechanism, the configuration is backed up in a temporary // KVS slot upon any changes and restored when the fail-safe timeout is triggered or the device // reboots without completing all the changes. // Not all KVS implementations support zero-length values, so use this special value, that is not a valid // dataset, to represent an empty dataset. We need that to be able to revert the network configuration // in the case of an unsuccessful commissioning. constexpr uint8_t kEmptyDataset[1] = {}; CHIP_ERROR GenericThreadDriver::Init(Internal::BaseDriver::NetworkStatusChangeCallback * statusChangeCallback) { ThreadStackMgrImpl().SetNetworkStatusChangeCallback(statusChangeCallback); VerifyOrReturnError(ThreadStackMgrImpl().IsThreadAttached(), CHIP_NO_ERROR); VerifyOrReturnError(ThreadStackMgrImpl().GetThreadProvision(mStagingNetwork) == CHIP_NO_ERROR, CHIP_NO_ERROR); return CHIP_NO_ERROR; } void GenericThreadDriver::Shutdown() { ThreadStackMgrImpl().SetNetworkStatusChangeCallback(nullptr); } CHIP_ERROR GenericThreadDriver::CommitConfiguration() { // OpenThread persists the network configuration on AttachToThreadNetwork, so simply remove // the backup, so that it cannot be restored. If no backup could be found, it means that the // configuration has not been modified since the fail-safe was armed, so return with no error. DefaultStorageKeyAllocator key; CHIP_ERROR error = KeyValueStoreMgr().Delete(key.FailSafeNetworkConfig()); return error == CHIP_ERROR_PERSISTED_STORAGE_VALUE_NOT_FOUND ? CHIP_NO_ERROR : error; } CHIP_ERROR GenericThreadDriver::RevertConfiguration() { DefaultStorageKeyAllocator key; uint8_t datasetBytes[Thread::kSizeOperationalDataset]; size_t datasetLength; CHIP_ERROR error = KeyValueStoreMgr().Get(key.FailSafeNetworkConfig(), datasetBytes, sizeof(datasetBytes), &datasetLength); // If no backup could be found, it means that the network configuration has not been modified // since the fail-safe was armed, so return with no error. ReturnErrorCodeIf(error == CHIP_ERROR_PERSISTED_STORAGE_VALUE_NOT_FOUND, CHIP_NO_ERROR); ReturnErrorOnFailure(error); ChipLogError(NetworkProvisioning, "Found Thread configuration backup: reverting configuration"); // Not all KVS implementations support zero-length values, so handle a special value representing an empty dataset. ByteSpan dataset(datasetBytes, datasetLength); if (dataset.data_equal(ByteSpan(kEmptyDataset))) { dataset = {}; } ReturnErrorOnFailure(mStagingNetwork.Init(dataset)); ReturnErrorOnFailure(DeviceLayer::ThreadStackMgrImpl().AttachToThreadNetwork(mStagingNetwork, /* callback */ nullptr)); // TODO: What happens on errors above? Why do we not remove the failsafe? return KeyValueStoreMgr().Delete(key.FailSafeNetworkConfig()); } Status GenericThreadDriver::AddOrUpdateNetwork(ByteSpan operationalDataset, MutableCharSpan & outDebugText, uint8_t & outNetworkIndex) { ByteSpan newExtpanid; Thread::OperationalDataset newDataset; outDebugText.reduce_size(0); outNetworkIndex = 0; VerifyOrReturnError(newDataset.Init(operationalDataset) == CHIP_NO_ERROR && newDataset.IsCommissioned(), Status::kOutOfRange); newDataset.GetExtendedPanIdAsByteSpan(newExtpanid); // We only support one active operational dataset. Add/Update based on either: // Staging network not commissioned yet (active) or we are updating the dataset with same Extended Pan ID. VerifyOrReturnError(!mStagingNetwork.IsCommissioned() || MatchesNetworkId(mStagingNetwork, newExtpanid) == Status::kSuccess, Status::kBoundsExceeded); VerifyOrReturnError(BackupConfiguration() == CHIP_NO_ERROR, Status::kUnknownError); mStagingNetwork = newDataset; return Status::kSuccess; } Status GenericThreadDriver::RemoveNetwork(ByteSpan networkId, MutableCharSpan & outDebugText, uint8_t & outNetworkIndex) { outDebugText.reduce_size(0); outNetworkIndex = 0; NetworkCommissioning::Status status = MatchesNetworkId(mStagingNetwork, networkId); VerifyOrReturnError(status == Status::kSuccess, status); VerifyOrReturnError(BackupConfiguration() == CHIP_NO_ERROR, Status::kUnknownError); mStagingNetwork.Clear(); return Status::kSuccess; } Status GenericThreadDriver::ReorderNetwork(ByteSpan networkId, uint8_t index, MutableCharSpan & outDebugText) { outDebugText.reduce_size(0); NetworkCommissioning::Status status = MatchesNetworkId(mStagingNetwork, networkId); VerifyOrReturnError(status == Status::kSuccess, status); VerifyOrReturnError(index == 0, Status::kOutOfRange); return Status::kSuccess; } void GenericThreadDriver::ConnectNetwork(ByteSpan networkId, ConnectCallback * callback) { NetworkCommissioning::Status status = MatchesNetworkId(mStagingNetwork, networkId); if (status == Status::kSuccess && BackupConfiguration() != CHIP_NO_ERROR) { status = Status::kUnknownError; } if (status == Status::kSuccess && DeviceLayer::ThreadStackMgrImpl().AttachToThreadNetwork(mStagingNetwork, callback) != CHIP_NO_ERROR) { status = Status::kUnknownError; } if (status != Status::kSuccess) { callback->OnResult(status, CharSpan(), 0); } } void GenericThreadDriver::ScanNetworks(ThreadDriver::ScanCallback * callback) { if (DeviceLayer::ThreadStackMgrImpl().StartThreadScan(callback) != CHIP_NO_ERROR) { callback->OnFinished(Status::kUnknownError, CharSpan(), nullptr); } } Status GenericThreadDriver::MatchesNetworkId(const Thread::OperationalDataset & dataset, const ByteSpan & networkId) const { ByteSpan extpanid; if (!dataset.IsCommissioned()) { return Status::kNetworkIDNotFound; } if (dataset.GetExtendedPanIdAsByteSpan(extpanid) != CHIP_NO_ERROR) { return Status::kUnknownError; } return networkId.data_equal(extpanid) ? Status::kSuccess : Status::kNetworkIDNotFound; } CHIP_ERROR GenericThreadDriver::BackupConfiguration() { DefaultStorageKeyAllocator key; uint8_t dummy; // If configuration is already backed up, return with no error if (KeyValueStoreMgr().Get(key.FailSafeNetworkConfig(), &dummy, 0) == CHIP_ERROR_BUFFER_TOO_SMALL) { return CHIP_NO_ERROR; } // Not all KVS implementations support zero-length values, so use a special value in such a case. ByteSpan dataset = mStagingNetwork.IsEmpty() ? ByteSpan(kEmptyDataset) : mStagingNetwork.AsByteSpan(); return KeyValueStoreMgr().Put(key.FailSafeNetworkConfig(), dataset.data(), dataset.size()); } size_t GenericThreadDriver::ThreadNetworkIterator::Count() { return driver->mStagingNetwork.IsCommissioned() ? 1 : 0; } bool GenericThreadDriver::ThreadNetworkIterator::Next(Network & item) { if (exhausted || !driver->mStagingNetwork.IsCommissioned()) { return false; } uint8_t extpanid[kSizeExtendedPanId]; VerifyOrReturnError(driver->mStagingNetwork.GetExtendedPanId(extpanid) == CHIP_NO_ERROR, false); memcpy(item.networkID, extpanid, kSizeExtendedPanId); item.networkIDLen = kSizeExtendedPanId; item.connected = false; exhausted = true; Thread::OperationalDataset currentDataset; uint8_t enabledExtPanId[Thread::kSizeExtendedPanId]; // The Thread network is not actually enabled. VerifyOrReturnError(ConnectivityMgrImpl().IsThreadAttached(), true); VerifyOrReturnError(ThreadStackMgrImpl().GetThreadProvision(currentDataset) == CHIP_NO_ERROR, true); // The Thread network is not enabled, but has a different extended pan id. VerifyOrReturnError(currentDataset.GetExtendedPanId(enabledExtPanId) == CHIP_NO_ERROR, true); VerifyOrReturnError(memcmp(extpanid, enabledExtPanId, kSizeExtendedPanId) == 0, true); // The Thread network is enabled and has the same extended pan id as the one in our record. item.connected = true; return true; } } // namespace NetworkCommissioning } // namespace DeviceLayer } // namespace chip <commit_msg>[OpenThread] Revert configuration on boot with fail-safe armed (#21597)<commit_after>/* * * Copyright (c) 2021 Project CHIP Authors * * 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 <lib/support/CodeUtils.h> #include <lib/support/DefaultStorageKeyAllocator.h> #include <lib/support/SafeInt.h> #include <lib/support/logging/CHIPLogging.h> #include <platform/CHIPDeviceLayer.h> #include <platform/KeyValueStoreManager.h> #include <platform/NetworkCommissioning.h> #include <platform/OpenThread/GenericNetworkCommissioningThreadDriver.h> #include <platform/OpenThread/GenericThreadStackManagerImpl_OpenThread.h> #include <platform/ThreadStackManager.h> #include <limits> using namespace chip; using namespace chip::Thread; using namespace chip::DeviceLayer::PersistedStorage; namespace chip { namespace DeviceLayer { namespace NetworkCommissioning { // NOTE: For GenericThreadDriver, we assume that the network configuration is persisted by // the OpenThread stack after ConnectNetwork command is called, and before that, all the changes // are made to a local copy of the dataset stored in mStagingNetwork. // Also, in order to support the fail-safe mechanism, the configuration is backed up in a temporary // KVS slot upon any changes and restored when the fail-safe timeout is triggered or the device // reboots without completing all the changes. CHIP_ERROR GenericThreadDriver::Init(Internal::BaseDriver::NetworkStatusChangeCallback * statusChangeCallback) { ThreadStackMgrImpl().SetNetworkStatusChangeCallback(statusChangeCallback); ThreadStackMgrImpl().GetThreadProvision(mStagingNetwork); // If the network configuration backup exists, it means that the device has been rebooted with // the fail-safe armed. Since OpenThread persists all operational dataset changes, the backup // must be restored on the boot. If there's no backup, the below function is a no-op. RevertConfiguration(); return CHIP_NO_ERROR; } void GenericThreadDriver::Shutdown() { ThreadStackMgrImpl().SetNetworkStatusChangeCallback(nullptr); } CHIP_ERROR GenericThreadDriver::CommitConfiguration() { // OpenThread persists the network configuration on AttachToThreadNetwork, so simply remove // the backup, so that it cannot be restored. If no backup could be found, it means that the // configuration has not been modified since the fail-safe was armed, so return with no error. DefaultStorageKeyAllocator key; CHIP_ERROR error = KeyValueStoreMgr().Delete(key.FailSafeNetworkConfig()); return error == CHIP_ERROR_PERSISTED_STORAGE_VALUE_NOT_FOUND ? CHIP_NO_ERROR : error; } CHIP_ERROR GenericThreadDriver::RevertConfiguration() { DefaultStorageKeyAllocator key; uint8_t datasetBytes[Thread::kSizeOperationalDataset]; size_t datasetLength; CHIP_ERROR error = KeyValueStoreMgr().Get(key.FailSafeNetworkConfig(), datasetBytes, sizeof(datasetBytes), &datasetLength); // If no backup could be found, it means that the network configuration has not been modified // since the fail-safe was armed, so return with no error. ReturnErrorCodeIf(error == CHIP_ERROR_PERSISTED_STORAGE_VALUE_NOT_FOUND, CHIP_NO_ERROR); ChipLogProgress(NetworkProvisioning, "Reverting Thread operational dataset"); if (error == CHIP_NO_ERROR) { error = mStagingNetwork.Init(ByteSpan(datasetBytes, datasetLength)); } if (error == CHIP_NO_ERROR) { error = DeviceLayer::ThreadStackMgrImpl().AttachToThreadNetwork(mStagingNetwork, /* callback */ nullptr); } // Always remove the backup, regardless if it can be successfully restored. KeyValueStoreMgr().Delete(key.FailSafeNetworkConfig()); return error; } Status GenericThreadDriver::AddOrUpdateNetwork(ByteSpan operationalDataset, MutableCharSpan & outDebugText, uint8_t & outNetworkIndex) { ByteSpan newExtpanid; Thread::OperationalDataset newDataset; outDebugText.reduce_size(0); outNetworkIndex = 0; VerifyOrReturnError(newDataset.Init(operationalDataset) == CHIP_NO_ERROR && newDataset.IsCommissioned(), Status::kOutOfRange); newDataset.GetExtendedPanIdAsByteSpan(newExtpanid); // We only support one active operational dataset. Add/Update based on either: // Staging network not commissioned yet (active) or we are updating the dataset with same Extended Pan ID. VerifyOrReturnError(!mStagingNetwork.IsCommissioned() || MatchesNetworkId(mStagingNetwork, newExtpanid) == Status::kSuccess, Status::kBoundsExceeded); VerifyOrReturnError(BackupConfiguration() == CHIP_NO_ERROR, Status::kUnknownError); mStagingNetwork = newDataset; return Status::kSuccess; } Status GenericThreadDriver::RemoveNetwork(ByteSpan networkId, MutableCharSpan & outDebugText, uint8_t & outNetworkIndex) { outDebugText.reduce_size(0); outNetworkIndex = 0; NetworkCommissioning::Status status = MatchesNetworkId(mStagingNetwork, networkId); VerifyOrReturnError(status == Status::kSuccess, status); VerifyOrReturnError(BackupConfiguration() == CHIP_NO_ERROR, Status::kUnknownError); mStagingNetwork.Clear(); return Status::kSuccess; } Status GenericThreadDriver::ReorderNetwork(ByteSpan networkId, uint8_t index, MutableCharSpan & outDebugText) { outDebugText.reduce_size(0); NetworkCommissioning::Status status = MatchesNetworkId(mStagingNetwork, networkId); VerifyOrReturnError(status == Status::kSuccess, status); VerifyOrReturnError(index == 0, Status::kOutOfRange); return Status::kSuccess; } void GenericThreadDriver::ConnectNetwork(ByteSpan networkId, ConnectCallback * callback) { NetworkCommissioning::Status status = MatchesNetworkId(mStagingNetwork, networkId); if (status == Status::kSuccess && BackupConfiguration() != CHIP_NO_ERROR) { status = Status::kUnknownError; } if (status == Status::kSuccess && DeviceLayer::ThreadStackMgrImpl().AttachToThreadNetwork(mStagingNetwork, callback) != CHIP_NO_ERROR) { status = Status::kUnknownError; } if (status != Status::kSuccess) { callback->OnResult(status, CharSpan(), 0); } } void GenericThreadDriver::ScanNetworks(ThreadDriver::ScanCallback * callback) { if (DeviceLayer::ThreadStackMgrImpl().StartThreadScan(callback) != CHIP_NO_ERROR) { callback->OnFinished(Status::kUnknownError, CharSpan(), nullptr); } } Status GenericThreadDriver::MatchesNetworkId(const Thread::OperationalDataset & dataset, const ByteSpan & networkId) const { ByteSpan extpanid; if (!dataset.IsCommissioned()) { return Status::kNetworkIDNotFound; } if (dataset.GetExtendedPanIdAsByteSpan(extpanid) != CHIP_NO_ERROR) { return Status::kUnknownError; } return networkId.data_equal(extpanid) ? Status::kSuccess : Status::kNetworkIDNotFound; } CHIP_ERROR GenericThreadDriver::BackupConfiguration() { DefaultStorageKeyAllocator key; // If configuration is already backed up, return with no error CHIP_ERROR err = KeyValueStoreMgr().Get(key.FailSafeNetworkConfig(), nullptr, 0); if (err == CHIP_NO_ERROR || err == CHIP_ERROR_BUFFER_TOO_SMALL) { return CHIP_NO_ERROR; } ByteSpan dataset = mStagingNetwork.AsByteSpan(); return KeyValueStoreMgr().Put(key.FailSafeNetworkConfig(), dataset.data(), dataset.size()); } size_t GenericThreadDriver::ThreadNetworkIterator::Count() { return driver->mStagingNetwork.IsCommissioned() ? 1 : 0; } bool GenericThreadDriver::ThreadNetworkIterator::Next(Network & item) { if (exhausted || !driver->mStagingNetwork.IsCommissioned()) { return false; } uint8_t extpanid[kSizeExtendedPanId]; VerifyOrReturnError(driver->mStagingNetwork.GetExtendedPanId(extpanid) == CHIP_NO_ERROR, false); memcpy(item.networkID, extpanid, kSizeExtendedPanId); item.networkIDLen = kSizeExtendedPanId; item.connected = false; exhausted = true; Thread::OperationalDataset currentDataset; uint8_t enabledExtPanId[Thread::kSizeExtendedPanId]; // The Thread network is not actually enabled. VerifyOrReturnError(ConnectivityMgrImpl().IsThreadAttached(), true); VerifyOrReturnError(ThreadStackMgrImpl().GetThreadProvision(currentDataset) == CHIP_NO_ERROR, true); // The Thread network is not enabled, but has a different extended pan id. VerifyOrReturnError(currentDataset.GetExtendedPanId(enabledExtPanId) == CHIP_NO_ERROR, true); VerifyOrReturnError(memcmp(extpanid, enabledExtPanId, kSizeExtendedPanId) == 0, true); // The Thread network is enabled and has the same extended pan id as the one in our record. item.connected = true; return true; } } // namespace NetworkCommissioning } // namespace DeviceLayer } // namespace chip <|endoftext|>
<commit_before>#include <Common.h> #include <Network/CommonNetwork.h> #include <Network/GamePacketNew.h> #include <Logging/Logger.h> #include <Exd/ExdDataGenerated.h> #include <Network/PacketContainer.h> #include <Network/CommonActorControl.h> #include <Network/PacketDef/Zone/ClientZoneDef.h> #include <Util/Util.h> #include "Zone/Zone.h" #include "Zone/ZonePosition.h" #include "Zone/HousingZone.h" #include "Zone/HousingMgr.h" #include "Zone/Land.h" #include "Network/GameConnection.h" #include "Network/PacketWrappers/ExaminePacket.h" #include "Network/PacketWrappers/InitUIPacket.h" #include "Network/PacketWrappers/PingPacket.h" #include "Network/PacketWrappers/MoveActorPacket.h" #include "Network/PacketWrappers/ChatPacket.h" #include "Network/PacketWrappers/ServerNoticePacket.h" #include "Network/PacketWrappers/ActorControlPacket142.h" #include "DebugCommand/DebugCommandHandler.h" #include "Event/EventHelper.h" #include "Action/Action.h" #include "Action/ActionTeleport.h" #include "Session.h" #include "ServerZone.h" #include "Forwards.h" #include "Framework.h" #include <Network/PacketDef/Lobby/ServerLobbyDef.h> extern Core::Framework g_fw; using namespace Core::Common; using namespace Core::Network::Packets; using namespace Core::Network::Packets::Server; using namespace Core::Network::ActorControl; void examineHandler( Core::Entity::Player& player, uint32_t targetId ) { using namespace Core; auto pSession = g_fw.get< Core::ServerZone >()->getSession( targetId ); if( pSession ) { auto pTarget = pSession->getPlayer(); if( pTarget ) { if( pTarget->isActingAsGm() || pTarget->getZoneId() != player.getZoneId() ) { player.queuePacket( makeActorControl142( player.getId(), ActorControlType::ExamineError ) ); } else { player.queuePacket( std::make_shared< ExaminePacket >( player, pTarget ) ); } } } } void Core::Network::GameConnection::clientTriggerHandler( const Packets::FFXIVARR_PACKET_RAW& inPacket, Entity::Player& player ) { auto pLog = g_fw.get< Logger >(); const auto packet = ZoneChannelPacket< Client::FFXIVIpcClientTrigger >( inPacket ); const auto commandId = packet.data().commandId; const auto param1 = *reinterpret_cast< const uint64_t* >( &packet.data().param11 ); const auto param11 = packet.data().param11; const auto param12 = packet.data().param12; const auto param2 = packet.data().param2; const auto param3 = packet.data().param3; pLog->debug( "[" + std::to_string( m_pSession->getId() ) + "] Incoming action: " + Util::intToHexString( static_cast< uint32_t >( commandId & 0xFFFF ), 4 ) + "\nparam1: " + Util::intToHexString( static_cast< uint64_t >( param1 & 0xFFFFFFFFFFFFFFF ), 16 ) + "\nparam2: " + Util::intToHexString( static_cast< uint32_t >( param2 & 0xFFFFFFFF ), 8 ) + "\nparam3: " + Util::intToHexString( static_cast< uint64_t >( param3 & 0xFFFFFFFFFFFFFFF ), 16 ) ); //g_log.Log(LoggingSeverity::debug, "[" + std::to_string(m_pSession->getId()) + "] " + pInPacket->toString()); switch( commandId ) { case ClientTriggerType::ToggleSheathe: // Toggle sheathe { if( param11 == 1 ) player.setStance( Common::Stance::Active ); else { player.setStance( Common::Stance::Passive ); player.setAutoattack( false ); } player.sendToInRangeSet( makeActorControl142( player.getId(), 0, param11, 1 ) ); break; } case ClientTriggerType::ToggleAutoAttack: // Toggle auto-attack { if( param11 == 1 ) { player.setAutoattack( true ); player.setStance( Common::Stance::Active ); } else player.setAutoattack( false ); player.sendToInRangeSet( makeActorControl142( player.getId(), 1, param11, 1 ) ); break; } case ClientTriggerType::ChangeTarget: // Change target { uint64_t targetId = param1; player.changeTarget( targetId ); break; } case ClientTriggerType::DismountReq: { player.dismount(); break; } case ClientTriggerType::RemoveStatusEffect: // Remove status (clicking it off) { // todo: check if status can be removed by client from exd player.removeSingleStatusEffectById( static_cast< uint32_t >( param1 ) ); break; } case ClientTriggerType::CastCancel: // Cancel cast { if( player.getCurrentAction() ) player.getCurrentAction()->setInterrupted(); break; } case ClientTriggerType::Examine: { uint32_t targetId = param11; examineHandler( player, targetId ); break; } case ClientTriggerType::MarkPlayer: // Mark player { break; } case ClientTriggerType::SetTitleReq: // Set player title { player.setTitle( static_cast< uint16_t >( param1 ) ); break; } case ClientTriggerType::TitleList: // Get title list { player.sendTitleList(); break; } case ClientTriggerType::UpdatedSeenHowTos: // Update howtos seen { uint32_t howToId = param11; player.updateHowtosSeen( howToId ); break; } case ClientTriggerType::CharaNameReq: { uint64_t targetContentId = param1; // todo: look up player by content id /* auto packet = makeZonePacket< FFXIVIpcCharaNameReq >( player.getId() ); packet->data().contentId = targetContentId; // lookup the name strcpy( packet->data().name, name ); player.queuePacket( packet ); */ break; } case ClientTriggerType::EmoteReq: // emote { uint64_t targetId = player.getTargetId(); uint32_t emoteId = param11; bool isSilent = param2 == 1; auto pExdData = g_fw.get< Data::ExdDataGenerated >(); auto emoteData = pExdData->get< Data::Emote >( emoteId ); if( !emoteData ) return; player.emote( emoteId, targetId, isSilent ); bool isPersistent = emoteData->emoteMode != 0; if( isPersistent ) { player.setStance( Common::Stance::Passive ); player.setAutoattack( false ); player.setPersistentEmote( emoteData->emoteMode ); player.setStatus( Common::ActorStatus::EmoteMode ); player.sendToInRangeSet( makeActorControl142( player.getId(), ActorControlType::SetStatus, static_cast< uint8_t >( Common::ActorStatus::EmoteMode ), emoteData->hasCancelEmote ? 1 : 0 ), true ); } if( emoteData->drawsWeapon ) { player.setStance( Common::Stance::Active ); } break; } case ClientTriggerType::EmoteCancel: // emote { player.emoteInterrupt(); break; } case ClientTriggerType::PersistentEmoteCancel: // cancel persistent emote { player.setPersistentEmote( 0 ); player.emoteInterrupt(); player.setStatus( Common::ActorStatus::Idle ); auto pSetStatusPacket = makeActorControl142( player.getId(), SetStatus, static_cast< uint8_t >( Common::ActorStatus::Idle ) ); player.sendToInRangeSet( pSetStatusPacket ); break; } case ClientTriggerType::PoseChange: // change pose case ClientTriggerType::PoseReapply: // reapply pose { player.setPose( param12 ); auto pSetStatusPacket = makeActorControl142( player.getId(), SetPose, param11, param12 ); player.sendToInRangeSet( pSetStatusPacket, true ); break; } case ClientTriggerType::PoseCancel: // cancel pose { player.setPose( param12 ); auto pSetStatusPacket = makeActorControl142( player.getId(), SetPose, param11, param12 ); player.sendToInRangeSet( pSetStatusPacket, true ); break; } case ClientTriggerType::Return: // return dead / accept raise { switch( static_cast < ResurrectType >( param1 ) ) { case ResurrectType::RaiseSpell: // todo: handle raise case (set position to raiser, apply weakness status, set hp/mp/tp as well as packet) player.returnToHomepoint(); break; case ResurrectType::Return: player.returnToHomepoint(); break; default: break; } } case ClientTriggerType::FinishZoning: // Finish zoning { player.finishZoning(); break; } case ClientTriggerType::Teleport: // Teleport { player.teleportQuery( param11 ); break; } case ClientTriggerType::DyeItem: // Dye item { break; } case ClientTriggerType::DirectorInitFinish: // Director init finish { player.getCurrentZone()->onInitDirector( player ); break; } case ClientTriggerType::DirectorSync: // Director init finish { player.getCurrentZone()->onDirectorSync( player ); break; } case ClientTriggerType::EnterTerritoryEventFinished:// this may still be something else. I think i have seen it elsewhere { player.setOnEnterEventDone( true ); break; } case ClientTriggerType::RequestInstanceLeave: { // todo: apply cf penalty if applicable, make sure player isnt in combat player.exitInstance(); break; } case ClientTriggerType::AbandonQuest: { player.removeQuest( static_cast< uint16_t >( param1 ) ); break; } case ClientTriggerType::RequestHousingSign: { auto plotPricePacket = makeZonePacket< Server::FFXIVIpcLandPriceUpdate >( player.getId() ); uint8_t ward = ( param12 & 0xFF00 ) >> 8; uint8_t plot = ( param12 & 0xFF ); pLog->debug( " Ward: " + std::to_string( ward ) + " Plot: " + std::to_string( plot ) ); player.setActiveLand( plot, ward ); auto zone = player.getCurrentZone(); auto hZone = std::dynamic_pointer_cast< HousingZone >( zone ); if( !hZone ) return; auto land = hZone->getLand( plot ); plotPricePacket->data().price = land->getCurrentPrice(); plotPricePacket->data().timeLeft = land->getDevaluationTime(); player.queuePacket( plotPricePacket ); break; } case ClientTriggerType::RequestHousingInfoSign: { auto LandInfoSignPacket = makeZonePacket< Server::FFXIVIpcLandInfoSign >( player.getId() ); uint8_t ward = ( param12 & 0xFF00 ) >> 8; uint8_t plot = ( param12 & 0xFF ); pLog->debug( " Ward: " + std::to_string( ward ) + " Plot: " + std::to_string( plot ) ); player.setActiveLand( plot, ward ); auto zone = player.getCurrentZone(); auto hZone = std::dynamic_pointer_cast< HousingZone >( zone ); auto land = hZone->getLand( plot ); if( !land ) { auto pHousingMgr = g_fw.get< HousingMgr >(); land = pHousingMgr->getLandByOwnerId( player.getId() ); } memcpy( &LandInfoSignPacket->data().landMsg, "Hello World", 11 ); //memcpy( &LandInfoSignPacket->data().landName, &land->getLandName(), 20 ); memcpy( &LandInfoSignPacket->data().landName, "Hello World", 11 ); LandInfoSignPacket->data().houseSize = land->getHouseSize(); LandInfoSignPacket->data().houseState = land->getState(); LandInfoSignPacket->data().landId = land->getLandId(); LandInfoSignPacket->data().ownerId = land->getPlayerOwner(); memcpy( &LandInfoSignPacket->data().ownerName, "Hello World", 11 ); LandInfoSignPacket->data().wardNum = land->getWardNum(); LandInfoSignPacket->data().worldId = 67; LandInfoSignPacket->data().zoneId = land->getZoneId(); player.queuePacket( LandInfoSignPacket ); break; } case ClientTriggerType::RequestHousingRename: { auto landRenamePacket = makeZonePacket< Server::FFXIVIpcRenameLand >( player.getId() ); uint8_t ward = ( param12 & 0xFF00 ) >> 8; uint8_t plot = ( param12 & 0xFF ); auto zone = player.getCurrentZone(); auto hZone = std::dynamic_pointer_cast< HousingZone >( zone ); auto land = hZone->getLand( plot ); if( !land ) { auto pHousingMgr = g_fw.get< HousingMgr >(); land = pHousingMgr->getLandByOwnerId( player.getId() ); } landRenamePacket->data().landId = land->getLandId(); landRenamePacket->data().wardNum = land->getWardNum(); landRenamePacket->data().worldId = 67; landRenamePacket->data().zoneId = land->getZoneId(); memcpy( &landRenamePacket->data().landName, &land->getLandName(), 20 ); player.queuePacket( landRenamePacket ); break; } case ClientTriggerType::RequestHousingItemUI: { uint8_t ward = ( param12 & 0xFF00 ) >> 8; uint8_t plot = ( param12 & 0xFF ); auto pShowHousingItemUIPacket = makeActorControl142( player.getId(), ShowHousingItemUI, 0, plot ); player.queuePacket( pShowHousingItemUIPacket ); //TODO: show item housing container break; } default: { pLog->debug( "[" + std::to_string( m_pSession->getId() ) + "] Unhandled action: " + Util::intToHexString( static_cast< uint32_t >( commandId & 0xFFFF ), 4 ) ); break; } } } <commit_msg>fixed errors<commit_after>#include <Common.h> #include <Network/CommonNetwork.h> #include <Network/GamePacketNew.h> #include <Logging/Logger.h> #include <Exd/ExdDataGenerated.h> #include <Network/PacketContainer.h> #include <Network/CommonActorControl.h> #include <Network/PacketDef/Zone/ClientZoneDef.h> #include <Util/Util.h> #include "Zone/Zone.h" #include "Zone/ZonePosition.h" #include "Zone/HousingZone.h" #include "Zone/HousingMgr.h" #include "Zone/Land.h" #include "Network/GameConnection.h" #include "Network/PacketWrappers/ExaminePacket.h" #include "Network/PacketWrappers/InitUIPacket.h" #include "Network/PacketWrappers/PingPacket.h" #include "Network/PacketWrappers/MoveActorPacket.h" #include "Network/PacketWrappers/ChatPacket.h" #include "Network/PacketWrappers/ServerNoticePacket.h" #include "Network/PacketWrappers/ActorControlPacket142.h" #include "DebugCommand/DebugCommandHandler.h" #include "Event/EventHelper.h" #include "Action/Action.h" #include "Action/ActionTeleport.h" #include "Session.h" #include "ServerZone.h" #include "Forwards.h" #include "Framework.h" #include <Network/PacketDef/Lobby/ServerLobbyDef.h> extern Core::Framework g_fw; using namespace Core::Common; using namespace Core::Network::Packets; using namespace Core::Network::Packets::Server; using namespace Core::Network::ActorControl; void examineHandler( Core::Entity::Player& player, uint32_t targetId ) { using namespace Core; auto pSession = g_fw.get< Core::ServerZone >()->getSession( targetId ); if( pSession ) { auto pTarget = pSession->getPlayer(); if( pTarget ) { if( pTarget->isActingAsGm() || pTarget->getZoneId() != player.getZoneId() ) { player.queuePacket( makeActorControl142( player.getId(), ActorControlType::ExamineError ) ); } else { player.queuePacket( std::make_shared< ExaminePacket >( player, pTarget ) ); } } } } void Core::Network::GameConnection::clientTriggerHandler( const Packets::FFXIVARR_PACKET_RAW& inPacket, Entity::Player& player ) { auto pLog = g_fw.get< Logger >(); const auto packet = ZoneChannelPacket< Client::FFXIVIpcClientTrigger >( inPacket ); const auto commandId = packet.data().commandId; const auto param1 = *reinterpret_cast< const uint64_t* >( &packet.data().param11 ); const auto param11 = packet.data().param11; const auto param12 = packet.data().param12; const auto param2 = packet.data().param2; const auto param3 = packet.data().param3; pLog->debug( "[" + std::to_string( m_pSession->getId() ) + "] Incoming action: " + Util::intToHexString( static_cast< uint32_t >( commandId & 0xFFFF ), 4 ) + "\nparam1: " + Util::intToHexString( static_cast< uint64_t >( param1 & 0xFFFFFFFFFFFFFFF ), 16 ) + "\nparam2: " + Util::intToHexString( static_cast< uint32_t >( param2 & 0xFFFFFFFF ), 8 ) + "\nparam3: " + Util::intToHexString( static_cast< uint64_t >( param3 & 0xFFFFFFFFFFFFFFF ), 16 ) ); //g_log.Log(LoggingSeverity::debug, "[" + std::to_string(m_pSession->getId()) + "] " + pInPacket->toString()); switch( commandId ) { case ClientTriggerType::ToggleSheathe: // Toggle sheathe { if( param11 == 1 ) player.setStance( Common::Stance::Active ); else { player.setStance( Common::Stance::Passive ); player.setAutoattack( false ); } player.sendToInRangeSet( makeActorControl142( player.getId(), 0, param11, 1 ) ); break; } case ClientTriggerType::ToggleAutoAttack: // Toggle auto-attack { if( param11 == 1 ) { player.setAutoattack( true ); player.setStance( Common::Stance::Active ); } else player.setAutoattack( false ); player.sendToInRangeSet( makeActorControl142( player.getId(), 1, param11, 1 ) ); break; } case ClientTriggerType::ChangeTarget: // Change target { uint64_t targetId = param1; player.changeTarget( targetId ); break; } case ClientTriggerType::DismountReq: { player.dismount(); break; } case ClientTriggerType::RemoveStatusEffect: // Remove status (clicking it off) { // todo: check if status can be removed by client from exd player.removeSingleStatusEffectById( static_cast< uint32_t >( param1 ) ); break; } case ClientTriggerType::CastCancel: // Cancel cast { if( player.getCurrentAction() ) player.getCurrentAction()->setInterrupted(); break; } case ClientTriggerType::Examine: { uint32_t targetId = param11; examineHandler( player, targetId ); break; } case ClientTriggerType::MarkPlayer: // Mark player { break; } case ClientTriggerType::SetTitleReq: // Set player title { player.setTitle( static_cast< uint16_t >( param1 ) ); break; } case ClientTriggerType::TitleList: // Get title list { player.sendTitleList(); break; } case ClientTriggerType::UpdatedSeenHowTos: // Update howtos seen { uint32_t howToId = param11; player.updateHowtosSeen( howToId ); break; } case ClientTriggerType::CharaNameReq: { uint64_t targetContentId = param1; // todo: look up player by content id /* auto packet = makeZonePacket< FFXIVIpcCharaNameReq >( player.getId() ); packet->data().contentId = targetContentId; // lookup the name strcpy( packet->data().name, name ); player.queuePacket( packet ); */ break; } case ClientTriggerType::EmoteReq: // emote { uint64_t targetId = player.getTargetId(); uint32_t emoteId = param11; bool isSilent = param2 == 1; auto pExdData = g_fw.get< Data::ExdDataGenerated >(); auto emoteData = pExdData->get< Data::Emote >( emoteId ); if( !emoteData ) return; player.emote( emoteId, targetId, isSilent ); bool isPersistent = emoteData->emoteMode != 0; if( isPersistent ) { player.setStance( Common::Stance::Passive ); player.setAutoattack( false ); player.setPersistentEmote( emoteData->emoteMode ); player.setStatus( Common::ActorStatus::EmoteMode ); player.sendToInRangeSet( makeActorControl142( player.getId(), ActorControlType::SetStatus, static_cast< uint8_t >( Common::ActorStatus::EmoteMode ), emoteData->hasCancelEmote ? 1 : 0 ), true ); } if( emoteData->drawsWeapon ) { player.setStance( Common::Stance::Active ); } break; } case ClientTriggerType::EmoteCancel: // emote { player.emoteInterrupt(); break; } case ClientTriggerType::PersistentEmoteCancel: // cancel persistent emote { player.setPersistentEmote( 0 ); player.emoteInterrupt(); player.setStatus( Common::ActorStatus::Idle ); auto pSetStatusPacket = makeActorControl142( player.getId(), SetStatus, static_cast< uint8_t >( Common::ActorStatus::Idle ) ); player.sendToInRangeSet( pSetStatusPacket ); break; } case ClientTriggerType::PoseChange: // change pose case ClientTriggerType::PoseReapply: // reapply pose { player.setPose( param12 ); auto pSetStatusPacket = makeActorControl142( player.getId(), SetPose, param11, param12 ); player.sendToInRangeSet( pSetStatusPacket, true ); break; } case ClientTriggerType::PoseCancel: // cancel pose { player.setPose( param12 ); auto pSetStatusPacket = makeActorControl142( player.getId(), SetPose, param11, param12 ); player.sendToInRangeSet( pSetStatusPacket, true ); break; } case ClientTriggerType::Return: // return dead / accept raise { switch( static_cast < ResurrectType >( param1 ) ) { case ResurrectType::RaiseSpell: // todo: handle raise case (set position to raiser, apply weakness status, set hp/mp/tp as well as packet) player.returnToHomepoint(); break; case ResurrectType::Return: player.returnToHomepoint(); break; default: break; } } case ClientTriggerType::FinishZoning: // Finish zoning { player.finishZoning(); break; } case ClientTriggerType::Teleport: // Teleport { player.teleportQuery( param11 ); break; } case ClientTriggerType::DyeItem: // Dye item { break; } case ClientTriggerType::DirectorInitFinish: // Director init finish { player.getCurrentZone()->onInitDirector( player ); break; } case ClientTriggerType::DirectorSync: // Director init finish { player.getCurrentZone()->onDirectorSync( player ); break; } case ClientTriggerType::EnterTerritoryEventFinished:// this may still be something else. I think i have seen it elsewhere { player.setOnEnterEventDone( true ); break; } case ClientTriggerType::RequestInstanceLeave: { // todo: apply cf penalty if applicable, make sure player isnt in combat player.exitInstance(); break; } case ClientTriggerType::AbandonQuest: { player.removeQuest( static_cast< uint16_t >( param1 ) ); break; } case ClientTriggerType::RequestHousingSign: { auto plotPricePacket = makeZonePacket< Server::FFXIVIpcLandPriceUpdate >( player.getId() ); uint8_t ward = ( param12 & 0xFF00 ) >> 8; uint8_t plot = ( param12 & 0xFF ); pLog->debug( " Ward: " + std::to_string( ward ) + " Plot: " + std::to_string( plot ) ); player.setActiveLand( plot, ward ); auto zone = player.getCurrentZone(); auto hZone = std::dynamic_pointer_cast< HousingZone >( zone ); if( !hZone ) return; auto land = hZone->getLand( plot ); plotPricePacket->data().price = land->getCurrentPrice(); plotPricePacket->data().timeLeft = land->getDevaluationTime(); player.queuePacket( plotPricePacket ); break; } case ClientTriggerType::RequestHousingInfoSign: { auto LandInfoSignPacket = makeZonePacket< Server::FFXIVIpcLandInfoSign >( player.getId() ); uint8_t ward = ( param12 & 0xFF00 ) >> 8; uint8_t plot = ( param12 & 0xFF ); pLog->debug( " Ward: " + std::to_string( ward ) + " Plot: " + std::to_string( plot ) ); player.setActiveLand( plot, ward ); auto zone = player.getCurrentZone(); auto hZone = std::dynamic_pointer_cast< HousingZone >( zone ); auto land = hZone->getLand( plot ); if( !land ) { auto pHousingMgr = g_fw.get< HousingMgr >(); land = pHousingMgr->getLandByOwnerId( player.getId() ); } memcpy( &LandInfoSignPacket->data().landMsg, "Hello World", 11 ); memcpy( &LandInfoSignPacket->data().landName, land->getLandName().c_str(), 20 ); LandInfoSignPacket->data().houseSize = land->getHouseSize(); LandInfoSignPacket->data().houseState = land->getState(); LandInfoSignPacket->data().landId = land->getLandId(); LandInfoSignPacket->data().ownerId = land->getPlayerOwner(); memcpy( &LandInfoSignPacket->data().ownerName, "Hello World", 11 ); LandInfoSignPacket->data().wardNum = land->getWardNum(); LandInfoSignPacket->data().worldId = 67; LandInfoSignPacket->data().zoneId = land->getZoneId(); player.queuePacket( LandInfoSignPacket ); break; } case ClientTriggerType::RequestHousingRename: { auto landRenamePacket = makeZonePacket< Server::FFXIVIpcRenameLand >( player.getId() ); uint8_t ward = ( param12 & 0xFF00 ) >> 8; uint8_t plot = ( param12 & 0xFF ); auto zone = player.getCurrentZone(); auto hZone = std::dynamic_pointer_cast< HousingZone >( zone ); auto land = hZone->getLand( plot ); if( !land ) { auto pHousingMgr = g_fw.get< HousingMgr >(); land = pHousingMgr->getLandByOwnerId( player.getId() ); } landRenamePacket->data().landId = land->getLandId(); landRenamePacket->data().wardNum = land->getWardNum(); landRenamePacket->data().worldId = 67; landRenamePacket->data().zoneId = land->getZoneId(); memcpy( &landRenamePacket->data().landName, land->getLandName().c_str(), 20 ); player.queuePacket( landRenamePacket ); break; } case ClientTriggerType::RequestHousingItemUI: { uint8_t ward = ( param12 & 0xFF00 ) >> 8; uint8_t plot = ( param12 & 0xFF ); auto pShowHousingItemUIPacket = makeActorControl142( player.getId(), ShowHousingItemUI, 0, plot ); player.queuePacket( pShowHousingItemUIPacket ); //TODO: show item housing container break; } default: { pLog->debug( "[" + std::to_string( m_pSession->getId() ) + "] Unhandled action: " + Util::intToHexString( static_cast< uint32_t >( commandId & 0xFFFF ), 4 ) ); break; } } } <|endoftext|>
<commit_before>//=======- MipsFrameLowering.cpp - Mips Frame Information ------*- C++ -*-====// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file contains the Mips implementation of TargetFrameLowering class. // //===----------------------------------------------------------------------===// #include "MipsFrameLowering.h" #include "MipsInstrInfo.h" #include "MipsMachineFunction.h" #include "llvm/Function.h" #include "llvm/CodeGen/MachineFrameInfo.h" #include "llvm/CodeGen/MachineFunction.h" #include "llvm/CodeGen/MachineInstrBuilder.h" #include "llvm/CodeGen/MachineModuleInfo.h" #include "llvm/CodeGen/MachineRegisterInfo.h" #include "llvm/Target/TargetData.h" #include "llvm/Target/TargetOptions.h" #include "llvm/Support/CommandLine.h" using namespace llvm; //===----------------------------------------------------------------------===// // // Stack Frame Processing methods // +----------------------------+ // // The stack is allocated decrementing the stack pointer on // the first instruction of a function prologue. Once decremented, // all stack references are done thought a positive offset // from the stack/frame pointer, so the stack is considering // to grow up! Otherwise terrible hacks would have to be made // to get this stack ABI compliant :) // // The stack frame required by the ABI (after call): // Offset // // 0 ---------- // 4 Args to pass // . saved $GP (used in PIC) // . Alloca allocations // . Local Area // . CPU "Callee Saved" Registers // . saved FP // . saved RA // . FPU "Callee Saved" Registers // StackSize ----------- // // Offset - offset from sp after stack allocation on function prologue // // The sp is the stack pointer subtracted/added from the stack size // at the Prologue/Epilogue // // References to the previous stack (to obtain arguments) are done // with offsets that exceeds the stack size: (stacksize+(4*(num_arg-1)) // // Examples: // - reference to the actual stack frame // for any local area var there is smt like : FI >= 0, StackOffset: 4 // sw REGX, 4(SP) // // - reference to previous stack frame // suppose there's a load to the 5th arguments : FI < 0, StackOffset: 16. // The emitted instruction will be something like: // lw REGX, 16+StackSize(SP) // // Since the total stack size is unknown on LowerFormalArguments, all // stack references (ObjectOffset) created to reference the function // arguments, are negative numbers. This way, on eliminateFrameIndex it's // possible to detect those references and the offsets are adjusted to // their real location. // //===----------------------------------------------------------------------===// // hasFP - Return true if the specified function should have a dedicated frame // pointer register. This is true if the function has variable sized allocas or // if frame pointer elimination is disabled. bool MipsFrameLowering::hasFP(const MachineFunction &MF) const { const MachineFrameInfo *MFI = MF.getFrameInfo(); return DisableFramePointerElim(MF) || MFI->hasVarSizedObjects(); } void MipsFrameLowering::adjustMipsStackFrame(MachineFunction &MF) const { MachineFrameInfo *MFI = MF.getFrameInfo(); MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>(); const std::vector<CalleeSavedInfo> &CSI = MFI->getCalleeSavedInfo(); unsigned StackAlign = getStackAlignment(); unsigned RegSize = STI.isGP32bit() ? 4 : 8; bool HasGP = MipsFI->needGPSaveRestore(); // Min and Max CSI FrameIndex. int MinCSFI = -1, MaxCSFI = -1; // See the description at MipsMachineFunction.h int TopCPUSavedRegOff = -1, TopFPUSavedRegOff = -1; // Replace the dummy '0' SPOffset by the negative offsets, as explained on // LowerFormalArguments. Leaving '0' for while is necessary to avoid the // approach done by calculateFrameObjectOffsets to the stack frame. MipsFI->adjustLoadArgsFI(MFI); MipsFI->adjustStoreVarArgsFI(MFI); // It happens that the default stack frame allocation order does not directly // map to the convention used for mips. So we must fix it. We move the callee // save register slots after the local variables area, as described in the // stack frame above. unsigned CalleeSavedAreaSize = 0; if (!CSI.empty()) { MinCSFI = CSI[0].getFrameIdx(); MaxCSFI = CSI[CSI.size()-1].getFrameIdx(); } for (unsigned i = 0, e = CSI.size(); i != e; ++i) CalleeSavedAreaSize += MFI->getObjectAlignment(CSI[i].getFrameIdx()); unsigned StackOffset = HasGP ? (MipsFI->getGPStackOffset()+RegSize) : (STI.isABI_O32() ? 16 : 0); // Adjust local variables. They should come on the stack right // after the arguments. int LastOffsetFI = -1; for (int i = 0, e = MFI->getObjectIndexEnd(); i != e; ++i) { if (i >= MinCSFI && i <= MaxCSFI) continue; if (MFI->isDeadObjectIndex(i)) continue; unsigned Offset = StackOffset + MFI->getObjectOffset(i) - CalleeSavedAreaSize; if (LastOffsetFI == -1) LastOffsetFI = i; if (Offset > MFI->getObjectOffset(LastOffsetFI)) LastOffsetFI = i; MFI->setObjectOffset(i, Offset); } // Adjust CPU Callee Saved Registers Area. Registers RA and FP must // be saved in this CPU Area. This whole area must be aligned to the // default Stack Alignment requirements. if (LastOffsetFI >= 0) StackOffset = MFI->getObjectOffset(LastOffsetFI)+ MFI->getObjectSize(LastOffsetFI); StackOffset = ((StackOffset+StackAlign-1)/StackAlign*StackAlign); for (unsigned i = 0, e = CSI.size(); i != e ; ++i) { unsigned Reg = CSI[i].getReg(); if (!Mips::CPURegsRegisterClass->contains(Reg)) break; MFI->setObjectOffset(CSI[i].getFrameIdx(), StackOffset); TopCPUSavedRegOff = StackOffset; StackOffset += MFI->getObjectAlignment(CSI[i].getFrameIdx()); } StackOffset = ((StackOffset+StackAlign-1)/StackAlign*StackAlign); // Adjust FPU Callee Saved Registers Area. This Area must be // aligned to the default Stack Alignment requirements. for (unsigned i = 0, e = CSI.size(); i != e; ++i) { unsigned Reg = CSI[i].getReg(); if (Mips::CPURegsRegisterClass->contains(Reg)) continue; MFI->setObjectOffset(CSI[i].getFrameIdx(), StackOffset); TopFPUSavedRegOff = StackOffset; StackOffset += MFI->getObjectAlignment(CSI[i].getFrameIdx()); } StackOffset = ((StackOffset+StackAlign-1)/StackAlign*StackAlign); // Update frame info MFI->setStackSize(StackOffset); // Recalculate the final tops offset. The final values must be '0' // if there isn't a callee saved register for CPU or FPU, otherwise // a negative offset is needed. if (TopCPUSavedRegOff >= 0) MipsFI->setCPUTopSavedRegOff(TopCPUSavedRegOff-StackOffset); if (TopFPUSavedRegOff >= 0) MipsFI->setFPUTopSavedRegOff(TopFPUSavedRegOff-StackOffset); } // expand pair of register and immediate if the immediate doesn't fit in the // 16-bit offset field. // e.g. // if OrigImm = 0x10000, OrigReg = $sp: // generate the following sequence of instrs: // lui $at, hi(0x10000) // addu $at, $sp, $at // // (NewReg, NewImm) = ($at, lo(Ox10000)) // return true static bool expandRegLargeImmPair(unsigned OrigReg, int OrigImm, unsigned& NewReg, int& NewImm, MachineBasicBlock& MBB, MachineBasicBlock::iterator I) { // OrigImm fits in the 16-bit field if (OrigImm < 0x8000 && OrigImm >= -0x8000) { NewReg = OrigReg; NewImm = OrigImm; return false; } MachineFunction* MF = MBB.getParent(); const TargetInstrInfo *TII = MF->getTarget().getInstrInfo(); DebugLoc DL = I->getDebugLoc(); int ImmLo = OrigImm & 0xffff; int ImmHi = (((unsigned)OrigImm & 0xffff0000) >> 16) + ((OrigImm & 0x8000) != 0); // FIXME: change this when mips goes MC". BuildMI(MBB, I, DL, TII->get(Mips::NOAT)); BuildMI(MBB, I, DL, TII->get(Mips::LUi), Mips::AT).addImm(ImmHi); BuildMI(MBB, I, DL, TII->get(Mips::ADDu), Mips::AT).addReg(OrigReg) .addReg(Mips::AT); NewReg = Mips::AT; NewImm = ImmLo; return true; } void MipsFrameLowering::emitPrologue(MachineFunction &MF) const { MachineBasicBlock &MBB = MF.front(); MachineFrameInfo *MFI = MF.getFrameInfo(); MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>(); const MipsRegisterInfo *RegInfo = static_cast<const MipsRegisterInfo*>(MF.getTarget().getRegisterInfo()); const MipsInstrInfo &TII = *static_cast<const MipsInstrInfo*>(MF.getTarget().getInstrInfo()); MachineBasicBlock::iterator MBBI = MBB.begin(); DebugLoc dl = MBBI != MBB.end() ? MBBI->getDebugLoc() : DebugLoc(); bool isPIC = (MF.getTarget().getRelocationModel() == Reloc::PIC_); unsigned NewReg = 0; int NewImm = 0; bool ATUsed; // Get the right frame order for Mips. adjustMipsStackFrame(MF); // Get the number of bytes to allocate from the FrameInfo. unsigned StackSize = MFI->getStackSize(); // No need to allocate space on the stack. if (StackSize == 0 && !MFI->adjustsStack()) return; BuildMI(MBB, MBBI, dl, TII.get(Mips::NOREORDER)); // TODO: check need from GP here. if (isPIC && STI.isABI_O32()) BuildMI(MBB, MBBI, dl, TII.get(Mips::CPLOAD)) .addReg(RegInfo->getPICCallReg()); BuildMI(MBB, MBBI, dl, TII.get(Mips::NOMACRO)); // Adjust stack : addi sp, sp, (-imm) ATUsed = expandRegLargeImmPair(Mips::SP, -StackSize, NewReg, NewImm, MBB, MBBI); BuildMI(MBB, MBBI, dl, TII.get(Mips::ADDiu), Mips::SP) .addReg(NewReg).addImm(NewImm); // FIXME: change this when mips goes MC". if (ATUsed) BuildMI(MBB, MBBI, dl, TII.get(Mips::ATMACRO)); // if framepointer enabled, set it to point to the stack pointer. if (hasFP(MF)) // move $fp, $sp BuildMI(MBB, MBBI, dl, TII.get(Mips::ADDu), Mips::FP) .addReg(Mips::SP).addReg(Mips::ZERO); // Restore GP from the saved stack location if (MipsFI->needGPSaveRestore()) BuildMI(MBB, MBBI, dl, TII.get(Mips::CPRESTORE)) .addImm(MipsFI->getGPStackOffset()); } void MipsFrameLowering::emitEpilogue(MachineFunction &MF, MachineBasicBlock &MBB) const { MachineBasicBlock::iterator MBBI = MBB.getLastNonDebugInstr(); MachineFrameInfo *MFI = MF.getFrameInfo(); const MipsInstrInfo &TII = *static_cast<const MipsInstrInfo*>(MF.getTarget().getInstrInfo()); DebugLoc dl = MBBI->getDebugLoc(); // Get the number of bytes from FrameInfo int NumBytes = (int) MFI->getStackSize(); unsigned NewReg = 0; int NewImm = 0; bool ATUsed = false; // if framepointer enabled, restore the stack pointer. if (hasFP(MF)) // move $sp, $fp BuildMI(MBB, MBBI, dl, TII.get(Mips::ADDu), Mips::SP) .addReg(Mips::FP).addReg(Mips::ZERO); // adjust stack : insert addi sp, sp, (imm) if (NumBytes) { ATUsed = expandRegLargeImmPair(Mips::SP, NumBytes, NewReg, NewImm, MBB, MBBI); BuildMI(MBB, MBBI, dl, TII.get(Mips::ADDiu), Mips::SP) .addReg(NewReg).addImm(NewImm); // FIXME: change this when mips goes MC". if (ATUsed) BuildMI(MBB, MBBI, dl, TII.get(Mips::ATMACRO)); } } void MipsFrameLowering:: processFunctionBeforeCalleeSavedScan(MachineFunction &MF, RegScavenger *RS) const { MachineRegisterInfo& MRI = MF.getRegInfo(); MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>(); // FIXME: remove this code if register allocator can correctly mark // $fp and $ra used or unused. // Mark $fp and $ra as used or unused. if (hasFP(MF)) MRI.setPhysRegUsed(Mips::FP); // The register allocator might determine $ra is used after seeing // instruction "jr $ra", but we do not want PrologEpilogInserter to insert // instructions to save/restore $ra unless there is a function call. // To correct this, $ra is explicitly marked unused if there is no // function call. if (MipsFI->hasCall()) MRI.setPhysRegUsed(Mips::RA); else MRI.setPhysRegUnused(Mips::RA); } void MipsFrameLowering:: processFunctionBeforeFrameFinalized(MachineFunction &MF) const { const MipsRegisterInfo *RegInfo = static_cast<const MipsRegisterInfo*>(MF.getTarget().getRegisterInfo()); RegInfo->processFunctionBeforeFrameFinalized(MF); } <commit_msg>Insert instructions that copy $sp to or from $fp at the right locations. <commit_after>//=======- MipsFrameLowering.cpp - Mips Frame Information ------*- C++ -*-====// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file contains the Mips implementation of TargetFrameLowering class. // //===----------------------------------------------------------------------===// #include "MipsFrameLowering.h" #include "MipsInstrInfo.h" #include "MipsMachineFunction.h" #include "llvm/Function.h" #include "llvm/CodeGen/MachineFrameInfo.h" #include "llvm/CodeGen/MachineFunction.h" #include "llvm/CodeGen/MachineInstrBuilder.h" #include "llvm/CodeGen/MachineModuleInfo.h" #include "llvm/CodeGen/MachineRegisterInfo.h" #include "llvm/Target/TargetData.h" #include "llvm/Target/TargetOptions.h" #include "llvm/Support/CommandLine.h" using namespace llvm; //===----------------------------------------------------------------------===// // // Stack Frame Processing methods // +----------------------------+ // // The stack is allocated decrementing the stack pointer on // the first instruction of a function prologue. Once decremented, // all stack references are done thought a positive offset // from the stack/frame pointer, so the stack is considering // to grow up! Otherwise terrible hacks would have to be made // to get this stack ABI compliant :) // // The stack frame required by the ABI (after call): // Offset // // 0 ---------- // 4 Args to pass // . saved $GP (used in PIC) // . Alloca allocations // . Local Area // . CPU "Callee Saved" Registers // . saved FP // . saved RA // . FPU "Callee Saved" Registers // StackSize ----------- // // Offset - offset from sp after stack allocation on function prologue // // The sp is the stack pointer subtracted/added from the stack size // at the Prologue/Epilogue // // References to the previous stack (to obtain arguments) are done // with offsets that exceeds the stack size: (stacksize+(4*(num_arg-1)) // // Examples: // - reference to the actual stack frame // for any local area var there is smt like : FI >= 0, StackOffset: 4 // sw REGX, 4(SP) // // - reference to previous stack frame // suppose there's a load to the 5th arguments : FI < 0, StackOffset: 16. // The emitted instruction will be something like: // lw REGX, 16+StackSize(SP) // // Since the total stack size is unknown on LowerFormalArguments, all // stack references (ObjectOffset) created to reference the function // arguments, are negative numbers. This way, on eliminateFrameIndex it's // possible to detect those references and the offsets are adjusted to // their real location. // //===----------------------------------------------------------------------===// // hasFP - Return true if the specified function should have a dedicated frame // pointer register. This is true if the function has variable sized allocas or // if frame pointer elimination is disabled. bool MipsFrameLowering::hasFP(const MachineFunction &MF) const { const MachineFrameInfo *MFI = MF.getFrameInfo(); return DisableFramePointerElim(MF) || MFI->hasVarSizedObjects(); } void MipsFrameLowering::adjustMipsStackFrame(MachineFunction &MF) const { MachineFrameInfo *MFI = MF.getFrameInfo(); MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>(); const std::vector<CalleeSavedInfo> &CSI = MFI->getCalleeSavedInfo(); unsigned StackAlign = getStackAlignment(); unsigned RegSize = STI.isGP32bit() ? 4 : 8; bool HasGP = MipsFI->needGPSaveRestore(); // Min and Max CSI FrameIndex. int MinCSFI = -1, MaxCSFI = -1; // See the description at MipsMachineFunction.h int TopCPUSavedRegOff = -1, TopFPUSavedRegOff = -1; // Replace the dummy '0' SPOffset by the negative offsets, as explained on // LowerFormalArguments. Leaving '0' for while is necessary to avoid the // approach done by calculateFrameObjectOffsets to the stack frame. MipsFI->adjustLoadArgsFI(MFI); MipsFI->adjustStoreVarArgsFI(MFI); // It happens that the default stack frame allocation order does not directly // map to the convention used for mips. So we must fix it. We move the callee // save register slots after the local variables area, as described in the // stack frame above. unsigned CalleeSavedAreaSize = 0; if (!CSI.empty()) { MinCSFI = CSI[0].getFrameIdx(); MaxCSFI = CSI[CSI.size()-1].getFrameIdx(); } for (unsigned i = 0, e = CSI.size(); i != e; ++i) CalleeSavedAreaSize += MFI->getObjectAlignment(CSI[i].getFrameIdx()); unsigned StackOffset = HasGP ? (MipsFI->getGPStackOffset()+RegSize) : (STI.isABI_O32() ? 16 : 0); // Adjust local variables. They should come on the stack right // after the arguments. int LastOffsetFI = -1; for (int i = 0, e = MFI->getObjectIndexEnd(); i != e; ++i) { if (i >= MinCSFI && i <= MaxCSFI) continue; if (MFI->isDeadObjectIndex(i)) continue; unsigned Offset = StackOffset + MFI->getObjectOffset(i) - CalleeSavedAreaSize; if (LastOffsetFI == -1) LastOffsetFI = i; if (Offset > MFI->getObjectOffset(LastOffsetFI)) LastOffsetFI = i; MFI->setObjectOffset(i, Offset); } // Adjust CPU Callee Saved Registers Area. Registers RA and FP must // be saved in this CPU Area. This whole area must be aligned to the // default Stack Alignment requirements. if (LastOffsetFI >= 0) StackOffset = MFI->getObjectOffset(LastOffsetFI)+ MFI->getObjectSize(LastOffsetFI); StackOffset = ((StackOffset+StackAlign-1)/StackAlign*StackAlign); for (unsigned i = 0, e = CSI.size(); i != e ; ++i) { unsigned Reg = CSI[i].getReg(); if (!Mips::CPURegsRegisterClass->contains(Reg)) break; MFI->setObjectOffset(CSI[i].getFrameIdx(), StackOffset); TopCPUSavedRegOff = StackOffset; StackOffset += MFI->getObjectAlignment(CSI[i].getFrameIdx()); } StackOffset = ((StackOffset+StackAlign-1)/StackAlign*StackAlign); // Adjust FPU Callee Saved Registers Area. This Area must be // aligned to the default Stack Alignment requirements. for (unsigned i = 0, e = CSI.size(); i != e; ++i) { unsigned Reg = CSI[i].getReg(); if (Mips::CPURegsRegisterClass->contains(Reg)) continue; MFI->setObjectOffset(CSI[i].getFrameIdx(), StackOffset); TopFPUSavedRegOff = StackOffset; StackOffset += MFI->getObjectAlignment(CSI[i].getFrameIdx()); } StackOffset = ((StackOffset+StackAlign-1)/StackAlign*StackAlign); // Update frame info MFI->setStackSize(StackOffset); // Recalculate the final tops offset. The final values must be '0' // if there isn't a callee saved register for CPU or FPU, otherwise // a negative offset is needed. if (TopCPUSavedRegOff >= 0) MipsFI->setCPUTopSavedRegOff(TopCPUSavedRegOff-StackOffset); if (TopFPUSavedRegOff >= 0) MipsFI->setFPUTopSavedRegOff(TopFPUSavedRegOff-StackOffset); } // expand pair of register and immediate if the immediate doesn't fit in the // 16-bit offset field. // e.g. // if OrigImm = 0x10000, OrigReg = $sp: // generate the following sequence of instrs: // lui $at, hi(0x10000) // addu $at, $sp, $at // // (NewReg, NewImm) = ($at, lo(Ox10000)) // return true static bool expandRegLargeImmPair(unsigned OrigReg, int OrigImm, unsigned& NewReg, int& NewImm, MachineBasicBlock& MBB, MachineBasicBlock::iterator I) { // OrigImm fits in the 16-bit field if (OrigImm < 0x8000 && OrigImm >= -0x8000) { NewReg = OrigReg; NewImm = OrigImm; return false; } MachineFunction* MF = MBB.getParent(); const TargetInstrInfo *TII = MF->getTarget().getInstrInfo(); DebugLoc DL = I->getDebugLoc(); int ImmLo = OrigImm & 0xffff; int ImmHi = (((unsigned)OrigImm & 0xffff0000) >> 16) + ((OrigImm & 0x8000) != 0); // FIXME: change this when mips goes MC". BuildMI(MBB, I, DL, TII->get(Mips::NOAT)); BuildMI(MBB, I, DL, TII->get(Mips::LUi), Mips::AT).addImm(ImmHi); BuildMI(MBB, I, DL, TII->get(Mips::ADDu), Mips::AT).addReg(OrigReg) .addReg(Mips::AT); NewReg = Mips::AT; NewImm = ImmLo; return true; } void MipsFrameLowering::emitPrologue(MachineFunction &MF) const { MachineBasicBlock &MBB = MF.front(); MachineFrameInfo *MFI = MF.getFrameInfo(); MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>(); const MipsRegisterInfo *RegInfo = static_cast<const MipsRegisterInfo*>(MF.getTarget().getRegisterInfo()); const MipsInstrInfo &TII = *static_cast<const MipsInstrInfo*>(MF.getTarget().getInstrInfo()); MachineBasicBlock::iterator MBBI = MBB.begin(); DebugLoc dl = MBBI != MBB.end() ? MBBI->getDebugLoc() : DebugLoc(); bool isPIC = (MF.getTarget().getRelocationModel() == Reloc::PIC_); unsigned NewReg = 0; int NewImm = 0; bool ATUsed; // Get the right frame order for Mips. adjustMipsStackFrame(MF); // Get the number of bytes to allocate from the FrameInfo. unsigned StackSize = MFI->getStackSize(); BuildMI(MBB, MBBI, dl, TII.get(Mips::NOREORDER)); // TODO: check need from GP here. if (isPIC && STI.isABI_O32()) BuildMI(MBB, MBBI, dl, TII.get(Mips::CPLOAD)) .addReg(RegInfo->getPICCallReg()); BuildMI(MBB, MBBI, dl, TII.get(Mips::NOMACRO)); // No need to allocate space on the stack. if (StackSize == 0 && !MFI->adjustsStack()) return; // Adjust stack : addi sp, sp, (-imm) ATUsed = expandRegLargeImmPair(Mips::SP, -StackSize, NewReg, NewImm, MBB, MBBI); BuildMI(MBB, MBBI, dl, TII.get(Mips::ADDiu), Mips::SP) .addReg(NewReg).addImm(NewImm); // FIXME: change this when mips goes MC". if (ATUsed) BuildMI(MBB, MBBI, dl, TII.get(Mips::ATMACRO)); // if framepointer enabled, set it to point to the stack pointer. if (hasFP(MF)) { // Find the instruction past the last instruction that saves a callee-saved // register to the stack. const std::vector<CalleeSavedInfo> &CSI = MFI->getCalleeSavedInfo(); for (unsigned i = 0; i < CSI.size(); ++i) ++MBBI; // Insert instruction "move $fp, $sp" at this location. BuildMI(MBB, MBBI, dl, TII.get(Mips::ADDu), Mips::FP) .addReg(Mips::SP).addReg(Mips::ZERO); } // Restore GP from the saved stack location if (MipsFI->needGPSaveRestore()) BuildMI(MBB, MBBI, dl, TII.get(Mips::CPRESTORE)) .addImm(MipsFI->getGPStackOffset()); } void MipsFrameLowering::emitEpilogue(MachineFunction &MF, MachineBasicBlock &MBB) const { MachineBasicBlock::iterator MBBI = MBB.getLastNonDebugInstr(); MachineFrameInfo *MFI = MF.getFrameInfo(); const MipsInstrInfo &TII = *static_cast<const MipsInstrInfo*>(MF.getTarget().getInstrInfo()); DebugLoc dl = MBBI->getDebugLoc(); // Get the number of bytes from FrameInfo unsigned StackSize = MFI->getStackSize(); unsigned NewReg = 0; int NewImm = 0; bool ATUsed = false; // if framepointer enabled, restore the stack pointer. if (hasFP(MF)) { // Find the first instruction that restores a callee-saved register. MachineBasicBlock::iterator I = MBBI; for (unsigned i = 0; i < MFI->getCalleeSavedInfo().size(); ++i) --I; // Insert instruction "move $sp, $fp" at this location. BuildMI(MBB, I, dl, TII.get(Mips::ADDu), Mips::SP) .addReg(Mips::FP).addReg(Mips::ZERO); } // adjust stack : insert addi sp, sp, (imm) if (StackSize) { ATUsed = expandRegLargeImmPair(Mips::SP, StackSize, NewReg, NewImm, MBB, MBBI); BuildMI(MBB, MBBI, dl, TII.get(Mips::ADDiu), Mips::SP) .addReg(NewReg).addImm(NewImm); // FIXME: change this when mips goes MC". if (ATUsed) BuildMI(MBB, MBBI, dl, TII.get(Mips::ATMACRO)); } } void MipsFrameLowering:: processFunctionBeforeCalleeSavedScan(MachineFunction &MF, RegScavenger *RS) const { MachineRegisterInfo& MRI = MF.getRegInfo(); MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>(); // FIXME: remove this code if register allocator can correctly mark // $fp and $ra used or unused. // Mark $fp and $ra as used or unused. if (hasFP(MF)) MRI.setPhysRegUsed(Mips::FP); // The register allocator might determine $ra is used after seeing // instruction "jr $ra", but we do not want PrologEpilogInserter to insert // instructions to save/restore $ra unless there is a function call. // To correct this, $ra is explicitly marked unused if there is no // function call. if (MipsFI->hasCall()) MRI.setPhysRegUsed(Mips::RA); else MRI.setPhysRegUnused(Mips::RA); } void MipsFrameLowering:: processFunctionBeforeFrameFinalized(MachineFunction &MF) const { const MipsRegisterInfo *RegInfo = static_cast<const MipsRegisterInfo*>(MF.getTarget().getRegisterInfo()); RegInfo->processFunctionBeforeFrameFinalized(MF); } <|endoftext|>
<commit_before>//===-- PPCCodeEmitter.cpp - JIT Code Emitter for PowerPC32 -------*- C++ -*-=// // // The LLVM Compiler Infrastructure // // This file was developed by the LLVM research group and is distributed under // the University of Illinois Open Source License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file defines the PowerPC 32-bit CodeEmitter and associated machinery to // JIT-compile bytecode to native PowerPC. // //===----------------------------------------------------------------------===// #include "PPCTargetMachine.h" #include "PPCRelocations.h" #include "PPC.h" #include "llvm/Module.h" #include "llvm/PassManager.h" #include "llvm/CodeGen/MachineCodeEmitter.h" #include "llvm/CodeGen/MachineFunctionPass.h" #include "llvm/CodeGen/MachineInstrBuilder.h" #include "llvm/CodeGen/Passes.h" #include "llvm/Support/Debug.h" using namespace llvm; namespace { class PPCCodeEmitter : public MachineFunctionPass { TargetMachine &TM; MachineCodeEmitter &MCE; // Tracks which instruction references which BasicBlock std::vector<std::pair<MachineBasicBlock*, unsigned*> > BBRefs; // Tracks where each BasicBlock starts std::map<MachineBasicBlock*, long> BBLocations; /// getMachineOpValue - evaluates the MachineOperand of a given MachineInstr /// int getMachineOpValue(MachineInstr &MI, MachineOperand &MO); public: PPCCodeEmitter(TargetMachine &T, MachineCodeEmitter &M) : TM(T), MCE(M) {} const char *getPassName() const { return "PowerPC Machine Code Emitter"; } /// runOnMachineFunction - emits the given MachineFunction to memory /// bool runOnMachineFunction(MachineFunction &MF); /// emitBasicBlock - emits the given MachineBasicBlock to memory /// void emitBasicBlock(MachineBasicBlock &MBB); /// emitWord - write a 32-bit word to memory at the current PC /// void emitWord(unsigned w) { MCE.emitWord(w); } /// getValueBit - return the particular bit of Val /// unsigned getValueBit(int64_t Val, unsigned bit) { return (Val >> bit) & 1; } /// getBinaryCodeForInstr - This function, generated by the /// CodeEmitterGenerator using TableGen, produces the binary encoding for /// machine instructions. /// unsigned getBinaryCodeForInstr(MachineInstr &MI); }; } /// addPassesToEmitMachineCode - Add passes to the specified pass manager to get /// machine code emitted. This uses a MachineCodeEmitter object to handle /// actually outputting the machine code and resolving things like the address /// of functions. This method should returns true if machine code emission is /// not supported. /// bool PPCTargetMachine::addPassesToEmitMachineCode(FunctionPassManager &PM, MachineCodeEmitter &MCE) { // Machine code emitter pass for PowerPC PM.add(new PPCCodeEmitter(*this, MCE)); // Delete machine code for this function after emitting it PM.add(createMachineCodeDeleter()); return false; } bool PPCCodeEmitter::runOnMachineFunction(MachineFunction &MF) { MCE.startFunction(MF); MCE.emitConstantPool(MF.getConstantPool()); for (MachineFunction::iterator BB = MF.begin(), E = MF.end(); BB != E; ++BB) emitBasicBlock(*BB); MCE.finishFunction(MF); // Resolve branches to BasicBlocks for the entire function for (unsigned i = 0, e = BBRefs.size(); i != e; ++i) { intptr_t Location = BBLocations[BBRefs[i].first]; unsigned *Ref = BBRefs[i].second; DEBUG(std::cerr << "Fixup @ " << (void*)Ref << " to " << (void*)Location << "\n"); unsigned Instr = *Ref; intptr_t BranchTargetDisp = (Location - (intptr_t)Ref) >> 2; switch (Instr >> 26) { default: assert(0 && "Unknown branch user!"); case 18: // This is B or BL *Ref |= (BranchTargetDisp & ((1 << 24)-1)) << 2; break; case 16: // This is BLT,BLE,BEQ,BGE,BGT,BNE, or other bcx instruction *Ref |= (BranchTargetDisp & ((1 << 14)-1)) << 2; break; } } BBRefs.clear(); BBLocations.clear(); return false; } void PPCCodeEmitter::emitBasicBlock(MachineBasicBlock &MBB) { assert(!PICEnabled && "CodeEmitter does not support PIC!"); BBLocations[&MBB] = MCE.getCurrentPCValue(); for (MachineBasicBlock::iterator I = MBB.begin(), E = MBB.end(); I != E; ++I){ MachineInstr &MI = *I; unsigned Opcode = MI.getOpcode(); switch (MI.getOpcode()) { default: emitWord(getBinaryCodeForInstr(*I)); break; case PPC::IMPLICIT_DEF_GPR: case PPC::IMPLICIT_DEF_F8: case PPC::IMPLICIT_DEF_F4: break; // pseudo opcode, no side effects case PPC::MovePCtoLR: assert(0 && "CodeEmitter does not support MovePCtoLR instruction"); break; } } } static unsigned enumRegToMachineReg(unsigned enumReg) { switch (enumReg) { case PPC::R0 : case PPC::F0 : case PPC::CR0: return 0; case PPC::R1 : case PPC::F1 : case PPC::CR1: return 1; case PPC::R2 : case PPC::F2 : case PPC::CR2: return 2; case PPC::R3 : case PPC::F3 : case PPC::CR3: return 3; case PPC::R4 : case PPC::F4 : case PPC::CR4: return 4; case PPC::R5 : case PPC::F5 : case PPC::CR5: return 5; case PPC::R6 : case PPC::F6 : case PPC::CR6: return 6; case PPC::R7 : case PPC::F7 : case PPC::CR7: return 7; case PPC::R8 : case PPC::F8 : return 8; case PPC::R9 : case PPC::F9 : return 9; case PPC::R10: case PPC::F10: return 10; case PPC::R11: case PPC::F11: return 11; case PPC::R12: case PPC::F12: return 12; case PPC::R13: case PPC::F13: return 13; case PPC::R14: case PPC::F14: return 14; case PPC::R15: case PPC::F15: return 15; case PPC::R16: case PPC::F16: return 16; case PPC::R17: case PPC::F17: return 17; case PPC::R18: case PPC::F18: return 18; case PPC::R19: case PPC::F19: return 19; case PPC::R20: case PPC::F20: return 20; case PPC::R21: case PPC::F21: return 21; case PPC::R22: case PPC::F22: return 22; case PPC::R23: case PPC::F23: return 23; case PPC::R24: case PPC::F24: return 24; case PPC::R25: case PPC::F25: return 25; case PPC::R26: case PPC::F26: return 26; case PPC::R27: case PPC::F27: return 27; case PPC::R28: case PPC::F28: return 28; case PPC::R29: case PPC::F29: return 29; case PPC::R30: case PPC::F30: return 30; case PPC::R31: case PPC::F31: return 31; default: std::cerr << "Unhandled reg in enumRegToRealReg!\n"; abort(); } } int PPCCodeEmitter::getMachineOpValue(MachineInstr &MI, MachineOperand &MO) { int rv = 0; // Return value; defaults to 0 for unhandled cases // or things that get fixed up later by the JIT. if (MO.isRegister()) { rv = enumRegToMachineReg(MO.getReg()); // Special encoding for MTCRF and MFOCRF, which uses a bit mask for the // register, not the register number directly. if ((MI.getOpcode() == PPC::MTCRF || MI.getOpcode() == PPC::MFOCRF) && (MO.getReg() >= PPC::CR0 && MO.getReg() <= PPC::CR7)) { rv = 0x80 >> rv; } } else if (MO.isImmediate()) { rv = MO.getImmedValue(); } else if (MO.isGlobalAddress() || MO.isExternalSymbol()) { bool isExternal = MO.isExternalSymbol() || MO.getGlobal()->hasWeakLinkage() || MO.getGlobal()->isExternal(); unsigned Reloc = 0; if (MI.getOpcode() == PPC::BL) Reloc = PPC::reloc_pcrel_bx; else { switch (MI.getOpcode()) { default: MI.dump(); assert(0 && "Unknown instruction for relocation!"); case PPC::LIS: if (isExternal) Reloc = PPC::reloc_absolute_ptr_high; // Pointer to stub else Reloc = PPC::reloc_absolute_high; // Pointer to symbol break; case PPC::LA: assert(!isExternal && "Something in the ISEL changed\n"); Reloc = PPC::reloc_absolute_low; break; case PPC::LBZ: case PPC::LHA: case PPC::LHZ: case PPC::LWZ: case PPC::LFS: case PPC::LFD: case PPC::STB: case PPC::STH: case PPC::STW: case PPC::STFS: case PPC::STFD: if (isExternal) Reloc = PPC::reloc_absolute_ptr_low; else Reloc = PPC::reloc_absolute_low; break; } } if (MO.isGlobalAddress()) MCE.addRelocation(MachineRelocation(MCE.getCurrentPCOffset(), Reloc, MO.getGlobal(), 0)); else MCE.addRelocation(MachineRelocation(MCE.getCurrentPCOffset(), Reloc, MO.getSymbolName(), 0)); } else if (MO.isMachineBasicBlock()) { unsigned* CurrPC = (unsigned*)(intptr_t)MCE.getCurrentPCValue(); BBRefs.push_back(std::make_pair(MO.getMachineBasicBlock(), CurrPC)); } else if (MO.isConstantPoolIndex()) { unsigned index = MO.getConstantPoolIndex(); unsigned Opcode = MI.getOpcode(); rv = MCE.getConstantPoolEntryAddress(index); if (Opcode == PPC::LIS) { // lis wants hi16(addr) if ((short)rv < 0) rv += 1 << 16; rv >>= 16; } else if (Opcode == PPC::LWZ || Opcode == PPC::LA || Opcode == PPC::LFS || Opcode == PPC::LFD) { // These load opcodes want lo16(addr) rv &= 0xffff; } else { assert(0 && "Unknown constant pool using instruction!"); } } else { std::cerr << "ERROR: Unknown type of MachineOperand: " << MO << "\n"; abort(); } return rv; } #include "PPCGenCodeEmitter.inc" <commit_msg>Fix the JIT failures from last night.<commit_after>//===-- PPCCodeEmitter.cpp - JIT Code Emitter for PowerPC32 -------*- C++ -*-=// // // The LLVM Compiler Infrastructure // // This file was developed by the LLVM research group and is distributed under // the University of Illinois Open Source License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file defines the PowerPC 32-bit CodeEmitter and associated machinery to // JIT-compile bytecode to native PowerPC. // //===----------------------------------------------------------------------===// #include "PPCTargetMachine.h" #include "PPCRelocations.h" #include "PPC.h" #include "llvm/Module.h" #include "llvm/PassManager.h" #include "llvm/CodeGen/MachineCodeEmitter.h" #include "llvm/CodeGen/MachineFunctionPass.h" #include "llvm/CodeGen/MachineInstrBuilder.h" #include "llvm/CodeGen/Passes.h" #include "llvm/Support/Debug.h" using namespace llvm; namespace { class PPCCodeEmitter : public MachineFunctionPass { TargetMachine &TM; MachineCodeEmitter &MCE; // Tracks which instruction references which BasicBlock std::vector<std::pair<MachineBasicBlock*, unsigned*> > BBRefs; // Tracks where each BasicBlock starts std::map<MachineBasicBlock*, long> BBLocations; /// getMachineOpValue - evaluates the MachineOperand of a given MachineInstr /// int getMachineOpValue(MachineInstr &MI, MachineOperand &MO); public: PPCCodeEmitter(TargetMachine &T, MachineCodeEmitter &M) : TM(T), MCE(M) {} const char *getPassName() const { return "PowerPC Machine Code Emitter"; } /// runOnMachineFunction - emits the given MachineFunction to memory /// bool runOnMachineFunction(MachineFunction &MF); /// emitBasicBlock - emits the given MachineBasicBlock to memory /// void emitBasicBlock(MachineBasicBlock &MBB); /// emitWord - write a 32-bit word to memory at the current PC /// void emitWord(unsigned w) { MCE.emitWord(w); } /// getValueBit - return the particular bit of Val /// unsigned getValueBit(int64_t Val, unsigned bit) { return (Val >> bit) & 1; } /// getBinaryCodeForInstr - This function, generated by the /// CodeEmitterGenerator using TableGen, produces the binary encoding for /// machine instructions. /// unsigned getBinaryCodeForInstr(MachineInstr &MI); }; } /// addPassesToEmitMachineCode - Add passes to the specified pass manager to get /// machine code emitted. This uses a MachineCodeEmitter object to handle /// actually outputting the machine code and resolving things like the address /// of functions. This method should returns true if machine code emission is /// not supported. /// bool PPCTargetMachine::addPassesToEmitMachineCode(FunctionPassManager &PM, MachineCodeEmitter &MCE) { // Machine code emitter pass for PowerPC PM.add(new PPCCodeEmitter(*this, MCE)); // Delete machine code for this function after emitting it PM.add(createMachineCodeDeleter()); return false; } bool PPCCodeEmitter::runOnMachineFunction(MachineFunction &MF) { MCE.startFunction(MF); MCE.emitConstantPool(MF.getConstantPool()); for (MachineFunction::iterator BB = MF.begin(), E = MF.end(); BB != E; ++BB) emitBasicBlock(*BB); MCE.finishFunction(MF); // Resolve branches to BasicBlocks for the entire function for (unsigned i = 0, e = BBRefs.size(); i != e; ++i) { intptr_t Location = BBLocations[BBRefs[i].first]; unsigned *Ref = BBRefs[i].second; DEBUG(std::cerr << "Fixup @ " << (void*)Ref << " to " << (void*)Location << "\n"); unsigned Instr = *Ref; intptr_t BranchTargetDisp = (Location - (intptr_t)Ref) >> 2; switch (Instr >> 26) { default: assert(0 && "Unknown branch user!"); case 18: // This is B or BL *Ref |= (BranchTargetDisp & ((1 << 24)-1)) << 2; break; case 16: // This is BLT,BLE,BEQ,BGE,BGT,BNE, or other bcx instruction *Ref |= (BranchTargetDisp & ((1 << 14)-1)) << 2; break; } } BBRefs.clear(); BBLocations.clear(); return false; } void PPCCodeEmitter::emitBasicBlock(MachineBasicBlock &MBB) { assert(!PICEnabled && "CodeEmitter does not support PIC!"); BBLocations[&MBB] = MCE.getCurrentPCValue(); for (MachineBasicBlock::iterator I = MBB.begin(), E = MBB.end(); I != E; ++I){ MachineInstr &MI = *I; unsigned Opcode = MI.getOpcode(); switch (MI.getOpcode()) { default: emitWord(getBinaryCodeForInstr(*I)); break; case PPC::IMPLICIT_DEF_GPR: case PPC::IMPLICIT_DEF_F8: case PPC::IMPLICIT_DEF_F4: break; // pseudo opcode, no side effects case PPC::MovePCtoLR: assert(0 && "CodeEmitter does not support MovePCtoLR instruction"); break; } } } static unsigned enumRegToMachineReg(unsigned enumReg) { switch (enumReg) { case PPC::R0 : case PPC::F0 : case PPC::CR0: return 0; case PPC::R1 : case PPC::F1 : case PPC::CR1: return 1; case PPC::R2 : case PPC::F2 : case PPC::CR2: return 2; case PPC::R3 : case PPC::F3 : case PPC::CR3: return 3; case PPC::R4 : case PPC::F4 : case PPC::CR4: return 4; case PPC::R5 : case PPC::F5 : case PPC::CR5: return 5; case PPC::R6 : case PPC::F6 : case PPC::CR6: return 6; case PPC::R7 : case PPC::F7 : case PPC::CR7: return 7; case PPC::R8 : case PPC::F8 : return 8; case PPC::R9 : case PPC::F9 : return 9; case PPC::R10: case PPC::F10: return 10; case PPC::R11: case PPC::F11: return 11; case PPC::R12: case PPC::F12: return 12; case PPC::R13: case PPC::F13: return 13; case PPC::R14: case PPC::F14: return 14; case PPC::R15: case PPC::F15: return 15; case PPC::R16: case PPC::F16: return 16; case PPC::R17: case PPC::F17: return 17; case PPC::R18: case PPC::F18: return 18; case PPC::R19: case PPC::F19: return 19; case PPC::R20: case PPC::F20: return 20; case PPC::R21: case PPC::F21: return 21; case PPC::R22: case PPC::F22: return 22; case PPC::R23: case PPC::F23: return 23; case PPC::R24: case PPC::F24: return 24; case PPC::R25: case PPC::F25: return 25; case PPC::R26: case PPC::F26: return 26; case PPC::R27: case PPC::F27: return 27; case PPC::R28: case PPC::F28: return 28; case PPC::R29: case PPC::F29: return 29; case PPC::R30: case PPC::F30: return 30; case PPC::R31: case PPC::F31: return 31; default: std::cerr << "Unhandled reg in enumRegToRealReg!\n"; abort(); } } int PPCCodeEmitter::getMachineOpValue(MachineInstr &MI, MachineOperand &MO) { int rv = 0; // Return value; defaults to 0 for unhandled cases // or things that get fixed up later by the JIT. if (MO.isRegister()) { rv = enumRegToMachineReg(MO.getReg()); // Special encoding for MTCRF and MFOCRF, which uses a bit mask for the // register, not the register number directly. if ((MI.getOpcode() == PPC::MTCRF || MI.getOpcode() == PPC::MFOCRF) && (MO.getReg() >= PPC::CR0 && MO.getReg() <= PPC::CR7)) { rv = 0x80 >> rv; } } else if (MO.isImmediate()) { rv = MO.getImmedValue(); } else if (MO.isGlobalAddress() || MO.isExternalSymbol()) { bool isExternal = MO.isExternalSymbol() || MO.getGlobal()->hasWeakLinkage() || MO.getGlobal()->isExternal(); unsigned Reloc = 0; if (MI.getOpcode() == PPC::BL) Reloc = PPC::reloc_pcrel_bx; else { switch (MI.getOpcode()) { default: MI.dump(); assert(0 && "Unknown instruction for relocation!"); case PPC::LIS: if (isExternal) Reloc = PPC::reloc_absolute_ptr_high; // Pointer to stub else Reloc = PPC::reloc_absolute_high; // Pointer to symbol break; case PPC::LA: assert(!isExternal && "Something in the ISEL changed\n"); Reloc = PPC::reloc_absolute_low; break; case PPC::LBZ: case PPC::LHA: case PPC::LHZ: case PPC::LWZ: case PPC::LFS: case PPC::LFD: case PPC::STB: case PPC::STH: case PPC::STW: case PPC::STFS: case PPC::STFD: if (isExternal) Reloc = PPC::reloc_absolute_ptr_low; else Reloc = PPC::reloc_absolute_low; break; } } if (MO.isGlobalAddress()) MCE.addRelocation(MachineRelocation(MCE.getCurrentPCOffset(), Reloc, MO.getGlobal(), 0)); else MCE.addRelocation(MachineRelocation(MCE.getCurrentPCOffset(), Reloc, MO.getSymbolName(), 0)); } else if (MO.isMachineBasicBlock()) { unsigned* CurrPC = (unsigned*)(intptr_t)MCE.getCurrentPCValue(); BBRefs.push_back(std::make_pair(MO.getMachineBasicBlock(), CurrPC)); } else if (MO.isConstantPoolIndex()) { unsigned index = MO.getConstantPoolIndex(); unsigned Opcode = MI.getOpcode(); rv = MCE.getConstantPoolEntryAddress(index); if (Opcode == PPC::LIS || Opcode == PPC::ADDIS) { // lis wants hi16(addr) if ((short)rv < 0) rv += 1 << 16; rv >>= 16; } else if (Opcode == PPC::LWZ || Opcode == PPC::LA || Opcode == PPC::LI || Opcode == PPC::LFS || Opcode == PPC::LFD) { // These load opcodes want lo16(addr) rv &= 0xffff; } else { assert(0 && "Unknown constant pool using instruction!"); } } else { std::cerr << "ERROR: Unknown type of MachineOperand: " << MO << "\n"; abort(); } return rv; } #include "PPCGenCodeEmitter.inc" <|endoftext|>
<commit_before>/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ #include <algorithm> #include <iostream> #include "TSocketPool.h" namespace apache { namespace thrift { namespace transport { using namespace std; using boost::shared_ptr; /** * TSocketPoolServer implementation * */ TSocketPoolServer::TSocketPoolServer() : host_(""), port_(0), socket_(-1), lastFailTime_(0), consecutiveFailures_(0) {} /** * Constructor for TSocketPool server */ TSocketPoolServer::TSocketPoolServer(const string &host, int port) : host_(host), port_(port), socket_(-1), lastFailTime_(0), consecutiveFailures_(0) {} /** * TSocketPool implementation. * */ TSocketPool::TSocketPool() : TSocket(), numRetries_(1), retryInterval_(60), maxConsecutiveFailures_(1), randomize_(true), alwaysTryLast_(true) { } TSocketPool::TSocketPool(const vector<string> &hosts, const vector<int> &ports) : TSocket(), numRetries_(1), retryInterval_(60), maxConsecutiveFailures_(1), randomize_(true), alwaysTryLast_(true) { if (hosts.size() != ports.size()) { GlobalOutput("TSocketPool::TSocketPool: hosts.size != ports.size"); throw TTransportException(TTransportException::BAD_ARGS); } for (unsigned int i = 0; i < hosts.size(); ++i) { addServer(hosts[i], ports[i]); } } TSocketPool::TSocketPool(const vector<pair<string, int> >& servers) : TSocket(), numRetries_(1), retryInterval_(60), maxConsecutiveFailures_(1), randomize_(true), alwaysTryLast_(true) { for (unsigned i = 0; i < servers.size(); ++i) { addServer(servers[i].first, servers[i].second); } } TSocketPool::TSocketPool(const vector< shared_ptr<TSocketPoolServer> >& servers) : TSocket(), servers_(servers), numRetries_(1), retryInterval_(60), maxConsecutiveFailures_(1), randomize_(true), alwaysTryLast_(true) { } TSocketPool::TSocketPool(const string& host, int port) : TSocket(), numRetries_(1), retryInterval_(60), maxConsecutiveFailures_(1), randomize_(true), alwaysTryLast_(true) { addServer(host, port); } TSocketPool::~TSocketPool() { vector< shared_ptr<TSocketPoolServer> >::const_iterator iter = servers_.begin(); vector< shared_ptr<TSocketPoolServer> >::const_iterator iterEnd = servers_.end(); for (; iter != iterEnd; ++iter) { setCurrentServer(*iter); TSocketPool::close(); } } void TSocketPool::addServer(const string& host, int port) { servers_.push_back(shared_ptr<TSocketPoolServer>(new TSocketPoolServer(host, port))); } void TSocketPool::addServer(shared_ptr<TSocketPoolServer> &server) { if (server) { servers_.push_back(server); } } void TSocketPool::setServers(const vector< shared_ptr<TSocketPoolServer> >& servers) { servers_ = servers; } void TSocketPool::getServers(vector< shared_ptr<TSocketPoolServer> >& servers) { servers = servers_; } void TSocketPool::setNumRetries(int numRetries) { numRetries_ = numRetries; } void TSocketPool::setRetryInterval(int retryInterval) { retryInterval_ = retryInterval; } void TSocketPool::setMaxConsecutiveFailures(int maxConsecutiveFailures) { maxConsecutiveFailures_ = maxConsecutiveFailures; } void TSocketPool::setRandomize(bool randomize) { randomize_ = randomize; } void TSocketPool::setAlwaysTryLast(bool alwaysTryLast) { alwaysTryLast_ = alwaysTryLast; } void TSocketPool::setCurrentServer(const shared_ptr<TSocketPoolServer> &server) { currentServer_ = server; host_ = server->host_; port_ = server->port_; socket_ = server->socket_; } /* TODO: without apc we ignore a lot of functionality from the php version */ void TSocketPool::open() { if (randomize_) { random_shuffle(servers_.begin(), servers_.end()); } unsigned int numServers = servers_.size(); for (unsigned int i = 0; i < numServers; ++i) { shared_ptr<TSocketPoolServer> &server = servers_[i]; bool retryIntervalPassed = (server->lastFailTime_ == 0); bool isLastServer = alwaysTryLast_ ? (i == (numServers - 1)) : false; // Impersonate the server socket setCurrentServer(server); if (isOpen()) { // already open means we're done return; } if (server->lastFailTime_ > 0) { // The server was marked as down, so check if enough time has elapsed to retry int elapsedTime = time(NULL) - server->lastFailTime_; if (elapsedTime > retryInterval_) { retryIntervalPassed = true; } } if (retryIntervalPassed || isLastServer) { for (int j = 0; j < numRetries_; ++j) { try { TSocket::open(); // Copy over the opened socket so that we can keep it persistent server->socket_ = socket_; // reset lastFailTime_ is required if (server->lastFailTime_) { server->lastFailTime_ = 0; } // success return; } catch (TException e) { string errStr = "TSocketPool::open failed "+getSocketInfo()+": "+e.what(); GlobalOutput(errStr.c_str()); // connection failed } } ++server->consecutiveFailures_; if (server->consecutiveFailures_ > maxConsecutiveFailures_) { // Mark server as down server->consecutiveFailures_ = 0; server->lastFailTime_ = time(NULL); } } } GlobalOutput("TSocketPool::open: all connections failed"); throw TTransportException(TTransportException::NOT_OPEN); } void TSocketPool::close() { if (isOpen()) { TSocket::close(); currentServer_->socket_ = -1; } } }}} // apache::thrift::transport <commit_msg>cpp: TSocketPool: Optimize the case of a single server in the pool.<commit_after>/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ #include <algorithm> #include <iostream> #include "TSocketPool.h" namespace apache { namespace thrift { namespace transport { using namespace std; using boost::shared_ptr; /** * TSocketPoolServer implementation * */ TSocketPoolServer::TSocketPoolServer() : host_(""), port_(0), socket_(-1), lastFailTime_(0), consecutiveFailures_(0) {} /** * Constructor for TSocketPool server */ TSocketPoolServer::TSocketPoolServer(const string &host, int port) : host_(host), port_(port), socket_(-1), lastFailTime_(0), consecutiveFailures_(0) {} /** * TSocketPool implementation. * */ TSocketPool::TSocketPool() : TSocket(), numRetries_(1), retryInterval_(60), maxConsecutiveFailures_(1), randomize_(true), alwaysTryLast_(true) { } TSocketPool::TSocketPool(const vector<string> &hosts, const vector<int> &ports) : TSocket(), numRetries_(1), retryInterval_(60), maxConsecutiveFailures_(1), randomize_(true), alwaysTryLast_(true) { if (hosts.size() != ports.size()) { GlobalOutput("TSocketPool::TSocketPool: hosts.size != ports.size"); throw TTransportException(TTransportException::BAD_ARGS); } for (unsigned int i = 0; i < hosts.size(); ++i) { addServer(hosts[i], ports[i]); } } TSocketPool::TSocketPool(const vector<pair<string, int> >& servers) : TSocket(), numRetries_(1), retryInterval_(60), maxConsecutiveFailures_(1), randomize_(true), alwaysTryLast_(true) { for (unsigned i = 0; i < servers.size(); ++i) { addServer(servers[i].first, servers[i].second); } } TSocketPool::TSocketPool(const vector< shared_ptr<TSocketPoolServer> >& servers) : TSocket(), servers_(servers), numRetries_(1), retryInterval_(60), maxConsecutiveFailures_(1), randomize_(true), alwaysTryLast_(true) { } TSocketPool::TSocketPool(const string& host, int port) : TSocket(), numRetries_(1), retryInterval_(60), maxConsecutiveFailures_(1), randomize_(true), alwaysTryLast_(true) { addServer(host, port); } TSocketPool::~TSocketPool() { vector< shared_ptr<TSocketPoolServer> >::const_iterator iter = servers_.begin(); vector< shared_ptr<TSocketPoolServer> >::const_iterator iterEnd = servers_.end(); for (; iter != iterEnd; ++iter) { setCurrentServer(*iter); TSocketPool::close(); } } void TSocketPool::addServer(const string& host, int port) { servers_.push_back(shared_ptr<TSocketPoolServer>(new TSocketPoolServer(host, port))); } void TSocketPool::addServer(shared_ptr<TSocketPoolServer> &server) { if (server) { servers_.push_back(server); } } void TSocketPool::setServers(const vector< shared_ptr<TSocketPoolServer> >& servers) { servers_ = servers; } void TSocketPool::getServers(vector< shared_ptr<TSocketPoolServer> >& servers) { servers = servers_; } void TSocketPool::setNumRetries(int numRetries) { numRetries_ = numRetries; } void TSocketPool::setRetryInterval(int retryInterval) { retryInterval_ = retryInterval; } void TSocketPool::setMaxConsecutiveFailures(int maxConsecutiveFailures) { maxConsecutiveFailures_ = maxConsecutiveFailures; } void TSocketPool::setRandomize(bool randomize) { randomize_ = randomize; } void TSocketPool::setAlwaysTryLast(bool alwaysTryLast) { alwaysTryLast_ = alwaysTryLast; } void TSocketPool::setCurrentServer(const shared_ptr<TSocketPoolServer> &server) { currentServer_ = server; host_ = server->host_; port_ = server->port_; socket_ = server->socket_; } /* TODO: without apc we ignore a lot of functionality from the php version */ void TSocketPool::open() { unsigned int numServers = servers_.size(); if (numServers == 1 && isOpen()) { // only one server that is already connected to return; } if (randomize_ && numServers > 1) { random_shuffle(servers_.begin(), servers_.end()); } for (unsigned int i = 0; i < numServers; ++i) { shared_ptr<TSocketPoolServer> &server = servers_[i]; // Impersonate the server socket setCurrentServer(server); if (isOpen()) { // already open means we're done return; } bool retryIntervalPassed = (server->lastFailTime_ == 0); bool isLastServer = alwaysTryLast_ ? (i == (numServers - 1)) : false; if (server->lastFailTime_ > 0) { // The server was marked as down, so check if enough time has elapsed to retry int elapsedTime = time(NULL) - server->lastFailTime_; if (elapsedTime > retryInterval_) { retryIntervalPassed = true; } } if (retryIntervalPassed || isLastServer) { for (int j = 0; j < numRetries_; ++j) { try { TSocket::open(); // Copy over the opened socket so that we can keep it persistent server->socket_ = socket_; // reset lastFailTime_ is required if (server->lastFailTime_) { server->lastFailTime_ = 0; } // success return; } catch (TException e) { string errStr = "TSocketPool::open failed "+getSocketInfo()+": "+e.what(); GlobalOutput(errStr.c_str()); // connection failed } } ++server->consecutiveFailures_; if (server->consecutiveFailures_ > maxConsecutiveFailures_) { // Mark server as down server->consecutiveFailures_ = 0; server->lastFailTime_ = time(NULL); } } } GlobalOutput("TSocketPool::open: all connections failed"); throw TTransportException(TTransportException::NOT_OPEN); } void TSocketPool::close() { if (isOpen()) { TSocket::close(); currentServer_->socket_ = -1; } } }}} // apache::thrift::transport <|endoftext|>
<commit_before>/***************************************************************************** * SegmentTimeline.cpp: Implement the SegmentTimeline tag. ***************************************************************************** * Copyright (C) 1998-2007 VLC authors and VideoLAN * $Id$ * * Authors: Hugo Beauzée-Luyssen <beauze.h@gmail.com> * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA. *****************************************************************************/ #include "SegmentTimeline.h" #include <algorithm> using namespace adaptative::playlist; SegmentTimeline::SegmentTimeline(TimescaleAble *parent) :TimescaleAble(parent) { } SegmentTimeline::~SegmentTimeline() { std::list<Element *>::iterator it; for(it = elements.begin(); it != elements.end(); ++it) delete *it; } void SegmentTimeline::addElement(uint64_t number, stime_t d, uint64_t r, stime_t t) { Element *element = new (std::nothrow) Element(number, d, r, t); if(element) { if(!elements.empty() && !t) { const Element *el = elements.back(); element->t = el->t + (el->d * (el->r + 1)); } elements.push_back(element); } } uint64_t SegmentTimeline::getElementNumberByScaledPlaybackTime(stime_t scaled) const { uint64_t prevnumber = 0; std::list<Element *>::const_iterator it; for(it = elements.begin(); it != elements.end(); ++it) { const Element *el = *it; for(uint64_t repeat = 1 + el->r; repeat; repeat--) { if(el->d >= scaled) return prevnumber; scaled -= el->d; prevnumber++; } /* might have been discontinuity */ prevnumber = el->number; } return prevnumber; } stime_t SegmentTimeline::getScaledPlaybackTimeByElementNumber(uint64_t number) const { stime_t totalscaledtime = 0; std::list<Element *>::const_iterator it; for(it = elements.begin(); it != elements.end(); ++it) { const Element *el = *it; if(number >= el->number) { if(number <= el->number + el->r) { return el->t + (number * el->d); } totalscaledtime = el->t + (number * el->d); } } return totalscaledtime; } uint64_t SegmentTimeline::maxElementNumber() const { if(elements.empty()) return 0; const Element *e = elements.back(); return e->number + e->r; } size_t SegmentTimeline::prune(mtime_t time) { stime_t scaled = time * inheritTimescale() / CLOCK_FREQ; size_t prunednow = 0; while(elements.size()) { Element *el = elements.front(); if(el->t + (el->d * (stime_t)(el->r + 1)) < scaled) { prunednow += el->r + 1; delete el; elements.pop_front(); } else break; } return prunednow; } void SegmentTimeline::mergeWith(SegmentTimeline &other) { if(elements.empty()) { while(other.elements.size()) { elements.push_back(other.elements.front()); other.elements.pop_front(); } return; } Element *last = elements.back(); while(other.elements.size()) { Element *el = other.elements.front(); other.elements.pop_front(); if(el->t == last->t) /* Same element, but prev could have been middle of repeat */ { last->r = std::max(last->r, el->r); delete el; } else if(el->t > last->t) /* Did not exist in previous list */ { if( el->t - last->t >= last->d * (stime_t)(last->r + 1) ) { elements.push_back(el); last = el; } else if(last->d == el->d) /* should always be in that case */ { last->r = ((el->t - last->t) / last->d) - 1; elements.push_back(el); last = el; } else { /* borked: skip */ delete el; } } else { delete el; } } } mtime_t SegmentTimeline::start() const { if(elements.empty()) return 0; return elements.front()->t * CLOCK_FREQ / inheritTimescale(); } mtime_t SegmentTimeline::end() const { if(elements.empty()) return 0; const Element *last = elements.back(); stime_t scaled = last->t + last->d * (last->r + 1); return scaled * CLOCK_FREQ / inheritTimescale(); } SegmentTimeline::Element::Element(uint64_t number_, stime_t d_, uint64_t r_, stime_t t_) { number = number_; d = d_; t = t_; r = r_; } <commit_msg>demux: adaptative: fix timeline number to time<commit_after>/***************************************************************************** * SegmentTimeline.cpp: Implement the SegmentTimeline tag. ***************************************************************************** * Copyright (C) 1998-2007 VLC authors and VideoLAN * $Id$ * * Authors: Hugo Beauzée-Luyssen <beauze.h@gmail.com> * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA. *****************************************************************************/ #include "SegmentTimeline.h" #include <algorithm> using namespace adaptative::playlist; SegmentTimeline::SegmentTimeline(TimescaleAble *parent) :TimescaleAble(parent) { } SegmentTimeline::~SegmentTimeline() { std::list<Element *>::iterator it; for(it = elements.begin(); it != elements.end(); ++it) delete *it; } void SegmentTimeline::addElement(uint64_t number, stime_t d, uint64_t r, stime_t t) { Element *element = new (std::nothrow) Element(number, d, r, t); if(element) { if(!elements.empty() && !t) { const Element *el = elements.back(); element->t = el->t + (el->d * (el->r + 1)); } elements.push_back(element); } } uint64_t SegmentTimeline::getElementNumberByScaledPlaybackTime(stime_t scaled) const { uint64_t prevnumber = 0; std::list<Element *>::const_iterator it; for(it = elements.begin(); it != elements.end(); ++it) { const Element *el = *it; for(uint64_t repeat = 1 + el->r; repeat; repeat--) { if(el->d >= scaled) return prevnumber; scaled -= el->d; prevnumber++; } /* might have been discontinuity */ prevnumber = el->number; } return prevnumber; } stime_t SegmentTimeline::getScaledPlaybackTimeByElementNumber(uint64_t number) const { stime_t totalscaledtime = 0; std::list<Element *>::const_iterator it; for(it = elements.begin(); it != elements.end(); ++it) { const Element *el = *it; /* set start time, or from discontinuity */ if(it == elements.begin() || el->t) { totalscaledtime = el->t; } if(number <= el->number) break; if(number <= el->number + el->r) { totalscaledtime += el->d * (number - el->number); break; } totalscaledtime += (el->d * (el->r + 1)); } return totalscaledtime; } uint64_t SegmentTimeline::maxElementNumber() const { if(elements.empty()) return 0; const Element *e = elements.back(); return e->number + e->r; } size_t SegmentTimeline::prune(mtime_t time) { stime_t scaled = time * inheritTimescale() / CLOCK_FREQ; size_t prunednow = 0; while(elements.size()) { Element *el = elements.front(); if(el->t + (el->d * (stime_t)(el->r + 1)) < scaled) { prunednow += el->r + 1; delete el; elements.pop_front(); } else break; } return prunednow; } void SegmentTimeline::mergeWith(SegmentTimeline &other) { if(elements.empty()) { while(other.elements.size()) { elements.push_back(other.elements.front()); other.elements.pop_front(); } return; } Element *last = elements.back(); while(other.elements.size()) { Element *el = other.elements.front(); other.elements.pop_front(); if(el->t == last->t) /* Same element, but prev could have been middle of repeat */ { last->r = std::max(last->r, el->r); delete el; } else if(el->t > last->t) /* Did not exist in previous list */ { if( el->t - last->t >= last->d * (stime_t)(last->r + 1) ) { elements.push_back(el); last = el; } else if(last->d == el->d) /* should always be in that case */ { last->r = ((el->t - last->t) / last->d) - 1; elements.push_back(el); last = el; } else { /* borked: skip */ delete el; } } else { delete el; } } } mtime_t SegmentTimeline::start() const { if(elements.empty()) return 0; return elements.front()->t * CLOCK_FREQ / inheritTimescale(); } mtime_t SegmentTimeline::end() const { if(elements.empty()) return 0; const Element *last = elements.back(); stime_t scaled = last->t + last->d * (last->r + 1); return scaled * CLOCK_FREQ / inheritTimescale(); } SegmentTimeline::Element::Element(uint64_t number_, stime_t d_, uint64_t r_, stime_t t_) { number = number_; d = d_; t = t_; r = r_; } <|endoftext|>
<commit_before>#include "SolidMaterialProperties.h" #include "R7Conversion.h" template<> InputParameters validParams<SolidMaterialProperties>() { InputParameters params = validParams<GeneralUserObject>(); params.addParam<std::string>("k", "Thermal conductivity"); params.addParam<std::string>("Cp", "Specific heat"); params.addParam<std::string>("rho", "Density"); // These are here so we are able to control these values params.addPrivateParam<Real>("thermal_conductivity", 0.0); params.addPrivateParam<Real>("specific_heat", 0.0); params.addPrivateParam<Real>("density", 0.0); params.addPrivateParam<MultiMooseEnum>("execute_on"); params.addPrivateParam<bool>("use_displaced_mesh"); params.registerBase("MaterialProperties"); return params; } SolidMaterialProperties::SolidMaterialProperties(const std::string & name, InputParameters parameters) : GeneralUserObject(name, parameters), ZeroInterface(parameters), _k_const(setConstRefParam("k", "thermal_conductivity")), _Cp_const(setConstRefParam("Cp", "specific_heat")), _rho_const(setConstRefParam("rho", "density")), _k(_k_const==0 ? &getFunctionByName(getParam<std::string>("k")) : NULL), _Cp(_Cp_const==0 ? &getFunctionByName(getParam<std::string>("Cp")) : NULL), _rho(_rho_const==0 ? &getFunctionByName(getParam<std::string>("rho")) : NULL) { mooseAssert(_k || _k_const != 0, "Thermal conductivity should never be zero"); mooseAssert(_Cp || _Cp_const != 0, "Specific heat should never be zero"); mooseAssert(_rho || _rho_const != 0, "Density should never be zero"); } SolidMaterialProperties::~SolidMaterialProperties() { } void SolidMaterialProperties::initialize() { } void SolidMaterialProperties::execute() { } void SolidMaterialProperties::finalize() { } Real SolidMaterialProperties::k(Real temp) const { if (_k != NULL) return _k->value(temp, Point()); else return _k_const; } Real SolidMaterialProperties::Cp(Real temp) const { if (_Cp != NULL) return _Cp->value(temp, Point()); else return _Cp_const; } Real SolidMaterialProperties::rho(Real temp) const { if (_rho != NULL) return _rho->value(temp, Point()); else return _rho_const; } const Real & SolidMaterialProperties::setConstRefParam(std::string get_string, std::string set_string) { std::string s = getParam<std::string>(get_string); if (isNumber(s)) { this->parameters().set<Real>(set_string) = toNumber(s); return getParam<Real>(set_string); } else { // We won't be using whatever the value of _XYZ_const is, so set // the reference value to _real_zero return _real_zero; } } <commit_msg>Set parameters in SolidMaterialProperties via the InputParameterWarehouse.<commit_after>#include "SolidMaterialProperties.h" #include "R7Conversion.h" template<> InputParameters validParams<SolidMaterialProperties>() { InputParameters params = validParams<GeneralUserObject>(); params.addParam<std::string>("k", "Thermal conductivity"); params.addParam<std::string>("Cp", "Specific heat"); params.addParam<std::string>("rho", "Density"); // These are here so we are able to control these values params.addPrivateParam<Real>("thermal_conductivity", 0.0); params.addPrivateParam<Real>("specific_heat", 0.0); params.addPrivateParam<Real>("density", 0.0); params.addPrivateParam<MultiMooseEnum>("execute_on"); params.addPrivateParam<bool>("use_displaced_mesh"); params.registerBase("MaterialProperties"); return params; } SolidMaterialProperties::SolidMaterialProperties(const std::string & name, InputParameters parameters) : GeneralUserObject(name, parameters), ZeroInterface(parameters), _k_const(setConstRefParam("k", "thermal_conductivity")), _Cp_const(setConstRefParam("Cp", "specific_heat")), _rho_const(setConstRefParam("rho", "density")), _k(_k_const==0 ? &getFunctionByName(getParam<std::string>("k")) : NULL), _Cp(_Cp_const==0 ? &getFunctionByName(getParam<std::string>("Cp")) : NULL), _rho(_rho_const==0 ? &getFunctionByName(getParam<std::string>("rho")) : NULL) { mooseAssert(_k || _k_const != 0, "Thermal conductivity should never be zero"); mooseAssert(_Cp || _Cp_const != 0, "Specific heat should never be zero"); mooseAssert(_rho || _rho_const != 0, "Density should never be zero"); } SolidMaterialProperties::~SolidMaterialProperties() { } void SolidMaterialProperties::initialize() { } void SolidMaterialProperties::execute() { } void SolidMaterialProperties::finalize() { } Real SolidMaterialProperties::k(Real temp) const { if (_k != NULL) return _k->value(temp, Point()); else return _k_const; } Real SolidMaterialProperties::Cp(Real temp) const { if (_Cp != NULL) return _Cp->value(temp, Point()); else return _Cp_const; } Real SolidMaterialProperties::rho(Real temp) const { if (_rho != NULL) return _rho->value(temp, Point()); else return _rho_const; } const Real & SolidMaterialProperties::setConstRefParam(std::string get_string, std::string set_string) { std::string s = getParam<std::string>(get_string); if (isNumber(s)) { InputParameters & params = _app.getInputParameterWarehouse().getInputParameters(getParam<std::string>("name"), _tid); params.set<Real>(set_string) = toNumber(s); return getParam<Real>(set_string); } else { // We won't be using whatever the value of _XYZ_const is, so set // the reference value to _real_zero return _real_zero; } } <|endoftext|>
<commit_before>/* * Copyright 2015 BrewPi / Elco Jacobs, Matthew McGowan. * * This file is part of BrewPi. * * BrewPi is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * BrewPi 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 BrewPi. If not, see <http://www.gnu.org/licenses/>. */ #include "Brewpi.h" #include "Platform.h" #include "fixstl.h" #include <algorithm> #include "startup_screen.h" #include "../BrewPiTouch/BrewPiTouch.h" #include "UI.h" #include "UIController.h" D4D_EXTERN_SCREEN(screen_startup); class StartupScreenModel { uint32_t timer; bool touched_flag; uint8_t fade_color; public: void start() { timer = millis(); touched_flag = false; fade_color = 255; } uint32_t elapsed() { return millis()-timer; } bool timeout() { return elapsed()>4500; } bool touched() { return touched_flag; } void flagTouched() { touched_flag = true; } bool fadeColorUpdate(uint8_t newColor) { bool changed = newColor!=fade_color; fade_color = newColor; return changed; } uint8_t fadeColor() { return fade_color; } }; // really would have liked to have this on the stack, but can't with re-entrant coding model. StartupScreenModel model; extern BrewPiTouch touch; void ScrStartup_OnInit() { } void ScrStartup_OnMain() { uint32_t elapsed = model.elapsed(); if (elapsed>2000) { if (model.fadeColorUpdate(min(255lu, ((elapsed-2000)*255)/(3000)))) { uint8_t c = model.fadeColor(); scrStartup_version.clrScheme->fore = D4D_COLOR_RGB(c,c,c); D4D_InvalidateObject(&scrStartup_version, D4D_FALSE); } } if (model.timeout() || model.touched()) uiController.notifyStartupComplete(); } void ScrStartup_OnActivate() { model.start(); touch.setStabilityThreshold(16000); // set to high Threshold to disable filter } void ScrStartup_OnDeactivate() { if (model.touched()){ touch.setStabilityThreshold(5); // require extra stable reading calibrateTouchScreen(); } touch.setStabilityThreshold(); // reset to default } Byte ScrStartup_OnObjectMsg(D4D_MESSAGE* pMsg) { if (pMsg->nMsgId==D4D_MSG_TOUCHED) model.flagTouched(); return 0; } <commit_msg>removes dependency on BrewpiTouch for cross compile<commit_after>/* * Copyright 2015 BrewPi / Elco Jacobs, Matthew McGowan. * * This file is part of BrewPi. * * BrewPi is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * BrewPi 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 BrewPi. If not, see <http://www.gnu.org/licenses/>. */ #include "Brewpi.h" #include "Platform.h" #include "fixstl.h" #include <algorithm> #include "startup_screen.h" #include "../BrewPiTouch/BrewPiTouch.h" #include "UI.h" #include "UIController.h" #include "d4dtch_tsc2046_brewpi_cfg.h" D4D_EXTERN_SCREEN(screen_startup); class StartupScreenModel { uint32_t timer; bool touched_flag; uint8_t fade_color; public: void start() { timer = millis(); touched_flag = false; fade_color = 255; } uint32_t elapsed() { return millis()-timer; } bool timeout() { return elapsed()>4500; } bool touched() { return touched_flag; } void flagTouched() { touched_flag = true; } bool fadeColorUpdate(uint8_t newColor) { bool changed = newColor!=fade_color; fade_color = newColor; return changed; } uint8_t fadeColor() { return fade_color; } }; // really would have liked to have this on the stack, but can't with re-entrant coding model. StartupScreenModel model; extern BrewPiTouch touch; void ScrStartup_OnInit() { } void ScrStartup_OnMain() { uint32_t elapsed = model.elapsed(); if (elapsed>2000) { if (model.fadeColorUpdate(min(255lu, ((elapsed-2000)*255)/(3000)))) { uint8_t c = model.fadeColor(); scrStartup_version.clrScheme->fore = D4D_COLOR_RGB(c,c,c); D4D_InvalidateObject(&scrStartup_version, D4D_FALSE); } } if (model.timeout() || model.touched()) uiController.notifyStartupComplete(); } void ScrStartup_OnActivate() { model.start(); // would ideally like to make this conditional on using the brewpi touch driver #if PLATFORM_ID!=3 touch.setStabilityThreshold(16000); // set to high Threshold to disable filter #endif } void ScrStartup_OnDeactivate() { if (model.touched()){ #if PLATFORM_ID!=3 touch.setStabilityThreshold(5); // require extra stable reading #endif calibrateTouchScreen(); } #if PLATFORM_ID!=3 touch.setStabilityThreshold(); // reset to default #endif } Byte ScrStartup_OnObjectMsg(D4D_MESSAGE* pMsg) { if (pMsg->nMsgId==D4D_MSG_TOUCHED) model.flagTouched(); return 0; } <|endoftext|>
<commit_before>#include "layouter.h" #include "utf-8.h" #include <harfbuzz/hb.h> #include <harfbuzz/hb-ft.h> #include <fribidi/fribidi.h> #include <linebreak.h> #include <vector> #include <string> #include <memory> #include <algorithm> typedef struct { std::vector<textLayout_c::commandData> run; int dx, dy; FriBidiLevel embeddingLevel; char linebreak; std::shared_ptr<fontFace_c> font; #ifdef _DEBUG_ std::u32string text; #endif } runInfo; // TODO create a sharing structure, where we only // define structures for each configuration once // and link to it // but for now it is good as it is typedef struct { uint8_t r, g, b; std::shared_ptr<fontFace_c> font; std::string lang; } codepointAttributes; FriBidiLevel getBidiEmbeddingLevels(const std::u32string & txt32, std::vector<FriBidiLevel> & embedding_levels) { std::vector<FriBidiCharType> bidiTypes(txt32.length()); fribidi_get_bidi_types((uint32_t*)txt32.c_str(), txt32.length(), bidiTypes.data()); FriBidiParType base_dir = FRIBIDI_TYPE_LTR_VAL; // TODO depends on main script of text embedding_levels.resize(txt32.length()); FriBidiLevel max_level = fribidi_get_par_embedding_levels(bidiTypes.data(), txt32.length(), &base_dir, embedding_levels.data()); return max_level; } textLayout_c layoutParagraph(const std::u32string & txt32, const std::vector<codepointAttributes> & attr, const shape_c & shape, const std::string & align) { // calculate embedding types for the text std::vector<FriBidiLevel> embedding_levels; FriBidiLevel max_level = getBidiEmbeddingLevels(txt32, embedding_levels); // calculate the possible linebreak positions std::vector<char> linebreaks(txt32.length()); set_linebreaks_utf32((utf32_t*)txt32.c_str(), txt32.length(), "", linebreaks.data()); // Get our harfbuzz font structs, TODO we need to do that for all the fonts std::map<const std::shared_ptr<fontFace_c>, hb_font_t *> hb_ft_fonts; for (const auto & a : attr) { if (hb_ft_fonts.find(a.font) == hb_ft_fonts.end()) { hb_ft_fonts[a.font] = hb_ft_font_create(a.font->getFace(), NULL); } } // Create a buffer for harfbuzz to use hb_buffer_t *buf = hb_buffer_create(); std::string lan = attr[0].lang.substr(0, 2); std::string s = attr[0].lang.substr(3, 4); hb_script_t scr = hb_script_from_iso15924_tag(HB_TAG(s[0], s[1], s[2], s[3])); hb_buffer_set_script(buf, scr); // TODO must come either from text or from rules hb_buffer_set_language(buf, hb_language_from_string(lan.c_str(), lan.length())); size_t runstart = 0; std::vector<runInfo> runs; while (runstart < txt32.length()) { size_t spos = runstart+1; // find end of current run while ( (spos < txt32.length()) && (embedding_levels[runstart] == embedding_levels[spos]) && (attr[runstart].font == attr[spos].font) && ( (linebreaks[spos-1] == LINEBREAK_NOBREAK) || (linebreaks[spos-1] == LINEBREAK_INSIDEACHAR) ) ) { spos++; } hb_buffer_add_utf32(buf, ((uint32_t*)txt32.c_str())+runstart, spos-runstart, 0, spos-runstart); if (embedding_levels[runstart] % 2 == 0) { hb_buffer_set_direction(buf, HB_DIRECTION_LTR); } else { hb_buffer_set_direction(buf, HB_DIRECTION_RTL); } hb_shape(hb_ft_fonts[attr[runstart].font], buf, NULL, 0); unsigned int glyph_count; hb_glyph_info_t *glyph_info = hb_buffer_get_glyph_infos(buf, &glyph_count); hb_glyph_position_t *glyph_pos = hb_buffer_get_glyph_positions(buf, &glyph_count); runInfo run; run.dx = run.dy = 0; run.embeddingLevel = embedding_levels[runstart]; run.linebreak = linebreaks[spos-1]; run.font = attr[runstart].font; #ifdef _DEBUG_ run.text = txt32.substr(runstart, spos-runstart); #endif for (size_t j=0; j < glyph_count; ++j) { textLayout_c::commandData g; g.glyphIndex = glyph_info[j].codepoint; g.font = attr[runstart].font; // TODO the other parameters g.x = run.dx + (glyph_pos[j].x_offset/64); g.y = run.dy - (glyph_pos[j].y_offset/64); run.dx += glyph_pos[j].x_advance/64; run.dy -= glyph_pos[j].y_advance/64; g.r = attr[glyph_info[j].cluster + runstart].r; g.g = attr[glyph_info[j].cluster + runstart].g; g.b = attr[glyph_info[j].cluster + runstart].b; g.command = textLayout_c::commandData::CMD_GLYPH; run.run.push_back(g); } runs.push_back(run); runstart = spos; hb_buffer_reset(buf); } hb_buffer_destroy(buf); for (auto & a : hb_ft_fonts) hb_font_destroy(a.second); std::vector<size_t> runorder(runs.size()); int n(0); std::generate(runorder.begin(), runorder.end(), [&]{ return n++; }); // layout a run // TODO take care of different font sizes of the different runs runstart = 0; int32_t ypos = 0; textLayout_c l; while (runstart < runs.size()) { int32_t curAscend = runs[runstart].font->getAscender()/64; int32_t curDescend = runs[runstart].font->getDescender()/64; uint32_t curWidth = runs[runstart].dx; size_t spos = runstart + 1; while (spos < runs.size()) { // check, if we can add another run // TODO keep non break runs in mind // TODO take properly care of spaces at the end of lines (they must be left out) int32_t newAscend = std::max(curAscend, runs[spos].font->getAscender()/64); int32_t newDescend = std::min(curDescend, runs[spos].font->getDescender()/64); uint32_t newWidth = curWidth + runs[spos].dx; if (shape.getLeft(ypos, ypos+newAscend-newDescend)+newWidth > shape.getRight(ypos, ypos+newAscend-newDescend)) { // next run would overrun break; } // additional run fits curAscend = newAscend; curDescend = newDescend; curWidth = newWidth; spos++; } // reorder runs for current line for (int i = max_level-1; i >= 0; i--) { // find starts of regions to reverse for (size_t j = runstart; j < spos; j++) { if (runs[runorder[j]].embeddingLevel > i) { // find the end of the current regions size_t k = j+1; while (k < spos && runs[runorder[k]].embeddingLevel > i) { k++; } std::reverse(runorder.begin()+j, runorder.begin()+k); j = k; } } } int32_t spaceLeft = shape.getRight(ypos, ypos+curAscend-curDescend) - shape.getLeft(ypos, ypos+curAscend-curDescend); spaceLeft -= curWidth; int32_t xpos; double spaceadder = 0; if (align == "left") { xpos = shape.getLeft(ypos, ypos+curAscend-curDescend); } else if (align == "right") { xpos = shape.getLeft(ypos, ypos+curAscend-curDescend) + spaceLeft; } else if (align == "center") { xpos = shape.getLeft(ypos, ypos+curAscend-curDescend) + spaceLeft/2; } else if (align == "justify") { xpos = shape.getLeft(ypos, ypos+curAscend-curDescend); // don't justify last paragraph if (spos-runstart > 1 && spos < runs.size()) spaceadder = 1.0 * spaceLeft / (spos-runstart - 1); } ypos += curAscend; for (size_t i = runstart; i < spos; i++) { l.addCommandVector(runs[runorder[i]].run, xpos+spaceadder*(i-runstart), ypos); xpos += runs[runorder[i]].dx; } ypos -= curDescend; runstart = spos; } // TODO proper font handling for multiple fonts in a line l.setHeight(ypos); return l; } static std::string normalizeHTML(const std::string & in, char prev) { std::string out; for (auto a : in) { if (a == '\n' || a == '\r') a = ' '; if (a != ' ' || prev != ' ') out += a; prev = a; } return out; } void layoutXML_text(pugi::xml_node xml, const textStyleSheet_c & rules, std::u32string & txt, std::vector<codepointAttributes> & attr) { for (const auto & i : xml) { if (i.type() == pugi::node_pcdata) { if (txt.length() == 0) txt = u8_convertToU32(normalizeHTML(i.value(), ' ')); else txt += u8_convertToU32(normalizeHTML(i.value(), txt[txt.length()-1])); codepointAttributes a; evalColor(rules.getValue(xml, "color"), a.r, a.g, a.b); std::string fontFamily = rules.getValue(xml, "font-family"); std::string fontStyle = rules.getValue(xml, "font-style"); std::string fontVariant = rules.getValue(xml, "font-variant"); std::string fontWeight = rules.getValue(xml, "font-weight"); double fontSize = evalSize(rules.getValue(xml, "font-size")); a.font = rules.findFamily(fontFamily)->getFont(64*fontSize, fontStyle, fontVariant, fontWeight); a.lang = "en-eng"; while (attr.size() < txt.length()) attr.push_back(a); } else if ( (i.type() == pugi::node_element) && ( (std::string("i") == i.name()) || (std::string("div") == i.name()) ) ) { layoutXML_text(i, rules, txt, attr); } } } // this whole stuff is a recursive descending parser of the XHTML stuff textLayout_c layoutXML_P(const pugi::xml_node & xml, const textStyleSheet_c & rules, const shape_c & shape) { std::u32string txt; std::vector<codepointAttributes> attr; layoutXML_text(xml, rules, txt, attr); return layoutParagraph(txt, attr, shape, rules.getValue(xml, "text-align")); } textLayout_c layoutXML_BODY(const pugi::xml_node & txt, const textStyleSheet_c & rules, const shape_c & shape) { textLayout_c l; for (const auto & i : txt) { if ( (i.type() == pugi::node_element) && ( (std::string("p") == i.name()) || (std::string("h1") == i.name()) || (std::string("h2") == i.name()) || (std::string("h3") == i.name()) || (std::string("h4") == i.name()) || (std::string("h5") == i.name()) || (std::string("h6") == i.name()) ) ) { // TODO rahmen und anderes beachten l.append(layoutXML_P(i, rules, shape), 0, l.getHeight()); } else if (i.type() == pugi::node_element && std::string("table") == i.name()) { } else { // TODO exception nothing else supported } } return l; } textLayout_c layoutXML_HTML(const pugi::xml_node & txt, const textStyleSheet_c & rules, const shape_c & shape) { textLayout_c l; bool headfound = false; bool bodyfound = false; for (const auto & i : txt) { if (std::string("head") == i.name() && !headfound) { headfound = true; } else if (std::string("body") == i.name() && !bodyfound) { bodyfound = true; l = layoutXML_BODY(i, rules, shape); } else { // nothing else permitted -> exception TODO } } return l; } textLayout_c layoutXML(const pugi::xml_document & txt, const textStyleSheet_c & rules, const shape_c & shape) { textLayout_c l; // we must have a HTML root node for (const auto & i : txt) { if (std::string("html") == i.name()) { l = layoutXML_HTML(i, rules, shape); } else { // nothing else permitted -> exception TODO } } return l; } textLayout_c layoutXHTML(const std::string & txt, const textStyleSheet_c & rules, const shape_c & shape) { pugi::xml_document doc; // TODO preprocess to get rid of linebreaks and multiple spaces // TODO handle parser errors doc.load_buffer(txt.c_str(), txt.length()); return layoutXML(doc, rules, shape); } textLayout_c layoutRaw(const std::string & txt, const std::shared_ptr<fontFace_c> font, const shape_c & shape, const std::string & language) { // when we layout raw text we // only have to convert the text to utf-32 // and assign the given font and language to all the codepoints of that text std::u32string txt32 = u8_convertToU32(txt); std::vector<codepointAttributes> attr(txt32.size()); for (auto & i : attr) { i.r = i.g = i.b = 255; i.font = font; i.lang = language; } return layoutParagraph(txt32, attr, shape, "left"); } <commit_msg>only break lines where allowed<commit_after>#include "layouter.h" #include "utf-8.h" #include <harfbuzz/hb.h> #include <harfbuzz/hb-ft.h> #include <fribidi/fribidi.h> #include <linebreak.h> #include <vector> #include <string> #include <memory> #include <algorithm> typedef struct { std::vector<textLayout_c::commandData> run; int dx, dy; FriBidiLevel embeddingLevel; char linebreak; std::shared_ptr<fontFace_c> font; #ifdef _DEBUG_ std::u32string text; #endif } runInfo; // TODO create a sharing structure, where we only // define structures for each configuration once // and link to it // but for now it is good as it is typedef struct { uint8_t r, g, b; std::shared_ptr<fontFace_c> font; std::string lang; } codepointAttributes; FriBidiLevel getBidiEmbeddingLevels(const std::u32string & txt32, std::vector<FriBidiLevel> & embedding_levels) { std::vector<FriBidiCharType> bidiTypes(txt32.length()); fribidi_get_bidi_types((uint32_t*)txt32.c_str(), txt32.length(), bidiTypes.data()); FriBidiParType base_dir = FRIBIDI_TYPE_LTR_VAL; // TODO depends on main script of text embedding_levels.resize(txt32.length()); FriBidiLevel max_level = fribidi_get_par_embedding_levels(bidiTypes.data(), txt32.length(), &base_dir, embedding_levels.data()); return max_level; } textLayout_c layoutParagraph(const std::u32string & txt32, const std::vector<codepointAttributes> & attr, const shape_c & shape, const std::string & align) { // calculate embedding types for the text std::vector<FriBidiLevel> embedding_levels; FriBidiLevel max_level = getBidiEmbeddingLevels(txt32, embedding_levels); // calculate the possible linebreak positions std::vector<char> linebreaks(txt32.length()); set_linebreaks_utf32((utf32_t*)txt32.c_str(), txt32.length(), "", linebreaks.data()); // Get our harfbuzz font structs, TODO we need to do that for all the fonts std::map<const std::shared_ptr<fontFace_c>, hb_font_t *> hb_ft_fonts; for (const auto & a : attr) { if (hb_ft_fonts.find(a.font) == hb_ft_fonts.end()) { hb_ft_fonts[a.font] = hb_ft_font_create(a.font->getFace(), NULL); } } // Create a buffer for harfbuzz to use hb_buffer_t *buf = hb_buffer_create(); std::string lan = attr[0].lang.substr(0, 2); std::string s = attr[0].lang.substr(3, 4); hb_script_t scr = hb_script_from_iso15924_tag(HB_TAG(s[0], s[1], s[2], s[3])); hb_buffer_set_script(buf, scr); // TODO must come either from text or from rules hb_buffer_set_language(buf, hb_language_from_string(lan.c_str(), lan.length())); size_t runstart = 0; std::vector<runInfo> runs; while (runstart < txt32.length()) { size_t spos = runstart+1; // find end of current run while ( (spos < txt32.length()) && (embedding_levels[runstart] == embedding_levels[spos]) && (attr[runstart].font == attr[spos].font) && ( (linebreaks[spos-1] == LINEBREAK_NOBREAK) || (linebreaks[spos-1] == LINEBREAK_INSIDEACHAR) ) ) { spos++; } hb_buffer_add_utf32(buf, ((uint32_t*)txt32.c_str())+runstart, spos-runstart, 0, spos-runstart); if (embedding_levels[runstart] % 2 == 0) { hb_buffer_set_direction(buf, HB_DIRECTION_LTR); } else { hb_buffer_set_direction(buf, HB_DIRECTION_RTL); } hb_shape(hb_ft_fonts[attr[runstart].font], buf, NULL, 0); unsigned int glyph_count; hb_glyph_info_t *glyph_info = hb_buffer_get_glyph_infos(buf, &glyph_count); hb_glyph_position_t *glyph_pos = hb_buffer_get_glyph_positions(buf, &glyph_count); runInfo run; run.dx = run.dy = 0; run.embeddingLevel = embedding_levels[runstart]; run.linebreak = linebreaks[spos-1]; run.font = attr[runstart].font; #ifdef _DEBUG_ run.text = txt32.substr(runstart, spos-runstart); #endif for (size_t j=0; j < glyph_count; ++j) { textLayout_c::commandData g; g.glyphIndex = glyph_info[j].codepoint; g.font = attr[runstart].font; // TODO the other parameters g.x = run.dx + (glyph_pos[j].x_offset/64); g.y = run.dy - (glyph_pos[j].y_offset/64); run.dx += glyph_pos[j].x_advance/64; run.dy -= glyph_pos[j].y_advance/64; g.r = attr[glyph_info[j].cluster + runstart].r; g.g = attr[glyph_info[j].cluster + runstart].g; g.b = attr[glyph_info[j].cluster + runstart].b; g.command = textLayout_c::commandData::CMD_GLYPH; run.run.push_back(g); } runs.push_back(run); runstart = spos; hb_buffer_reset(buf); } hb_buffer_destroy(buf); for (auto & a : hb_ft_fonts) hb_font_destroy(a.second); std::vector<size_t> runorder(runs.size()); int n(0); std::generate(runorder.begin(), runorder.end(), [&]{ return n++; }); // layout a run // TODO take care of different font sizes of the different runs runstart = 0; int32_t ypos = 0; textLayout_c l; while (runstart < runs.size()) { int32_t curAscend = 0; int32_t curDescend = 0; uint32_t curWidth = 0; size_t spos = runstart; // add runs until we run out of runs while (spos < runs.size()) { // check, if we can add another run // TODO keep non break runs in mind // TODO take properly care of spaces at the end of lines (they must be left out) int32_t newAscend = curAscend; int32_t newDescend = curDescend; uint32_t newWidth = curWidth; size_t newspos = spos; while (newspos < runs.size()) { newAscend = std::max(newAscend, runs[newspos].font->getAscender()/64); newDescend = std::min(newDescend, runs[newspos].font->getDescender()/64); newWidth += runs[newspos].dx; if ( (runs[newspos].linebreak == LINEBREAK_ALLOWBREAK) || (runs[newspos].linebreak == LINEBREAK_MUSTBREAK) ) break; newspos++; } newspos++; if (spos > runstart && shape.getLeft(ypos, ypos+newAscend-newDescend)+newWidth > shape.getRight(ypos, ypos+newAscend-newDescend)) { // next run would overrun break; } // additional run fits curAscend = newAscend; curDescend = newDescend; curWidth = newWidth; spos = newspos; } // reorder runs for current line for (int i = max_level-1; i >= 0; i--) { // find starts of regions to reverse for (size_t j = runstart; j < spos; j++) { if (runs[runorder[j]].embeddingLevel > i) { // find the end of the current regions size_t k = j+1; while (k < spos && runs[runorder[k]].embeddingLevel > i) { k++; } std::reverse(runorder.begin()+j, runorder.begin()+k); j = k; } } } int32_t spaceLeft = shape.getRight(ypos, ypos+curAscend-curDescend) - shape.getLeft(ypos, ypos+curAscend-curDescend); spaceLeft -= curWidth; int32_t xpos; double spaceadder = 0; if (align == "left") { xpos = shape.getLeft(ypos, ypos+curAscend-curDescend); } else if (align == "right") { xpos = shape.getLeft(ypos, ypos+curAscend-curDescend) + spaceLeft; } else if (align == "center") { xpos = shape.getLeft(ypos, ypos+curAscend-curDescend) + spaceLeft/2; } else if (align == "justify") { xpos = shape.getLeft(ypos, ypos+curAscend-curDescend); // don't justify last paragraph if (spos-runstart > 1 && spos < runs.size()) spaceadder = 1.0 * spaceLeft / (spos-runstart - 1); } ypos += curAscend; for (size_t i = runstart; i < spos; i++) { l.addCommandVector(runs[runorder[i]].run, xpos+spaceadder*(i-runstart), ypos); xpos += runs[runorder[i]].dx; } ypos -= curDescend; runstart = spos; } // TODO proper font handling for multiple fonts in a line l.setHeight(ypos); return l; } static std::string normalizeHTML(const std::string & in, char prev) { std::string out; for (auto a : in) { if (a == '\n' || a == '\r') a = ' '; if (a != ' ' || prev != ' ') out += a; prev = a; } return out; } void layoutXML_text(pugi::xml_node xml, const textStyleSheet_c & rules, std::u32string & txt, std::vector<codepointAttributes> & attr) { for (const auto & i : xml) { if (i.type() == pugi::node_pcdata) { if (txt.length() == 0) txt = u8_convertToU32(normalizeHTML(i.value(), ' ')); else txt += u8_convertToU32(normalizeHTML(i.value(), txt[txt.length()-1])); codepointAttributes a; evalColor(rules.getValue(xml, "color"), a.r, a.g, a.b); std::string fontFamily = rules.getValue(xml, "font-family"); std::string fontStyle = rules.getValue(xml, "font-style"); std::string fontVariant = rules.getValue(xml, "font-variant"); std::string fontWeight = rules.getValue(xml, "font-weight"); double fontSize = evalSize(rules.getValue(xml, "font-size")); a.font = rules.findFamily(fontFamily)->getFont(64*fontSize, fontStyle, fontVariant, fontWeight); a.lang = "en-eng"; while (attr.size() < txt.length()) attr.push_back(a); } else if ( (i.type() == pugi::node_element) && ( (std::string("i") == i.name()) || (std::string("div") == i.name()) ) ) { layoutXML_text(i, rules, txt, attr); } } } // this whole stuff is a recursive descending parser of the XHTML stuff textLayout_c layoutXML_P(const pugi::xml_node & xml, const textStyleSheet_c & rules, const shape_c & shape) { std::u32string txt; std::vector<codepointAttributes> attr; layoutXML_text(xml, rules, txt, attr); return layoutParagraph(txt, attr, shape, rules.getValue(xml, "text-align")); } textLayout_c layoutXML_BODY(const pugi::xml_node & txt, const textStyleSheet_c & rules, const shape_c & shape) { textLayout_c l; for (const auto & i : txt) { if ( (i.type() == pugi::node_element) && ( (std::string("p") == i.name()) || (std::string("h1") == i.name()) || (std::string("h2") == i.name()) || (std::string("h3") == i.name()) || (std::string("h4") == i.name()) || (std::string("h5") == i.name()) || (std::string("h6") == i.name()) ) ) { // TODO rahmen und anderes beachten l.append(layoutXML_P(i, rules, shape), 0, l.getHeight()); } else if (i.type() == pugi::node_element && std::string("table") == i.name()) { } else { // TODO exception nothing else supported } } return l; } textLayout_c layoutXML_HTML(const pugi::xml_node & txt, const textStyleSheet_c & rules, const shape_c & shape) { textLayout_c l; bool headfound = false; bool bodyfound = false; for (const auto & i : txt) { if (std::string("head") == i.name() && !headfound) { headfound = true; } else if (std::string("body") == i.name() && !bodyfound) { bodyfound = true; l = layoutXML_BODY(i, rules, shape); } else { // nothing else permitted -> exception TODO } } return l; } textLayout_c layoutXML(const pugi::xml_document & txt, const textStyleSheet_c & rules, const shape_c & shape) { textLayout_c l; // we must have a HTML root node for (const auto & i : txt) { if (std::string("html") == i.name()) { l = layoutXML_HTML(i, rules, shape); } else { // nothing else permitted -> exception TODO } } return l; } textLayout_c layoutXHTML(const std::string & txt, const textStyleSheet_c & rules, const shape_c & shape) { pugi::xml_document doc; // TODO preprocess to get rid of linebreaks and multiple spaces // TODO handle parser errors doc.load_buffer(txt.c_str(), txt.length()); return layoutXML(doc, rules, shape); } textLayout_c layoutRaw(const std::string & txt, const std::shared_ptr<fontFace_c> font, const shape_c & shape, const std::string & language) { // when we layout raw text we // only have to convert the text to utf-32 // and assign the given font and language to all the codepoints of that text std::u32string txt32 = u8_convertToU32(txt); std::vector<codepointAttributes> attr(txt32.size()); for (auto & i : attr) { i.r = i.g = i.b = 255; i.font = font; i.lang = language; } return layoutParagraph(txt32, attr, shape, "left"); } <|endoftext|>
<commit_before>/**************************************************************************** ** ** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). ** All rights reserved. ** Contact: Nokia Corporation (qt-info@nokia.com) ** ** This file is part of the Qt 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 qt-info@nokia.com. ** ** ** ** ** ** ** ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #include "s60audioencodercontrol.h" #include "s60audiocapturesession.h" #include <QAudioFormat> #include <QtCore/qdebug.h> S60AudioEncoderControl::S60AudioEncoderControl(QObject *session, QObject *parent) :QAudioEncoderControl(parent), m_quality(QtMultimedia::NormalQuality) { m_session = qobject_cast<S60AudioCaptureSession*>(session); QAudioFormat fmt = m_session->format(); // medium, 22050Hz mono S16 fmt.setSampleType(QAudioFormat::SignedInt); fmt.setSampleSize(16); fmt.setFrequency(22050); fmt.setChannels(1); m_session->setFormat(fmt); } S60AudioEncoderControl::~S60AudioEncoderControl() { } QStringList S60AudioEncoderControl::supportedAudioCodecs() const { return m_session->supportedAudioCodecs(); } QString S60AudioEncoderControl::codecDescription(const QString &codecName) const { return m_session->codecDescription(codecName); } QtMultimedia::EncodingQuality S60AudioEncoderControl::quality() const { return m_quality; } void S60AudioEncoderControl::setQuality(QtMultimedia::EncodingQuality value) { QAudioFormat fmt = m_session->format(); switch (value) { case QtMultimedia::VeryLowQuality: case QtMultimedia::LowQuality: // low, 8000Hz mono U8 fmt.setSampleType(QAudioFormat::UnSignedInt); fmt.setSampleSize(8); fmt.setFrequency(8000); fmt.setChannels(1); break; case QtMultimedia::NormalQuality: // medium, 22050Hz mono S16 fmt.setSampleType(QAudioFormat::SignedInt); fmt.setSampleSize(16); fmt.setFrequency(22050); fmt.setChannels(1); break; case QtMultimedia::HighQuality: case QtMultimedia::VeryHighQuality: // high, 44100Hz mono S16 fmt.setSampleType(QAudioFormat::SignedInt); fmt.setSampleSize(16); fmt.setFrequency(44100); fmt.setChannels(2); break; default: break; } } QStringList S60AudioEncoderControl::supportedEncodingOptions(const QString &codec) const { Q_UNUSED(codec) QStringList list; if (codec == "PCM") list << "quality" << "channels" << "samplerate"; return list; } QVariant S60AudioEncoderControl::encodingOption(const QString &codec, const QString &name) const { if (codec == "PCM") { QAudioFormat fmt = m_session->format(); if(qstrcmp(name.toLocal8Bit().constData(), "quality") == 0) { return QVariant(quality()); } else if(qstrcmp(name.toLocal8Bit().constData(), "channels") == 0) { return QVariant(fmt.channels()); } else if(qstrcmp(name.toLocal8Bit().constData(), "samplerate") == 0) { return QVariant(fmt.frequency()); } } return QVariant(); } void S60AudioEncoderControl::setEncodingOption( const QString &codec, const QString &name, const QVariant &value) { if (codec == "PCM") { QAudioFormat fmt = m_session->format(); if(qstrcmp(name.toLocal8Bit().constData(), "quality") == 0) { setQuality((QtMultimedia::EncodingQuality)value.toInt(), fmt); } else if(qstrcmp(name.toLocal8Bit().constData(), "channels") == 0) { fmt.setChannels(value.toInt()); } else if(qstrcmp(name.toLocal8Bit().constData(), "samplerate") == 0) { fmt.setFrequency(value.toInt()); } m_session->setFormat(fmt); } } QList<int> S60AudioEncoderControl::supportedSampleRates(const QAudioEncoderSettings &settings, bool *continuous) const { if (continuous) *continuous = false; return m_session->supportedAudioSampleRates(settings); } QAudioEncoderSettings S60AudioEncoderControl::audioSettings() const { return m_settings; } void S60AudioEncoderControl::setAudioSettings(const QAudioEncoderSettings &settings) { QAudioFormat fmt = m_session->format(); if (settings.encodingMode() == QtMultimedia::ConstantQualityEncoding) { fmt.setCodec(settings.codec()); setQuality(settings.quality(), fmt); if (settings.sampleRate() > 0) { fmt.setFrequency(settings.sampleRate()); } if (settings.channelCount() > 0) fmt.setChannels(settings.channelCount()); }else { if (settings.sampleRate() == 8000) { fmt.setSampleType(QAudioFormat::UnSignedInt); fmt.setSampleSize(8); } else { fmt.setSampleType(QAudioFormat::SignedInt); fmt.setSampleSize(16); } fmt.setCodec(settings.codec()); fmt.setFrequency(settings.sampleRate()); fmt.setChannels(settings.channelCount()); } m_session->setFormat(fmt); m_settings = settings; } <commit_msg>symbian: fix compile<commit_after>/**************************************************************************** ** ** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). ** All rights reserved. ** Contact: Nokia Corporation (qt-info@nokia.com) ** ** This file is part of the Qt 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 qt-info@nokia.com. ** ** ** ** ** ** ** ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #include "s60audioencodercontrol.h" #include "s60audiocapturesession.h" #include <QAudioFormat> #include <QtCore/qdebug.h> S60AudioEncoderControl::S60AudioEncoderControl(QObject *session, QObject *parent) :QAudioEncoderControl(parent), m_quality(QtMultimedia::NormalQuality) { m_session = qobject_cast<S60AudioCaptureSession*>(session); QAudioFormat fmt = m_session->format(); // medium, 22050Hz mono S16 fmt.setSampleType(QAudioFormat::SignedInt); fmt.setSampleSize(16); fmt.setFrequency(22050); fmt.setChannels(1); m_session->setFormat(fmt); } S60AudioEncoderControl::~S60AudioEncoderControl() { } QStringList S60AudioEncoderControl::supportedAudioCodecs() const { return m_session->supportedAudioCodecs(); } QString S60AudioEncoderControl::codecDescription(const QString &codecName) const { return m_session->codecDescription(codecName); } QtMultimedia::EncodingQuality S60AudioEncoderControl::quality() const { return m_quality; } void S60AudioEncoderControl::setQuality(QtMultimedia::EncodingQuality value, QAudioFormat &fmt) { switch (value) { case QtMultimedia::VeryLowQuality: case QtMultimedia::LowQuality: // low, 8000Hz mono U8 fmt.setSampleType(QAudioFormat::UnSignedInt); fmt.setSampleSize(8); fmt.setFrequency(8000); fmt.setChannels(1); break; case QtMultimedia::NormalQuality: // medium, 22050Hz mono S16 fmt.setSampleType(QAudioFormat::SignedInt); fmt.setSampleSize(16); fmt.setFrequency(22050); fmt.setChannels(1); break; case QtMultimedia::HighQuality: case QtMultimedia::VeryHighQuality: // high, 44100Hz mono S16 fmt.setSampleType(QAudioFormat::SignedInt); fmt.setSampleSize(16); fmt.setFrequency(44100); fmt.setChannels(2); break; default: break; } } QStringList S60AudioEncoderControl::supportedEncodingOptions(const QString &codec) const { Q_UNUSED(codec) QStringList list; if (codec == "PCM") list << "quality" << "channels" << "samplerate"; return list; } QVariant S60AudioEncoderControl::encodingOption(const QString &codec, const QString &name) const { if (codec == "PCM") { QAudioFormat fmt = m_session->format(); if(qstrcmp(name.toLocal8Bit().constData(), "quality") == 0) { return QVariant(quality()); } else if(qstrcmp(name.toLocal8Bit().constData(), "channels") == 0) { return QVariant(fmt.channels()); } else if(qstrcmp(name.toLocal8Bit().constData(), "samplerate") == 0) { return QVariant(fmt.frequency()); } } return QVariant(); } void S60AudioEncoderControl::setEncodingOption( const QString &codec, const QString &name, const QVariant &value) { if (codec == "PCM") { QAudioFormat fmt = m_session->format(); if(qstrcmp(name.toLocal8Bit().constData(), "quality") == 0) { setQuality((QtMultimedia::EncodingQuality)value.toInt(), fmt); } else if(qstrcmp(name.toLocal8Bit().constData(), "channels") == 0) { fmt.setChannels(value.toInt()); } else if(qstrcmp(name.toLocal8Bit().constData(), "samplerate") == 0) { fmt.setFrequency(value.toInt()); } m_session->setFormat(fmt); } } QList<int> S60AudioEncoderControl::supportedSampleRates(const QAudioEncoderSettings &settings, bool *continuous) const { if (continuous) *continuous = false; return m_session->supportedAudioSampleRates(settings); } QAudioEncoderSettings S60AudioEncoderControl::audioSettings() const { return m_settings; } void S60AudioEncoderControl::setAudioSettings(const QAudioEncoderSettings &settings) { QAudioFormat fmt = m_session->format(); if (settings.encodingMode() == QtMultimedia::ConstantQualityEncoding) { fmt.setCodec(settings.codec()); setQuality(settings.quality(), fmt); if (settings.sampleRate() > 0) { fmt.setFrequency(settings.sampleRate()); } if (settings.channelCount() > 0) fmt.setChannels(settings.channelCount()); }else { if (settings.sampleRate() == 8000) { fmt.setSampleType(QAudioFormat::UnSignedInt); fmt.setSampleSize(8); } else { fmt.setSampleType(QAudioFormat::SignedInt); fmt.setSampleSize(16); } fmt.setCodec(settings.codec()); fmt.setFrequency(settings.sampleRate()); fmt.setChannels(settings.channelCount()); } m_session->setFormat(fmt); m_settings = settings; } <|endoftext|>
<commit_before>/* * libjingle * Copyright 2014 Google Inc. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * 3. The name of the author may not be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR 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. */ #if defined(LIBPEERCONNECTION_LIB) || defined(LIBPEERCONNECTION_IMPLEMENTATION) #include "talk/media/webrtc/webrtcmediaengine.h" #include "talk/media/webrtc/webrtcvideoengine.h" #include "talk/media/webrtc/webrtcvideoengine2.h" #include "talk/media/webrtc/webrtcvoiceengine.h" #include "webrtc/system_wrappers/interface/field_trial.h" namespace cricket { class WebRtcMediaEngine : public CompositeMediaEngine<WebRtcVoiceEngine, WebRtcVideoEngine> { public: WebRtcMediaEngine() {} WebRtcMediaEngine(webrtc::AudioDeviceModule* adm, webrtc::AudioDeviceModule* adm_sc, WebRtcVideoEncoderFactory* encoder_factory, WebRtcVideoDecoderFactory* decoder_factory) { voice_.SetAudioDeviceModule(adm, adm_sc); video_.SetExternalEncoderFactory(encoder_factory); video_.SetExternalDecoderFactory(decoder_factory); } }; class WebRtcMediaEngine2 : public CompositeMediaEngine<WebRtcVoiceEngine, WebRtcVideoEngine2> { public: WebRtcMediaEngine2(webrtc::AudioDeviceModule* adm, webrtc::AudioDeviceModule* adm_sc, WebRtcVideoEncoderFactory* encoder_factory, WebRtcVideoDecoderFactory* decoder_factory) { voice_.SetAudioDeviceModule(adm, adm_sc); video_.SetExternalDecoderFactory(decoder_factory); video_.SetExternalEncoderFactory(encoder_factory); } }; } // namespace cricket WRME_EXPORT cricket::MediaEngineInterface* CreateWebRtcMediaEngine( webrtc::AudioDeviceModule* adm, webrtc::AudioDeviceModule* adm_sc, cricket::WebRtcVideoEncoderFactory* encoder_factory, cricket::WebRtcVideoDecoderFactory* decoder_factory) { if (webrtc::field_trial::FindFullName("WebRTC-NewVideoAPI") == "Enabled") { return new cricket::WebRtcMediaEngine2(adm, adm_sc, encoder_factory, decoder_factory); } return new cricket::WebRtcMediaEngine(adm, adm_sc, encoder_factory, decoder_factory); } WRME_EXPORT void DestroyWebRtcMediaEngine(cricket::MediaEngineInterface* media_engine) { delete media_engine; } namespace cricket { // Used by ChannelManager when no media engine is passed in to it // explicitly (acts as a default). MediaEngineInterface* WebRtcMediaEngineFactory::Create() { return new cricket::WebRtcMediaEngine(); } // Used by PeerConnectionFactory to create a media engine passed into // ChannelManager. MediaEngineInterface* WebRtcMediaEngineFactory::Create( webrtc::AudioDeviceModule* adm, webrtc::AudioDeviceModule* adm_sc, WebRtcVideoEncoderFactory* encoder_factory, WebRtcVideoDecoderFactory* decoder_factory) { return CreateWebRtcMediaEngine(adm, adm_sc, encoder_factory, decoder_factory); } } // namespace cricket #endif // defined(LIBPEERCONNECTION_LIB) || // defined(LIBPEERCONNECTION_IMPLEMENTATION) <commit_msg>Set WebRtcVideoEngine2 as the WebRtcMediaEngine.<commit_after>/* * libjingle * Copyright 2014 Google Inc. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * 3. The name of the author may not be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR 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. */ #if defined(LIBPEERCONNECTION_LIB) || defined(LIBPEERCONNECTION_IMPLEMENTATION) #include "talk/media/webrtc/webrtcmediaengine.h" #include "talk/media/webrtc/webrtcvideoengine.h" #include "talk/media/webrtc/webrtcvideoengine2.h" #include "talk/media/webrtc/webrtcvoiceengine.h" #include "webrtc/system_wrappers/interface/field_trial.h" namespace cricket { class WebRtcMediaEngine : public CompositeMediaEngine<WebRtcVoiceEngine, WebRtcVideoEngine> { public: WebRtcMediaEngine() {} WebRtcMediaEngine(webrtc::AudioDeviceModule* adm, webrtc::AudioDeviceModule* adm_sc, WebRtcVideoEncoderFactory* encoder_factory, WebRtcVideoDecoderFactory* decoder_factory) { voice_.SetAudioDeviceModule(adm, adm_sc); video_.SetExternalEncoderFactory(encoder_factory); video_.SetExternalDecoderFactory(decoder_factory); } }; class WebRtcMediaEngine2 : public CompositeMediaEngine<WebRtcVoiceEngine, WebRtcVideoEngine2> { public: WebRtcMediaEngine2(webrtc::AudioDeviceModule* adm, webrtc::AudioDeviceModule* adm_sc, WebRtcVideoEncoderFactory* encoder_factory, WebRtcVideoDecoderFactory* decoder_factory) { voice_.SetAudioDeviceModule(adm, adm_sc); video_.SetExternalDecoderFactory(decoder_factory); video_.SetExternalEncoderFactory(encoder_factory); } }; } // namespace cricket WRME_EXPORT cricket::MediaEngineInterface* CreateWebRtcMediaEngine( webrtc::AudioDeviceModule* adm, webrtc::AudioDeviceModule* adm_sc, cricket::WebRtcVideoEncoderFactory* encoder_factory, cricket::WebRtcVideoDecoderFactory* decoder_factory) { return new cricket::WebRtcMediaEngine2(adm, adm_sc, encoder_factory, decoder_factory); } WRME_EXPORT void DestroyWebRtcMediaEngine(cricket::MediaEngineInterface* media_engine) { delete media_engine; } namespace cricket { // Used by ChannelManager when no media engine is passed in to it // explicitly (acts as a default). MediaEngineInterface* WebRtcMediaEngineFactory::Create() { return new cricket::WebRtcMediaEngine(); } // Used by PeerConnectionFactory to create a media engine passed into // ChannelManager. MediaEngineInterface* WebRtcMediaEngineFactory::Create( webrtc::AudioDeviceModule* adm, webrtc::AudioDeviceModule* adm_sc, WebRtcVideoEncoderFactory* encoder_factory, WebRtcVideoDecoderFactory* decoder_factory) { return CreateWebRtcMediaEngine(adm, adm_sc, encoder_factory, decoder_factory); } } // namespace cricket #endif // defined(LIBPEERCONNECTION_LIB) || // defined(LIBPEERCONNECTION_IMPLEMENTATION) <|endoftext|>
<commit_before>/*********************************************************************** created: Sun May 25 2014 author: Timotei Dolean *************************************************************************/ /*************************************************************************** * Copyright (C) 2004 - 2014 Paul D Turner & The CEGUI Development Team * * Permission is hereby granted, free of charge, to any person obtaining * a copy of this software and associated documentation files (the * "Software"), to deal in the Software without restriction, including * without limitation the rights to use, copy, modify, merge, publish, * distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, subject to * the following conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. * IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR * OTHER DEALINGS IN THE SOFTWARE. ***************************************************************************/ #include "ModelView.h" #include "CEGUI/CEGUI.h" #include <iostream> #include <sstream> using namespace CEGUI; ModelViewSample::ModelViewSample() { d_name = "ModelViewSample"; d_credits = "Timotei Dolean"; d_summary = ""; d_description = ""; } /** This sample uses most of the code from the 'HelloWorld' sample. Thus, most of the clarifying comments have been removed for brevity. **/ /************************************************************************* Sample specific initialisation goes here. *************************************************************************/ bool ModelViewSample::initialise(GUIContext* gui_context) { d_usedFiles = String(__FILE__); SchemeManager::getSingleton().createFromFile("TaharezLook.scheme"); SchemeManager::getSingleton().createFromFile("WindowsLook.scheme"); gui_context->getPointerIndicator().setDefaultImage("TaharezLook/MouseArrow"); WindowManager& win_mgr = WindowManager::getSingleton(); d_root = win_mgr.loadLayoutFromFile("ModelViewSample.layout"); ImageManager::getSingleton().loadImageset("DriveIcons.imageset"); Font& defaultFont = FontManager::getSingleton().createFromFile("DejaVuSans-12.font"); gui_context->setDefaultFont(&defaultFont); gui_context->setRootWindow(d_root); gui_context->setDefaultTooltipType("TaharezLook/Tooltip"); d_inventoryModel.load(); d_newItemsCount = 0; d_listView = static_cast<ListView*>(win_mgr.createWindow("TaharezLook/ListView", "listView")); d_listView->setModel(&d_inventoryModel); d_listView->setItemTooltipsEnabled(true); d_listView->setSelectionColourRect(ColourRect(Colour(1.0f, 0, 0, 1))); d_root->getChild("ListViewHolder")->addChild(d_listView); d_treeView = static_cast<TreeView*>(win_mgr.createWindow("TaharezLook/TreeView", "treeView")); d_treeView->setModel(&d_inventoryModel); d_treeView->setItemTooltipsEnabled(true); d_root->getChild("TreeViewHolder")->addChild(d_treeView); ListWidget* list_widget = static_cast<ListWidget*>(win_mgr.createWindow("TaharezLook/ListWidget", "listWidget")); d_root->getChild("ListWidgetHolder")->addChild(list_widget); initListWidgetItems(list_widget); d_root->getChild("btnAddRandomItem")->subscribeEvent(PushButton::EventClicked, Event::Subscriber(&ModelViewSample::handleAddRandomItem, this)); d_root->getChild("btnAddRandomItemInList")->subscribeEvent(PushButton::EventClicked, Event::Subscriber(&ModelViewSample::handleAddItemInList, this)); d_root->getChild("btnAddRandomItemInTree")->subscribeEvent(PushButton::EventClicked, Event::Subscriber(&ModelViewSample::handleAddItemInTree, this)); d_root->getChild("btnRemoveSelectedListItem")->subscribeEvent(PushButton::EventClicked, Event::Subscriber(&ModelViewSample::handleRemoveSelectedListItems, this)); d_root->getChild("btnRemoveSelectedTreeItem")->subscribeEvent(PushButton::EventClicked, Event::Subscriber(&ModelViewSample::handleRemoveSelectedTreeItems, this)); d_root->getChild("btnClearAllItems")->subscribeEvent(PushButton::EventClicked, Event::Subscriber(&ModelViewSample::handleClearItems, this)); d_root->getChild("btnUpdateListItemName")->subscribeEvent(PushButton::EventClicked, Event::Subscriber(&ModelViewSample::handleUpdateListItemName, this)); d_root->getChild("btnUpdateTreeItemName")->subscribeEvent(PushButton::EventClicked, Event::Subscriber(&ModelViewSample::handleUpdateTreeItemName, this)); d_root->getChild("chkMultiSelectEnabled")->subscribeEvent( ToggleButton::EventSelectStateChanged, Event::Subscriber(&ModelViewSample::toggleMultiSelect, this)); d_root->getChild("btnSwitchSortingMode")->subscribeEvent( PushButton::EventClicked, Event::Subscriber(&ModelViewSample::toggleSorting, this)); d_txtNewItemName = d_root->getChild("txtNewItemName"); return true; } /************************************************************************* Cleans up resources allocated in the initialiseSample call. *************************************************************************/ void ModelViewSample::deinitialise() { } //----------------------------------------------------------------------------// bool ModelViewSample::handleClearItems(const EventArgs& e) { d_inventoryModel.clear(); return true; } //----------------------------------------------------------------------------// bool ModelViewSample::handleRemoveSelectedListItems(const EventArgs& e) { removeSelectedItemsFromView(d_listView); return true; } //----------------------------------------------------------------------------// bool ModelViewSample::handleRemoveSelectedTreeItems(const EventArgs& e) { removeSelectedItemsFromView(d_treeView); return true; } //----------------------------------------------------------------------------// bool ModelViewSample::handleAddRandomItem(const EventArgs& e) { d_inventoryModel.addRandomItemWithChildren(d_inventoryModel.getRootIndex(), 0); return true; } //----------------------------------------------------------------------------// bool ModelViewSample::handleAddItemInList(const EventArgs& e) { const std::vector<ModelIndexSelectionState>& selections = d_listView->getIndexSelectionStates(); if (selections.empty()) return false; const ModelIndexSelectionState& selection = (*selections.begin()); d_inventoryModel.addRandomItemWithChildren(selection.d_parentIndex, selection.d_childId + 1); return true; } //----------------------------------------------------------------------------// bool ModelViewSample::handleAddItemInTree(const EventArgs& e) { const std::vector<ModelIndexSelectionState>& selections = d_treeView->getIndexSelectionStates(); if (selections.empty()) return false; const ModelIndexSelectionState& selection = (*selections.begin()); d_inventoryModel.addRandomItemWithChildren(selection.d_selectedIndex, 0); return true; } //----------------------------------------------------------------------------// bool ModelViewSample::handleUpdateListItemName(const EventArgs& e) { updateSelectedIndexText(d_listView, d_txtNewItemName->getText()); return true; } //----------------------------------------------------------------------------// bool ModelViewSample::handleUpdateTreeItemName(const EventArgs& e) { updateSelectedIndexText(d_treeView, d_txtNewItemName->getText()); return true; } //----------------------------------------------------------------------------// void ModelViewSample::removeSelectedItemsFromView(ItemView* view) { while(!view->getIndexSelectionStates().empty()) { d_inventoryModel.removeItem(view->getIndexSelectionStates().back().d_selectedIndex); } } //----------------------------------------------------------------------------// void ModelViewSample::updateSelectedIndexText(ItemView* view, const String& text) { const std::vector<ModelIndexSelectionState>& selections = view->getIndexSelectionStates(); if (selections.empty()) return; const ModelIndexSelectionState& selection = (*selections.begin()); d_inventoryModel.updateItemName(selection.d_selectedIndex, text); } //----------------------------------------------------------------------------// bool ModelViewSample::toggleMultiSelect(const EventArgs& e) { bool enabled = d_listView->isMultiSelectEnabled(); d_listView->setMultiSelectEnabled(!enabled); d_treeView->setMultiSelectEnabled(!enabled); return true; } //----------------------------------------------------------------------------// bool ModelViewSample::toggleSorting(const EventArgs& e) { Window* switch_button = d_root->getChild("btnSwitchSortingMode"); ViewSortMode sort_mode = d_listView->getSortMode(); ViewSortMode next_sort_mode = static_cast<ViewSortMode>((sort_mode + 1) % 3); d_listView->setSortMode(next_sort_mode); d_treeView->setSortMode(next_sort_mode); switch_button->setText( "Current sort mode: " + PropertyHelper<ViewSortMode>::toString(next_sort_mode)); return true; } //----------------------------------------------------------------------------// void ModelViewSample::initListWidgetItems(ListWidget* list_widget) { ImageManager::ImageIterator itor = ImageManager::getSingleton().getIterator(); while (!itor.isAtEnd()) { list_widget->addItem(new StandardItem(itor.getCurrentKey(), itor.getCurrentKey())); ++itor; } } /************************************************************************* Define the module function that returns an instance of the sample *************************************************************************/ extern "C" SAMPLE_EXPORT Sample& getSampleInstance() { static ModelViewSample sample; return sample; } <commit_msg>MOD: (SAMPLES) added summary and description to ModelView sample<commit_after>/*********************************************************************** created: Sun May 25 2014 author: Timotei Dolean *************************************************************************/ /*************************************************************************** * Copyright (C) 2004 - 2014 Paul D Turner & The CEGUI Development Team * * Permission is hereby granted, free of charge, to any person obtaining * a copy of this software and associated documentation files (the * "Software"), to deal in the Software without restriction, including * without limitation the rights to use, copy, modify, merge, publish, * distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, subject to * the following conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. * IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR * OTHER DEALINGS IN THE SOFTWARE. ***************************************************************************/ #include "ModelView.h" #include "CEGUI/CEGUI.h" #include <iostream> #include <sstream> using namespace CEGUI; ModelViewSample::ModelViewSample() { d_name = "ModelViewSample"; d_credits = "Timotei Dolean"; d_summary = "A demo that shows the usage of the new Model-View widgets."; d_description = "The demo uses the WindowManager to create from code a window with a listview, treeview and GridView."; } /** This sample uses most of the code from the 'HelloWorld' sample. Thus, most of the clarifying comments have been removed for brevity. **/ /************************************************************************* Sample specific initialisation goes here. *************************************************************************/ bool ModelViewSample::initialise(GUIContext* gui_context) { d_usedFiles = String(__FILE__); SchemeManager::getSingleton().createFromFile("TaharezLook.scheme"); SchemeManager::getSingleton().createFromFile("WindowsLook.scheme"); gui_context->getPointerIndicator().setDefaultImage("TaharezLook/MouseArrow"); WindowManager& win_mgr = WindowManager::getSingleton(); d_root = win_mgr.loadLayoutFromFile("ModelViewSample.layout"); ImageManager::getSingleton().loadImageset("DriveIcons.imageset"); Font& defaultFont = FontManager::getSingleton().createFromFile("DejaVuSans-12.font"); gui_context->setDefaultFont(&defaultFont); gui_context->setRootWindow(d_root); gui_context->setDefaultTooltipType("TaharezLook/Tooltip"); d_inventoryModel.load(); d_newItemsCount = 0; d_listView = static_cast<ListView*>(win_mgr.createWindow("TaharezLook/ListView", "listView")); d_listView->setModel(&d_inventoryModel); d_listView->setItemTooltipsEnabled(true); d_listView->setSelectionColourRect(ColourRect(Colour(1.0f, 0, 0, 1))); d_root->getChild("ListViewHolder")->addChild(d_listView); d_treeView = static_cast<TreeView*>(win_mgr.createWindow("TaharezLook/TreeView", "treeView")); d_treeView->setModel(&d_inventoryModel); d_treeView->setItemTooltipsEnabled(true); d_root->getChild("TreeViewHolder")->addChild(d_treeView); ListWidget* list_widget = static_cast<ListWidget*>(win_mgr.createWindow("TaharezLook/ListWidget", "listWidget")); d_root->getChild("ListWidgetHolder")->addChild(list_widget); initListWidgetItems(list_widget); d_root->getChild("btnAddRandomItem")->subscribeEvent(PushButton::EventClicked, Event::Subscriber(&ModelViewSample::handleAddRandomItem, this)); d_root->getChild("btnAddRandomItemInList")->subscribeEvent(PushButton::EventClicked, Event::Subscriber(&ModelViewSample::handleAddItemInList, this)); d_root->getChild("btnAddRandomItemInTree")->subscribeEvent(PushButton::EventClicked, Event::Subscriber(&ModelViewSample::handleAddItemInTree, this)); d_root->getChild("btnRemoveSelectedListItem")->subscribeEvent(PushButton::EventClicked, Event::Subscriber(&ModelViewSample::handleRemoveSelectedListItems, this)); d_root->getChild("btnRemoveSelectedTreeItem")->subscribeEvent(PushButton::EventClicked, Event::Subscriber(&ModelViewSample::handleRemoveSelectedTreeItems, this)); d_root->getChild("btnClearAllItems")->subscribeEvent(PushButton::EventClicked, Event::Subscriber(&ModelViewSample::handleClearItems, this)); d_root->getChild("btnUpdateListItemName")->subscribeEvent(PushButton::EventClicked, Event::Subscriber(&ModelViewSample::handleUpdateListItemName, this)); d_root->getChild("btnUpdateTreeItemName")->subscribeEvent(PushButton::EventClicked, Event::Subscriber(&ModelViewSample::handleUpdateTreeItemName, this)); d_root->getChild("chkMultiSelectEnabled")->subscribeEvent( ToggleButton::EventSelectStateChanged, Event::Subscriber(&ModelViewSample::toggleMultiSelect, this)); d_root->getChild("btnSwitchSortingMode")->subscribeEvent( PushButton::EventClicked, Event::Subscriber(&ModelViewSample::toggleSorting, this)); d_txtNewItemName = d_root->getChild("txtNewItemName"); return true; } /************************************************************************* Cleans up resources allocated in the initialiseSample call. *************************************************************************/ void ModelViewSample::deinitialise() { } //----------------------------------------------------------------------------// bool ModelViewSample::handleClearItems(const EventArgs& e) { d_inventoryModel.clear(); return true; } //----------------------------------------------------------------------------// bool ModelViewSample::handleRemoveSelectedListItems(const EventArgs& e) { removeSelectedItemsFromView(d_listView); return true; } //----------------------------------------------------------------------------// bool ModelViewSample::handleRemoveSelectedTreeItems(const EventArgs& e) { removeSelectedItemsFromView(d_treeView); return true; } //----------------------------------------------------------------------------// bool ModelViewSample::handleAddRandomItem(const EventArgs& e) { d_inventoryModel.addRandomItemWithChildren(d_inventoryModel.getRootIndex(), 0); return true; } //----------------------------------------------------------------------------// bool ModelViewSample::handleAddItemInList(const EventArgs& e) { const std::vector<ModelIndexSelectionState>& selections = d_listView->getIndexSelectionStates(); if (selections.empty()) return false; const ModelIndexSelectionState& selection = (*selections.begin()); d_inventoryModel.addRandomItemWithChildren(selection.d_parentIndex, selection.d_childId + 1); return true; } //----------------------------------------------------------------------------// bool ModelViewSample::handleAddItemInTree(const EventArgs& e) { const std::vector<ModelIndexSelectionState>& selections = d_treeView->getIndexSelectionStates(); if (selections.empty()) return false; const ModelIndexSelectionState& selection = (*selections.begin()); d_inventoryModel.addRandomItemWithChildren(selection.d_selectedIndex, 0); return true; } //----------------------------------------------------------------------------// bool ModelViewSample::handleUpdateListItemName(const EventArgs& e) { updateSelectedIndexText(d_listView, d_txtNewItemName->getText()); return true; } //----------------------------------------------------------------------------// bool ModelViewSample::handleUpdateTreeItemName(const EventArgs& e) { updateSelectedIndexText(d_treeView, d_txtNewItemName->getText()); return true; } //----------------------------------------------------------------------------// void ModelViewSample::removeSelectedItemsFromView(ItemView* view) { while(!view->getIndexSelectionStates().empty()) { d_inventoryModel.removeItem(view->getIndexSelectionStates().back().d_selectedIndex); } } //----------------------------------------------------------------------------// void ModelViewSample::updateSelectedIndexText(ItemView* view, const String& text) { const std::vector<ModelIndexSelectionState>& selections = view->getIndexSelectionStates(); if (selections.empty()) return; const ModelIndexSelectionState& selection = (*selections.begin()); d_inventoryModel.updateItemName(selection.d_selectedIndex, text); } //----------------------------------------------------------------------------// bool ModelViewSample::toggleMultiSelect(const EventArgs& e) { bool enabled = d_listView->isMultiSelectEnabled(); d_listView->setMultiSelectEnabled(!enabled); d_treeView->setMultiSelectEnabled(!enabled); return true; } //----------------------------------------------------------------------------// bool ModelViewSample::toggleSorting(const EventArgs& e) { Window* switch_button = d_root->getChild("btnSwitchSortingMode"); ViewSortMode sort_mode = d_listView->getSortMode(); ViewSortMode next_sort_mode = static_cast<ViewSortMode>((sort_mode + 1) % 3); d_listView->setSortMode(next_sort_mode); d_treeView->setSortMode(next_sort_mode); switch_button->setText( "Current sort mode: " + PropertyHelper<ViewSortMode>::toString(next_sort_mode)); return true; } //----------------------------------------------------------------------------// void ModelViewSample::initListWidgetItems(ListWidget* list_widget) { ImageManager::ImageIterator itor = ImageManager::getSingleton().getIterator(); while (!itor.isAtEnd()) { list_widget->addItem(new StandardItem(itor.getCurrentKey(), itor.getCurrentKey())); ++itor; } } /************************************************************************* Define the module function that returns an instance of the sample *************************************************************************/ extern "C" SAMPLE_EXPORT Sample& getSampleInstance() { static ModelViewSample sample; return sample; } <|endoftext|>
<commit_before>// -*- Mode: C++; tab-width: 2; -*- // vi: set ts=2: // // $Id: dataset.C,v 1.1.4.2 2007/05/10 21:40:37 amoll Exp $ // #include <BALL/VIEW/DATATYPE/dataset.h> #include <BALL/VIEW/WIDGETS/datasetControl.h> #include <BALL/VIEW/KERNEL/common.h> #include <BALL/VIEW/KERNEL/mainControl.h> #include <BALL/VIEW/KERNEL/message.h> #include <BALL/CONCEPT/molecularInformation.h> #include <QtGui/QFileDialog> #include <QtCore/QStringList> using namespace std; namespace BALL { namespace VIEW { Dataset::Dataset() : composite_(0) { } Dataset::Dataset(const Dataset& ds) : composite_(ds.composite_), name_(ds.name_), type_(ds.type_) { } Dataset::~Dataset() { #ifdef BALL_VIEW_DEBUG cout << "Destructing object " << (void *)this << " of class " << RTTI::getName<Dataset>() << endl; #endif } void Dataset::clear() { composite_ = 0; name_ = ""; type_ = ""; } void Dataset::set(const Dataset& ds) { composite_ = ds.composite_; name_ = ds.name_; type_ = ds.type_; } const Dataset& Dataset::operator = (const Dataset& v) { set(v); return *this; } void Dataset::dump(std::ostream& s, Size depth) const { BALL_DUMP_STREAM_PREFIX(s); BALL_DUMP_DEPTH(s, depth); BALL_DUMP_HEADER(s, this, this); BALL_DUMP_STREAM_SUFFIX(s); } //////////////////////////////////////////////////////////////////////// // Controller: DatasetController::DatasetController() : QObject(), Embeddable("DatasetController"), type_("undefined type"), file_formats_(), control_(0) { registerThis(); } DatasetController::DatasetController(DatasetController& dc) : QObject(), Embeddable(dc), type_(dc.type_), file_formats_(dc.file_formats_), control_(dc.control_) { registerThis(); } DatasetController::~DatasetController() throw() { } bool DatasetController::write(Dataset* /*set*/, String /*filetype*/, String /*filename*/) { Log.error() << "DatasetController::write() should have been overloaded in derived class!" <<std::endl; return false; } Dataset* DatasetController::open(String /*filetype*/, String /*filename*/) { Log.error() << "DatasetController::open() should have been overloaded in derived class!" <<std::endl; return 0; } bool DatasetController::insertDataset(Dataset* set) { if (getDatasetControl() == 0) { BALLVIEW_DEBUG Log.error() << "DatasetController not bound to Dataset!" << std::endl; return false; } if (set == 0) { BALLVIEW_DEBUG return false; } QStringList sl; sl << set->getName().c_str(); if (set->getComposite() != 0) { MolecularInformation mi; mi.visit(*set->getComposite()); sl << mi.getName().c_str(); } else { sl << ""; } sl << set->getType().c_str(); QTreeWidgetItem* item = getDatasetControl()->addRow(sl); item_to_dataset_[item] = set; dataset_to_item_[set] = item; return true; } QMenu* DatasetController::buildContextMenu(QTreeWidgetItem* item) { if (!item_to_dataset_.has(item)) return 0; QMenu* menu = new QMenu(control_); menu->addAction("Save as...", this, SLOT(write())); menu->addAction("Delete", this, SLOT(deleteDataset())); return menu; } vector<Dataset*> DatasetController::getDatasets() { vector<Dataset*> result; HashMap<Dataset*, QTreeWidgetItem*>::Iterator it = dataset_to_item_.begin(); for (; it != dataset_to_item_.end(); ++it) { result.push_back((*it).first); } return result; } vector<Dataset*> DatasetController::getSelectedDatasets() { vector<Dataset*> result; if (getDatasetControl() == 0) { BALLVIEW_DEBUG Log.error() << "DatasetController not bound to Dataset!" << std::endl; return result; } DatasetControl::ItemList il = getDatasetControl()->getSelectedItems(); DatasetControl::ItemList::iterator it = il.begin(); for (; it != il.end(); it++) { if (item_to_dataset_.has(*it)) { result.push_back(item_to_dataset_[*it]); } } return result; } Dataset* DatasetController::getSelectedDataset() { vector<Dataset*> v = getSelectedDatasets(); if (v.size() != 1) return 0; if (getDatasetControl()->getSelectedItems().size() == 1) { return v[0]; } return 0; } bool DatasetController::deleteDatasets() { bool ok = true; vector<Dataset*> sets = getSelectedDatasets(); for (Position p = 0; p < sets.size(); p++) { Dataset* dp = sets[p]; if (dp == 0) { BALLVIEW_DEBUG return false; } ok &= deleteDataset(dp); } return ok; } bool DatasetController::deleteDataset() { bool ok = true; vector<Dataset*> v = getSelectedDatasets(); for (Position p = 0; p < v.size(); p++) { Dataset* set = v[p]; if (set == 0) return false; ok &= deleteDataset(set); } return ok; } bool DatasetController::deleteDataset(Dataset* set) { if (getDatasetControl() == 0) { BALLVIEW_DEBUG Log.error() << "DatasetController not bound to Dataset!" << std::endl; return false; } if (set == 0) { BALLVIEW_DEBUG return false; } if (!dataset_to_item_.has(set)) { return false; } QTreeWidgetItem* item = dataset_to_item_[set]; dataset_to_item_.erase(set); item_to_dataset_.erase(item); delete item; deleteDataset_(set); return true; } bool DatasetController::createMenuEntries() { if (getDatasetControl() == 0) { BALLVIEW_DEBUG Log.error() << "DatasetController not bound to Dataset!" << std::endl; return false; } QAction* action = getDatasetControl()->insertMenuEntry(MainControl::FILE_OPEN, type_, this, SLOT(open()), "Shortcut|File|Open|Dataset"); actions_for_one_set_.insert(action); return true; } String DatasetController::getFileTypes_() { String result(type_); result += " ("; for (Position p = 0; p < file_formats_.size(); p++) { result += "*."; result += file_formats_[p]; } result += ")"; return result; } bool DatasetController::write() { Dataset* set = getSelectedDataset(); if (set == 0) return 0; QString file = QFileDialog::getSaveFileName(0, QString("Save as ") + type_.c_str(), getDatasetControl()->getWorkingDir().c_str(), getFileTypes_().c_str()); if (file == QString::null) return false; vector<String> fields; String s(ascii(file)); s.split(fields, "."); if (fields.size() == 0) { BALLVIEW_DEBUG return false; } return write(set, fields[fields.size() - 1], ascii(file)); } bool DatasetController::open() { QString file = QFileDialog::getOpenFileName(0, QString("Open ") + type_.c_str(), getDatasetControl()->getWorkingDir().c_str(), getFileTypes_().c_str()); if (file == QString::null) return false; vector<String> fields; String s(ascii(file)); s.split(fields, "."); if (fields.size() == 0) { BALLVIEW_DEBUG return false; } Dataset* set = open(fields[fields.size() - 1], ascii(file)); if (set == 0) return false; return insertDataset(set); } QAction* DatasetController::insertMenuEntry_(Position pid, const String& name, const char* slot, const String& description, QKeySequence accel) { if (getDatasetControl() == 0) return 0; QAction* action = getDatasetControl()->insertMenuEntry(pid, name, this, slot, description, accel); actions_.push_back(action); actions_for_one_set_.insert(action); return action; } String DatasetController::getNameFromFileName_(String filename) { Position pos = 0; for (Position p = 0; p < filename.size(); p++) { if (filename[p] == FileSystem::PATH_SEPARATOR) pos = p; } if (pos) pos++; return filename.getSubstring(pos); } void DatasetController::setStatusbarText(const String& text, bool important) { if (getDatasetControl() == 0) return; getDatasetControl()->setStatusbarText(text, important); } void DatasetController::checkMenu(MainControl& mc) { Size selected = getSelectedDatasets().size(); Size all_selected = getDatasetControl()->getSelectionSize(); bool other_selection = selected != all_selected; for (Position p = 0; p < actions_.size(); p++) { QAction& action = *actions_[p]; if (other_selection || mc.isBusy() || selected == 0) { action.setEnabled(false); continue; } if (selected > 1 && actions_for_one_set_.has(&action)) { action.setEnabled(false); continue; } action.setEnabled(true); } } bool DatasetController::handle(DatasetMessage* msg) { DatasetMessage::Type type = msg->getType(); if (type == DatasetMessage::ADD) { insertDataset(msg->getDataset()); return true; } if (type == DatasetMessage::REMOVE) { deleteDataset(msg->getDataset()); return true; } return false; } bool DatasetController::hasDataset(Dataset* set) { return dataset_to_item_.has(set); } bool DatasetController::hasItem(QTreeWidgetItem* item) { return item_to_dataset_.has(item); } Dataset* DatasetController::getDataset(QTreeWidgetItem* item) { if (!item_to_dataset_.has(item)) return 0; return item_to_dataset_[item]; } } // namespace VIEW } // namespace BALL <commit_msg>Fixed the "Double shortcut entry Shortcut|File|Open|Dataset" bug.<commit_after>// -*- Mode: C++; tab-width: 2; -*- // vi: set ts=2: // // $Id: dataset.C,v 1.1.4.2 2007/05/10 21:40:37 amoll Exp $ // #include <BALL/VIEW/DATATYPE/dataset.h> #include <BALL/VIEW/WIDGETS/datasetControl.h> #include <BALL/VIEW/KERNEL/common.h> #include <BALL/VIEW/KERNEL/mainControl.h> #include <BALL/VIEW/KERNEL/message.h> #include <BALL/CONCEPT/molecularInformation.h> #include <QtGui/QFileDialog> #include <QtCore/QStringList> using namespace std; namespace BALL { namespace VIEW { Dataset::Dataset() : composite_(0) { } Dataset::Dataset(const Dataset& ds) : composite_(ds.composite_), name_(ds.name_), type_(ds.type_) { } Dataset::~Dataset() { #ifdef BALL_VIEW_DEBUG cout << "Destructing object " << (void *)this << " of class " << RTTI::getName<Dataset>() << endl; #endif } void Dataset::clear() { composite_ = 0; name_ = ""; type_ = ""; } void Dataset::set(const Dataset& ds) { composite_ = ds.composite_; name_ = ds.name_; type_ = ds.type_; } const Dataset& Dataset::operator = (const Dataset& v) { set(v); return *this; } void Dataset::dump(std::ostream& s, Size depth) const { BALL_DUMP_STREAM_PREFIX(s); BALL_DUMP_DEPTH(s, depth); BALL_DUMP_HEADER(s, this, this); BALL_DUMP_STREAM_SUFFIX(s); } //////////////////////////////////////////////////////////////////////// // Controller: DatasetController::DatasetController() : QObject(), Embeddable("DatasetController"), type_("undefined type"), file_formats_(), control_(0) { registerThis(); } DatasetController::DatasetController(DatasetController& dc) : QObject(), Embeddable(dc), type_(dc.type_), file_formats_(dc.file_formats_), control_(dc.control_) { registerThis(); } DatasetController::~DatasetController() throw() { } bool DatasetController::write(Dataset* /*set*/, String /*filetype*/, String /*filename*/) { Log.error() << "DatasetController::write() should have been overloaded in derived class!" <<std::endl; return false; } Dataset* DatasetController::open(String /*filetype*/, String /*filename*/) { Log.error() << "DatasetController::open() should have been overloaded in derived class!" <<std::endl; return 0; } bool DatasetController::insertDataset(Dataset* set) { if (getDatasetControl() == 0) { BALLVIEW_DEBUG Log.error() << "DatasetController not bound to Dataset!" << std::endl; return false; } if (set == 0) { BALLVIEW_DEBUG return false; } QStringList sl; sl << set->getName().c_str(); if (set->getComposite() != 0) { MolecularInformation mi; mi.visit(*set->getComposite()); sl << mi.getName().c_str(); } else { sl << ""; } sl << set->getType().c_str(); QTreeWidgetItem* item = getDatasetControl()->addRow(sl); item_to_dataset_[item] = set; dataset_to_item_[set] = item; return true; } QMenu* DatasetController::buildContextMenu(QTreeWidgetItem* item) { if (!item_to_dataset_.has(item)) return 0; QMenu* menu = new QMenu(control_); menu->addAction("Save as...", this, SLOT(write())); menu->addAction("Delete", this, SLOT(deleteDataset())); return menu; } vector<Dataset*> DatasetController::getDatasets() { vector<Dataset*> result; HashMap<Dataset*, QTreeWidgetItem*>::Iterator it = dataset_to_item_.begin(); for (; it != dataset_to_item_.end(); ++it) { result.push_back((*it).first); } return result; } vector<Dataset*> DatasetController::getSelectedDatasets() { vector<Dataset*> result; if (getDatasetControl() == 0) { BALLVIEW_DEBUG Log.error() << "DatasetController not bound to Dataset!" << std::endl; return result; } DatasetControl::ItemList il = getDatasetControl()->getSelectedItems(); DatasetControl::ItemList::iterator it = il.begin(); for (; it != il.end(); it++) { if (item_to_dataset_.has(*it)) { result.push_back(item_to_dataset_[*it]); } } return result; } Dataset* DatasetController::getSelectedDataset() { vector<Dataset*> v = getSelectedDatasets(); if (v.size() != 1) return 0; if (getDatasetControl()->getSelectedItems().size() == 1) { return v[0]; } return 0; } bool DatasetController::deleteDatasets() { bool ok = true; vector<Dataset*> sets = getSelectedDatasets(); for (Position p = 0; p < sets.size(); p++) { Dataset* dp = sets[p]; if (dp == 0) { BALLVIEW_DEBUG return false; } ok &= deleteDataset(dp); } return ok; } bool DatasetController::deleteDataset() { bool ok = true; vector<Dataset*> v = getSelectedDatasets(); for (Position p = 0; p < v.size(); p++) { Dataset* set = v[p]; if (set == 0) return false; ok &= deleteDataset(set); } return ok; } bool DatasetController::deleteDataset(Dataset* set) { if (getDatasetControl() == 0) { BALLVIEW_DEBUG Log.error() << "DatasetController not bound to Dataset!" << std::endl; return false; } if (set == 0) { BALLVIEW_DEBUG return false; } if (!dataset_to_item_.has(set)) { return false; } QTreeWidgetItem* item = dataset_to_item_[set]; dataset_to_item_.erase(set); item_to_dataset_.erase(item); delete item; deleteDataset_(set); return true; } bool DatasetController::createMenuEntries() { if (getDatasetControl() == 0) { BALLVIEW_DEBUG Log.error() << "DatasetController not bound to Dataset!" << std::endl; return false; } String temp_type(type_); temp_type.substitute(" ", "_"); String description = "Shortcut|File|Open|Dataset|" + temp_type; QAction* action = getDatasetControl()->insertMenuEntry(MainControl::FILE_OPEN, type_, this, SLOT(open()), description); actions_for_one_set_.insert(action); return true; } String DatasetController::getFileTypes_() { String result(type_); result += " ("; for (Position p = 0; p < file_formats_.size(); p++) { result += "*."; result += file_formats_[p]; } result += ")"; return result; } bool DatasetController::write() { Dataset* set = getSelectedDataset(); if (set == 0) return 0; QString file = QFileDialog::getSaveFileName(0, QString("Save as ") + type_.c_str(), getDatasetControl()->getWorkingDir().c_str(), getFileTypes_().c_str()); if (file == QString::null) return false; vector<String> fields; String s(ascii(file)); s.split(fields, "."); if (fields.size() == 0) { BALLVIEW_DEBUG return false; } return write(set, fields[fields.size() - 1], ascii(file)); } bool DatasetController::open() { QString file = QFileDialog::getOpenFileName(0, QString("Open ") + type_.c_str(), getDatasetControl()->getWorkingDir().c_str(), getFileTypes_().c_str()); if (file == QString::null) return false; vector<String> fields; String s(ascii(file)); s.split(fields, "."); if (fields.size() == 0) { BALLVIEW_DEBUG return false; } Dataset* set = open(fields[fields.size() - 1], ascii(file)); if (set == 0) return false; return insertDataset(set); } QAction* DatasetController::insertMenuEntry_(Position pid, const String& name, const char* slot, const String& description, QKeySequence accel) { if (getDatasetControl() == 0) return 0; QAction* action = getDatasetControl()->insertMenuEntry(pid, name, this, slot, description, accel); actions_.push_back(action); actions_for_one_set_.insert(action); return action; } String DatasetController::getNameFromFileName_(String filename) { Position pos = 0; for (Position p = 0; p < filename.size(); p++) { if (filename[p] == FileSystem::PATH_SEPARATOR) pos = p; } if (pos) pos++; return filename.getSubstring(pos); } void DatasetController::setStatusbarText(const String& text, bool important) { if (getDatasetControl() == 0) return; getDatasetControl()->setStatusbarText(text, important); } void DatasetController::checkMenu(MainControl& mc) { Size selected = getSelectedDatasets().size(); Size all_selected = getDatasetControl()->getSelectionSize(); bool other_selection = selected != all_selected; for (Position p = 0; p < actions_.size(); p++) { QAction& action = *actions_[p]; if (other_selection || mc.isBusy() || selected == 0) { action.setEnabled(false); continue; } if (selected > 1 && actions_for_one_set_.has(&action)) { action.setEnabled(false); continue; } action.setEnabled(true); } } bool DatasetController::handle(DatasetMessage* msg) { DatasetMessage::Type type = msg->getType(); if (type == DatasetMessage::ADD) { insertDataset(msg->getDataset()); return true; } if (type == DatasetMessage::REMOVE) { deleteDataset(msg->getDataset()); return true; } return false; } bool DatasetController::hasDataset(Dataset* set) { return dataset_to_item_.has(set); } bool DatasetController::hasItem(QTreeWidgetItem* item) { return item_to_dataset_.has(item); } Dataset* DatasetController::getDataset(QTreeWidgetItem* item) { if (!item_to_dataset_.has(item)) return 0; return item_to_dataset_[item]; } } // namespace VIEW } // namespace BALL <|endoftext|>
<commit_before>// -*- Mode: C++; tab-width: 2; -*- // vi: set ts=2: // // $Id: pyWidget.C,v 1.13 2003/11/12 12:31:49 amoll Exp $ // // This include has to be first in order to avoid collisions. #include <Python.h> #include <BALL/VIEW/WIDGETS/pyWidget.h> #include <BALL/VIEW/KERNEL/mainControl.h> #include <BALL/VIEW/DIALOGS/pythonSettings.h> #include <BALL/PYTHON/pyInterpreter.h> #include <BALL/VIEW/DIALOGS/preferences.h> #include <BALL/FORMAT/lineBasedFile.h> #include <qscrollbar.h> #include <qfiledialog.h> namespace BALL { namespace VIEW { PyWidgetData::PyWidgetData(QWidget* parent, const char* name) : QTextEdit(parent, name) { setWrapPolicy(QTextEdit::Anywhere); } PyWidgetData::PyWidgetData(const PyWidgetData& /*widget*/) : QTextEdit() { } PyWidgetData::~PyWidgetData() throw() { } void PyWidgetData::stopInterpreter() { PyInterpreter::finalize(); } void PyWidgetData::startInterpreter() { // initialize the interpreter PyInterpreter::initialize(); // print the PyBALL version and clear // the widget's contents in case of a restart setText((String("BALL ") + VersionInfo::getVersion()).c_str()); // print the first prompt multi_line_mode_ = false; newPrompt_(); history_position_ = history_.size() + 1; } void PyWidgetData::retrieveHistoryLine_(Position index) { if (index > history_.size()) { history_position_ = history_.size(); return; } int row, col; getCursorPosition(&row, &col); if (index == history_.size()) { history_position_ = history_.size(); removeParagraph(row); insertParagraph(getPrompt_(), row); setCursorPosition(row, col); QScrollBar* sb = verticalScrollBar(); if (sb != 0) { sb->setValue(sb->maxValue()); } removeParagraph(row +1); return; } String line = getPrompt_()+ history_[index]; // replace the line's contents removeParagraph(row); insertParagraph(line.c_str(), row); setCursorPosition(row, line.size()); QScrollBar* sb = verticalScrollBar(); if (sb != 0) { sb->setValue(sb->maxValue()); } // update the history position history_position_ = index; removeParagraph(row +1); } void PyWidgetData::contentsMousePressEvent(QMouseEvent* /* m */) { setCursorPosition(lines() - 1, 4); // we ignore the mouse events! // they might place the cursor anywhere! } void PyWidgetData::mousePressEvent(QMouseEvent* /* m */) { setCursorPosition(lines() - 1, 4); // we ignore the mouse events! // they might place the cursor anywhere! } bool PyWidgetData::returnPressed() { // check for an empty line (respect the prompt) int row, col; getCursorPosition(&row, &col); current_line_ = getCurrentLine_(); if (col < 5) { if (multi_line_mode_) { // in multi line mode: end of input - parse it! QTextEdit::returnPressed(); parseLine_(); } else { // return on an empty line is handled // as in the interactive interpreter: do nothing and // print another prompt QTextEdit::returnPressed(); newPrompt_(); } } else { // parse the line QTextEdit::returnPressed(); parseLine_(); } return false; } void PyWidgetData::parseLine_() { if (!Py_IsInitialized()) { append("ERROR: no interpreter running!\n"); return; } history_position_ = history_.size(); String line = current_line_.getSubstring(4); line.trimRight(); if (!multi_line_mode_) { if (line.isEmpty()) return; if ((line.hasPrefix("for ") || line.hasPrefix("def ") || line.hasPrefix("class ") || line.hasPrefix("while ") || line.hasPrefix("if ")) && line.hasSuffix(":")) { multi_line_mode_ = true; multi_line_text_ = line; multi_line_text_.append("\n"); multi_lines_ = 1; appendToHistory_(line); newPrompt_(); return; } multi_lines_ = 0; appendToHistory_(line); } else // Multiline mode { multi_lines_ += 1; appendToHistory_(line); if (!line.isEmpty()) { multi_line_text_ += line + "\n"; newPrompt_(); return; } line = multi_line_text_ + "\n"; } bool state; String result = PyInterpreter::run(line, state); if (result != "") append(result.c_str()); if (!multi_line_mode_) { results_.push_back(state); } else { for (Position p = 0; p <= multi_lines_ -1; p++) results_.push_back(state); } multi_line_mode_ = false; newPrompt_(); } void PyWidgetData::appendToHistory_(const String& line) { history_.push_back(line); history_position_ = history_.size(); } const char* PyWidgetData::getPrompt_() const { return (multi_line_mode_ ? "... " : ">>> "); } void PyWidgetData::newPrompt_() { append(getPrompt_()); //scrollToBottom(); setCursorPosition(lines() - 1, 4); } void PyWidgetData::keyPressEvent(QKeyEvent* e) { int row, col; getCursorPosition(&row, &col); if (e->key() == Key_Left || e->key() == Key_Backspace) { if (col <= 4) return; } else if (e->key() == Key_Right) { setCursorPosition(row, col+1); return; } else if (e->key() == Key_Up) { if (history_position_ != 0) retrieveHistoryLine_(history_position_ - 1); return; } else if (e->key() == Key_Down) { retrieveHistoryLine_(history_position_ + 1); return; } else if (e->key() == Key_Home) { setCursorPosition(row, 4); return; } else if (e->key() == Key_Return) { if (!returnPressed()) return; } else if (e->key() == Key_PageUp || e->key() == Key_PageDown) { return; } QTextEdit::keyPressEvent(e); } void PyWidgetData::dump(std::ostream& s, Size depth) const throw() { BALL_DUMP_STREAM_PREFIX(s); BALL_DUMP_HEADER(s, this, this); BALL_DUMP_DEPTH(s, depth); s << "multiline_mode : " << multi_line_mode_<< std::endl; BALL_DUMP_DEPTH(s, depth); s << "multi_line_text : " << multi_line_text_<< std::endl; BALL_DUMP_DEPTH(s, depth); s << "history : "<< std::endl; for (Position i = 0; i < history_.size(); i++) { BALL_DUMP_DEPTH(s, depth); s << history_[i]<< std::endl; } BALL_DUMP_DEPTH(s, depth); s << "history_position : " << history_position_ << std::endl; BALL_DUMP_DEPTH(s, depth); s << "current_line : " << current_line_ << std::endl; BALL_DUMP_STREAM_SUFFIX(s); } String PyWidgetData::getCurrentLine_() { int row, col; getCursorPosition(&row, &col); return String(text(row).ascii()); } void PyWidgetData::runFile(const String& filename) { append(String("> running File " + filename + "\n").c_str()); bool result; String result_string; LineBasedFile file; try { file.open(filename); } catch(Exception::GeneralException e) { append(String("> Could not find file " + filename + "\n").c_str()); newPrompt_(); return; } while (file.readLine()) { result_string = PyInterpreter::run(file.getLine(), result); if (!result) { result_string += "> Error in Line " + String(file.getLineNumber()) + " in file " + filename + "\n"; append(result_string.c_str()); newPrompt_(); return; } append(result_string.c_str()); } append("> finished..."); newPrompt_(); } void PyWidgetData::scriptDialog() { // no throw specifier because of that #$%@* moc QFileDialog *fd = new QFileDialog(this, "Run Python Script", true); fd->setMode(QFileDialog::ExistingFile); fd->addFilter("Python Scripts(*.py)"); fd->setSelectedFilter(1); fd->setCaption("Run Python Script"); fd->setViewMode(QFileDialog::Detail); fd->setGeometry(300, 150, 400, 400); int result_dialog = fd->exec(); if (!result_dialog == QDialog::Accepted) return; String filename(fd->selectedFile().ascii()); runFile(filename); } void PyWidgetData::exportHistory() { QFileDialog *fd = new QFileDialog(this, "Export History", true); fd->setMode(QFileDialog::AnyFile); fd->addFilter("Python Scripts(*.py)"); fd->setSelectedFilter(1); fd->setCaption("Export History"); fd->setViewMode(QFileDialog::Detail); fd->setGeometry(300, 150, 400, 400); int result_dialog = fd->exec(); if (!result_dialog == QDialog::Accepted) return; String filename(fd->selectedFile().ascii()); File file(filename, std::ios::out); if (!file.isOpen()) { append(String("> Could not export history to file " + filename + "\n").c_str()); newPrompt_(); return; } for (Position p = 0; p < history_.size(); p++) { if (results_[p]) file << history_[p] << std::endl; } file.close(); } PyWidget::PyWidget(QWidget *parent, const char *name) throw() : DockWidget(parent, name), text_edit_(new PyWidgetData(this)) { #ifdef BALL_VIEW_DEBUG Log.error() << "new PyWidget " << this << std::endl; #endif default_visible_ = false; setGuest(*text_edit_); } void PyWidget::initializeWidget(MainControl& main_control) throw() { main_control.insertMenuEntry(MainControl::TOOLS_PYTHON, "Restart Python", text_edit_, SLOT(startInterpreter())); main_control.insertMenuEntry(MainControl::TOOLS_PYTHON, "Run Python Script", text_edit_, SLOT(scriptDialog())); main_control.insertMenuEntry(MainControl::TOOLS_PYTHON, "Export History", text_edit_, SLOT(exportHistory())); DockWidget::initializeWidget(main_control); } void PyWidget::finalizeWidget(MainControl& main_control) throw() { main_control.removeMenuEntry(MainControl::TOOLS_PYTHON, "Restart Python", text_edit_, SLOT(startInterpreter())); main_control.removeMenuEntry(MainControl::TOOLS_PYTHON, "Run Python Script", text_edit_, SLOT(scriptDialog())); main_control.removeMenuEntry(MainControl::TOOLS_PYTHON, "Export History", text_edit_, SLOT(exportHistory())); DockWidget::finalizeWidget(main_control); } void PyWidget::fetchPreferences(INIFile& inifile) throw() { DockWidget::fetchPreferences(inifile); if (!inifile.hasEntry("PYTHON", "StartupScript")) return; text_edit_->startup_script_ = inifile.getValue("PYTHON", "StartupScript"); text_edit_->python_settings_->setFilename(text_edit_->startup_script_); if (text_edit_->startup_script_ != "") text_edit_->runFile(text_edit_->startup_script_); } void PyWidget::writePreferences(INIFile& inifile) throw() { inifile.appendSection("PYTHON"); inifile.insertValue("PYTHON", "StartupScript", text_edit_->startup_script_); DockWidget::writePreferences(inifile); } void PyWidget::initializePreferencesTab(Preferences &preferences) throw() { text_edit_->python_settings_= new PythonSettings(this); text_edit_->python_settings_->setFilename(text_edit_->startup_script_); preferences.insertTab(text_edit_->python_settings_, "Python"); } void PyWidget::finalizePreferencesTab(Preferences &preferences) throw() { if (text_edit_->python_settings_ != 0) { preferences.removeTab(text_edit_->python_settings_); delete text_edit_->python_settings_; text_edit_->python_settings_ = 0; } } void PyWidget::applyPreferences(Preferences & /* preferences */) throw() { if (text_edit_->python_settings_ == 0) return; text_edit_->startup_script_ = text_edit_->python_settings_->getFilename(); } void PyWidget::cancelPreferences(Preferences&) throw() { if (text_edit_->python_settings_ != 0) { text_edit_->python_settings_->setFilename(text_edit_->startup_script_); } } void PyWidget::startInterpreter() { text_edit_->startInterpreter(); } void PyWidget::stopInterpreter() { text_edit_->stopInterpreter(); } } // namespace VIEW } // namespace BALL <commit_msg>fixed problem with wraping<commit_after>// -*- Mode: C++; tab-width: 2; -*- // vi: set ts=2: // // $Id: pyWidget.C,v 1.14 2003/11/13 15:01:57 amoll Exp $ // // This include has to be first in order to avoid collisions. #include <Python.h> #include <BALL/VIEW/WIDGETS/pyWidget.h> #include <BALL/VIEW/KERNEL/mainControl.h> #include <BALL/VIEW/DIALOGS/pythonSettings.h> #include <BALL/PYTHON/pyInterpreter.h> #include <BALL/VIEW/DIALOGS/preferences.h> #include <BALL/FORMAT/lineBasedFile.h> #include <qscrollbar.h> #include <qfiledialog.h> namespace BALL { namespace VIEW { PyWidgetData::PyWidgetData(QWidget* parent, const char* name) : QTextEdit(parent, name) { setWrapPolicy(QTextEdit::Anywhere); } PyWidgetData::PyWidgetData(const PyWidgetData& /*widget*/) : QTextEdit() { } PyWidgetData::~PyWidgetData() throw() { } void PyWidgetData::stopInterpreter() { PyInterpreter::finalize(); } void PyWidgetData::startInterpreter() { // initialize the interpreter PyInterpreter::initialize(); // print the PyBALL version and clear // the widget's contents in case of a restart setText((String("BALL ") + VersionInfo::getVersion()).c_str()); // print the first prompt multi_line_mode_ = false; newPrompt_(); history_position_ = history_.size() + 1; } void PyWidgetData::retrieveHistoryLine_(Position index) { if (index > history_.size()) { history_position_ = history_.size(); return; } int row, col; getCursorPosition(&row, &col); if (index == history_.size()) { history_position_ = history_.size(); removeParagraph(row); insertParagraph(getPrompt_(), row); setCursorPosition(paragraphs()-1, col); QScrollBar* sb = verticalScrollBar(); if (sb != 0) { sb->setValue(sb->maxValue()); } removeParagraph(row +1); return; } String line = getPrompt_()+ history_[index]; // replace the line's contents removeParagraph(row); insertParagraph(line.c_str(), row); setCursorPosition(row, line.size()); QScrollBar* sb = verticalScrollBar(); if (sb != 0) { sb->setValue(sb->maxValue()); } // update the history position history_position_ = index; removeParagraph(row +1); } void PyWidgetData::contentsMousePressEvent(QMouseEvent* /* m */) { setCursorPosition(paragraphs() - 1, 4); // we ignore the mouse events! // they might place the cursor anywhere! } void PyWidgetData::mousePressEvent(QMouseEvent* /* m */) { setCursorPosition(paragraphs() - 1, 4); // we ignore the mouse events! // they might place the cursor anywhere! } bool PyWidgetData::returnPressed() { // check for an empty line (respect the prompt) int row, col; getCursorPosition(&row, &col); current_line_ = getCurrentLine_(); if (col < 5) { if (multi_line_mode_) { // in multi line mode: end of input - parse it! QTextEdit::returnPressed(); parseLine_(); } else { // return on an empty line is handled // as in the interactive interpreter: do nothing and // print another prompt QTextEdit::returnPressed(); newPrompt_(); } } else { // parse the line QTextEdit::returnPressed(); parseLine_(); } return false; } void PyWidgetData::parseLine_() { if (!Py_IsInitialized()) { append("ERROR: no interpreter running!\n"); return; } history_position_ = history_.size(); String line = current_line_.getSubstring(4); line.trimRight(); if (!multi_line_mode_) { if (line.isEmpty()) return; if ((line.hasPrefix("for ") || line.hasPrefix("def ") || line.hasPrefix("class ") || line.hasPrefix("while ") || line.hasPrefix("if ")) && line.hasSuffix(":")) { multi_line_mode_ = true; multi_line_text_ = line; multi_line_text_.append("\n"); multi_lines_ = 1; appendToHistory_(line); newPrompt_(); return; } multi_lines_ = 0; appendToHistory_(line); } else // Multiline mode { multi_lines_ += 1; appendToHistory_(line); if (!line.isEmpty()) { multi_line_text_ += line + "\n"; newPrompt_(); return; } line = multi_line_text_ + "\n"; } bool state; String result = PyInterpreter::run(line, state); if (result != "") append(result.c_str()); if (!multi_line_mode_) { results_.push_back(state); } else { for (Position p = 0; p <= multi_lines_ -1; p++) results_.push_back(state); } multi_line_mode_ = false; newPrompt_(); } void PyWidgetData::appendToHistory_(const String& line) { history_.push_back(line); history_position_ = history_.size(); } const char* PyWidgetData::getPrompt_() const { return (multi_line_mode_ ? "... " : ">>> "); } void PyWidgetData::newPrompt_() { append(getPrompt_()); setCursorPosition(paragraphs() - 1, 4); } void PyWidgetData::keyPressEvent(QKeyEvent* e) { int row, col; getCursorPosition(&row, &col); if (e->key() == Key_Left || e->key() == Key_Backspace) { if (col <= 4) return; } else if (e->key() == Key_Right) { setCursorPosition(paragraphs()-1, col+1); return; } else if (e->key() == Key_Up) { if (history_position_ != 0) retrieveHistoryLine_(history_position_ - 1); return; } else if (e->key() == Key_Down) { retrieveHistoryLine_(history_position_ + 1); return; } else if (e->key() == Key_Home) { setCursorPosition(row, 4); return; } else if (e->key() == Key_Return) { if (!returnPressed()) return; } else if (e->key() == Key_PageUp) { return; } else if (e->key() == Key_PageDown) { return; } QTextEdit::keyPressEvent(e); } void PyWidgetData::dump(std::ostream& s, Size depth) const throw() { BALL_DUMP_STREAM_PREFIX(s); BALL_DUMP_HEADER(s, this, this); BALL_DUMP_DEPTH(s, depth); s << "multiline_mode : " << multi_line_mode_<< std::endl; BALL_DUMP_DEPTH(s, depth); s << "multi_line_text : " << multi_line_text_<< std::endl; BALL_DUMP_DEPTH(s, depth); s << "history : "<< std::endl; for (Position i = 0; i < history_.size(); i++) { BALL_DUMP_DEPTH(s, depth); s << history_[i]<< std::endl; } BALL_DUMP_DEPTH(s, depth); s << "history_position : " << history_position_ << std::endl; BALL_DUMP_DEPTH(s, depth); s << "current_line : " << current_line_ << std::endl; BALL_DUMP_STREAM_SUFFIX(s); } String PyWidgetData::getCurrentLine_() { int row, col; getCursorPosition(&row, &col); return String(text(row).ascii()); } void PyWidgetData::runFile(const String& filename) { append(String("> running File " + filename + "\n").c_str()); bool result; String result_string; LineBasedFile file; try { file.open(filename); } catch(Exception::GeneralException e) { append(String("> Could not find file " + filename + "\n").c_str()); newPrompt_(); return; } while (file.readLine()) { result_string = PyInterpreter::run(file.getLine(), result); if (!result) { result_string += "> Error in Line " + String(file.getLineNumber()) + " in file " + filename + "\n"; append(result_string.c_str()); newPrompt_(); return; } append(result_string.c_str()); } append("> finished..."); newPrompt_(); } void PyWidgetData::scriptDialog() { // no throw specifier because of that #$%@* moc QFileDialog *fd = new QFileDialog(this, "Run Python Script", true); fd->setMode(QFileDialog::ExistingFile); fd->addFilter("Python Scripts(*.py)"); fd->setSelectedFilter(1); fd->setCaption("Run Python Script"); fd->setViewMode(QFileDialog::Detail); fd->setGeometry(300, 150, 400, 400); int result_dialog = fd->exec(); if (!result_dialog == QDialog::Accepted) return; String filename(fd->selectedFile().ascii()); runFile(filename); } void PyWidgetData::exportHistory() { QFileDialog *fd = new QFileDialog(this, "Export History", true); fd->setMode(QFileDialog::AnyFile); fd->addFilter("Python Scripts(*.py)"); fd->setSelectedFilter(1); fd->setCaption("Export History"); fd->setViewMode(QFileDialog::Detail); fd->setGeometry(300, 150, 400, 400); int result_dialog = fd->exec(); if (!result_dialog == QDialog::Accepted) return; String filename(fd->selectedFile().ascii()); File file(filename, std::ios::out); if (!file.isOpen()) { append(String("> Could not export history to file " + filename + "\n").c_str()); newPrompt_(); return; } for (Position p = 0; p < history_.size(); p++) { if (results_[p]) file << history_[p] << std::endl; } file.close(); } void PyWidgetData::cut() { QTextEdit::cut(); newPrompt_(); } void PyWidgetData::clear() { QTextEdit::clear(); newPrompt_(); } // ###################################################################################################### PyWidget::PyWidget(QWidget *parent, const char *name) throw() : DockWidget(parent, name), text_edit_(new PyWidgetData(this)) { #ifdef BALL_VIEW_DEBUG Log.error() << "new PyWidget " << this << std::endl; #endif default_visible_ = false; setGuest(*text_edit_); } void PyWidget::initializeWidget(MainControl& main_control) throw() { main_control.insertMenuEntry(MainControl::TOOLS_PYTHON, "Restart Python", text_edit_, SLOT(startInterpreter())); main_control.insertMenuEntry(MainControl::TOOLS_PYTHON, "Run Python Script", text_edit_, SLOT(scriptDialog())); main_control.insertMenuEntry(MainControl::TOOLS_PYTHON, "Export History", text_edit_, SLOT(exportHistory())); DockWidget::initializeWidget(main_control); } void PyWidget::finalizeWidget(MainControl& main_control) throw() { main_control.removeMenuEntry(MainControl::TOOLS_PYTHON, "Restart Python", text_edit_, SLOT(startInterpreter())); main_control.removeMenuEntry(MainControl::TOOLS_PYTHON, "Run Python Script", text_edit_, SLOT(scriptDialog())); main_control.removeMenuEntry(MainControl::TOOLS_PYTHON, "Export History", text_edit_, SLOT(exportHistory())); DockWidget::finalizeWidget(main_control); } void PyWidget::fetchPreferences(INIFile& inifile) throw() { DockWidget::fetchPreferences(inifile); if (!inifile.hasEntry("PYTHON", "StartupScript")) return; text_edit_->startup_script_ = inifile.getValue("PYTHON", "StartupScript"); text_edit_->python_settings_->setFilename(text_edit_->startup_script_); if (text_edit_->startup_script_ != "") text_edit_->runFile(text_edit_->startup_script_); } void PyWidget::writePreferences(INIFile& inifile) throw() { inifile.appendSection("PYTHON"); inifile.insertValue("PYTHON", "StartupScript", text_edit_->startup_script_); DockWidget::writePreferences(inifile); } void PyWidget::initializePreferencesTab(Preferences &preferences) throw() { text_edit_->python_settings_= new PythonSettings(this); text_edit_->python_settings_->setFilename(text_edit_->startup_script_); preferences.insertTab(text_edit_->python_settings_, "Python"); } void PyWidget::finalizePreferencesTab(Preferences &preferences) throw() { if (text_edit_->python_settings_ != 0) { preferences.removeTab(text_edit_->python_settings_); delete text_edit_->python_settings_; text_edit_->python_settings_ = 0; } } void PyWidget::applyPreferences(Preferences & /* preferences */) throw() { if (text_edit_->python_settings_ == 0) return; text_edit_->startup_script_ = text_edit_->python_settings_->getFilename(); } void PyWidget::cancelPreferences(Preferences&) throw() { if (text_edit_->python_settings_ != 0) { text_edit_->python_settings_->setFilename(text_edit_->startup_script_); } } void PyWidget::startInterpreter() { text_edit_->startInterpreter(); } void PyWidget::stopInterpreter() { text_edit_->stopInterpreter(); } } // namespace VIEW } // namespace BALL <|endoftext|>
<commit_before>#include "CUVElement.hpp" /* Documentation at: http://www.metroid2002.com/retromodding/wiki/Particle_Script#UV_Elements */ namespace urde { CUVEAnimTexture::CUVEAnimTexture(TToken<CTexture>&& tex, std::unique_ptr<CIntElement>&& tileW, std::unique_ptr<CIntElement>&& tileH, std::unique_ptr<CIntElement>&& strideW, std::unique_ptr<CIntElement>&& strideH, std::unique_ptr<CIntElement>&& cycleFrames, bool loop) : x4_tex(std::move(tex)), x24_loop(loop), x28_cycleFrames(std::move(cycleFrames)) { tileW->GetValue(0, x10_tileW); tileH->GetValue(0, x14_tileH); strideW->GetValue(0, x18_strideW); strideH->GetValue(0, x1c_strideH); const int width = int(x4_tex.GetObj()->GetWidth()); const int height = int(x4_tex.GetObj()->GetHeight()); const float widthF = float(width); const float heightF = float(height); const int xTiles = std::max(1, width / x18_strideW); const int yTiles = std::max(1, height / x1c_strideH); x20_tiles = xTiles * yTiles; x2c_uvElems.reserve(x20_tiles); for (int y = yTiles - 1; y >= 0; --y) { for (int x = 0; x < xTiles; ++x) { const int px = x18_strideW * x; const int px2 = px + x10_tileW; const int py = x1c_strideH * y; const int py2 = py + x14_tileH; x2c_uvElems.push_back({ float(px) / widthF, float(py) / heightF, float(px2) / widthF, float(py2) / heightF, }); } } } void CUVEAnimTexture::GetValueUV(int frame, SUVElementSet& valOut) const { int cv; x28_cycleFrames->GetValue(frame, cv); float cvf = float(cv) / float(x20_tiles); cvf = float(frame) / cvf; int tile = int(cvf); if (x24_loop) { if (cvf >= float(x20_tiles)) { tile = int(cvf) % x20_tiles; } } else { if (cvf >= float(x20_tiles)) { tile = x20_tiles - 1; } } valOut = x2c_uvElems[tile]; } } // namespace urde <commit_msg>CUVElement: Provide initial value for cv in GetValueUV()<commit_after>#include "CUVElement.hpp" /* Documentation at: http://www.metroid2002.com/retromodding/wiki/Particle_Script#UV_Elements */ namespace urde { CUVEAnimTexture::CUVEAnimTexture(TToken<CTexture>&& tex, std::unique_ptr<CIntElement>&& tileW, std::unique_ptr<CIntElement>&& tileH, std::unique_ptr<CIntElement>&& strideW, std::unique_ptr<CIntElement>&& strideH, std::unique_ptr<CIntElement>&& cycleFrames, bool loop) : x4_tex(std::move(tex)), x24_loop(loop), x28_cycleFrames(std::move(cycleFrames)) { tileW->GetValue(0, x10_tileW); tileH->GetValue(0, x14_tileH); strideW->GetValue(0, x18_strideW); strideH->GetValue(0, x1c_strideH); const int width = int(x4_tex.GetObj()->GetWidth()); const int height = int(x4_tex.GetObj()->GetHeight()); const float widthF = float(width); const float heightF = float(height); const int xTiles = std::max(1, width / x18_strideW); const int yTiles = std::max(1, height / x1c_strideH); x20_tiles = xTiles * yTiles; x2c_uvElems.reserve(x20_tiles); for (int y = yTiles - 1; y >= 0; --y) { for (int x = 0; x < xTiles; ++x) { const int px = x18_strideW * x; const int px2 = px + x10_tileW; const int py = x1c_strideH * y; const int py2 = py + x14_tileH; x2c_uvElems.push_back({ float(px) / widthF, float(py) / heightF, float(px2) / widthF, float(py2) / heightF, }); } } } void CUVEAnimTexture::GetValueUV(int frame, SUVElementSet& valOut) const { int cv = 1; x28_cycleFrames->GetValue(frame, cv); float cvf = float(cv) / float(x20_tiles); cvf = float(frame) / cvf; int tile = int(cvf); if (x24_loop) { if (cvf >= float(x20_tiles)) { tile = int(cvf) % x20_tiles; } } else { if (cvf >= float(x20_tiles)) { tile = x20_tiles - 1; } } valOut = x2c_uvElems[tile]; } } // namespace urde <|endoftext|>
<commit_before>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ /************************************************************************* * * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * Copyright 2000, 2010 Oracle and/or its affiliates. * * OpenOffice.org - a multi-platform office productivity suite * * 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 SC_ADIASYNC_HXX #define SC_ADIASYNC_HXX #include <svl/broadcast.hxx> #include <set> #include "callform.hxx" extern "C" { void CALLTYPE ScAddInAsyncCallBack( double& nHandle, void* pData ); } class ScDocument; class ScAddInDocs : public std::set<ScDocument*> {}; class String; class ScAddInAsync : public SvtBroadcaster { private: union { double nVal; // current value String* pStr; }; ScAddInDocs* pDocs; // List of using documents FuncData* mpFuncData; // Pointer to files in collection sal_uLong nHandle; // is casted from double to sal_uLong ParamType meType; // result of type PTR_DOUBLE or PTR_STRING bool bValid; // is value valid? public: // cTor only if ScAddInAsync::Get fails. // nIndex: Index from FunctionCollection ScAddInAsync(sal_uLong nHandle, FuncData* pFuncData, ScDocument* pDoc); // default-cTor only for that single, global aSeekObj! ScAddInAsync(); virtual ~ScAddInAsync(); static ScAddInAsync* Get( sal_uLong nHandle ); static void CallBack( sal_uLong nHandle, void* pData ); static void RemoveDocument( ScDocument* pDocument ); bool IsValid() const { return bValid; } ParamType GetType() const { return meType; } double GetValue() const { return nVal; } const String& GetString() const { return *pStr; } bool HasDocument( ScDocument* pDoc ) const { return pDocs->find( pDoc ) != pDocs->end(); } void AddDocument( ScDocument* pDoc ) { pDocs->insert( pDoc ); } // Comparators for PtrArrSort bool operator< ( const ScAddInAsync& r ) const { return nHandle < r.nHandle; } bool operator==( const ScAddInAsync& r ) const { return nHandle == r.nHandle; } }; struct CompareScAddInAsync { bool operator()( ScAddInAsync* const& lhs, ScAddInAsync* const& rhs ) const { return (*lhs)<(*rhs); } }; class ScAddInAsyncs : public std::set<ScAddInAsync*, CompareScAddInAsync> {}; extern ScAddInAsyncs theAddInAsyncTbl; // in adiasync.cxx #endif /* vim:set shiftwidth=4 softtabstop=4 expandtab: */ <commit_msg>fix errorin translation from german to english<commit_after>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ /************************************************************************* * * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * Copyright 2000, 2010 Oracle and/or its affiliates. * * OpenOffice.org - a multi-platform office productivity suite * * 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 SC_ADIASYNC_HXX #define SC_ADIASYNC_HXX #include <svl/broadcast.hxx> #include <set> #include "callform.hxx" extern "C" { void CALLTYPE ScAddInAsyncCallBack( double& nHandle, void* pData ); } class ScDocument; class ScAddInDocs : public std::set<ScDocument*> {}; class String; class ScAddInAsync : public SvtBroadcaster { private: union { double nVal; // current value String* pStr; }; ScAddInDocs* pDocs; // List of using documents FuncData* mpFuncData; // Pointer to data in collection sal_uLong nHandle; // is casted from double to sal_uLong ParamType meType; // result of type PTR_DOUBLE or PTR_STRING bool bValid; // is value valid? public: // cTor only if ScAddInAsync::Get fails. // nIndex: Index from FunctionCollection ScAddInAsync(sal_uLong nHandle, FuncData* pFuncData, ScDocument* pDoc); // default-cTor only for that single, global aSeekObj! ScAddInAsync(); virtual ~ScAddInAsync(); static ScAddInAsync* Get( sal_uLong nHandle ); static void CallBack( sal_uLong nHandle, void* pData ); static void RemoveDocument( ScDocument* pDocument ); bool IsValid() const { return bValid; } ParamType GetType() const { return meType; } double GetValue() const { return nVal; } const String& GetString() const { return *pStr; } bool HasDocument( ScDocument* pDoc ) const { return pDocs->find( pDoc ) != pDocs->end(); } void AddDocument( ScDocument* pDoc ) { pDocs->insert( pDoc ); } // Comparators for PtrArrSort bool operator< ( const ScAddInAsync& r ) const { return nHandle < r.nHandle; } bool operator==( const ScAddInAsync& r ) const { return nHandle == r.nHandle; } }; struct CompareScAddInAsync { bool operator()( ScAddInAsync* const& lhs, ScAddInAsync* const& rhs ) const { return (*lhs)<(*rhs); } }; class ScAddInAsyncs : public std::set<ScAddInAsync*, CompareScAddInAsync> {}; extern ScAddInAsyncs theAddInAsyncTbl; // in adiasync.cxx #endif /* vim:set shiftwidth=4 softtabstop=4 expandtab: */ <|endoftext|>
<commit_before>#ifndef _A_STAR_HPP_ #define _A_STAR_HPP_ #include <vector> #include <boost/none.hpp> #include <boost/optional.hpp> #include <boost/pool/pool_alloc.hpp> #include <boost/unordered_map.hpp> #include "search/BucketPriorityQueue.hpp" #include "util/PointerOps.hpp" template < class Domain, class Node > class AStar { private: typedef BucketPriorityQueue<Node> Open; typedef boost::unordered_map< Node *, boost::optional<typename Open::ItemPointer>, PointerHash<Node>, PointerEq<Node> , boost::fast_pool_allocator< std::pair<Node * const, boost::optional<typename Open::ItemPointer> > > > Closed; public: AStar(const Domain &domain) : open(*new Open()) , closed(*new Closed(50000000)) // requested number of hash buckets , goal(NULL) , domain(domain) , num_expanded(0) , num_generated(0) { } ~AStar() { // I don't delete open or closed. This appears to be acceptable, // due to my use of memory pools in key places. Check for // yourself, with valgrind: no memory is leaked. } void search() { // TODO: the following check is buggy. What if there is no goal, // and the search has been completed? if (goal != NULL) return; typename std::vector<Node *> succs; // re-use a stack-allocated // vector for successor // nodes, thus avoiding // repeated heap // allocation. { assert(all_closed_item_ptrs_valid()); Node *start_node = domain.create_start_node(); boost::optional<typename Open::ItemPointer> open_ptr = open.push(start_node); assert(open_ptr); closed[start_node] = open_ptr; assert(closed.find(start_node) != closed.end()); assert(open.size() == 1); assert(closed.size() == 1); assert(all_closed_item_ptrs_valid()); } while (!open.empty()) { // #ifndef NDEBUG // std::cerr << "open size is " << open.size() << std::endl // << "closed size is " << closed.size() << std::endl; // #endif Node *n = open.top(); open.pop(); assert(closed.find(n) != closed.end()); closed[n] = boost::none; assert(all_closed_item_ptrs_valid()); if (domain.is_goal(n->get_state())) { goal = n; return; } domain.expand(*n, succs); num_expanded += 1; num_generated += succs.size(); for (unsigned succ_i = 0; succ_i < succs.size(); succ_i += 1) { Node *succ = succs[succ_i]; assert(open.size() <= closed.size()); assert(all_closed_item_ptrs_valid()); typename Closed::iterator closed_it = closed.find(succ); if (closed.find(succ) != closed.end()) { boost::optional<typename Open::ItemPointer> &open_ptr = closed_it->second; if ( open_ptr ) { Node *old_succ = open.lookup(*open_ptr); if ( succ->get_f() < old_succ->get_f() ) { // A worse copy of succ is in the open list. Replace it! assert(old_succ->get_state() == succ->get_state()); assert(*old_succ == *succ); domain.free_node(old_succ); // get rid of the old copy open.erase(*open_ptr); closed.erase(succ); open_ptr = open.push(succ); // insert the new copy closed[succ] = open_ptr; assert(all_closed_item_ptrs_valid()); } } else { // succ is not in the open list, but is closed. Drop it! domain.free_node(succ); } } else { // succ has not been generated before. boost::optional<typename Open::ItemPointer> open_ptr = open.push(succ); closed[succ] = open_ptr; assert(closed.find(open.lookup(*open_ptr)) != closed.end()); assert(all_closed_item_ptrs_valid()); } } /* end for */ } /* end while */ } const Node * get_goal() const { #ifndef NDEBUG std::cerr << open.size() << " nodes in open at end of search" << std::endl << closed.size() << " nodes in closed at end of search" << std::endl; #endif return goal; } const Domain & get_domain() const { return domain; } unsigned get_num_generated() const { return num_generated; } unsigned get_num_expanded() const { return num_expanded; } private: bool all_closed_item_ptrs_valid() const { return true; std::cerr << "checking if item pointers are valid" << std::endl << " " << closed.size() << " pointers to check" << std::endl; for (typename Closed::const_iterator closed_it = closed.begin(); closed_it != closed.end(); ++closed_it) { if ( closed_it->second && !open.valid_item_pointer(*closed_it->second) ) return false; } return true; } private: Open &open; Closed &closed; const Node * goal; const Domain &domain; unsigned num_expanded; unsigned num_generated; private: AStar(const AStar<Domain, Node> &); AStar<Domain, Node> & operator =(const AStar<Domain, Node> &); }; #endif /* !_A_STAR_HPP_ */ <commit_msg>Fixed a bug where search could be repeated if no goal exists.<commit_after>#ifndef _A_STAR_HPP_ #define _A_STAR_HPP_ #include <vector> #include <boost/none.hpp> #include <boost/optional.hpp> #include <boost/pool/pool_alloc.hpp> #include <boost/unordered_map.hpp> #include "search/BucketPriorityQueue.hpp" #include "util/PointerOps.hpp" template < class Domain, class Node > class AStar { private: typedef BucketPriorityQueue<Node> Open; typedef boost::unordered_map< Node *, boost::optional<typename Open::ItemPointer>, PointerHash<Node>, PointerEq<Node> , boost::fast_pool_allocator< std::pair<Node * const, boost::optional<typename Open::ItemPointer> > > > Closed; public: AStar(const Domain &domain) : open(*new Open()) , closed(*new Closed(50000000)) // requested number of hash buckets , goal(NULL) , searched(false) , domain(domain) , num_expanded(0) , num_generated(0) { } ~AStar() { // I don't delete open or closed. This appears to be acceptable, // due to my use of memory pools in key places. Check for // yourself, with valgrind: no memory is leaked. } void search() { if (searched || goal != NULL) return; searched = true; typename std::vector<Node *> succs; // re-use a stack-allocated // vector for successor // nodes, thus avoiding // repeated heap // allocation. { assert(all_closed_item_ptrs_valid()); Node *start_node = domain.create_start_node(); boost::optional<typename Open::ItemPointer> open_ptr = open.push(start_node); assert(open_ptr); closed[start_node] = open_ptr; assert(closed.find(start_node) != closed.end()); assert(open.size() == 1); assert(closed.size() == 1); assert(all_closed_item_ptrs_valid()); } while (!open.empty()) { // #ifndef NDEBUG // std::cerr << "open size is " << open.size() << std::endl // << "closed size is " << closed.size() << std::endl; // #endif Node *n = open.top(); open.pop(); assert(closed.find(n) != closed.end()); closed[n] = boost::none; assert(all_closed_item_ptrs_valid()); if (domain.is_goal(n->get_state())) { goal = n; return; } domain.expand(*n, succs); num_expanded += 1; num_generated += succs.size(); for (unsigned succ_i = 0; succ_i < succs.size(); succ_i += 1) { Node *succ = succs[succ_i]; assert(open.size() <= closed.size()); assert(all_closed_item_ptrs_valid()); typename Closed::iterator closed_it = closed.find(succ); if (closed.find(succ) != closed.end()) { boost::optional<typename Open::ItemPointer> &open_ptr = closed_it->second; if ( open_ptr ) { Node *old_succ = open.lookup(*open_ptr); if ( succ->get_f() < old_succ->get_f() ) { // A worse copy of succ is in the open list. Replace it! assert(old_succ->get_state() == succ->get_state()); assert(*old_succ == *succ); domain.free_node(old_succ); // get rid of the old copy open.erase(*open_ptr); closed.erase(succ); open_ptr = open.push(succ); // insert the new copy closed[succ] = open_ptr; assert(all_closed_item_ptrs_valid()); } } else { // succ is not in the open list, but is closed. Drop it! domain.free_node(succ); } } else { // succ has not been generated before. boost::optional<typename Open::ItemPointer> open_ptr = open.push(succ); closed[succ] = open_ptr; assert(closed.find(open.lookup(*open_ptr)) != closed.end()); assert(all_closed_item_ptrs_valid()); } } /* end for */ } /* end while */ } const Node * get_goal() const { #ifndef NDEBUG std::cerr << open.size() << " nodes in open at end of search" << std::endl << closed.size() << " nodes in closed at end of search" << std::endl; #endif return goal; } const Domain & get_domain() const { return domain; } unsigned get_num_generated() const { return num_generated; } unsigned get_num_expanded() const { return num_expanded; } private: bool all_closed_item_ptrs_valid() const { return true; std::cerr << "checking if item pointers are valid" << std::endl << " " << closed.size() << " pointers to check" << std::endl; for (typename Closed::const_iterator closed_it = closed.begin(); closed_it != closed.end(); ++closed_it) { if ( closed_it->second && !open.valid_item_pointer(*closed_it->second) ) return false; } return true; } private: Open &open; Closed &closed; const Node * goal; bool searched; const Domain &domain; unsigned num_expanded; unsigned num_generated; private: AStar(const AStar<Domain, Node> &); AStar<Domain, Node> & operator =(const AStar<Domain, Node> &); }; #endif /* !_A_STAR_HPP_ */ <|endoftext|>
<commit_before>/** * Licensed under Apache License v2. See LICENSE for more information. */ #include <CppUTest/TestHarness.h> #include "CppUTest/CommandLineTestRunner.h" extern "C" { #include <stdio.h> #include <stdint.h> #include <stdlib.h> #include <string.h> #include <ctype.h> #include <ffi.h> #include "dyn_common.h" #include "dyn_type.h" #include "json_serializer.h" static void stdLog(void *handle, int level, const char *file, int line, const char *msg, ...) { va_list ap; const char *levels[5] = {"NIL", "ERROR", "WARNING", "INFO", "DEBUG"}; fprintf(stderr, "%s: FILE:%s, LINE:%i, MSG:",levels[level], file, line); va_start(ap, msg); vfprintf(stderr, msg, ap); fprintf(stderr, "\n"); } /*********** example 1 ************************/ /** struct type ******************************/ const char *example1_descriptor = "{DJISF a b c d e}"; const char *example1_input = "{ \ \"a\" : 1.0, \ \"b\" : 22, \ \"c\" : 32, \ \"d\" : 42, \ \"e\" : 4.4 \ }"; struct example1 { double a; //0 int64_t b; //1 int32_t c; //2 int16_t d; //3 float e; //4 }; static void check_example1(void *data) { struct example1 *ex = (struct example1 *)data; CHECK_EQUAL(1.0, ex->a); LONGS_EQUAL(22, ex->b); LONGS_EQUAL(32, ex->c); LONGS_EQUAL(42, ex->d); CHECK_EQUAL(4.4f, ex->e); } /*********** example 2 ************************/ const char *example2_descriptor = "{BJJDFD byte long1 long2 double1 float1 double2}"; const char *example2_input = "{ \ \"byte\" : 42, \ \"long1\" : 232, \ \"long2\" : 242, \ \"double1\" : 4.2, \ \"float1\" : 3.2, \ \"double2\" : 4.4 \ }"; struct example2 { char byte; //0 int64_t long1; //1 int64_t long2; //2 double double1; //3 float float1; //4 double double2; //5 }; static void check_example2(void *data) { struct example2 *ex = (struct example2 *)data; CHECK_EQUAL(42, ex->byte); LONGS_EQUAL(232, ex->long1); LONGS_EQUAL(242, ex->long2); CHECK_EQUAL(4.2, ex->double1); CHECK_EQUAL(3.2f, ex->float1); CHECK_EQUAL(4.4, ex->double2); } /*********** example 3 ************************/ /** sequence with a simple type **************/ const char *example3_descriptor = "{[I numbers}"; const char *example3_input = "{ \ \"numbers\" : [22,32,42] \ }"; struct example3 { struct { uint32_t cap; uint32_t len; int32_t *buf; } numbers; }; static void check_example3(void *data) { struct example3 *ex = (struct example3 *)data; CHECK_EQUAL(3, ex->numbers.len); CHECK_EQUAL(22, ex->numbers.buf[0]); CHECK_EQUAL(32, ex->numbers.buf[1]); CHECK_EQUAL(42, ex->numbers.buf[2]); } /*********** example 4 ************************/ /** structs within a struct (by reference)*******/ const char *example4_descriptor = "{{IDD index val1 val2}{IDD index val1 val2} left right}"; static const char *example4_input = "{ \ \"left\" : {\"index\":1, \"val1\":1.0, \"val2\":2.0 }, \ \"right\" : {\"index\":2, \"val1\":5.0, \"val2\":4.0 } \ }"; struct ex4_leaf { int32_t index; double val1; double val2; }; struct example4 { struct ex4_leaf left; struct ex4_leaf right; }; static void check_example4(void *data) { struct example4 *ex = (struct example4 *)data; CHECK_EQUAL(1, ex->left.index); CHECK_EQUAL(1.0, ex->left.val1); CHECK_EQUAL(2.0, ex->left.val2); CHECK_EQUAL(2, ex->right.index); CHECK_EQUAL(5.0, ex->right.val1); CHECK_EQUAL(4.0, ex->right.val2); } /*********** example 4 ************************/ /** structs within a struct (by reference)*******/ const char *example5_descriptor = "Tleaf={ts name age};Tnode={Lnode;Lnode;Lleaf; left right value};{Lnode; head}"; static const char *example5_input = "{ \ \"head\" : {\ \"left\" : {\ \"value\" : {\ \"name\" : \"John\",\ \"age\" : 44 \ }\ },\ \"right\" : {\ \"value\" : {\ \"name\" : \"Peter\", \ \"age\" : 55 \ }\ }\ }\ }"; struct leaf { const char *name; uint16_t age; }; struct node { struct node *left; struct node *right; struct leaf *value; }; struct example5 { struct node *head; }; static void check_example5(void *data) { struct example5 *ex = (struct example5 *)data; CHECK_TRUE(ex->head != NULL); CHECK(ex->head->left != NULL); CHECK(ex->head->left->value != NULL); STRCMP_EQUAL("John", ex->head->left->value->name); CHECK_EQUAL(44, ex->head->left->value->age); CHECK(ex->head->left->left == NULL); CHECK(ex->head->left->right == NULL); CHECK(ex->head->right != NULL); CHECK(ex->head->right->value != NULL); STRCMP_EQUAL("Peter", ex->head->right->value->name); CHECK_EQUAL(55, ex->head->right->value->age); CHECK(ex->head->right->left == NULL); CHECK(ex->head->right->right == NULL); } static const char *example6_descriptor = "Tsample={DD v1 v2};[lsample;"; static const char *example6_input = "[{\"v1\":0.1,\"v2\":0.2},{\"v1\":1.1,\"v2\":1.2},{\"v1\":2.1,\"v2\":2.2}]"; struct ex6_sample { double v1; double v2; }; struct ex6_sequence { uint32_t cap; uint32_t len; struct ex6_sample *buf; }; static void check_example6(struct ex6_sequence seq) { CHECK_EQUAL(3, seq.cap); CHECK_EQUAL(3, seq.len); CHECK_EQUAL(0.1, seq.buf[0].v1); CHECK_EQUAL(0.2, seq.buf[0].v2); CHECK_EQUAL(1.1, seq.buf[1].v1); CHECK_EQUAL(1.2, seq.buf[1].v2); CHECK_EQUAL(2.1, seq.buf[2].v1); CHECK_EQUAL(2.2, seq.buf[2].v2); } static void parseTests(void) { dyn_type *type; void *inst; int rc; type = NULL; inst = NULL; rc = dynType_parseWithStr(example1_descriptor, NULL, NULL, &type); CHECK_EQUAL(0, rc); rc = jsonSerializer_deserialize(type, example1_input, &inst); CHECK_EQUAL(0, rc); check_example1(inst); dynType_free(type, inst); dynType_destroy(type); type = NULL; inst = NULL; rc = dynType_parseWithStr(example2_descriptor, NULL, NULL, &type); CHECK_EQUAL(0, rc); rc = jsonSerializer_deserialize(type, example2_input, &inst); CHECK_EQUAL(0, rc); check_example2(inst); dynType_free(type, inst); dynType_destroy(type); type = NULL; inst = NULL; rc = dynType_parseWithStr(example3_descriptor, NULL, NULL, &type); CHECK_EQUAL(0, rc); rc = jsonSerializer_deserialize(type, example3_input, &inst); CHECK_EQUAL(0, rc); check_example3(inst); dynType_free(type, inst); dynType_destroy(type); type = NULL; inst = NULL; rc = dynType_parseWithStr(example4_descriptor, NULL, NULL, &type); CHECK_EQUAL(0, rc); rc = jsonSerializer_deserialize(type, example4_input, &inst); CHECK_EQUAL(0, rc); check_example4(inst); dynType_free(type, inst); dynType_destroy(type); type = NULL; inst = NULL; rc = dynType_parseWithStr(example5_descriptor, NULL, NULL, &type); CHECK_EQUAL(0, rc); rc = jsonSerializer_deserialize(type, example5_input, &inst); CHECK_EQUAL(0, rc); check_example5(inst); dynType_free(type, inst); dynType_destroy(type); type = NULL; struct ex6_sequence *seq; rc = dynType_parseWithStr(example6_descriptor, NULL, NULL, &type); CHECK_EQUAL(0, rc); rc = jsonSerializer_deserialize(type, example6_input, (void **)&seq); CHECK_EQUAL(0, rc); check_example6((*seq)); dynType_free(type, seq); dynType_destroy(type); } const char *write_example1_descriptor = "{BSIJsijFDN a b c d e f g h i j}"; struct write_example1 { char a; int16_t b; int32_t c; int64_t d; uint16_t e; uint32_t f; uint64_t g; float h; double i; int j; }; void writeTest1(void) { struct write_example1 ex1 = {.a=1, .b=2, .c=3, .d=4, .e=5, .f=6, .g=7, .h=8.8f, .i=9.9, .j=10}; dyn_type *type = NULL; char *result = NULL; int rc = dynType_parseWithStr(write_example1_descriptor, "ex1", NULL, &type); CHECK_EQUAL(0, rc); rc = jsonSerializer_serialize(type, &ex1, &result); CHECK_EQUAL(0, rc); STRCMP_CONTAINS("\"a\":1", result); STRCMP_CONTAINS("\"b\":2", result); STRCMP_CONTAINS("\"c\":3", result); STRCMP_CONTAINS("\"d\":4", result); STRCMP_CONTAINS("\"e\":5", result); STRCMP_CONTAINS("\"f\":6", result); STRCMP_CONTAINS("\"g\":7", result); STRCMP_CONTAINS("\"h\":8.8", result); STRCMP_CONTAINS("\"i\":9.9", result); STRCMP_CONTAINS("\"j\":10", result); //printf("example 1 result: '%s'\n", result); dynType_destroy(type); free(result); } const char *write_example2_descriptor = "{*{JJ a b}{SS c d} sub1 sub2}"; struct write_example2_sub { int64_t a; int64_t b; }; struct write_example2 { struct write_example2_sub *sub1; struct { int16_t c; int16_t d; } sub2; }; void writeTest2(void) { struct write_example2_sub sub1 = { .a = 1, .b = 2 }; struct write_example2 ex = { .sub1 = &sub1 }; ex.sub2.c = 3; ex.sub2.d = 4; dyn_type *type = NULL; char *result = NULL; int rc = dynType_parseWithStr(write_example2_descriptor, "ex2", NULL, &type); CHECK_EQUAL(0, rc); rc = jsonSerializer_serialize(type, &ex, &result); CHECK_EQUAL(0, rc); STRCMP_CONTAINS("\"a\":1", result); STRCMP_CONTAINS("\"b\":2", result); STRCMP_CONTAINS("\"c\":3", result); STRCMP_CONTAINS("\"d\":4", result); //printf("example 2 result: '%s'\n", result); dynType_destroy(type); free(result); } const char *write_example3_descriptor = "Tperson={ti name age};[Lperson;"; struct write_example3_person { const char *name; uint32_t age; }; struct write_example3 { uint32_t cap; uint32_t len; struct write_example3_person **buf; }; void writeTest3(void) { struct write_example3_person p1 = {.name = "John", .age = 33}; struct write_example3_person p2 = {.name = "Peter", .age = 44}; struct write_example3_person p3 = {.name = "Carol", .age = 55}; struct write_example3_person p4 = {.name = "Elton", .age = 66}; struct write_example3 seq; seq.buf = (struct write_example3_person **) calloc(4, sizeof(void *)); seq.len = seq.cap = 4; seq.buf[0] = &p1; seq.buf[1] = &p2; seq.buf[2] = &p3; seq.buf[3] = &p4; dyn_type *type = NULL; char *result = NULL; int rc = dynType_parseWithStr(write_example3_descriptor, "ex3", NULL, &type); CHECK_EQUAL(0, rc); rc = jsonSerializer_serialize(type, &seq, &result); CHECK_EQUAL(0, rc); STRCMP_CONTAINS("\"age\":33", result); STRCMP_CONTAINS("\"age\":44", result); STRCMP_CONTAINS("\"age\":55", result); STRCMP_CONTAINS("\"age\":66", result); //printf("example 3 result: '%s'\n", result); free(seq.buf); dynType_destroy(type); free(result); } } TEST_GROUP(JsonSerializerTests) { void setup() { int lvl = 1; dynCommon_logSetup(stdLog, NULL, lvl); dynType_logSetup(stdLog, NULL,lvl); jsonSerializer_logSetup(stdLog, NULL, lvl); } }; TEST(JsonSerializerTests, ParseTests) { //TODO split up parseTests(); } TEST(JsonSerializerTests, WriteTest1) { writeTest1(); } TEST(JsonSerializerTests, WriteTest2) { writeTest2(); } TEST(JsonSerializerTests, WriteTest3) { writeTest3(); } <commit_msg>CELIX-237: Changed intialization of test structs.<commit_after>/** * Licensed under Apache License v2. See LICENSE for more information. */ #include <CppUTest/TestHarness.h> #include "CppUTest/CommandLineTestRunner.h" extern "C" { #include <stdio.h> #include <stdint.h> #include <stdlib.h> #include <string.h> #include <ctype.h> #include <ffi.h> #include "dyn_common.h" #include "dyn_type.h" #include "json_serializer.h" static void stdLog(void *handle, int level, const char *file, int line, const char *msg, ...) { va_list ap; const char *levels[5] = {"NIL", "ERROR", "WARNING", "INFO", "DEBUG"}; fprintf(stderr, "%s: FILE:%s, LINE:%i, MSG:",levels[level], file, line); va_start(ap, msg); vfprintf(stderr, msg, ap); fprintf(stderr, "\n"); } /*********** example 1 ************************/ /** struct type ******************************/ const char *example1_descriptor = "{DJISF a b c d e}"; const char *example1_input = "{ \ \"a\" : 1.0, \ \"b\" : 22, \ \"c\" : 32, \ \"d\" : 42, \ \"e\" : 4.4 \ }"; struct example1 { double a; //0 int64_t b; //1 int32_t c; //2 int16_t d; //3 float e; //4 }; static void check_example1(void *data) { struct example1 *ex = (struct example1 *)data; CHECK_EQUAL(1.0, ex->a); LONGS_EQUAL(22, ex->b); LONGS_EQUAL(32, ex->c); LONGS_EQUAL(42, ex->d); CHECK_EQUAL(4.4f, ex->e); } /*********** example 2 ************************/ const char *example2_descriptor = "{BJJDFD byte long1 long2 double1 float1 double2}"; const char *example2_input = "{ \ \"byte\" : 42, \ \"long1\" : 232, \ \"long2\" : 242, \ \"double1\" : 4.2, \ \"float1\" : 3.2, \ \"double2\" : 4.4 \ }"; struct example2 { char byte; //0 int64_t long1; //1 int64_t long2; //2 double double1; //3 float float1; //4 double double2; //5 }; static void check_example2(void *data) { struct example2 *ex = (struct example2 *)data; CHECK_EQUAL(42, ex->byte); LONGS_EQUAL(232, ex->long1); LONGS_EQUAL(242, ex->long2); CHECK_EQUAL(4.2, ex->double1); CHECK_EQUAL(3.2f, ex->float1); CHECK_EQUAL(4.4, ex->double2); } /*********** example 3 ************************/ /** sequence with a simple type **************/ const char *example3_descriptor = "{[I numbers}"; const char *example3_input = "{ \ \"numbers\" : [22,32,42] \ }"; struct example3 { struct { uint32_t cap; uint32_t len; int32_t *buf; } numbers; }; static void check_example3(void *data) { struct example3 *ex = (struct example3 *)data; CHECK_EQUAL(3, ex->numbers.len); CHECK_EQUAL(22, ex->numbers.buf[0]); CHECK_EQUAL(32, ex->numbers.buf[1]); CHECK_EQUAL(42, ex->numbers.buf[2]); } /*********** example 4 ************************/ /** structs within a struct (by reference)*******/ const char *example4_descriptor = "{{IDD index val1 val2}{IDD index val1 val2} left right}"; static const char *example4_input = "{ \ \"left\" : {\"index\":1, \"val1\":1.0, \"val2\":2.0 }, \ \"right\" : {\"index\":2, \"val1\":5.0, \"val2\":4.0 } \ }"; struct ex4_leaf { int32_t index; double val1; double val2; }; struct example4 { struct ex4_leaf left; struct ex4_leaf right; }; static void check_example4(void *data) { struct example4 *ex = (struct example4 *)data; CHECK_EQUAL(1, ex->left.index); CHECK_EQUAL(1.0, ex->left.val1); CHECK_EQUAL(2.0, ex->left.val2); CHECK_EQUAL(2, ex->right.index); CHECK_EQUAL(5.0, ex->right.val1); CHECK_EQUAL(4.0, ex->right.val2); } /*********** example 4 ************************/ /** structs within a struct (by reference)*******/ const char *example5_descriptor = "Tleaf={ts name age};Tnode={Lnode;Lnode;Lleaf; left right value};{Lnode; head}"; static const char *example5_input = "{ \ \"head\" : {\ \"left\" : {\ \"value\" : {\ \"name\" : \"John\",\ \"age\" : 44 \ }\ },\ \"right\" : {\ \"value\" : {\ \"name\" : \"Peter\", \ \"age\" : 55 \ }\ }\ }\ }"; struct leaf { const char *name; uint16_t age; }; struct node { struct node *left; struct node *right; struct leaf *value; }; struct example5 { struct node *head; }; static void check_example5(void *data) { struct example5 *ex = (struct example5 *)data; CHECK_TRUE(ex->head != NULL); CHECK(ex->head->left != NULL); CHECK(ex->head->left->value != NULL); STRCMP_EQUAL("John", ex->head->left->value->name); CHECK_EQUAL(44, ex->head->left->value->age); CHECK(ex->head->left->left == NULL); CHECK(ex->head->left->right == NULL); CHECK(ex->head->right != NULL); CHECK(ex->head->right->value != NULL); STRCMP_EQUAL("Peter", ex->head->right->value->name); CHECK_EQUAL(55, ex->head->right->value->age); CHECK(ex->head->right->left == NULL); CHECK(ex->head->right->right == NULL); } static const char *example6_descriptor = "Tsample={DD v1 v2};[lsample;"; static const char *example6_input = "[{\"v1\":0.1,\"v2\":0.2},{\"v1\":1.1,\"v2\":1.2},{\"v1\":2.1,\"v2\":2.2}]"; struct ex6_sample { double v1; double v2; }; struct ex6_sequence { uint32_t cap; uint32_t len; struct ex6_sample *buf; }; static void check_example6(struct ex6_sequence seq) { CHECK_EQUAL(3, seq.cap); CHECK_EQUAL(3, seq.len); CHECK_EQUAL(0.1, seq.buf[0].v1); CHECK_EQUAL(0.2, seq.buf[0].v2); CHECK_EQUAL(1.1, seq.buf[1].v1); CHECK_EQUAL(1.2, seq.buf[1].v2); CHECK_EQUAL(2.1, seq.buf[2].v1); CHECK_EQUAL(2.2, seq.buf[2].v2); } static void parseTests(void) { dyn_type *type; void *inst; int rc; type = NULL; inst = NULL; rc = dynType_parseWithStr(example1_descriptor, NULL, NULL, &type); CHECK_EQUAL(0, rc); rc = jsonSerializer_deserialize(type, example1_input, &inst); CHECK_EQUAL(0, rc); check_example1(inst); dynType_free(type, inst); dynType_destroy(type); type = NULL; inst = NULL; rc = dynType_parseWithStr(example2_descriptor, NULL, NULL, &type); CHECK_EQUAL(0, rc); rc = jsonSerializer_deserialize(type, example2_input, &inst); CHECK_EQUAL(0, rc); check_example2(inst); dynType_free(type, inst); dynType_destroy(type); type = NULL; inst = NULL; rc = dynType_parseWithStr(example3_descriptor, NULL, NULL, &type); CHECK_EQUAL(0, rc); rc = jsonSerializer_deserialize(type, example3_input, &inst); CHECK_EQUAL(0, rc); check_example3(inst); dynType_free(type, inst); dynType_destroy(type); type = NULL; inst = NULL; rc = dynType_parseWithStr(example4_descriptor, NULL, NULL, &type); CHECK_EQUAL(0, rc); rc = jsonSerializer_deserialize(type, example4_input, &inst); CHECK_EQUAL(0, rc); check_example4(inst); dynType_free(type, inst); dynType_destroy(type); type = NULL; inst = NULL; rc = dynType_parseWithStr(example5_descriptor, NULL, NULL, &type); CHECK_EQUAL(0, rc); rc = jsonSerializer_deserialize(type, example5_input, &inst); CHECK_EQUAL(0, rc); check_example5(inst); dynType_free(type, inst); dynType_destroy(type); type = NULL; struct ex6_sequence *seq; rc = dynType_parseWithStr(example6_descriptor, NULL, NULL, &type); CHECK_EQUAL(0, rc); rc = jsonSerializer_deserialize(type, example6_input, (void **)&seq); CHECK_EQUAL(0, rc); check_example6((*seq)); dynType_free(type, seq); dynType_destroy(type); } const char *write_example1_descriptor = "{BSIJsijFDN a b c d e f g h i j}"; struct write_example1 { char a; int16_t b; int32_t c; int64_t d; uint16_t e; uint32_t f; uint64_t g; float h; double i; int j; }; void writeTest1(void) { struct write_example1 ex1; ex1.a=1; ex1.b=2; ex1.c=3; ex1.d=4; ex1.e=5; ex1.f=6; ex1.g=7; ex1.h=8.8f; ex1.i=9.9; ex1.j=10; dyn_type *type = NULL; char *result = NULL; int rc = dynType_parseWithStr(write_example1_descriptor, "ex1", NULL, &type); CHECK_EQUAL(0, rc); rc = jsonSerializer_serialize(type, &ex1, &result); CHECK_EQUAL(0, rc); STRCMP_CONTAINS("\"a\":1", result); STRCMP_CONTAINS("\"b\":2", result); STRCMP_CONTAINS("\"c\":3", result); STRCMP_CONTAINS("\"d\":4", result); STRCMP_CONTAINS("\"e\":5", result); STRCMP_CONTAINS("\"f\":6", result); STRCMP_CONTAINS("\"g\":7", result); STRCMP_CONTAINS("\"h\":8.8", result); STRCMP_CONTAINS("\"i\":9.9", result); STRCMP_CONTAINS("\"j\":10", result); //printf("example 1 result: '%s'\n", result); dynType_destroy(type); free(result); } const char *write_example2_descriptor = "{*{JJ a b}{SS c d} sub1 sub2}"; struct write_example2_sub { int64_t a; int64_t b; }; struct write_example2 { struct write_example2_sub *sub1; struct { int16_t c; int16_t d; } sub2; }; void writeTest2(void) { struct write_example2_sub sub1; sub1.a = 1; sub1.b = 2; struct write_example2 ex; ex.sub1=&sub1; ex.sub2.c = 3; ex.sub2.d = 4; dyn_type *type = NULL; char *result = NULL; int rc = dynType_parseWithStr(write_example2_descriptor, "ex2", NULL, &type); CHECK_EQUAL(0, rc); rc = jsonSerializer_serialize(type, &ex, &result); CHECK_EQUAL(0, rc); STRCMP_CONTAINS("\"a\":1", result); STRCMP_CONTAINS("\"b\":2", result); STRCMP_CONTAINS("\"c\":3", result); STRCMP_CONTAINS("\"d\":4", result); //printf("example 2 result: '%s'\n", result); dynType_destroy(type); free(result); } const char *write_example3_descriptor = "Tperson={ti name age};[Lperson;"; struct write_example3_person { const char *name; uint32_t age; }; struct write_example3 { uint32_t cap; uint32_t len; struct write_example3_person **buf; }; void writeTest3(void) { struct write_example3_person p1; p1.name = "John"; p1.age = 33; struct write_example3_person p2; p2.name = "Peter"; p2.age = 44; struct write_example3_person p3; p3.name = "Carol"; p3.age = 55; struct write_example3_person p4; p4.name = "Elton"; p4.age = 66; struct write_example3 seq; seq.buf = (struct write_example3_person **) calloc(4, sizeof(void *)); seq.len = seq.cap = 4; seq.buf[0] = &p1; seq.buf[1] = &p2; seq.buf[2] = &p3; seq.buf[3] = &p4; dyn_type *type = NULL; char *result = NULL; int rc = dynType_parseWithStr(write_example3_descriptor, "ex3", NULL, &type); CHECK_EQUAL(0, rc); rc = jsonSerializer_serialize(type, &seq, &result); CHECK_EQUAL(0, rc); STRCMP_CONTAINS("\"age\":33", result); STRCMP_CONTAINS("\"age\":44", result); STRCMP_CONTAINS("\"age\":55", result); STRCMP_CONTAINS("\"age\":66", result); //printf("example 3 result: '%s'\n", result); free(seq.buf); dynType_destroy(type); free(result); } } TEST_GROUP(JsonSerializerTests) { void setup() { int lvl = 1; dynCommon_logSetup(stdLog, NULL, lvl); dynType_logSetup(stdLog, NULL,lvl); jsonSerializer_logSetup(stdLog, NULL, lvl); } }; TEST(JsonSerializerTests, ParseTests) { //TODO split up parseTests(); } TEST(JsonSerializerTests, WriteTest1) { writeTest1(); } TEST(JsonSerializerTests, WriteTest2) { writeTest2(); } TEST(JsonSerializerTests, WriteTest3) { writeTest3(); } <|endoftext|>
<commit_before>/* * Copyright 2016, Masayoshi Mizutani, mizutani@sfc.wide.ad.jp * 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 <vector> #include <string> #include "./gtest.h" #include "../argparse.hpp" TEST(Parser, basic_usage) { argparse::Parser *psr = new argparse::Parser("test"); argparse::Argv args = {"./test", "-a"}; psr->add_argument("-a").action("store_true"); argparse::Values val = psr->parse_args(args); EXPECT_TRUE(val.is_true("a")); } TEST(Parser, basic_argument) { argparse::Parser *psr = new argparse::Parser("test"); argparse::Argv args = {"./test", "-a", "v"}; psr->add_argument("-a"); argparse::Values val = psr->parse_args(args); EXPECT_EQ("v", val.get("a")); EXPECT_EQ("v", val.get("a", 0)); EXPECT_EQ("v", val["a"]); // ["x"] is same with get("x", 0) } TEST(Parser, nargs1) { argparse::Parser *psr = new argparse::Parser("test"); psr->add_argument("-a").nargs(1); argparse::Argv args1 = {"./test", "-a", "v"}; argparse::Argv args2 = {"./test", "-a", "v", "w"}; argparse::Values val = psr->parse_args(args1); EXPECT_EQ(val.get("a"), "v"); EXPECT_THROW(val.get("a", 1), argparse::exception::IndexError); EXPECT_THROW(psr->parse_args(args2), argparse::exception::ParseError); } TEST(Parser, nargs2) { argparse::Parser *psr = new argparse::Parser("test"); psr->add_argument("-a").nargs(2); argparse::Argv args1 = {"./test", "-a", "v"}; argparse::Argv args2 = {"./test", "-a", "v", "w"}; argparse::Argv args3 = {"./test", "-a", "v", "w", "x"}; argparse::Values val = psr->parse_args(args2); EXPECT_EQ(val.get("a"), "v"); EXPECT_EQ(val.get("a", 0), "v"); EXPECT_EQ(val.get("a", 1), "w"); EXPECT_THROW(val.get("a", 2), argparse::exception::IndexError); EXPECT_THROW(psr->parse_args(args1), argparse::exception::ParseError); EXPECT_THROW(psr->parse_args(args3), argparse::exception::ParseError); } TEST(Parser, nargs_asterisk) { argparse::Parser *psr = new argparse::Parser("test"); psr->add_argument("-a").nargs("*"); psr->add_argument("-b"); // Stop parsing by end of arguments. argparse::Argv ok1 = {"./test", "-a", "v1", "v2"}; argparse::Values v1 = psr->parse_args(ok1); EXPECT_EQ(2, v1.size("a")); EXPECT_EQ("v1", v1.get("a", 0)); EXPECT_EQ("v2", v1.get("a", 1)); // Stop parsing by an other option. argparse::Argv ok2 = {"./test", "-a", "v1", "v2", "-b", "r1"}; argparse::Values v2 = psr->parse_args(ok2); EXPECT_EQ(2, v2.size("a")); EXPECT_EQ("v1", v2.get("a", 0)); EXPECT_EQ("v2", v2.get("a", 1)); EXPECT_EQ(1, v2.size("b")); EXPECT_EQ("r1", v2.get("b")); // No option value. argparse::Argv ok3 = {"./test", "-a", "-b", "r1"}; argparse::Values v3 = psr->parse_args(ok3); EXPECT_EQ(0, v3.size("a")); EXPECT_TRUE(v3.is_set("a")); EXPECT_EQ(1, v3.size("b")); EXPECT_EQ("r1", v3.get("b")); } class ParserNargsQuestion : public ::testing::Test { public: argparse::Parser *psr; argparse::Argument *arg; virtual void SetUp() { psr = new argparse::Parser("test"); arg = &(psr->add_argument("-a").nargs("?")); // 0 or 1 value psr->add_argument("-b"); } virtual void TearDown() { delete psr; } }; TEST_F(ParserNargsQuestion, ok0) { argparse::Argv seq = {"./test"}; argparse::Values v = psr->parse_args(seq); EXPECT_FALSE(v.is_set("a")); EXPECT_EQ(0, v.size("a")); EXPECT_FALSE(v.is_set("b")); } TEST_F(ParserNargsQuestion, ok1) { argparse::Argv seq = {"./test", "-a"}; argparse::Values v = psr->parse_args(seq); EXPECT_TRUE(v.is_set("a")); EXPECT_EQ(1, v.size("a")); EXPECT_FALSE(v.is_set("b")); } TEST_F(ParserNargsQuestion, ok2) { argparse::Argv seq = {"./test", "-a", "v1"}; argparse::Values v = psr->parse_args(seq); EXPECT_TRUE(v.is_set("a")); EXPECT_EQ(1, v.size("a")); EXPECT_EQ("v1", v["a"]); EXPECT_FALSE(v.is_set("b")); } TEST_F(ParserNargsQuestion, ok3) { argparse::Argv seq = {"./test", "-a", "v1", "-b", "r1"}; argparse::Values v = psr->parse_args(seq); EXPECT_TRUE(v.is_set("a")); EXPECT_EQ(1, v.size("a")); EXPECT_EQ("v1", v["a"]); EXPECT_TRUE(v.is_set("b")); } TEST_F(ParserNargsQuestion, with_default1) { arg->set_default("d"); argparse::Argv seq = {"./test", "-a"}; argparse::Values v = psr->parse_args(seq); EXPECT_TRUE(v.is_set("a")); EXPECT_EQ(1, v.size("a")); EXPECT_EQ("d", v["a"]); } TEST_F(ParserNargsQuestion, with_default2) { arg->set_default("d"); argparse::Argv seq = {"./test"}; argparse::Values v = psr->parse_args(seq); EXPECT_TRUE(v.is_set("a")); EXPECT_EQ(1, v.size("a")); EXPECT_EQ("d", v["a"]); } TEST_F(ParserNargsQuestion, with_const) { arg->set_const("c"); argparse::Argv seq = {"./test", "-a"}; argparse::Values v = psr->parse_args(seq); EXPECT_TRUE(v.is_set("a")); EXPECT_EQ(1, v.size("a")); EXPECT_EQ("c", v["a"]); } TEST(Parser, name2) { argparse::Parser *psr = new argparse::Parser("test"); psr->add_argument("-a").name("--action"); argparse::Argv ok1 = {"./test", "-a", "v"}; argparse::Argv ok2 = {"./test", "--action", "v"}; argparse::Argv ng1 = {"./test", "-a"}; // Not enough arguments argparse::Argv ng2 = {"./test", "--action"}; // Same as above argparse::Values v1 = psr->parse_args(ok1); argparse::Values v2 = psr->parse_args(ok2); EXPECT_EQ(v1.get("a"), "v"); // Using "name" instead of "dest". EXPECT_EQ(v2.get("a"), "v"); // Same if the option is set by 2nd name (--aciton) EXPECT_THROW(psr->parse_args(ng1), argparse::exception::ParseError); EXPECT_THROW(psr->parse_args(ng1), argparse::exception::ParseError); } <commit_msg>add test for ParserNargsQuestion with both of default and const<commit_after>/* * Copyright 2016, Masayoshi Mizutani, mizutani@sfc.wide.ad.jp * 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 <vector> #include <string> #include "./gtest.h" #include "../argparse.hpp" TEST(Parser, basic_usage) { argparse::Parser *psr = new argparse::Parser("test"); argparse::Argv args = {"./test", "-a"}; psr->add_argument("-a").action("store_true"); argparse::Values val = psr->parse_args(args); EXPECT_TRUE(val.is_true("a")); } TEST(Parser, basic_argument) { argparse::Parser *psr = new argparse::Parser("test"); argparse::Argv args = {"./test", "-a", "v"}; psr->add_argument("-a"); argparse::Values val = psr->parse_args(args); EXPECT_EQ("v", val.get("a")); EXPECT_EQ("v", val.get("a", 0)); EXPECT_EQ("v", val["a"]); // ["x"] is same with get("x", 0) } TEST(Parser, nargs1) { argparse::Parser *psr = new argparse::Parser("test"); psr->add_argument("-a").nargs(1); argparse::Argv args1 = {"./test", "-a", "v"}; argparse::Argv args2 = {"./test", "-a", "v", "w"}; argparse::Values val = psr->parse_args(args1); EXPECT_EQ(val.get("a"), "v"); EXPECT_THROW(val.get("a", 1), argparse::exception::IndexError); EXPECT_THROW(psr->parse_args(args2), argparse::exception::ParseError); } TEST(Parser, nargs2) { argparse::Parser *psr = new argparse::Parser("test"); psr->add_argument("-a").nargs(2); argparse::Argv args1 = {"./test", "-a", "v"}; argparse::Argv args2 = {"./test", "-a", "v", "w"}; argparse::Argv args3 = {"./test", "-a", "v", "w", "x"}; argparse::Values val = psr->parse_args(args2); EXPECT_EQ(val.get("a"), "v"); EXPECT_EQ(val.get("a", 0), "v"); EXPECT_EQ(val.get("a", 1), "w"); EXPECT_THROW(val.get("a", 2), argparse::exception::IndexError); EXPECT_THROW(psr->parse_args(args1), argparse::exception::ParseError); EXPECT_THROW(psr->parse_args(args3), argparse::exception::ParseError); } TEST(Parser, nargs_asterisk) { argparse::Parser *psr = new argparse::Parser("test"); psr->add_argument("-a").nargs("*"); psr->add_argument("-b"); // Stop parsing by end of arguments. argparse::Argv ok1 = {"./test", "-a", "v1", "v2"}; argparse::Values v1 = psr->parse_args(ok1); EXPECT_EQ(2, v1.size("a")); EXPECT_EQ("v1", v1.get("a", 0)); EXPECT_EQ("v2", v1.get("a", 1)); // Stop parsing by an other option. argparse::Argv ok2 = {"./test", "-a", "v1", "v2", "-b", "r1"}; argparse::Values v2 = psr->parse_args(ok2); EXPECT_EQ(2, v2.size("a")); EXPECT_EQ("v1", v2.get("a", 0)); EXPECT_EQ("v2", v2.get("a", 1)); EXPECT_EQ(1, v2.size("b")); EXPECT_EQ("r1", v2.get("b")); // No option value. argparse::Argv ok3 = {"./test", "-a", "-b", "r1"}; argparse::Values v3 = psr->parse_args(ok3); EXPECT_EQ(0, v3.size("a")); EXPECT_TRUE(v3.is_set("a")); EXPECT_EQ(1, v3.size("b")); EXPECT_EQ("r1", v3.get("b")); } class ParserNargsQuestion : public ::testing::Test { public: argparse::Parser *psr; argparse::Argument *arg; virtual void SetUp() { psr = new argparse::Parser("test"); arg = &(psr->add_argument("-a").nargs("?")); // 0 or 1 value psr->add_argument("-b"); } virtual void TearDown() { delete psr; } }; TEST_F(ParserNargsQuestion, ok0) { argparse::Argv seq = {"./test"}; argparse::Values v = psr->parse_args(seq); EXPECT_FALSE(v.is_set("a")); EXPECT_EQ(0, v.size("a")); EXPECT_FALSE(v.is_set("b")); } TEST_F(ParserNargsQuestion, ok1) { argparse::Argv seq = {"./test", "-a"}; argparse::Values v = psr->parse_args(seq); EXPECT_TRUE(v.is_set("a")); EXPECT_EQ(1, v.size("a")); EXPECT_FALSE(v.is_set("b")); } TEST_F(ParserNargsQuestion, ok2) { argparse::Argv seq = {"./test", "-a", "v1"}; argparse::Values v = psr->parse_args(seq); EXPECT_TRUE(v.is_set("a")); EXPECT_EQ(1, v.size("a")); EXPECT_EQ("v1", v["a"]); EXPECT_FALSE(v.is_set("b")); } TEST_F(ParserNargsQuestion, ok3) { argparse::Argv seq = {"./test", "-a", "v1", "-b", "r1"}; argparse::Values v = psr->parse_args(seq); EXPECT_TRUE(v.is_set("a")); EXPECT_EQ(1, v.size("a")); EXPECT_EQ("v1", v["a"]); EXPECT_TRUE(v.is_set("b")); } TEST_F(ParserNargsQuestion, with_default1) { arg->set_default("d"); argparse::Argv seq = {"./test", "-a"}; argparse::Values v = psr->parse_args(seq); EXPECT_TRUE(v.is_set("a")); EXPECT_EQ(1, v.size("a")); EXPECT_EQ("d", v["a"]); } TEST_F(ParserNargsQuestion, with_default2) { arg->set_default("d"); argparse::Argv seq = {"./test"}; argparse::Values v = psr->parse_args(seq); EXPECT_TRUE(v.is_set("a")); EXPECT_EQ(1, v.size("a")); EXPECT_EQ("d", v["a"]); } TEST_F(ParserNargsQuestion, with_const) { arg->set_const("c"); argparse::Argv seq = {"./test", "-a"}; argparse::Values v = psr->parse_args(seq); EXPECT_TRUE(v.is_set("a")); EXPECT_EQ(1, v.size("a")); EXPECT_EQ("c", v["a"]); } TEST_F(ParserNargsQuestion, with_default_and_const) { arg->set_const("c").set_default("d"); argparse::Argv seq = {"./test", "-a"}; argparse::Values v = psr->parse_args(seq); EXPECT_TRUE(v.is_set("a")); EXPECT_EQ(1, v.size("a")); // 'const' has priority over 'default' EXPECT_EQ("c", v["a"]); } TEST(Parser, name2) { argparse::Parser *psr = new argparse::Parser("test"); psr->add_argument("-a").name("--action"); argparse::Argv ok1 = {"./test", "-a", "v"}; argparse::Argv ok2 = {"./test", "--action", "v"}; argparse::Argv ng1 = {"./test", "-a"}; // Not enough arguments argparse::Argv ng2 = {"./test", "--action"}; // Same as above argparse::Values v1 = psr->parse_args(ok1); argparse::Values v2 = psr->parse_args(ok2); EXPECT_EQ(v1.get("a"), "v"); // Using "name" instead of "dest". EXPECT_EQ(v2.get("a"), "v"); // Same if the option is set by 2nd name (--aciton) EXPECT_THROW(psr->parse_args(ng1), argparse::exception::ParseError); EXPECT_THROW(psr->parse_args(ng1), argparse::exception::ParseError); } <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: xlpage.hxx,v $ * * $Revision: 1.5 $ * * last change: $Author: rt $ $Date: 2005-09-08 19:37:34 $ * * 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 SC_XLPAGE_HXX #define SC_XLPAGE_HXX #ifndef _GEN_HXX #include <tools/gen.hxx> #endif #ifndef SC_XLTOOLS_HXX #include "xltools.hxx" #endif // Constants and Enumerations ================================================= // (0x0014, 0x0015) HEADER, FOOTER -------------------------------------------- const sal_uInt16 EXC_ID_HEADER = 0x0014; const sal_uInt16 EXC_ID_FOOTER = 0x0015; // (0x001A, 0x001B) VERTICAL-, HORIZONTALPAGEBREAKS --------------------------- const sal_uInt16 EXC_ID_VERPAGEBREAKS = 0x001A; const sal_uInt16 EXC_ID_HORPAGEBREAKS = 0x001B; // (0x0026, 0x0027, 0x0028, 0x0029) LEFT-, RIGHT-, TOP-, BOTTOMMARGIN --------- const sal_uInt16 EXC_ID_LEFTMARGIN = 0x0026; const sal_uInt16 EXC_ID_RIGHTMARGIN = 0x0027; const sal_uInt16 EXC_ID_TOPMARGIN = 0x0028; const sal_uInt16 EXC_ID_BOTTOMMARGIN = 0x0029; const sal_Int32 EXC_MARGIN_DEFAULT_LR = 1900; /// Left/right default margin in 1/100mm. const sal_Int32 EXC_MARGIN_DEFAULT_TB = 2500; /// Top/bottom default margin in 1/100mm. const sal_Int32 EXC_MARGIN_DEFAULT_HF = 1300; /// Header/footer default margin in 1/100mm. const sal_Int32 EXC_MARGIN_DEFAULT_HLR = 1900; /// Left/right header default margin in 1/100mm. const sal_Int32 EXC_MARGIN_DEFAULT_FLR = 1900; /// Left/right footer default margin in 1/100mm. // (0x002A, 0x002B) PRINTHEADERS, PRINTGRIDLINES ------------------------------ const sal_uInt16 EXC_ID_PRINTHEADERS = 0x002A; const sal_uInt16 EXC_ID_PRINTGRIDLINES = 0x002B; // (0x0082, 0x0083, 0x0084) GRIDSET, HCENTER, VCENTER ------------------------- const sal_uInt16 EXC_ID_GRIDSET = 0x0082; const sal_uInt16 EXC_ID_HCENTER = 0x0083; const sal_uInt16 EXC_ID_VCENTER = 0x0084; // (0x00A1) SETUP ------------------------------------------------------------- const sal_uInt16 EXC_ID_SETUP = 0x00A1; const sal_uInt16 EXC_SETUP_INROWS = 0x0001; const sal_uInt16 EXC_SETUP_PORTRAIT = 0x0002; const sal_uInt16 EXC_SETUP_INVALID = 0x0004; const sal_uInt16 EXC_SETUP_BLACKWHITE = 0x0008; const sal_uInt16 EXC_SETUP_DRAFT = 0x0010; const sal_uInt16 EXC_SETUP_PRINTNOTES = 0x0020; const sal_uInt16 EXC_SETUP_STARTPAGE = 0x0080; const sal_uInt16 EXC_SETUP_NOTES_END = 0x0200; const sal_uInt16 EXC_PAPERSIZE_DEFAULT = 0; // (0x00E9) BITMAP ------------------------------------------------------------ const sal_uInt16 EXC_ID_BITMAP = 0x00E9; const sal_uInt32 EXC_BITMAP_UNKNOWNID = 0x00010009; const sal_uInt32 EXC_BITMAP_MAXREC = 0x201C; const sal_uInt32 EXC_BITMAP_MAXCONT = 0x2014; // ============================================================================ // Page settings ============================================================== class SvxBrushItem; class SfxPrinter; /** Contains all page (print) settings for a single sheet. */ struct XclPageData : ScfNoCopy { typedef ::std::auto_ptr< SvxBrushItem > SvxBrushItemPtr; ScfUInt16Vec maHorPageBreaks; /// Horizontal page breaks. ScfUInt16Vec maVerPageBreaks; /// Vertical page breaks. SvxBrushItemPtr mxBrushItem; /// Background bitmap. String maHeader; /// Excel header string (empty = off). String maFooter; /// Excel footer string (empty = off). double mfLeftMargin; /// Left margin in inches. double mfRightMargin; /// Right margin in inches. double mfTopMargin; /// Top margin in inches. double mfBottomMargin; /// Bottom margin in inches. double mfHeaderMargin; /// Margin main page to header. double mfFooterMargin; /// Margin main page to footer. double mfHdrLeftMargin; /// Left margin to header. double mfHdrRightMargin; /// Right margin to header. double mfFtrLeftMargin; /// Left margin to footer. double mfFtrRightMargin; /// Right margin to footer. sal_uInt16 mnPaperSize; /// Index into paper size table. sal_uInt16 mnCopies; /// Number of copies. sal_uInt16 mnStartPage; /// Start page number. sal_uInt16 mnScaling; /// Scaling in percent. sal_uInt16 mnFitToWidth; /// Fit to number of pages in width. sal_uInt16 mnFitToHeight; /// Fit to number of pages in height. sal_uInt16 mnHorPrintRes; /// Horizontal printing resolution. sal_uInt16 mnVerPrintRes; /// Vertical printing resolution. bool mbValid; /// false = some of the values are not valid. bool mbPortrait; /// true = portrait; false = landscape. bool mbPrintInRows; /// true = in rows; false = in columns. bool mbBlackWhite; /// true = black/white; false = colors. bool mbDraftQuality; /// true = draft; false = default quality. bool mbPrintNotes; /// true = print notes. bool mbManualStart; /// true = mnStartPage valid; false = automatic. bool mbFitToPages; /// true = fit to pages; false = scale in percent. bool mbHorCenter; /// true = centered horizontally; false = left aligned. bool mbVerCenter; /// true = centered vertically; false = top aligned. bool mbPrintHeadings; /// true = print column and row headings. bool mbPrintGrid; /// true = print grid lines. explicit XclPageData(); ~XclPageData(); /** Sets Excel default page settings. */ void SetDefaults(); /** Returns the real paper size (twips) from the paper size index and paper orientation. */ Size GetScPaperSize( SfxPrinter* pPrinter ) const; /** Sets the Excel paper size index and paper orientation from Calc paper size (twips). */ void SetScPaperSize( const Size& rSize, bool bPortrait ); }; // ============================================================================ #endif <commit_msg>INTEGRATION: CWS chart2mst3 (1.5.26); FILE MERGED 2006/07/11 14:13:49 dr 1.5.26.1: #export of chart line and area formats<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: xlpage.hxx,v $ * * $Revision: 1.6 $ * * last change: $Author: vg $ $Date: 2007-05-22 19:59:39 $ * * 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 SC_XLPAGE_HXX #define SC_XLPAGE_HXX #ifndef _GEN_HXX #include <tools/gen.hxx> #endif #ifndef SC_XLTOOLS_HXX #include "xltools.hxx" #endif // Constants and Enumerations ================================================= // (0x0014, 0x0015) HEADER, FOOTER -------------------------------------------- const sal_uInt16 EXC_ID_HEADER = 0x0014; const sal_uInt16 EXC_ID_FOOTER = 0x0015; // (0x001A, 0x001B) VERTICAL-, HORIZONTALPAGEBREAKS --------------------------- const sal_uInt16 EXC_ID_VERPAGEBREAKS = 0x001A; const sal_uInt16 EXC_ID_HORPAGEBREAKS = 0x001B; // (0x0026, 0x0027, 0x0028, 0x0029) LEFT-, RIGHT-, TOP-, BOTTOMMARGIN --------- const sal_uInt16 EXC_ID_LEFTMARGIN = 0x0026; const sal_uInt16 EXC_ID_RIGHTMARGIN = 0x0027; const sal_uInt16 EXC_ID_TOPMARGIN = 0x0028; const sal_uInt16 EXC_ID_BOTTOMMARGIN = 0x0029; const sal_Int32 EXC_MARGIN_DEFAULT_LR = 1900; /// Left/right default margin in 1/100mm. const sal_Int32 EXC_MARGIN_DEFAULT_TB = 2500; /// Top/bottom default margin in 1/100mm. const sal_Int32 EXC_MARGIN_DEFAULT_HF = 1300; /// Header/footer default margin in 1/100mm. const sal_Int32 EXC_MARGIN_DEFAULT_HLR = 1900; /// Left/right header default margin in 1/100mm. const sal_Int32 EXC_MARGIN_DEFAULT_FLR = 1900; /// Left/right footer default margin in 1/100mm. // (0x002A, 0x002B) PRINTHEADERS, PRINTGRIDLINES ------------------------------ const sal_uInt16 EXC_ID_PRINTHEADERS = 0x002A; const sal_uInt16 EXC_ID_PRINTGRIDLINES = 0x002B; // (0x0033) PRINTSIZE --------------------------------------------------------- const sal_uInt16 EXC_ID_PRINTSIZE = 0x0033; const sal_uInt16 EXC_PRINTSIZE_SCREEN = 1; const sal_uInt16 EXC_PRINTSIZE_PAGE = 2; const sal_uInt16 EXC_PRINTSIZE_FULL = 3; // (0x0082, 0x0083, 0x0084) GRIDSET, HCENTER, VCENTER ------------------------- const sal_uInt16 EXC_ID_GRIDSET = 0x0082; const sal_uInt16 EXC_ID_HCENTER = 0x0083; const sal_uInt16 EXC_ID_VCENTER = 0x0084; // (0x00A1) SETUP ------------------------------------------------------------- const sal_uInt16 EXC_ID_SETUP = 0x00A1; const sal_uInt16 EXC_SETUP_INROWS = 0x0001; const sal_uInt16 EXC_SETUP_PORTRAIT = 0x0002; const sal_uInt16 EXC_SETUP_INVALID = 0x0004; const sal_uInt16 EXC_SETUP_BLACKWHITE = 0x0008; const sal_uInt16 EXC_SETUP_DRAFT = 0x0010; const sal_uInt16 EXC_SETUP_PRINTNOTES = 0x0020; const sal_uInt16 EXC_SETUP_STARTPAGE = 0x0080; const sal_uInt16 EXC_SETUP_NOTES_END = 0x0200; const sal_uInt16 EXC_PAPERSIZE_DEFAULT = 0; // (0x00E9) BITMAP ------------------------------------------------------------ const sal_uInt16 EXC_ID_BITMAP = 0x00E9; const sal_uInt32 EXC_BITMAP_UNKNOWNID = 0x00010009; const sal_uInt32 EXC_BITMAP_MAXREC = 0x201C; const sal_uInt32 EXC_BITMAP_MAXCONT = 0x2014; // ============================================================================ // Page settings ============================================================== class SvxBrushItem; class SfxPrinter; /** Contains all page (print) settings for a single sheet. */ struct XclPageData : ScfNoCopy { typedef ::std::auto_ptr< SvxBrushItem > SvxBrushItemPtr; ScfUInt16Vec maHorPageBreaks; /// Horizontal page breaks. ScfUInt16Vec maVerPageBreaks; /// Vertical page breaks. SvxBrushItemPtr mxBrushItem; /// Background bitmap. String maHeader; /// Excel header string (empty = off). String maFooter; /// Excel footer string (empty = off). double mfLeftMargin; /// Left margin in inches. double mfRightMargin; /// Right margin in inches. double mfTopMargin; /// Top margin in inches. double mfBottomMargin; /// Bottom margin in inches. double mfHeaderMargin; /// Margin main page to header. double mfFooterMargin; /// Margin main page to footer. double mfHdrLeftMargin; /// Left margin to header. double mfHdrRightMargin; /// Right margin to header. double mfFtrLeftMargin; /// Left margin to footer. double mfFtrRightMargin; /// Right margin to footer. sal_uInt16 mnPaperSize; /// Index into paper size table. sal_uInt16 mnCopies; /// Number of copies. sal_uInt16 mnStartPage; /// Start page number. sal_uInt16 mnScaling; /// Scaling in percent. sal_uInt16 mnFitToWidth; /// Fit to number of pages in width. sal_uInt16 mnFitToHeight; /// Fit to number of pages in height. sal_uInt16 mnHorPrintRes; /// Horizontal printing resolution. sal_uInt16 mnVerPrintRes; /// Vertical printing resolution. bool mbValid; /// false = some of the values are not valid. bool mbPortrait; /// true = portrait; false = landscape. bool mbPrintInRows; /// true = in rows; false = in columns. bool mbBlackWhite; /// true = black/white; false = colors. bool mbDraftQuality; /// true = draft; false = default quality. bool mbPrintNotes; /// true = print notes. bool mbManualStart; /// true = mnStartPage valid; false = automatic. bool mbFitToPages; /// true = fit to pages; false = scale in percent. bool mbHorCenter; /// true = centered horizontally; false = left aligned. bool mbVerCenter; /// true = centered vertically; false = top aligned. bool mbPrintHeadings; /// true = print column and row headings. bool mbPrintGrid; /// true = print grid lines. explicit XclPageData(); ~XclPageData(); /** Sets Excel default page settings. */ void SetDefaults(); /** Returns the real paper size (twips) from the paper size index and paper orientation. */ Size GetScPaperSize( SfxPrinter* pPrinter ) const; /** Sets the Excel paper size index and paper orientation from Calc paper size (twips). */ void SetScPaperSize( const Size& rSize, bool bPortrait ); }; // ============================================================================ #endif <|endoftext|>
<commit_before>/*************************************************************************/ /* navigation_link_2d.cpp */ /*************************************************************************/ /* This file is part of: */ /* GODOT ENGINE */ /* https://godotengine.org */ /*************************************************************************/ /* Copyright (c) 2007-2022 Juan Linietsky, Ariel Manzur. */ /* Copyright (c) 2014-2022 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 "navigation_link_2d.h" #include "core/math/geometry_2d.h" #include "scene/resources/world_2d.h" #include "servers/navigation_server_2d.h" #include "servers/navigation_server_3d.h" void NavigationLink2D::_bind_methods() { ClassDB::bind_method(D_METHOD("set_enabled", "enabled"), &NavigationLink2D::set_enabled); ClassDB::bind_method(D_METHOD("is_enabled"), &NavigationLink2D::is_enabled); ClassDB::bind_method(D_METHOD("set_bidirectional", "bidirectional"), &NavigationLink2D::set_bidirectional); ClassDB::bind_method(D_METHOD("is_bidirectional"), &NavigationLink2D::is_bidirectional); ClassDB::bind_method(D_METHOD("set_navigation_layers", "navigation_layers"), &NavigationLink2D::set_navigation_layers); ClassDB::bind_method(D_METHOD("get_navigation_layers"), &NavigationLink2D::get_navigation_layers); ClassDB::bind_method(D_METHOD("set_navigation_layer_value", "layer_number", "value"), &NavigationLink2D::set_navigation_layer_value); ClassDB::bind_method(D_METHOD("get_navigation_layer_value", "layer_number"), &NavigationLink2D::get_navigation_layer_value); ClassDB::bind_method(D_METHOD("set_start_location", "location"), &NavigationLink2D::set_start_location); ClassDB::bind_method(D_METHOD("get_start_location"), &NavigationLink2D::get_start_location); ClassDB::bind_method(D_METHOD("set_end_location", "location"), &NavigationLink2D::set_end_location); ClassDB::bind_method(D_METHOD("get_end_location"), &NavigationLink2D::get_end_location); ClassDB::bind_method(D_METHOD("set_enter_cost", "enter_cost"), &NavigationLink2D::set_enter_cost); ClassDB::bind_method(D_METHOD("get_enter_cost"), &NavigationLink2D::get_enter_cost); ClassDB::bind_method(D_METHOD("set_travel_cost", "travel_cost"), &NavigationLink2D::set_travel_cost); ClassDB::bind_method(D_METHOD("get_travel_cost"), &NavigationLink2D::get_travel_cost); ADD_PROPERTY(PropertyInfo(Variant::BOOL, "enabled"), "set_enabled", "is_enabled"); ADD_PROPERTY(PropertyInfo(Variant::BOOL, "bidirectional"), "set_bidirectional", "is_bidirectional"); ADD_PROPERTY(PropertyInfo(Variant::INT, "navigation_layers", PROPERTY_HINT_LAYERS_2D_NAVIGATION), "set_navigation_layers", "get_navigation_layers"); ADD_PROPERTY(PropertyInfo(Variant::VECTOR2, "start_location"), "set_start_location", "get_start_location"); ADD_PROPERTY(PropertyInfo(Variant::VECTOR2, "end_location"), "set_end_location", "get_end_location"); ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "enter_cost"), "set_enter_cost", "get_enter_cost"); ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "travel_cost"), "set_travel_cost", "get_travel_cost"); } void NavigationLink2D::_notification(int p_what) { switch (p_what) { case NOTIFICATION_ENTER_TREE: { if (enabled) { NavigationServer2D::get_singleton()->link_set_map(link, get_world_2d()->get_navigation_map()); // Update global positions for the link. Transform2D gt = get_global_transform(); NavigationServer2D::get_singleton()->link_set_start_location(link, gt.xform(start_location)); NavigationServer2D::get_singleton()->link_set_end_location(link, gt.xform(end_location)); } } break; case NOTIFICATION_TRANSFORM_CHANGED: { // Update global positions for the link. Transform2D gt = get_global_transform(); NavigationServer2D::get_singleton()->link_set_start_location(link, gt.xform(start_location)); NavigationServer2D::get_singleton()->link_set_end_location(link, gt.xform(end_location)); } break; case NOTIFICATION_EXIT_TREE: { NavigationServer2D::get_singleton()->link_set_map(link, RID()); } break; case NOTIFICATION_DRAW: { #ifdef DEBUG_ENABLED if (is_inside_tree() && (Engine::get_singleton()->is_editor_hint() || NavigationServer2D::get_singleton()->get_debug_enabled())) { Color color; if (enabled) { color = NavigationServer2D::get_singleton()->get_debug_navigation_link_connection_color(); } else { color = NavigationServer2D::get_singleton()->get_debug_navigation_link_connection_disabled_color(); } real_t radius = NavigationServer2D::get_singleton()->map_get_link_connection_radius(get_world_2d()->get_navigation_map()); draw_line(get_start_location(), get_end_location(), color); draw_arc(get_start_location(), radius, 0, Math_TAU, 10, color); draw_arc(get_end_location(), radius, 0, Math_TAU, 10, color); } #endif // DEBUG_ENABLED } break; } } #ifdef TOOLS_ENABLED Rect2 NavigationLink2D::_edit_get_rect() const { real_t radius = NavigationServer2D::get_singleton()->map_get_link_connection_radius(get_world_2d()->get_navigation_map()); Rect2 rect(get_start_location(), Size2()); rect.expand_to(get_end_location()); rect.grow_by(radius); return rect; } bool NavigationLink2D::_edit_is_selected_on_click(const Point2 &p_point, double p_tolerance) const { Point2 segment[2] = { get_start_location(), get_end_location() }; Vector2 closest_point = Geometry2D::get_closest_point_to_segment(p_point, segment); return p_point.distance_to(closest_point) < p_tolerance; } #endif // TOOLS_ENABLED void NavigationLink2D::set_enabled(bool p_enabled) { if (enabled == p_enabled) { return; } enabled = p_enabled; if (!is_inside_tree()) { return; } if (!enabled) { NavigationServer2D::get_singleton()->link_set_map(link, RID()); } else { NavigationServer2D::get_singleton()->link_set_map(link, get_world_2d()->get_navigation_map()); } #ifdef DEBUG_ENABLED if (Engine::get_singleton()->is_editor_hint() || NavigationServer2D::get_singleton()->get_debug_enabled()) { update(); } #endif // DEBUG_ENABLED } void NavigationLink2D::set_bidirectional(bool p_bidirectional) { if (bidirectional == p_bidirectional) { return; } bidirectional = p_bidirectional; NavigationServer2D::get_singleton()->link_set_bidirectional(link, bidirectional); } void NavigationLink2D::set_navigation_layers(uint32_t p_navigation_layers) { if (navigation_layers == p_navigation_layers) { return; } navigation_layers = p_navigation_layers; NavigationServer2D::get_singleton()->link_set_navigation_layers(link, navigation_layers); } void NavigationLink2D::set_navigation_layer_value(int p_layer_number, bool p_value) { ERR_FAIL_COND_MSG(p_layer_number < 1, "Navigation layer number must be between 1 and 32 inclusive."); ERR_FAIL_COND_MSG(p_layer_number > 32, "Navigation layer number must be between 1 and 32 inclusive."); uint32_t _navigation_layers = get_navigation_layers(); if (p_value) { _navigation_layers |= 1 << (p_layer_number - 1); } else { _navigation_layers &= ~(1 << (p_layer_number - 1)); } set_navigation_layers(_navigation_layers); } bool NavigationLink2D::get_navigation_layer_value(int p_layer_number) const { ERR_FAIL_COND_V_MSG(p_layer_number < 1, false, "Navigation layer number must be between 1 and 32 inclusive."); ERR_FAIL_COND_V_MSG(p_layer_number > 32, false, "Navigation layer number must be between 1 and 32 inclusive."); return get_navigation_layers() & (1 << (p_layer_number - 1)); } void NavigationLink2D::set_start_location(Vector2 p_location) { if (start_location.is_equal_approx(p_location)) { return; } start_location = p_location; if (!is_inside_tree()) { return; } Transform2D gt = get_global_transform(); NavigationServer2D::get_singleton()->link_set_start_location(link, gt.xform(start_location)); update_configuration_warnings(); #ifdef DEBUG_ENABLED if (Engine::get_singleton()->is_editor_hint() || NavigationServer2D::get_singleton()->get_debug_enabled()) { update(); } #endif // DEBUG_ENABLED } void NavigationLink2D::set_end_location(Vector2 p_location) { if (end_location.is_equal_approx(p_location)) { return; } end_location = p_location; if (!is_inside_tree()) { return; } Transform2D gt = get_global_transform(); NavigationServer2D::get_singleton()->link_set_end_location(link, gt.xform(end_location)); update_configuration_warnings(); #ifdef DEBUG_ENABLED if (Engine::get_singleton()->is_editor_hint() || NavigationServer2D::get_singleton()->get_debug_enabled()) { update(); } #endif // DEBUG_ENABLED } void NavigationLink2D::set_enter_cost(real_t p_enter_cost) { ERR_FAIL_COND_MSG(p_enter_cost < 0.0, "The enter_cost must be positive."); if (Math::is_equal_approx(enter_cost, p_enter_cost)) { return; } enter_cost = p_enter_cost; NavigationServer2D::get_singleton()->link_set_enter_cost(link, enter_cost); } void NavigationLink2D::set_travel_cost(real_t p_travel_cost) { ERR_FAIL_COND_MSG(p_travel_cost < 0.0, "The travel_cost must be positive."); if (Math::is_equal_approx(travel_cost, p_travel_cost)) { return; } travel_cost = p_travel_cost; NavigationServer2D::get_singleton()->link_set_travel_cost(link, travel_cost); } TypedArray<String> NavigationLink2D::get_configuration_warnings() const { TypedArray<String> warnings = Node::get_configuration_warnings(); if (start_location.is_equal_approx(end_location)) { warnings.push_back(RTR("NavigationLink2D start location should be different than the end location to be useful.")); } return warnings; } NavigationLink2D::NavigationLink2D() { link = NavigationServer2D::get_singleton()->link_create(); set_notify_transform(true); } NavigationLink2D::~NavigationLink2D() { NavigationServer2D::get_singleton()->free(link); link = RID(); } <commit_msg>Fix build after merge of #63479<commit_after>/*************************************************************************/ /* navigation_link_2d.cpp */ /*************************************************************************/ /* This file is part of: */ /* GODOT ENGINE */ /* https://godotengine.org */ /*************************************************************************/ /* Copyright (c) 2007-2022 Juan Linietsky, Ariel Manzur. */ /* Copyright (c) 2014-2022 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 "navigation_link_2d.h" #include "core/math/geometry_2d.h" #include "scene/resources/world_2d.h" #include "servers/navigation_server_2d.h" #include "servers/navigation_server_3d.h" void NavigationLink2D::_bind_methods() { ClassDB::bind_method(D_METHOD("set_enabled", "enabled"), &NavigationLink2D::set_enabled); ClassDB::bind_method(D_METHOD("is_enabled"), &NavigationLink2D::is_enabled); ClassDB::bind_method(D_METHOD("set_bidirectional", "bidirectional"), &NavigationLink2D::set_bidirectional); ClassDB::bind_method(D_METHOD("is_bidirectional"), &NavigationLink2D::is_bidirectional); ClassDB::bind_method(D_METHOD("set_navigation_layers", "navigation_layers"), &NavigationLink2D::set_navigation_layers); ClassDB::bind_method(D_METHOD("get_navigation_layers"), &NavigationLink2D::get_navigation_layers); ClassDB::bind_method(D_METHOD("set_navigation_layer_value", "layer_number", "value"), &NavigationLink2D::set_navigation_layer_value); ClassDB::bind_method(D_METHOD("get_navigation_layer_value", "layer_number"), &NavigationLink2D::get_navigation_layer_value); ClassDB::bind_method(D_METHOD("set_start_location", "location"), &NavigationLink2D::set_start_location); ClassDB::bind_method(D_METHOD("get_start_location"), &NavigationLink2D::get_start_location); ClassDB::bind_method(D_METHOD("set_end_location", "location"), &NavigationLink2D::set_end_location); ClassDB::bind_method(D_METHOD("get_end_location"), &NavigationLink2D::get_end_location); ClassDB::bind_method(D_METHOD("set_enter_cost", "enter_cost"), &NavigationLink2D::set_enter_cost); ClassDB::bind_method(D_METHOD("get_enter_cost"), &NavigationLink2D::get_enter_cost); ClassDB::bind_method(D_METHOD("set_travel_cost", "travel_cost"), &NavigationLink2D::set_travel_cost); ClassDB::bind_method(D_METHOD("get_travel_cost"), &NavigationLink2D::get_travel_cost); ADD_PROPERTY(PropertyInfo(Variant::BOOL, "enabled"), "set_enabled", "is_enabled"); ADD_PROPERTY(PropertyInfo(Variant::BOOL, "bidirectional"), "set_bidirectional", "is_bidirectional"); ADD_PROPERTY(PropertyInfo(Variant::INT, "navigation_layers", PROPERTY_HINT_LAYERS_2D_NAVIGATION), "set_navigation_layers", "get_navigation_layers"); ADD_PROPERTY(PropertyInfo(Variant::VECTOR2, "start_location"), "set_start_location", "get_start_location"); ADD_PROPERTY(PropertyInfo(Variant::VECTOR2, "end_location"), "set_end_location", "get_end_location"); ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "enter_cost"), "set_enter_cost", "get_enter_cost"); ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "travel_cost"), "set_travel_cost", "get_travel_cost"); } void NavigationLink2D::_notification(int p_what) { switch (p_what) { case NOTIFICATION_ENTER_TREE: { if (enabled) { NavigationServer2D::get_singleton()->link_set_map(link, get_world_2d()->get_navigation_map()); // Update global positions for the link. Transform2D gt = get_global_transform(); NavigationServer2D::get_singleton()->link_set_start_location(link, gt.xform(start_location)); NavigationServer2D::get_singleton()->link_set_end_location(link, gt.xform(end_location)); } } break; case NOTIFICATION_TRANSFORM_CHANGED: { // Update global positions for the link. Transform2D gt = get_global_transform(); NavigationServer2D::get_singleton()->link_set_start_location(link, gt.xform(start_location)); NavigationServer2D::get_singleton()->link_set_end_location(link, gt.xform(end_location)); } break; case NOTIFICATION_EXIT_TREE: { NavigationServer2D::get_singleton()->link_set_map(link, RID()); } break; case NOTIFICATION_DRAW: { #ifdef DEBUG_ENABLED if (is_inside_tree() && (Engine::get_singleton()->is_editor_hint() || NavigationServer2D::get_singleton()->get_debug_enabled())) { Color color; if (enabled) { color = NavigationServer2D::get_singleton()->get_debug_navigation_link_connection_color(); } else { color = NavigationServer2D::get_singleton()->get_debug_navigation_link_connection_disabled_color(); } real_t radius = NavigationServer2D::get_singleton()->map_get_link_connection_radius(get_world_2d()->get_navigation_map()); draw_line(get_start_location(), get_end_location(), color); draw_arc(get_start_location(), radius, 0, Math_TAU, 10, color); draw_arc(get_end_location(), radius, 0, Math_TAU, 10, color); } #endif // DEBUG_ENABLED } break; } } #ifdef TOOLS_ENABLED Rect2 NavigationLink2D::_edit_get_rect() const { real_t radius = NavigationServer2D::get_singleton()->map_get_link_connection_radius(get_world_2d()->get_navigation_map()); Rect2 rect(get_start_location(), Size2()); rect.expand_to(get_end_location()); rect.grow_by(radius); return rect; } bool NavigationLink2D::_edit_is_selected_on_click(const Point2 &p_point, double p_tolerance) const { Point2 segment[2] = { get_start_location(), get_end_location() }; Vector2 closest_point = Geometry2D::get_closest_point_to_segment(p_point, segment); return p_point.distance_to(closest_point) < p_tolerance; } #endif // TOOLS_ENABLED void NavigationLink2D::set_enabled(bool p_enabled) { if (enabled == p_enabled) { return; } enabled = p_enabled; if (!is_inside_tree()) { return; } if (!enabled) { NavigationServer2D::get_singleton()->link_set_map(link, RID()); } else { NavigationServer2D::get_singleton()->link_set_map(link, get_world_2d()->get_navigation_map()); } #ifdef DEBUG_ENABLED if (Engine::get_singleton()->is_editor_hint() || NavigationServer2D::get_singleton()->get_debug_enabled()) { queue_redraw(); } #endif // DEBUG_ENABLED } void NavigationLink2D::set_bidirectional(bool p_bidirectional) { if (bidirectional == p_bidirectional) { return; } bidirectional = p_bidirectional; NavigationServer2D::get_singleton()->link_set_bidirectional(link, bidirectional); } void NavigationLink2D::set_navigation_layers(uint32_t p_navigation_layers) { if (navigation_layers == p_navigation_layers) { return; } navigation_layers = p_navigation_layers; NavigationServer2D::get_singleton()->link_set_navigation_layers(link, navigation_layers); } void NavigationLink2D::set_navigation_layer_value(int p_layer_number, bool p_value) { ERR_FAIL_COND_MSG(p_layer_number < 1, "Navigation layer number must be between 1 and 32 inclusive."); ERR_FAIL_COND_MSG(p_layer_number > 32, "Navigation layer number must be between 1 and 32 inclusive."); uint32_t _navigation_layers = get_navigation_layers(); if (p_value) { _navigation_layers |= 1 << (p_layer_number - 1); } else { _navigation_layers &= ~(1 << (p_layer_number - 1)); } set_navigation_layers(_navigation_layers); } bool NavigationLink2D::get_navigation_layer_value(int p_layer_number) const { ERR_FAIL_COND_V_MSG(p_layer_number < 1, false, "Navigation layer number must be between 1 and 32 inclusive."); ERR_FAIL_COND_V_MSG(p_layer_number > 32, false, "Navigation layer number must be between 1 and 32 inclusive."); return get_navigation_layers() & (1 << (p_layer_number - 1)); } void NavigationLink2D::set_start_location(Vector2 p_location) { if (start_location.is_equal_approx(p_location)) { return; } start_location = p_location; if (!is_inside_tree()) { return; } Transform2D gt = get_global_transform(); NavigationServer2D::get_singleton()->link_set_start_location(link, gt.xform(start_location)); update_configuration_warnings(); #ifdef DEBUG_ENABLED if (Engine::get_singleton()->is_editor_hint() || NavigationServer2D::get_singleton()->get_debug_enabled()) { queue_redraw(); } #endif // DEBUG_ENABLED } void NavigationLink2D::set_end_location(Vector2 p_location) { if (end_location.is_equal_approx(p_location)) { return; } end_location = p_location; if (!is_inside_tree()) { return; } Transform2D gt = get_global_transform(); NavigationServer2D::get_singleton()->link_set_end_location(link, gt.xform(end_location)); update_configuration_warnings(); #ifdef DEBUG_ENABLED if (Engine::get_singleton()->is_editor_hint() || NavigationServer2D::get_singleton()->get_debug_enabled()) { queue_redraw(); } #endif // DEBUG_ENABLED } void NavigationLink2D::set_enter_cost(real_t p_enter_cost) { ERR_FAIL_COND_MSG(p_enter_cost < 0.0, "The enter_cost must be positive."); if (Math::is_equal_approx(enter_cost, p_enter_cost)) { return; } enter_cost = p_enter_cost; NavigationServer2D::get_singleton()->link_set_enter_cost(link, enter_cost); } void NavigationLink2D::set_travel_cost(real_t p_travel_cost) { ERR_FAIL_COND_MSG(p_travel_cost < 0.0, "The travel_cost must be positive."); if (Math::is_equal_approx(travel_cost, p_travel_cost)) { return; } travel_cost = p_travel_cost; NavigationServer2D::get_singleton()->link_set_travel_cost(link, travel_cost); } TypedArray<String> NavigationLink2D::get_configuration_warnings() const { TypedArray<String> warnings = Node::get_configuration_warnings(); if (start_location.is_equal_approx(end_location)) { warnings.push_back(RTR("NavigationLink2D start location should be different than the end location to be useful.")); } return warnings; } NavigationLink2D::NavigationLink2D() { link = NavigationServer2D::get_singleton()->link_create(); set_notify_transform(true); } NavigationLink2D::~NavigationLink2D() { NavigationServer2D::get_singleton()->free(link); link = RID(); } <|endoftext|>
<commit_before>namespace CTF_int{ double blres_mdl_init[] = {1.2880E-05, 1.1099E-08}; double long_contig_transp_mdl_init[] = {9.1201E-15, 2.1816E-09}; double shrt_contig_transp_mdl_init[] = {5.5768E-03, 1.7220E-08}; double non_contig_transp_mdl_init[] = {1.0753E-06, 4.1534E-08}; double dgtog_res_mdl_init[] = {-8.1392E-04, 1.2781E-04, 1.2295E-09}; double seq_tsr_ctr_mdl_cst_init[] = {3.8587E-13, 5.0935E-09, 4.2446E-10}; double seq_tsr_ctr_mdl_ref_init[] = {3.0374E-05, 6.9969E+00, -8.3962E+01}; double seq_tsr_ctr_mdl_inr_init[] = {-1.0012E-05, 2.8040E-10, 4.0944E-11}; double seq_tsr_ctr_mdl_off_init[] = {2.5413E-04, 1.5889E-10, 9.6735E-12}; double alltoall_mdl_init[] = {1.0000E-06, 1.0000E-06, 5.0000E-10}; double alltoallv_mdl_init[] = {-5.4974E-06, -1.4211E-05, 6.3309E-10}; double allred_mdl_init[] = {2.1127E-05, 2.7072E-06, 4.2328E-09}; double bcast_mdl_init[] = {6.7536E-05, 3.3990E-06, 2.4632E-09}; } <commit_msg>New model parameters based on 400 sec training run on 384 cores of Edison with 6 processes per node. They seem to do well for AQ CCSD/CCSDT with flat MPI or threads on 384 cores.<commit_after>namespace CTF_int{ double blres_mdl_init[] = {3.7870E-05, 1.2061E-08}; double dgtog_res_mdl_init[] = {2.9484E-04, -3.7854E-05, 1.7446E-09}; double alltoall_mdl_init[] = {1.0000E-06, 1.0000E-06, 5.0000E-10}; double alltoallv_mdl_init[] = {-7.2507E-06, 1.0362E-05, 1.6246E-10}; double allred_mdl_init[] = {-3.0267E-06, 7.0181E-06, 3.8877E-09}; double bcast_mdl_init[] = {-3.5337E-07, 2.5071E-05, 1.5186E-09}; double long_contig_transp_mdl_init[] = {4.2322E-06, 1.3565E-09}; double shrt_contig_transp_mdl_init[] = {5.7366E-06, 2.0807E-09}; double non_contig_transp_mdl_init[] = {5.2266E-06, 2.9382E-09}; double seq_tsr_ctr_mdl_cst_init[] = {5.3745E-06, 3.6464E-08, 2.2334E-10}; double seq_tsr_ctr_mdl_ref_init[] = {5.3745E-06, 3.6464E-08, 2.2334E-10}; double seq_tsr_ctr_mdl_inr_init[] = {5.3745E-06, 3.6464E-11, 8.2334E-12}; double seq_tsr_ctr_mdl_off_init[] = {2.5413E-04, 1.5889E-10, 9.6735E-12}; } <|endoftext|>
<commit_before>// Copyright (c) 2012 Intel Corp // Copyright (c) 2012 The Chromium Authors // // 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 co // pies 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 al // l copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IM // PLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNES // S FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS // OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WH // ETHER 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 "content/nw/src/shell_main_delegate.h" #include "base/command_line.h" #include "base/files/file_path.h" #include "base/file_util.h" #include "base/lazy_instance.h" #include "base/logging.h" #include "base/path_service.h" #include "base/strings/utf_string_conversions.h" #include "content/public/browser/browser_main_runner.h" #include "content/public/browser/render_process_host.h" #include "content/public/common/content_switches.h" #include "content/public/common/url_constants.h" #include "content/nw/src/breakpad_linux.h" #include "content/nw/src/chrome_breakpad_client.h" #include "content/nw/src/common/shell_switches.h" #include "content/nw/src/nw_version.h" #include "content/nw/src/renderer/shell_content_renderer_client.h" #include "content/nw/src/shell_browser_main.h" #include "content/nw/src/shell_content_browser_client.h" #include "net/cookies/cookie_monster.h" #include "third_party/node/src/node_version.h" #include "ui/base/l10n/l10n_util.h" #if defined(OS_MACOSX) #include "ui/base/l10n/l10n_util_mac.h" #endif #include "ui/base/resource/resource_bundle.h" #include "ui/base/ui_base_paths.h" #include "ui/base/ui_base_switches.h" #include <stdio.h> using base::FilePath; #if defined(OS_MACOSX) #include "content/nw/src/paths_mac.h" #endif // OS_MACOSX #if defined(OS_WIN) #include "base/logging_win.h" #include <initguid.h> #endif #include "ipc/ipc_message.h" // For IPC_MESSAGE_LOG_ENABLED. #if defined(IPC_MESSAGE_LOG_ENABLED) #define IPC_MESSAGE_MACROS_LOG_ENABLED #include "content/public/common/content_ipc_logging.h" #define IPC_LOG_TABLE_ADD_ENTRY(msg_id, logger) \ content::RegisterIPCLogger(msg_id, logger) #include "content/nw/src/common/common_message_generator.h" #include "components/autofill/core/common/autofill_messages.h" #endif namespace { #if defined(OS_WIN) // If "Content Shell" doesn't show up in your list of trace providers in // Sawbuck, add these registry entries to your machine (NOTE the optional // Wow6432Node key for x64 machines): // 1. Find: HKLM\SOFTWARE\[Wow6432Node\]Google\Sawbuck\Providers // 2. Add a subkey with the name "{6A3E50A4-7E15-4099-8413-EC94D8C2A4B6}" // 3. Add these values: // "default_flags"=dword:00000001 // "default_level"=dword:00000004 // @="Content Shell" // {6A3E50A4-7E15-4099-8413-EC94D8C2A4B6} const GUID kContentShellProviderName = { 0x6a3e50a4, 0x7e15, 0x4099, { 0x84, 0x13, 0xec, 0x94, 0xd8, 0xc2, 0xa4, 0xb6 } }; #endif base::LazyInstance<chrome::ChromeBreakpadClient>::Leaky g_chrome_breakpad_client = LAZY_INSTANCE_INITIALIZER; void InitLogging() { base::FilePath log_filename; PathService::Get(base::DIR_EXE, &log_filename); log_filename = log_filename.AppendASCII("debug.log"); logging::LoggingSettings settings; if (CommandLine::ForCurrentProcess()->HasSwitch(switches::kEnableLogging)) { settings.logging_dest = logging::LOG_TO_ALL; settings.log_file = log_filename.value().c_str(); settings.delete_old = logging::DELETE_OLD_LOG_FILE; }else{ #if defined(OS_WIN) settings.logging_dest = logging::LOG_NONE; #endif } logging::InitLogging(settings); logging::SetLogItems(true, false, true, false); } } // namespace namespace content { ShellMainDelegate::ShellMainDelegate() { } ShellMainDelegate::~ShellMainDelegate() { } bool ShellMainDelegate::BasicStartupComplete(int* exit_code) { #if defined(OS_WIN) // Enable trace control and transport through event tracing for Windows. logging::LogEventProvider::Initialize(kContentShellProviderName); #endif InitLogging(); net::CookieMonster::EnableFileScheme(); SetContentClient(&content_client_); return false; } void ShellMainDelegate::PreSandboxStartup() { breakpad::SetBreakpadClient(g_chrome_breakpad_client.Pointer()); CommandLine* command_line = CommandLine::ForCurrentProcess(); std::string pref_locale; if (command_line->HasSwitch(switches::kLang)) { pref_locale = command_line->GetSwitchValueASCII(switches::kLang); } #if defined(OS_MACOSX) OverrideFrameworkBundlePath(); OverrideChildProcessPath(); l10n_util::OverrideLocaleWithUserDefault(); #endif // OS_MACOSX InitializeResourceBundle(pref_locale); std::string process_type = command_line->GetSwitchValueASCII(switches::kProcessType); if (process_type != switches::kZygoteProcess) InitCrashReporter(); // Just prevent sandbox. command_line->AppendSwitch(switches::kNoSandbox); // Make sure we keep using only one render process for one app, by using the // process-per-tab mode, we can make Chrome only create new site instance // when we require to, the default mode is creating different site instances // for different domains. // This is needed because we want our Window API to have full control of new // windows created, which require all windows to be in one render process // host. command_line->AppendSwitch(switches::kProcessPerTab); // Allow file:// URIs can read other file:// URIs by default. command_line->AppendSwitch(switches::kAllowFileAccessFromFiles); command_line->AppendSwitch(switches::kEnableExperimentalWebPlatformFeatures); command_line->AppendSwitch(switches::kEnableCssShaders); } int ShellMainDelegate::RunProcess( const std::string& process_type, const MainFunctionParams& main_function_params) { if (!process_type.empty()) return -1; return ShellBrowserMain(main_function_params); } void ShellMainDelegate::InitializeResourceBundle(const std::string& pref_locale) { FilePath pak_file; #if defined(OS_MACOSX) FilePath locale_file; if (!GetResourcesPakFilePath(pak_file)) LOG(FATAL) << "nw.pak file not found."; std::string locale = l10n_util::GetApplicationLocale(pref_locale); if (!GetLocalePakFilePath(locale, locale_file)) LOG(FATAL) << locale << ".pak file not found."; ui::ResourceBundle::InitSharedInstanceWithPakPath2(pak_file, locale_file); #else FilePath pak_dir; PathService::Get(base::DIR_MODULE, &pak_dir); pak_file = pak_dir.Append(FILE_PATH_LITERAL("nw.pak")); CHECK(base::PathExists(pak_file)) << "nw.pak is missing"; ui::ResourceBundle::InitSharedInstanceWithPakPath(pak_file); #endif } ContentBrowserClient* ShellMainDelegate::CreateContentBrowserClient() { browser_client_.reset(new ShellContentBrowserClient); return browser_client_.get(); } ContentRendererClient* ShellMainDelegate::CreateContentRendererClient() { renderer_client_.reset(new ShellContentRendererClient); return renderer_client_.get(); } #if defined(OS_POSIX) && !defined(OS_MACOSX) void ShellMainDelegate::ZygoteForked() { // Needs to be called after we have chrome::DIR_USER_DATA. BrowserMain sets // this up for the browser process in a different manner. InitCrashReporter(); } #endif } // namespace content <commit_msg>Mac: fallback to en-US.pak on missing locale.pak<commit_after>// Copyright (c) 2012 Intel Corp // Copyright (c) 2012 The Chromium Authors // // 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 co // pies 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 al // l copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IM // PLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNES // S FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS // OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WH // ETHER 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 "content/nw/src/shell_main_delegate.h" #include "base/command_line.h" #include "base/files/file_path.h" #include "base/file_util.h" #include "base/lazy_instance.h" #include "base/logging.h" #include "base/path_service.h" #include "base/strings/utf_string_conversions.h" #include "content/public/browser/browser_main_runner.h" #include "content/public/browser/render_process_host.h" #include "content/public/common/content_switches.h" #include "content/public/common/url_constants.h" #include "content/nw/src/breakpad_linux.h" #include "content/nw/src/chrome_breakpad_client.h" #include "content/nw/src/common/shell_switches.h" #include "content/nw/src/nw_version.h" #include "content/nw/src/renderer/shell_content_renderer_client.h" #include "content/nw/src/shell_browser_main.h" #include "content/nw/src/shell_content_browser_client.h" #include "net/cookies/cookie_monster.h" #include "third_party/node/src/node_version.h" #include "ui/base/l10n/l10n_util.h" #if defined(OS_MACOSX) #include "ui/base/l10n/l10n_util_mac.h" #endif #include "ui/base/resource/resource_bundle.h" #include "ui/base/ui_base_paths.h" #include "ui/base/ui_base_switches.h" #include <stdio.h> using base::FilePath; #if defined(OS_MACOSX) #include "content/nw/src/paths_mac.h" #endif // OS_MACOSX #if defined(OS_WIN) #include "base/logging_win.h" #include <initguid.h> #endif #include "ipc/ipc_message.h" // For IPC_MESSAGE_LOG_ENABLED. #if defined(IPC_MESSAGE_LOG_ENABLED) #define IPC_MESSAGE_MACROS_LOG_ENABLED #include "content/public/common/content_ipc_logging.h" #define IPC_LOG_TABLE_ADD_ENTRY(msg_id, logger) \ content::RegisterIPCLogger(msg_id, logger) #include "content/nw/src/common/common_message_generator.h" #include "components/autofill/core/common/autofill_messages.h" #endif namespace { #if defined(OS_WIN) // If "Content Shell" doesn't show up in your list of trace providers in // Sawbuck, add these registry entries to your machine (NOTE the optional // Wow6432Node key for x64 machines): // 1. Find: HKLM\SOFTWARE\[Wow6432Node\]Google\Sawbuck\Providers // 2. Add a subkey with the name "{6A3E50A4-7E15-4099-8413-EC94D8C2A4B6}" // 3. Add these values: // "default_flags"=dword:00000001 // "default_level"=dword:00000004 // @="Content Shell" // {6A3E50A4-7E15-4099-8413-EC94D8C2A4B6} const GUID kContentShellProviderName = { 0x6a3e50a4, 0x7e15, 0x4099, { 0x84, 0x13, 0xec, 0x94, 0xd8, 0xc2, 0xa4, 0xb6 } }; #endif base::LazyInstance<chrome::ChromeBreakpadClient>::Leaky g_chrome_breakpad_client = LAZY_INSTANCE_INITIALIZER; void InitLogging() { base::FilePath log_filename; PathService::Get(base::DIR_EXE, &log_filename); log_filename = log_filename.AppendASCII("debug.log"); logging::LoggingSettings settings; if (CommandLine::ForCurrentProcess()->HasSwitch(switches::kEnableLogging)) { settings.logging_dest = logging::LOG_TO_ALL; settings.log_file = log_filename.value().c_str(); settings.delete_old = logging::DELETE_OLD_LOG_FILE; }else{ #if defined(OS_WIN) settings.logging_dest = logging::LOG_NONE; #endif } logging::InitLogging(settings); logging::SetLogItems(true, false, true, false); } } // namespace namespace content { ShellMainDelegate::ShellMainDelegate() { } ShellMainDelegate::~ShellMainDelegate() { } bool ShellMainDelegate::BasicStartupComplete(int* exit_code) { #if defined(OS_WIN) // Enable trace control and transport through event tracing for Windows. logging::LogEventProvider::Initialize(kContentShellProviderName); #endif InitLogging(); net::CookieMonster::EnableFileScheme(); SetContentClient(&content_client_); return false; } void ShellMainDelegate::PreSandboxStartup() { breakpad::SetBreakpadClient(g_chrome_breakpad_client.Pointer()); CommandLine* command_line = CommandLine::ForCurrentProcess(); std::string pref_locale; if (command_line->HasSwitch(switches::kLang)) { pref_locale = command_line->GetSwitchValueASCII(switches::kLang); } #if defined(OS_MACOSX) OverrideFrameworkBundlePath(); OverrideChildProcessPath(); l10n_util::OverrideLocaleWithUserDefault(); #endif // OS_MACOSX InitializeResourceBundle(pref_locale); std::string process_type = command_line->GetSwitchValueASCII(switches::kProcessType); if (process_type != switches::kZygoteProcess) InitCrashReporter(); // Just prevent sandbox. command_line->AppendSwitch(switches::kNoSandbox); // Make sure we keep using only one render process for one app, by using the // process-per-tab mode, we can make Chrome only create new site instance // when we require to, the default mode is creating different site instances // for different domains. // This is needed because we want our Window API to have full control of new // windows created, which require all windows to be in one render process // host. command_line->AppendSwitch(switches::kProcessPerTab); // Allow file:// URIs can read other file:// URIs by default. command_line->AppendSwitch(switches::kAllowFileAccessFromFiles); command_line->AppendSwitch(switches::kEnableExperimentalWebPlatformFeatures); command_line->AppendSwitch(switches::kEnableCssShaders); } int ShellMainDelegate::RunProcess( const std::string& process_type, const MainFunctionParams& main_function_params) { if (!process_type.empty()) return -1; return ShellBrowserMain(main_function_params); } void ShellMainDelegate::InitializeResourceBundle(const std::string& pref_locale) { FilePath pak_file; #if defined(OS_MACOSX) FilePath locale_file; if (!GetResourcesPakFilePath(pak_file)) LOG(FATAL) << "nw.pak file not found."; std::string locale = l10n_util::GetApplicationLocale(pref_locale); if (!GetLocalePakFilePath(locale, locale_file)) { LOG(WARNING) << locale << ".pak file not found."; locale = "en-US"; if (!GetLocalePakFilePath(locale, locale_file)) LOG(ERROR) << locale << ".pak file not found."; } ui::ResourceBundle::InitSharedInstanceWithPakPath2(pak_file, locale_file); #else FilePath pak_dir; PathService::Get(base::DIR_MODULE, &pak_dir); pak_file = pak_dir.Append(FILE_PATH_LITERAL("nw.pak")); CHECK(base::PathExists(pak_file)) << "nw.pak is missing"; ui::ResourceBundle::InitSharedInstanceWithPakPath(pak_file); #endif } ContentBrowserClient* ShellMainDelegate::CreateContentBrowserClient() { browser_client_.reset(new ShellContentBrowserClient); return browser_client_.get(); } ContentRendererClient* ShellMainDelegate::CreateContentRendererClient() { renderer_client_.reset(new ShellContentRendererClient); return renderer_client_.get(); } #if defined(OS_POSIX) && !defined(OS_MACOSX) void ShellMainDelegate::ZygoteForked() { // Needs to be called after we have chrome::DIR_USER_DATA. BrowserMain sets // this up for the browser process in a different manner. InitCrashReporter(); } #endif } // namespace content <|endoftext|>
<commit_before>#include <algorithm> #include "SpMP/CSR.hpp" #include "CSR_Interface.h" using namespace std; using namespace SpMP; // w = (alpha*A*x + beta*y + gamma)*z template<class T, bool HAS_VALUE = true, bool HAS_Z = false> static void SpMV_( int m, T *w, T alpha, const int *rowptr, const int *colidx, const T* values, const T *x, T beta, const T *y, T gamma, const T *z) { assert(w != x); int base = rowptr[0]; rowptr -= base; colidx -= base; if (values) values -= base; w -= base; x -= base; if (y) y -= base; if (z) z -= base; //#define MEASURE_LOAD_BALANCE #ifdef MEASURE_LOAD_BALANCE double barrierTimes[omp_get_max_threads()]; double tBegin = omp_get_wtime(); #endif #pragma omp parallel { int iBegin, iEnd; getLoadBalancedPartition(&iBegin, &iEnd, rowptr + base, m); iBegin += base; iEnd += base; if (1 == alpha) { if (0 == beta) { if (0 == gamma) { for (int i = iBegin; i < iEnd; ++i) { T sum = 0; for (int j = rowptr[i]; j < rowptr[i + 1]; ++j) { if (values) { sum += values[j]*x[colidx[j]]; } else { sum += x[colidx[j]]; } } if (z) w[i] = z[i]*sum; else w[i] = sum; } } else { for (int i = iBegin; i < iEnd; ++i) { T sum = gamma; for (int j = rowptr[i]; j < rowptr[i + 1]; ++j) { if (values) { sum += values[j]*x[colidx[j]]; } else { sum += x[colidx[j]]; } } if (z) w[i] = z[i]*sum; else w[i] = sum; } } } else { // alpha == 1 && beta != 0 if (0 == gamma) { for (int i = iBegin; i < iEnd; ++i) { T sum = beta*y[i]; for (int j = rowptr[i]; j < rowptr[i + 1]; ++j) { if (values) { sum += values[j]*x[colidx[j]]; } else { sum += x[colidx[j]]; } } if (z) w[i] = z[i]*sum; else w[i] = sum; } } else { for (int i = iBegin; i < iEnd; ++i) { T sum = beta*y[i] + gamma; for (int j = rowptr[i]; j < rowptr[i + 1]; ++j) { if (values) { sum += values[j]*x[colidx[j]]; } else { sum += x[colidx[j]]; } } if (z) w[i] = z[i]*sum; else w[i] = sum; } } } } else { // alpha != 1 if (0 == beta) { if (0 == gamma) { for (int i = iBegin; i < iEnd; ++i) { T sum = 0; for (int j = rowptr[i]; j < rowptr[i + 1]; ++j) { if (values) { sum += values[j]*x[colidx[j]]; } else { sum += x[colidx[j]]; } } sum *= alpha; if (z) w[i] = z[i]*sum; else w[i] = sum; } } else { for (int i = iBegin; i < iEnd; ++i) { T sum = gamma; for (int j = rowptr[i]; j < rowptr[i + 1]; ++j) { if (values) { sum += values[j]*x[colidx[j]]; } else { sum += x[colidx[j]]; } } sum *= alpha; if (z) w[i] = z[i]*sum; else w[i] = sum; } } } else { // alpha != 1 && beta != 0 if (0 == gamma) { for (int i = iBegin; i < iEnd; ++i) { T sum = beta*y[i]; for (int j = rowptr[i]; j < rowptr[i + 1]; ++j) { if (values) { sum += values[j]*x[colidx[j]]; } else { sum += x[colidx[j]]; } } sum *= alpha; if (z) w[i] = z[i]*sum; else w[i] = sum; } } else { for (int i = iBegin; i < iEnd; ++i) { T sum = beta*y[i] + gamma; for (int j = rowptr[i]; j < rowptr[i + 1]; ++j) { if (values) { sum += values[j]*x[colidx[j]]; } else { sum += x[colidx[j]]; } } sum *= alpha; if (z) w[i] = z[i]*sum; else w[i] = sum; } } } } // alpha != 1 #ifdef MEASURE_LOAD_BALANCE double t = omp_get_wtime(); #pragma omp barrier barrierTimes[tid] = omp_get_wtime() - t; #pragma omp barrier #pragma omp master { double tEnd = omp_get_wtime(); double barrierTimeSum = 0; for (int i = 0; i < nthreads; ++i) { barrierTimeSum += barrierTimes[i]; } printf("%f load imbalance = %f\n", tEnd - tBegin, barrierTimeSum/(tEnd - tBegin)/nthreads); } #undef MEASURE_LOAD_BALANCE #endif // MEASURE_LOAD_BALANCE } // omp parallel } void multiplyWithVector( double *w, double alpha, const CSR *A, const double *x, double beta, const double *y, double gamma, const double *z) { if (A->values) { if (z) { SpMV_<double, true, true>( A->m, w, alpha, A->rowptr, A->colidx, A->values, x, beta, y, gamma, z); } else { SpMV_<double, true, false>( A->m, w, alpha, A->rowptr, A->colidx, A->values, x, beta, y, gamma, z); } } else { if (z) { SpMV_<double, false, true>( A->m, w, alpha, A->rowptr, A->colidx, A->values, x, beta, y, gamma, z); } else { SpMV_<double, false, false>( A->m, w, alpha, A->rowptr, A->colidx, A->values, x, beta, y, gamma, z); } } } extern "C" { void CSR_MultiplyWithVector( double *w, double alpha, const CSR_Handle *A, const double *x, double beta, const double *y, double gamma, const double *z) { multiplyWithVector(w, alpha, (CSR *)A, x, beta, y, gamma, z); } void CSR_MultiplyWithDenseMatrix( double *W, int k, int wRowStride, int wColumnStride, double alpha, const CSR_Handle *A, const double *X, int xRowStride, int xColumnStride, double beta, const double *Y, int yRowStride, int yColumnStride, double gamma) { ((CSR *)A)->multiplyWithDenseMatrix( W, k, wRowStride, wColumnStride, alpha, X, xRowStride, xColumnStride, beta, Y, yRowStride, yColumnStride, gamma); } } // extern "C" <commit_msg>bug fix<commit_after>#include <algorithm> #include "SpMP/CSR.hpp" #include "CSR_Interface.h" using namespace std; using namespace SpMP; // w = (alpha*A*x + beta*y + gamma)*z template<class T, bool HAS_VALUE = true, bool HAS_Z = false> static void SpMV_( int m, T *w, T alpha, const int *rowptr, const int *colidx, const T* values, const T *x, T beta, const T *y, T gamma, const T *z) { assert(w != x); int base = rowptr[0]; rowptr -= base; colidx -= base; if (values) values -= base; w -= base; x -= base; if (y) y -= base; if (z) z -= base; //#define MEASURE_LOAD_BALANCE #ifdef MEASURE_LOAD_BALANCE double barrierTimes[omp_get_max_threads()]; double tBegin = omp_get_wtime(); #endif #pragma omp parallel { int iBegin, iEnd; getLoadBalancedPartition(&iBegin, &iEnd, rowptr + base, m); iBegin += base; iEnd += base; if (1 == alpha) { if (0 == beta) { if (0 == gamma) { for (int i = iBegin; i < iEnd; ++i) { T sum = 0; for (int j = rowptr[i]; j < rowptr[i + 1]; ++j) { if (HAS_VALUE) { sum += values[j]*x[colidx[j]]; } else { sum += x[colidx[j]]; } } if (HAS_Z) w[i] = z[i]*sum; else w[i] = sum; } } else { for (int i = iBegin; i < iEnd; ++i) { T sum = 0; for (int j = rowptr[i]; j < rowptr[i + 1]; ++j) { if (HAS_VALUE) { sum += values[j]*x[colidx[j]]; } else { sum += x[colidx[j]]; } } sum += gamma; if (HAS_Z) w[i] = z[i]*sum; else w[i] = sum; } } } else { // alpha == 1 && beta != 0 if (0 == gamma) { for (int i = iBegin; i < iEnd; ++i) { T sum = 0; for (int j = rowptr[i]; j < rowptr[i + 1]; ++j) { if (HAS_VALUE) { sum += values[j]*x[colidx[j]]; } else { sum += x[colidx[j]]; } } sum += beta*y[i]; if (HAS_Z) w[i] = z[i]*sum; else w[i] = sum; } } else { for (int i = iBegin; i < iEnd; ++i) { T sum = 0; for (int j = rowptr[i]; j < rowptr[i + 1]; ++j) { if (HAS_VALUE) { sum += values[j]*x[colidx[j]]; } else { sum += x[colidx[j]]; } } sum += beta*y[i] + gamma; if (HAS_Z) w[i] = z[i]*sum; else w[i] = sum; } } } } else { // alpha != 1 if (0 == beta) { if (0 == gamma) { for (int i = iBegin; i < iEnd; ++i) { T sum = 0; for (int j = rowptr[i]; j < rowptr[i + 1]; ++j) { if (HAS_VALUE) { sum += values[j]*x[colidx[j]]; } else { sum += x[colidx[j]]; } } sum *= alpha; if (HAS_Z) w[i] = z[i]*sum; else w[i] = sum; } } else { for (int i = iBegin; i < iEnd; ++i) { T sum = 0; for (int j = rowptr[i]; j < rowptr[i + 1]; ++j) { if (HAS_VALUE) { sum += values[j]*x[colidx[j]]; } else { sum += x[colidx[j]]; } } sum = alpha*sum + beta*y[i]; if (HAS_Z) w[i] = z[i]*sum; else w[i] = sum; } } } else { // alpha != 1 && beta != 0 if (0 == gamma) { for (int i = iBegin; i < iEnd; ++i) { T sum = 0; for (int j = rowptr[i]; j < rowptr[i + 1]; ++j) { if (HAS_VALUE) { sum += values[j]*x[colidx[j]]; } else { sum += x[colidx[j]]; } } sum = alpha*sum + beta*y[i]; if (HAS_Z) w[i] = z[i]*sum; else w[i] = sum; } } else { for (int i = iBegin; i < iEnd; ++i) { T sum = 0; for (int j = rowptr[i]; j < rowptr[i + 1]; ++j) { if (HAS_VALUE) { sum += values[j]*x[colidx[j]]; } else { sum += x[colidx[j]]; } } sum = alpha*sum + beta*y[i] + gamma; if (HAS_Z) w[i] = z[i]*sum; else w[i] = sum; } } } } // alpha != 1 #ifdef MEASURE_LOAD_BALANCE double t = omp_get_wtime(); #pragma omp barrier barrierTimes[tid] = omp_get_wtime() - t; #pragma omp barrier #pragma omp master { double tEnd = omp_get_wtime(); double barrierTimeSum = 0; for (int i = 0; i < nthreads; ++i) { barrierTimeSum += barrierTimes[i]; } printf("%f load imbalance = %f\n", tEnd - tBegin, barrierTimeSum/(tEnd - tBegin)/nthreads); } #undef MEASURE_LOAD_BALANCE #endif // MEASURE_LOAD_BALANCE } // omp parallel } void multiplyWithVector( double *w, double alpha, const CSR *A, const double *x, double beta, const double *y, double gamma, const double *z) { if (A->values) { if (z) { SpMV_<double, true, true>( A->m, w, alpha, A->rowptr, A->colidx, A->values, x, beta, y, gamma, z); } else { SpMV_<double, true, false>( A->m, w, alpha, A->rowptr, A->colidx, A->values, x, beta, y, gamma, z); } } else { if (z) { SpMV_<double, false, true>( A->m, w, alpha, A->rowptr, A->colidx, A->values, x, beta, y, gamma, z); } else { SpMV_<double, false, false>( A->m, w, alpha, A->rowptr, A->colidx, A->values, x, beta, y, gamma, z); } } } extern "C" { void CSR_MultiplyWithVector( double *w, double alpha, const CSR_Handle *A, const double *x, double beta, const double *y, double gamma, const double *z) { multiplyWithVector(w, alpha, (CSR *)A, x, beta, y, gamma, z); } void CSR_MultiplyWithDenseMatrix( double *W, int k, int wRowStride, int wColumnStride, double alpha, const CSR_Handle *A, const double *X, int xRowStride, int xColumnStride, double beta, const double *Y, int yRowStride, int yColumnStride, double gamma) { ((CSR *)A)->multiplyWithDenseMatrix( W, k, wRowStride, wColumnStride, alpha, X, xRowStride, xColumnStride, beta, Y, yRowStride, yColumnStride, gamma); } } // extern "C" <|endoftext|>
<commit_before>// This is free and unencumbered software released into the public domain. // For more information, please refer to <http://unlicense.org/> #include "span_analyzer_frame.h" #include "wx/aboutdlg.h" #include "wx/xrc/xmlres.h" #include "analysis_filter_manager_dialog.h" #include "cable_file_manager_dialog.h" #include "cable_unit_converter.h" #include "file_handler.h" #include "preferences_dialog.h" #include "span_analyzer_app.h" #include "span_analyzer_doc.h" #include "span_analyzer_view.h" #include "weather_load_case_manager_dialog.h" #include "weather_load_case_unit_converter.h" #include "xpm/icon.xpm" DocumentFileDropTarget::DocumentFileDropTarget(wxWindow* parent) { parent_ = parent; // creates data object to store dropped information SetDataObject(new wxFileDataObject()); SetDefaultAction(wxDragCopy); } bool DocumentFileDropTarget::OnDropFiles(wxCoord x, wxCoord y, const wxArrayString& filenames) { // gets data from drag-and-drop operation wxFileDataObject* data = dynamic_cast<wxFileDataObject*>(GetDataObject()); // tests if file exists // only the first file in the list is processed const wxString& str_file = data->GetFilenames().front(); if (wxFileName::Exists(str_file) == false) { return false; } // tests if extension matches application document wxFileName path(str_file); if (path.GetExt() == ".spananalyzer") { return false; } // freezes frame, opens document, and thaws frame parent_->Freeze(); wxGetApp().manager_doc()->CreateDocument(str_file); parent_->Thaw(); return true; } BEGIN_EVENT_TABLE(SpanAnalyzerFrame, wxDocParentFrame) EVT_MENU(XRCID("menuitem_edit_analysisfilters"), SpanAnalyzerFrame::OnMenuEditAnalysisFilters) EVT_MENU(XRCID("menuitem_edit_cables"), SpanAnalyzerFrame::OnMenuEditCables) EVT_MENU(XRCID("menuitem_edit_weathercases"), SpanAnalyzerFrame::OnMenuEditWeathercases) EVT_MENU(XRCID("menuitem_file_preferences"), SpanAnalyzerFrame::OnMenuFilePreferences) EVT_MENU(XRCID("menuitem_help_about"), SpanAnalyzerFrame::OnMenuHelpAbout) EVT_MENU(XRCID("menuitem_view_cable_model"), SpanAnalyzerFrame::OnMenuViewCableModel) EVT_MENU(XRCID("menuitem_view_log"), SpanAnalyzerFrame::OnMenuViewLog) END_EVENT_TABLE() SpanAnalyzerFrame::SpanAnalyzerFrame(wxDocManager* manager) : wxDocParentFrame(manager, nullptr, wxID_ANY, "Span Analyzer") { // loads dialog from virtual xrc file system wxXmlResource::Get()->LoadMenuBar(this, "span_analyzer_menubar"); // sets the frame icon SetIcon(wxIcon(icon_xpm)); // sets the drag and drop target SetDropTarget(new DocumentFileDropTarget(this)); // tells aui manager to manage this frame manager_.SetManagedWindow(this); // creates status bar wxStatusBar* status_bar = CreateStatusBar(); const int kFieldsCount = 2; const int widths_field[2] = {-1, 170}; status_bar->SetFieldsCount(kFieldsCount); status_bar->SetStatusWidths(kFieldsCount, widths_field); // creates log AUI window and adds to manager wxAuiPaneInfo info; info.Name("Log"); info.Float(); info.Caption("Log"); info.CloseButton(true); info.Show(false); pane_log_ = new LogPane(this); manager_.AddPane(pane_log_, info); manager_.Update(); } SpanAnalyzerFrame::~SpanAnalyzerFrame() { // saves frame size to application config SpanAnalyzerConfig* config = wxGetApp().config(); if (this->IsMaximized() == true) { config->size_frame = wxSize(0, 0); } else { config->size_frame = this->GetSize(); } manager_.UnInit(); } void SpanAnalyzerFrame::OnMenuEditAnalysisFilters(wxCommandEvent& event) { // gets application config and data const SpanAnalyzerConfig* config = wxGetApp().config(); SpanAnalyzerData* data = wxGetApp().data(); // creates and shows the analysis filter manager dialog AnalysisFilterManagerDialog dialog(this, &data->weathercases, &data->groups_filters); if (dialog.ShowModal() == wxID_OK) { wxBusyCursor cursor; wxLogVerbose("Updating analysis filters."); // saves application data FileHandler::SaveAppData(config->filepath_data, *data, config->units); // updates document/views SpanAnalyzerDoc* doc = wxGetApp().GetDocument(); if (doc != nullptr) { UpdateHint hint(HintType::kAnalysisFilterGroupEdit); doc->UpdateAllViews(nullptr, &hint); } } } void SpanAnalyzerFrame::OnMenuEditCables(wxCommandEvent& event) { // gets application config and data const SpanAnalyzerConfig* config = wxGetApp().config(); SpanAnalyzerData* data = wxGetApp().data(); // creates and shows the cable file manager dialog CableFileManagerDialog dialog(this, config->units, &data->cablefiles); if (dialog.ShowModal() == wxID_OK) { wxBusyCursor cursor; wxLogVerbose("Updating cables."); // saves application data FileHandler::SaveAppData(config->filepath_data, *data, config->units); } wxBusyCursor cursor; // updates document/views SpanAnalyzerDoc* doc = wxGetApp().GetDocument(); if (doc != nullptr) { doc->RunAnalysis(); UpdateHint hint(HintType::kCablesEdit); doc->UpdateAllViews(nullptr, &hint); } } void SpanAnalyzerFrame::OnMenuEditWeathercases( wxCommandEvent& event) { // gets application data SpanAnalyzerData* data = wxGetApp().data(); // shows an editor WeatherLoadCaseManagerDialog dialog( this, wxGetApp().config()->units, &data->weathercases); if (dialog.ShowModal() == wxID_OK) { wxBusyCursor cursor; wxLogVerbose("Updating weathercases."); // saves application data FileHandler::SaveAppData(wxGetApp().config()->filepath_data, *data, wxGetApp().config()->units); } // updates document/views SpanAnalyzerDoc* doc = wxGetApp().GetDocument(); if (doc != nullptr) { doc->RunAnalysis(); UpdateHint hint(HintType::kWeathercasesEdit); doc->UpdateAllViews(nullptr, &hint); } } void SpanAnalyzerFrame::OnMenuFilePreferences(wxCommandEvent& event) { // gets the application config SpanAnalyzerConfig* config = wxGetApp().config(); // stores a copy of the unit system before letting user edit units::UnitSystem units_before = config->units; // creates preferences editor dialog and shows // exits if user closes/cancels PreferencesDialog preferences(this, config); if (preferences.ShowModal() != wxID_OK) { return; } wxBusyCursor cursor; // application data change is implemented on app restart // converts unit system if it changed SpanAnalyzerData* data = wxGetApp().data(); if (units_before != config->units) { wxLogVerbose("Converting unit system."); // converts app data for (auto iter = data->weathercases.begin(); iter != data->weathercases.end(); iter++) { WeatherLoadCase* weathercase = *iter; WeatherLoadCaseUnitConverter::ConvertUnitSystem( units_before, config->units, *weathercase); } for (auto iter = data->cablefiles.begin(); iter != data->cablefiles.end(); iter++) { CableFile* cablefile = *iter; CableUnitConverter::ConvertUnitSystem( units_before, config->units, cablefile->cable); } // updates document/views SpanAnalyzerDoc* doc = wxGetApp().GetDocument(); if (doc != nullptr) { doc->ConvertUnitSystem(units_before, config->units); doc->RunAnalysis(); // updates views UpdateHint hint(HintType::kPreferencesEdit); doc->UpdateAllViews(nullptr, &hint); } } // updates logging level wxLog::SetLogLevel(config->level_log); if (config->level_log == wxLOG_Message) { wxLog::SetVerbose(false); } else if (config->level_log == wxLOG_Info) { wxLog::SetVerbose(true); } } void SpanAnalyzerFrame::OnMenuHelpAbout(wxCommandEvent& event) { // sets the dialog info wxAboutDialogInfo info; info.SetIcon(wxICON(icon)); info.SetName(wxGetApp().GetAppDisplayName()); info.SetVersion("0.2.0"); info.SetCopyright("License: http://unlicense.org/"); info.SetDescription( "This application provides a GUI for calculating the sag-tension response\n" "of transmission line cables.\n" "\n" "This application is part of the Overhead Transmission Line Software\n" "suite. For the actual engineering modeling and sag-tension computations,\n" "see the Models library.\n" "\n" "This software was developed so that transmission engineers can know\n" "exactly how results are calculated, and so that the software can be\n" "freely modified to fit the unique needs of the utility they represent.\n" "\n" "To get involved in project development, or to review the code, see the\n" "website link."); info.SetWebSite("https://github.com/OverheadTransmissionLineSoftware/SpanAnalyzer"); // shows the dialog wxAboutBox(info, this); } void SpanAnalyzerFrame::OnMenuViewCableModel(wxCommandEvent& event) { wxAuiPaneInfo& info = manager_.GetPane("Cable"); if (info.IsShown() == false) { info.Show(true); } else { info.Show(false); } manager_.Update(); } void SpanAnalyzerFrame::OnMenuViewLog(wxCommandEvent& event) { wxAuiPaneInfo& info = manager_.GetPane("Log"); if (info.IsShown() == false) { info.Show(true); } else { info.Show(false); } manager_.Update(); } LogPane* SpanAnalyzerFrame::pane_log() { return pane_log_; } <commit_msg>Updated version number.<commit_after>// This is free and unencumbered software released into the public domain. // For more information, please refer to <http://unlicense.org/> #include "span_analyzer_frame.h" #include "wx/aboutdlg.h" #include "wx/xrc/xmlres.h" #include "analysis_filter_manager_dialog.h" #include "cable_file_manager_dialog.h" #include "cable_unit_converter.h" #include "file_handler.h" #include "preferences_dialog.h" #include "span_analyzer_app.h" #include "span_analyzer_doc.h" #include "span_analyzer_view.h" #include "weather_load_case_manager_dialog.h" #include "weather_load_case_unit_converter.h" #include "xpm/icon.xpm" DocumentFileDropTarget::DocumentFileDropTarget(wxWindow* parent) { parent_ = parent; // creates data object to store dropped information SetDataObject(new wxFileDataObject()); SetDefaultAction(wxDragCopy); } bool DocumentFileDropTarget::OnDropFiles(wxCoord x, wxCoord y, const wxArrayString& filenames) { // gets data from drag-and-drop operation wxFileDataObject* data = dynamic_cast<wxFileDataObject*>(GetDataObject()); // tests if file exists // only the first file in the list is processed const wxString& str_file = data->GetFilenames().front(); if (wxFileName::Exists(str_file) == false) { return false; } // tests if extension matches application document wxFileName path(str_file); if (path.GetExt() == ".spananalyzer") { return false; } // freezes frame, opens document, and thaws frame parent_->Freeze(); wxGetApp().manager_doc()->CreateDocument(str_file); parent_->Thaw(); return true; } BEGIN_EVENT_TABLE(SpanAnalyzerFrame, wxDocParentFrame) EVT_MENU(XRCID("menuitem_edit_analysisfilters"), SpanAnalyzerFrame::OnMenuEditAnalysisFilters) EVT_MENU(XRCID("menuitem_edit_cables"), SpanAnalyzerFrame::OnMenuEditCables) EVT_MENU(XRCID("menuitem_edit_weathercases"), SpanAnalyzerFrame::OnMenuEditWeathercases) EVT_MENU(XRCID("menuitem_file_preferences"), SpanAnalyzerFrame::OnMenuFilePreferences) EVT_MENU(XRCID("menuitem_help_about"), SpanAnalyzerFrame::OnMenuHelpAbout) EVT_MENU(XRCID("menuitem_view_cable_model"), SpanAnalyzerFrame::OnMenuViewCableModel) EVT_MENU(XRCID("menuitem_view_log"), SpanAnalyzerFrame::OnMenuViewLog) END_EVENT_TABLE() SpanAnalyzerFrame::SpanAnalyzerFrame(wxDocManager* manager) : wxDocParentFrame(manager, nullptr, wxID_ANY, "Span Analyzer") { // loads dialog from virtual xrc file system wxXmlResource::Get()->LoadMenuBar(this, "span_analyzer_menubar"); // sets the frame icon SetIcon(wxIcon(icon_xpm)); // sets the drag and drop target SetDropTarget(new DocumentFileDropTarget(this)); // tells aui manager to manage this frame manager_.SetManagedWindow(this); // creates status bar wxStatusBar* status_bar = CreateStatusBar(); const int kFieldsCount = 2; const int widths_field[2] = {-1, 170}; status_bar->SetFieldsCount(kFieldsCount); status_bar->SetStatusWidths(kFieldsCount, widths_field); // creates log AUI window and adds to manager wxAuiPaneInfo info; info.Name("Log"); info.Float(); info.Caption("Log"); info.CloseButton(true); info.Show(false); pane_log_ = new LogPane(this); manager_.AddPane(pane_log_, info); manager_.Update(); } SpanAnalyzerFrame::~SpanAnalyzerFrame() { // saves frame size to application config SpanAnalyzerConfig* config = wxGetApp().config(); if (this->IsMaximized() == true) { config->size_frame = wxSize(0, 0); } else { config->size_frame = this->GetSize(); } manager_.UnInit(); } void SpanAnalyzerFrame::OnMenuEditAnalysisFilters(wxCommandEvent& event) { // gets application config and data const SpanAnalyzerConfig* config = wxGetApp().config(); SpanAnalyzerData* data = wxGetApp().data(); // creates and shows the analysis filter manager dialog AnalysisFilterManagerDialog dialog(this, &data->weathercases, &data->groups_filters); if (dialog.ShowModal() == wxID_OK) { wxBusyCursor cursor; wxLogVerbose("Updating analysis filters."); // saves application data FileHandler::SaveAppData(config->filepath_data, *data, config->units); // updates document/views SpanAnalyzerDoc* doc = wxGetApp().GetDocument(); if (doc != nullptr) { UpdateHint hint(HintType::kAnalysisFilterGroupEdit); doc->UpdateAllViews(nullptr, &hint); } } } void SpanAnalyzerFrame::OnMenuEditCables(wxCommandEvent& event) { // gets application config and data const SpanAnalyzerConfig* config = wxGetApp().config(); SpanAnalyzerData* data = wxGetApp().data(); // creates and shows the cable file manager dialog CableFileManagerDialog dialog(this, config->units, &data->cablefiles); if (dialog.ShowModal() == wxID_OK) { wxBusyCursor cursor; wxLogVerbose("Updating cables."); // saves application data FileHandler::SaveAppData(config->filepath_data, *data, config->units); } wxBusyCursor cursor; // updates document/views SpanAnalyzerDoc* doc = wxGetApp().GetDocument(); if (doc != nullptr) { doc->RunAnalysis(); UpdateHint hint(HintType::kCablesEdit); doc->UpdateAllViews(nullptr, &hint); } } void SpanAnalyzerFrame::OnMenuEditWeathercases( wxCommandEvent& event) { // gets application data SpanAnalyzerData* data = wxGetApp().data(); // shows an editor WeatherLoadCaseManagerDialog dialog( this, wxGetApp().config()->units, &data->weathercases); if (dialog.ShowModal() == wxID_OK) { wxBusyCursor cursor; wxLogVerbose("Updating weathercases."); // saves application data FileHandler::SaveAppData(wxGetApp().config()->filepath_data, *data, wxGetApp().config()->units); } // updates document/views SpanAnalyzerDoc* doc = wxGetApp().GetDocument(); if (doc != nullptr) { doc->RunAnalysis(); UpdateHint hint(HintType::kWeathercasesEdit); doc->UpdateAllViews(nullptr, &hint); } } void SpanAnalyzerFrame::OnMenuFilePreferences(wxCommandEvent& event) { // gets the application config SpanAnalyzerConfig* config = wxGetApp().config(); // stores a copy of the unit system before letting user edit units::UnitSystem units_before = config->units; // creates preferences editor dialog and shows // exits if user closes/cancels PreferencesDialog preferences(this, config); if (preferences.ShowModal() != wxID_OK) { return; } wxBusyCursor cursor; // application data change is implemented on app restart // converts unit system if it changed SpanAnalyzerData* data = wxGetApp().data(); if (units_before != config->units) { wxLogVerbose("Converting unit system."); // converts app data for (auto iter = data->weathercases.begin(); iter != data->weathercases.end(); iter++) { WeatherLoadCase* weathercase = *iter; WeatherLoadCaseUnitConverter::ConvertUnitSystem( units_before, config->units, *weathercase); } for (auto iter = data->cablefiles.begin(); iter != data->cablefiles.end(); iter++) { CableFile* cablefile = *iter; CableUnitConverter::ConvertUnitSystem( units_before, config->units, cablefile->cable); } // updates document/views SpanAnalyzerDoc* doc = wxGetApp().GetDocument(); if (doc != nullptr) { doc->ConvertUnitSystem(units_before, config->units); doc->RunAnalysis(); // updates views UpdateHint hint(HintType::kPreferencesEdit); doc->UpdateAllViews(nullptr, &hint); } } // updates logging level wxLog::SetLogLevel(config->level_log); if (config->level_log == wxLOG_Message) { wxLog::SetVerbose(false); } else if (config->level_log == wxLOG_Info) { wxLog::SetVerbose(true); } } void SpanAnalyzerFrame::OnMenuHelpAbout(wxCommandEvent& event) { // sets the dialog info wxAboutDialogInfo info; info.SetIcon(wxICON(icon)); info.SetName(wxGetApp().GetAppDisplayName()); info.SetVersion("0.3.0"); info.SetCopyright("License: http://unlicense.org/"); info.SetDescription( "This application provides a GUI for calculating the sag-tension response\n" "of transmission line cables.\n" "\n" "This application is part of the Overhead Transmission Line Software\n" "suite. For the actual engineering modeling and sag-tension computations,\n" "see the Models library.\n" "\n" "This software was developed so that transmission engineers can know\n" "exactly how results are calculated, and so that the software can be\n" "freely modified to fit the unique needs of the utility they represent.\n" "\n" "To get involved in project development, or to review the code, see the\n" "website link."); info.SetWebSite("https://github.com/OverheadTransmissionLineSoftware/SpanAnalyzer"); // shows the dialog wxAboutBox(info, this); } void SpanAnalyzerFrame::OnMenuViewCableModel(wxCommandEvent& event) { wxAuiPaneInfo& info = manager_.GetPane("Cable"); if (info.IsShown() == false) { info.Show(true); } else { info.Show(false); } manager_.Update(); } void SpanAnalyzerFrame::OnMenuViewLog(wxCommandEvent& event) { wxAuiPaneInfo& info = manager_.GetPane("Log"); if (info.IsShown() == false) { info.Show(true); } else { info.Show(false); } manager_.Update(); } LogPane* SpanAnalyzerFrame::pane_log() { return pane_log_; } <|endoftext|>
<commit_before>/** ========================================================================== * Original code made by Robert Engeln. Given as a PUBLIC DOMAIN dedication for * the benefit of g3log. It was originally published at: * http://code-freeze.blogspot.com/2012/01/generating-stack-traces-from-c.html * 2014-2015: adapted for g3log by Kjell Hedstrom (KjellKod). * * This is PUBLIC DOMAIN to use at your own risk and comes * with no warranties. This code is yours to share, use and modify with no * strings attached and no restrictions or obligations. * * For more information see g3log/LICENSE or refer refer to http://unlicense.org * ============================================================================*/ #include "g3log/stacktrace_windows.hpp" #include <windows.h> #include <dbghelp.h> #include <map> #include <memory> #include <cassert> #include <vector> #include <mutex> #include <g3log/g3log.hpp> #pragma comment(lib, "dbghelp.lib") #if !(defined(WIN32) || defined(_WIN32) || defined(__WIN32__)) #error "stacktrace_win.cpp used but not on a windows system" #endif #define g3_MAP_PAIR_STRINGIFY(x) {x, #x} namespace { thread_local size_t g_thread_local_recursive_crash_check = 0; const std::map<g3::SignalType, std::string> kExceptionsAsText = { g3_MAP_PAIR_STRINGIFY(EXCEPTION_ACCESS_VIOLATION) , g3_MAP_PAIR_STRINGIFY(EXCEPTION_ARRAY_BOUNDS_EXCEEDED) , g3_MAP_PAIR_STRINGIFY(EXCEPTION_DATATYPE_MISALIGNMENT) , g3_MAP_PAIR_STRINGIFY(EXCEPTION_FLT_DENORMAL_OPERAND) , g3_MAP_PAIR_STRINGIFY(EXCEPTION_FLT_DIVIDE_BY_ZERO) , g3_MAP_PAIR_STRINGIFY(EXCEPTION_FLT_INEXACT_RESULT) , g3_MAP_PAIR_STRINGIFY(EXCEPTION_FLT_INEXACT_RESULT) , g3_MAP_PAIR_STRINGIFY(EXCEPTION_FLT_INVALID_OPERATION) , g3_MAP_PAIR_STRINGIFY(EXCEPTION_FLT_OVERFLOW) , g3_MAP_PAIR_STRINGIFY(EXCEPTION_FLT_STACK_CHECK) , g3_MAP_PAIR_STRINGIFY(EXCEPTION_FLT_UNDERFLOW) , g3_MAP_PAIR_STRINGIFY(EXCEPTION_ILLEGAL_INSTRUCTION) , g3_MAP_PAIR_STRINGIFY(EXCEPTION_IN_PAGE_ERROR) , g3_MAP_PAIR_STRINGIFY(EXCEPTION_INT_DIVIDE_BY_ZERO) , g3_MAP_PAIR_STRINGIFY(EXCEPTION_INT_OVERFLOW) , g3_MAP_PAIR_STRINGIFY(EXCEPTION_INVALID_DISPOSITION) , g3_MAP_PAIR_STRINGIFY(EXCEPTION_NONCONTINUABLE_EXCEPTION) , g3_MAP_PAIR_STRINGIFY(EXCEPTION_PRIV_INSTRUCTION) , g3_MAP_PAIR_STRINGIFY(EXCEPTION_STACK_OVERFLOW) , g3_MAP_PAIR_STRINGIFY(EXCEPTION_BREAKPOINT) , g3_MAP_PAIR_STRINGIFY(EXCEPTION_SINGLE_STEP) }; // Using the given context, fill in all the stack frames. // Which then later can be interpreted to human readable text void captureStackTrace(CONTEXT *context, std::vector<uint64_t> &frame_pointers) { DWORD machine_type = 0; STACKFRAME64 frame = {}; // force zeroing frame.AddrPC.Mode = AddrModeFlat; frame.AddrFrame.Mode = AddrModeFlat; frame.AddrStack.Mode = AddrModeFlat; #ifdef _M_X64 frame.AddrPC.Offset = context->Rip; frame.AddrFrame.Offset = context->Rbp; frame.AddrStack.Offset = context->Rsp; machine_type = IMAGE_FILE_MACHINE_AMD64; #else frame.AddrPC.Offset = context->Eip; frame.AddrPC.Offset = context->Ebp; frame.AddrPC.Offset = context->Esp; machine_type = IMAGE_FILE_MACHINE_I386; #endif for (size_t index = 0; index < frame_pointers.size(); ++index) { if (StackWalk64(machine_type, GetCurrentProcess(), GetCurrentThread(), &frame, context, NULL, SymFunctionTableAccess64, SymGetModuleBase64, NULL)) { frame_pointers[index] = frame.AddrPC.Offset; } else { break; } } } // extract readable text from a given stack frame. All thanks to // using SymFromAddr and SymGetLineFromAddr64 with the stack pointer std::string getSymbolInformation(const size_t index, const std::vector<uint64_t> &frame_pointers) { auto addr = frame_pointers[index]; std::string frame_dump = "stack dump [" + std::to_string(index) + "]\t"; DWORD64 displacement64; DWORD displacement; char symbol_buffer[sizeof(SYMBOL_INFO) + MAX_SYM_NAME]; SYMBOL_INFO *symbol = reinterpret_cast<SYMBOL_INFO *>(symbol_buffer); symbol->SizeOfStruct = sizeof(SYMBOL_INFO); symbol->MaxNameLen = MAX_SYM_NAME; IMAGEHLP_LINE64 line; line.SizeOfStruct = sizeof(IMAGEHLP_LINE64); std::string lineInformation; std::string callInformation; if (SymFromAddr(GetCurrentProcess(), addr, &displacement64, symbol)) { callInformation.append(" ").append(std::string(symbol->Name, symbol->NameLen)); if (SymGetLineFromAddr64(GetCurrentProcess(), addr, &displacement, &line)) { lineInformation.append("\t").append(line.FileName).append(" L: "); lineInformation.append(std::to_string(line.LineNumber)); } } frame_dump.append(lineInformation).append(callInformation); return frame_dump; } // Retrieves all the symbols for the stack frames, fills them within a text representation and returns it std::string convertFramesToText(std::vector<uint64_t> &frame_pointers) { std::string dump; // slightly more efficient than ostringstream const size_t kSize = frame_pointers.size(); for (size_t index = 0; index < kSize && frame_pointers[index]; ++index) { dump += getSymbolInformation(index, frame_pointers); dump += "\n"; } return dump; } } // anonymous namespace stacktrace { const std::string kUnknown = {"UNKNOWN EXCEPTION"}; /// return the text description of a Windows exception code /// From MSDN GetExceptionCode http://msdn.microsoft.com/en-us/library/windows/desktop/ms679356(v=vs.85).aspx std::string exceptionIdToText(g3::SignalType id) { const auto iter = kExceptionsAsText.find(id); if ( iter == kExceptionsAsText.end()) { std::string unknown = {kUnknown + ":" + std::to_string(id)}; return unknown; } return iter->second; } /// Yes a double lookup: first for isKnownException and then exceptionIdToText /// for vectored exceptions we only deal with known exceptions so this tiny /// overhead we can live with bool isKnownException(g3::SignalType id) { return (kExceptionsAsText.end() != kExceptionsAsText.find(id)); } /// helper function: retrieve stackdump from no excisting exception pointer std::string stackdump() { CONTEXT current_context; memset(&current_context, 0, sizeof(CONTEXT)); RtlCaptureContext(&current_context); return stackdump(&current_context); } /// helper function: retrieve stackdump, starting from an exception pointer std::string stackdump(EXCEPTION_POINTERS *info) { auto context = info->ContextRecord; return stackdump(context); } /// main stackdump function. retrieve stackdump, from the given context std::string stackdump(CONTEXT *context) { if (g_thread_local_recursive_crash_check >= 2) { // In Debug scenarios we allow one extra pass std::string recursive_crash = {"\n\n\n***** Recursive crash detected"}; recursive_crash.append(", cannot continue stackdump traversal. *****\n\n\n"); return recursive_crash; } ++g_thread_local_recursive_crash_check; static std::mutex m; std::lock_guard<std::mutex> lock(m); { const BOOL kLoadSymModules = TRUE; const auto initialized = SymInitialize(GetCurrentProcess(), nullptr, kLoadSymModules); if (TRUE != initialized) { return { "Error: Cannot call SymInitialize(...) for retrieving symbols in stack" }; } std::shared_ptr<void> RaiiSymCleaner(nullptr, [&](void *) { SymCleanup(GetCurrentProcess()); }); // Raii sym cleanup const size_t kmax_frame_dump_size = 64; std::vector<uint64_t> frame_pointers(kmax_frame_dump_size); // C++11: size set and values are zeroed assert(frame_pointers.size() == kmax_frame_dump_size); captureStackTrace(context, frame_pointers); return convertFramesToText(frame_pointers); } } } // stacktrace <commit_msg>Fix ARM compilation for windows. (#401)<commit_after>/** ========================================================================== * Original code made by Robert Engeln. Given as a PUBLIC DOMAIN dedication for * the benefit of g3log. It was originally published at: * http://code-freeze.blogspot.com/2012/01/generating-stack-traces-from-c.html * 2014-2015: adapted for g3log by Kjell Hedstrom (KjellKod). * * This is PUBLIC DOMAIN to use at your own risk and comes * with no warranties. This code is yours to share, use and modify with no * strings attached and no restrictions or obligations. * * For more information see g3log/LICENSE or refer refer to http://unlicense.org * ============================================================================*/ #include "g3log/stacktrace_windows.hpp" #include <windows.h> #include <dbghelp.h> #include <map> #include <memory> #include <cassert> #include <vector> #include <mutex> #include <g3log/g3log.hpp> #pragma comment(lib, "dbghelp.lib") #if !(defined(WIN32) || defined(_WIN32) || defined(__WIN32__)) #error "stacktrace_win.cpp used but not on a windows system" #endif #define g3_MAP_PAIR_STRINGIFY(x) {x, #x} namespace { thread_local size_t g_thread_local_recursive_crash_check = 0; const std::map<g3::SignalType, std::string> kExceptionsAsText = { g3_MAP_PAIR_STRINGIFY(EXCEPTION_ACCESS_VIOLATION) , g3_MAP_PAIR_STRINGIFY(EXCEPTION_ARRAY_BOUNDS_EXCEEDED) , g3_MAP_PAIR_STRINGIFY(EXCEPTION_DATATYPE_MISALIGNMENT) , g3_MAP_PAIR_STRINGIFY(EXCEPTION_FLT_DENORMAL_OPERAND) , g3_MAP_PAIR_STRINGIFY(EXCEPTION_FLT_DIVIDE_BY_ZERO) , g3_MAP_PAIR_STRINGIFY(EXCEPTION_FLT_INEXACT_RESULT) , g3_MAP_PAIR_STRINGIFY(EXCEPTION_FLT_INEXACT_RESULT) , g3_MAP_PAIR_STRINGIFY(EXCEPTION_FLT_INVALID_OPERATION) , g3_MAP_PAIR_STRINGIFY(EXCEPTION_FLT_OVERFLOW) , g3_MAP_PAIR_STRINGIFY(EXCEPTION_FLT_STACK_CHECK) , g3_MAP_PAIR_STRINGIFY(EXCEPTION_FLT_UNDERFLOW) , g3_MAP_PAIR_STRINGIFY(EXCEPTION_ILLEGAL_INSTRUCTION) , g3_MAP_PAIR_STRINGIFY(EXCEPTION_IN_PAGE_ERROR) , g3_MAP_PAIR_STRINGIFY(EXCEPTION_INT_DIVIDE_BY_ZERO) , g3_MAP_PAIR_STRINGIFY(EXCEPTION_INT_OVERFLOW) , g3_MAP_PAIR_STRINGIFY(EXCEPTION_INVALID_DISPOSITION) , g3_MAP_PAIR_STRINGIFY(EXCEPTION_NONCONTINUABLE_EXCEPTION) , g3_MAP_PAIR_STRINGIFY(EXCEPTION_PRIV_INSTRUCTION) , g3_MAP_PAIR_STRINGIFY(EXCEPTION_STACK_OVERFLOW) , g3_MAP_PAIR_STRINGIFY(EXCEPTION_BREAKPOINT) , g3_MAP_PAIR_STRINGIFY(EXCEPTION_SINGLE_STEP) }; // Using the given context, fill in all the stack frames. // Which then later can be interpreted to human readable text void captureStackTrace(CONTEXT *context, std::vector<uint64_t> &frame_pointers) { DWORD machine_type = 0; STACKFRAME64 frame = {}; // force zeroing frame.AddrPC.Mode = AddrModeFlat; frame.AddrFrame.Mode = AddrModeFlat; frame.AddrStack.Mode = AddrModeFlat; #if defined(_M_ARM64) frame.AddrPC.Offset = context->Pc; frame.AddrFrame.Offset = context->Fp; frame.AddrStack.Offset = context->Sp; machine_type = IMAGE_FILE_MACHINE_ARM64; #elif defined(_M_ARM) frame.AddrPC.Offset = context->Pc; frame.AddrFrame.Offset = context->R11; frame.AddrStack.Offset = context->Sp; machine_type = IMAGE_FILE_MACHINE_ARM; #elif defined(_M_X64) frame.AddrPC.Offset = context->Rip; frame.AddrFrame.Offset = context->Rbp; frame.AddrStack.Offset = context->Rsp; machine_type = IMAGE_FILE_MACHINE_AMD64; #else frame.AddrPC.Offset = context->Eip; frame.AddrPC.Offset = context->Ebp; frame.AddrPC.Offset = context->Esp; machine_type = IMAGE_FILE_MACHINE_I386; #endif for (size_t index = 0; index < frame_pointers.size(); ++index) { if (StackWalk64(machine_type, GetCurrentProcess(), GetCurrentThread(), &frame, context, NULL, SymFunctionTableAccess64, SymGetModuleBase64, NULL)) { frame_pointers[index] = frame.AddrPC.Offset; } else { break; } } } // extract readable text from a given stack frame. All thanks to // using SymFromAddr and SymGetLineFromAddr64 with the stack pointer std::string getSymbolInformation(const size_t index, const std::vector<uint64_t> &frame_pointers) { auto addr = frame_pointers[index]; std::string frame_dump = "stack dump [" + std::to_string(index) + "]\t"; DWORD64 displacement64; DWORD displacement; char symbol_buffer[sizeof(SYMBOL_INFO) + MAX_SYM_NAME]; SYMBOL_INFO *symbol = reinterpret_cast<SYMBOL_INFO *>(symbol_buffer); symbol->SizeOfStruct = sizeof(SYMBOL_INFO); symbol->MaxNameLen = MAX_SYM_NAME; IMAGEHLP_LINE64 line; line.SizeOfStruct = sizeof(IMAGEHLP_LINE64); std::string lineInformation; std::string callInformation; if (SymFromAddr(GetCurrentProcess(), addr, &displacement64, symbol)) { callInformation.append(" ").append(std::string(symbol->Name, symbol->NameLen)); if (SymGetLineFromAddr64(GetCurrentProcess(), addr, &displacement, &line)) { lineInformation.append("\t").append(line.FileName).append(" L: "); lineInformation.append(std::to_string(line.LineNumber)); } } frame_dump.append(lineInformation).append(callInformation); return frame_dump; } // Retrieves all the symbols for the stack frames, fills them within a text representation and returns it std::string convertFramesToText(std::vector<uint64_t> &frame_pointers) { std::string dump; // slightly more efficient than ostringstream const size_t kSize = frame_pointers.size(); for (size_t index = 0; index < kSize && frame_pointers[index]; ++index) { dump += getSymbolInformation(index, frame_pointers); dump += "\n"; } return dump; } } // anonymous namespace stacktrace { const std::string kUnknown = {"UNKNOWN EXCEPTION"}; /// return the text description of a Windows exception code /// From MSDN GetExceptionCode http://msdn.microsoft.com/en-us/library/windows/desktop/ms679356(v=vs.85).aspx std::string exceptionIdToText(g3::SignalType id) { const auto iter = kExceptionsAsText.find(id); if ( iter == kExceptionsAsText.end()) { std::string unknown = {kUnknown + ":" + std::to_string(id)}; return unknown; } return iter->second; } /// Yes a double lookup: first for isKnownException and then exceptionIdToText /// for vectored exceptions we only deal with known exceptions so this tiny /// overhead we can live with bool isKnownException(g3::SignalType id) { return (kExceptionsAsText.end() != kExceptionsAsText.find(id)); } /// helper function: retrieve stackdump from no excisting exception pointer std::string stackdump() { CONTEXT current_context; memset(&current_context, 0, sizeof(CONTEXT)); RtlCaptureContext(&current_context); return stackdump(&current_context); } /// helper function: retrieve stackdump, starting from an exception pointer std::string stackdump(EXCEPTION_POINTERS *info) { auto context = info->ContextRecord; return stackdump(context); } /// main stackdump function. retrieve stackdump, from the given context std::string stackdump(CONTEXT *context) { if (g_thread_local_recursive_crash_check >= 2) { // In Debug scenarios we allow one extra pass std::string recursive_crash = {"\n\n\n***** Recursive crash detected"}; recursive_crash.append(", cannot continue stackdump traversal. *****\n\n\n"); return recursive_crash; } ++g_thread_local_recursive_crash_check; static std::mutex m; std::lock_guard<std::mutex> lock(m); { const BOOL kLoadSymModules = TRUE; const auto initialized = SymInitialize(GetCurrentProcess(), nullptr, kLoadSymModules); if (TRUE != initialized) { return { "Error: Cannot call SymInitialize(...) for retrieving symbols in stack" }; } std::shared_ptr<void> RaiiSymCleaner(nullptr, [&](void *) { SymCleanup(GetCurrentProcess()); }); // Raii sym cleanup const size_t kmax_frame_dump_size = 64; std::vector<uint64_t> frame_pointers(kmax_frame_dump_size); // C++11: size set and values are zeroed assert(frame_pointers.size() == kmax_frame_dump_size); captureStackTrace(context, frame_pointers); return convertFramesToText(frame_pointers); } } } // stacktrace <|endoftext|>
<commit_before>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ /************************************************************************* * * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * Copyright 2000, 2010 Oracle and/or its affiliates. * * OpenOffice.org - a multi-platform office productivity suite * * 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 _SDRPAINTWINDOW_HXX #define _SDRPAINTWINDOW_HXX #include <rtl/ref.hxx> #include <vcl/virdev.hxx> #include "svx/svxdllapi.h" //////////////////////////////////////////////////////////////////////////////////////////////////// // predeclarations class SdrPaintView; namespace sdr { namespace overlay { class OverlayManager; } // end of namespace overlay } // end of namespace sdr //////////////////////////////////////////////////////////////////////////////////////////////////// class SdrPreRenderDevice { // The original OutputDevice OutputDevice& mrOutputDevice; // The VirtualDevice for PreRendering VirtualDevice maPreRenderDevice; public: SdrPreRenderDevice(OutputDevice& rOriginal); ~SdrPreRenderDevice(); void PreparePreRenderDevice(); void OutputPreRenderDevice(const Region& rExpandedRegion); OutputDevice& GetOriginalOutputDevice() const { return mrOutputDevice; } OutputDevice& GetPreRenderDevice() { return maPreRenderDevice; } }; //////////////////////////////////////////////////////////////////////////////////////////////////// class SVX_DLLPUBLIC SdrPaintWindow { private: // the OutputDevice this window represents OutputDevice& mrOutputDevice; // the SdrPaintView this window belongs to SdrPaintView& mrPaintView; // the new OverlayManager for the new OverlayObjects. Test add here, will // replace the IAOManager as soon as it works. rtl::Reference< ::sdr::overlay::OverlayManager > mxOverlayManager; // The PreRenderDevice for PreRendering SdrPreRenderDevice* mpPreRenderDevice; // The RedrawRegion used for rendering Region maRedrawRegion; // bitfield // #i72889# flag if this is only a temporary target for repaint, default is false unsigned mbTemporaryTarget : 1; /** Remember whether the mxOverlayManager supports buffering. Using this flags expensive dynamic_casts on mxOverlayManager in order to detect this. */ bool mbUseBuffer; // helpers /** Create mxOverlayManager member on demand. @param bUseBuffer Specifies whether to use the buffered (OverlayManagerBuffered) or the unbuffered (OverlayManager) version of the overlay manager. When this values is different from that of the previous call then the overlay manager is replaced by the specified one. The bUseBuffer flag will typically change its value when text editing is started or stopped. */ void impCreateOverlayManager(const bool bUseBuffer); public: SdrPaintWindow(SdrPaintView& rNewPaintView, OutputDevice& rOut); ~SdrPaintWindow(); // data read accesses SdrPaintView& GetPaintView() const { return mrPaintView; } OutputDevice& GetOutputDevice() const { return mrOutputDevice; } // OVERLAYMANAGER rtl::Reference< ::sdr::overlay::OverlayManager > GetOverlayManager() const; // #i73602# add flag if buffer shall be used void DrawOverlay(const Region& rRegion, bool bUseBuffer); // calculate visible area and return Rectangle GetVisibleArea() const; // Is OutDev a printer? sal_Bool OutputToPrinter() const { return (OUTDEV_PRINTER == mrOutputDevice.GetOutDevType()); } // Is OutDev a window? sal_Bool OutputToWindow() const { return (OUTDEV_WINDOW == mrOutputDevice.GetOutDevType()); } // Is OutDev a VirtualDevice? sal_Bool OutputToVirtualDevice() const { return (OUTDEV_VIRDEV == mrOutputDevice.GetOutDevType()); } // Is OutDev a recording MetaFile? sal_Bool OutputToRecordingMetaFile() const; // prepare PreRendering (evtl.) void PreparePreRenderDevice(); void DestroyPreRenderDevice(); void OutputPreRenderDevice(const Region& rExpandedRegion); SdrPreRenderDevice* GetPreRenderDevice() const { return mpPreRenderDevice; } // RedrawRegion const Region& GetRedrawRegion() const; void SetRedrawRegion(const Region& rNew); // #i72889# read/write access to TempoparyTarget bool getTemporaryTarget() const { return (bool)mbTemporaryTarget; } void setTemporaryTarget(bool bNew) { if(bNew != (bool)mbTemporaryTarget) mbTemporaryTarget = bNew; } // #i72889# get target output device, take into account output buffering OutputDevice& GetTargetOutputDevice() { if(mpPreRenderDevice) return mpPreRenderDevice->GetPreRenderDevice(); else return mrOutputDevice; } }; // typedefs for a list of SdrPaintWindows typedef ::std::vector< SdrPaintWindow* > SdrPaintWindowVector; //////////////////////////////////////////////////////////////////////////////////////////////////// #endif //_SDRPAINTWINDOW_HXX /* vim:set shiftwidth=4 softtabstop=4 expandtab: */ <commit_msg>workaround broken msvc template instantiation<commit_after>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ /************************************************************************* * * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * Copyright 2000, 2010 Oracle and/or its affiliates. * * OpenOffice.org - a multi-platform office productivity suite * * 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 _SDRPAINTWINDOW_HXX #define _SDRPAINTWINDOW_HXX #include <rtl/ref.hxx> #include <vcl/virdev.hxx> #include "svx/svxdllapi.h" //////////////////////////////////////////////////////////////////////////////////////////////////// // predeclarations class SdrPaintView; namespace sdr { namespace overlay { class OverlayManager; } // end of namespace overlay } // end of namespace sdr #ifdef _MSC_VER // broken msvc template instantiation #include <svx/sdr/overlay/overlaymanager.hxx> #endif //////////////////////////////////////////////////////////////////////////////////////////////////// class SdrPreRenderDevice { // The original OutputDevice OutputDevice& mrOutputDevice; // The VirtualDevice for PreRendering VirtualDevice maPreRenderDevice; public: SdrPreRenderDevice(OutputDevice& rOriginal); ~SdrPreRenderDevice(); void PreparePreRenderDevice(); void OutputPreRenderDevice(const Region& rExpandedRegion); OutputDevice& GetOriginalOutputDevice() const { return mrOutputDevice; } OutputDevice& GetPreRenderDevice() { return maPreRenderDevice; } }; //////////////////////////////////////////////////////////////////////////////////////////////////// class SVX_DLLPUBLIC SdrPaintWindow { private: // the OutputDevice this window represents OutputDevice& mrOutputDevice; // the SdrPaintView this window belongs to SdrPaintView& mrPaintView; // the new OverlayManager for the new OverlayObjects. Test add here, will // replace the IAOManager as soon as it works. rtl::Reference< ::sdr::overlay::OverlayManager > mxOverlayManager; // The PreRenderDevice for PreRendering SdrPreRenderDevice* mpPreRenderDevice; // The RedrawRegion used for rendering Region maRedrawRegion; // bitfield // #i72889# flag if this is only a temporary target for repaint, default is false unsigned mbTemporaryTarget : 1; /** Remember whether the mxOverlayManager supports buffering. Using this flags expensive dynamic_casts on mxOverlayManager in order to detect this. */ bool mbUseBuffer; // helpers /** Create mxOverlayManager member on demand. @param bUseBuffer Specifies whether to use the buffered (OverlayManagerBuffered) or the unbuffered (OverlayManager) version of the overlay manager. When this values is different from that of the previous call then the overlay manager is replaced by the specified one. The bUseBuffer flag will typically change its value when text editing is started or stopped. */ void impCreateOverlayManager(const bool bUseBuffer); public: SdrPaintWindow(SdrPaintView& rNewPaintView, OutputDevice& rOut); ~SdrPaintWindow(); // data read accesses SdrPaintView& GetPaintView() const { return mrPaintView; } OutputDevice& GetOutputDevice() const { return mrOutputDevice; } // OVERLAYMANAGER rtl::Reference< ::sdr::overlay::OverlayManager > GetOverlayManager() const; // #i73602# add flag if buffer shall be used void DrawOverlay(const Region& rRegion, bool bUseBuffer); // calculate visible area and return Rectangle GetVisibleArea() const; // Is OutDev a printer? sal_Bool OutputToPrinter() const { return (OUTDEV_PRINTER == mrOutputDevice.GetOutDevType()); } // Is OutDev a window? sal_Bool OutputToWindow() const { return (OUTDEV_WINDOW == mrOutputDevice.GetOutDevType()); } // Is OutDev a VirtualDevice? sal_Bool OutputToVirtualDevice() const { return (OUTDEV_VIRDEV == mrOutputDevice.GetOutDevType()); } // Is OutDev a recording MetaFile? sal_Bool OutputToRecordingMetaFile() const; // prepare PreRendering (evtl.) void PreparePreRenderDevice(); void DestroyPreRenderDevice(); void OutputPreRenderDevice(const Region& rExpandedRegion); SdrPreRenderDevice* GetPreRenderDevice() const { return mpPreRenderDevice; } // RedrawRegion const Region& GetRedrawRegion() const; void SetRedrawRegion(const Region& rNew); // #i72889# read/write access to TempoparyTarget bool getTemporaryTarget() const { return (bool)mbTemporaryTarget; } void setTemporaryTarget(bool bNew) { if(bNew != (bool)mbTemporaryTarget) mbTemporaryTarget = bNew; } // #i72889# get target output device, take into account output buffering OutputDevice& GetTargetOutputDevice() { if(mpPreRenderDevice) return mpPreRenderDevice->GetPreRenderDevice(); else return mrOutputDevice; } }; // typedefs for a list of SdrPaintWindows typedef ::std::vector< SdrPaintWindow* > SdrPaintWindowVector; //////////////////////////////////////////////////////////////////////////////////////////////////// #endif //_SDRPAINTWINDOW_HXX /* vim:set shiftwidth=4 softtabstop=4 expandtab: */ <|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 <vcl/bitmap.hxx> #include <vcl/builder.hxx> #include <vcl/settings.hxx> #include <editeng/frmdiritem.hxx> #include <svx/pageitem.hxx> #include <svx/pagectrl.hxx> #include <editeng/boxitem.hxx> #include <algorithm> #include <basegfx/matrix/b2dhommatrix.hxx> #include <drawinglayer/geometry/viewinformation2d.hxx> #include <drawinglayer/processor2d/processor2dtools.hxx> #include <drawinglayer/primitive2d/polygonprimitive2d.hxx> #include <basegfx/polygon/b2dpolygontools.hxx> #define CELL_WIDTH 1600L #define CELL_HEIGHT 800L SvxPageWindow::SvxPageWindow(vcl::Window* pParent) : Window(pParent), aWinSize(), aSize(), nTop(0), nBottom(0), nLeft(0), nRight(0), //UUUU pBorder(0), bResetBackground(false), bFrameDirection(false), nFrameDirection(0), nHdLeft(0), nHdRight(0), nHdDist(0), nHdHeight(0), pHdBorder(0), nFtLeft(0), nFtRight(0), nFtDist(0), nFtHeight(0), pFtBorder(0), maHeaderFillAttributes(), maFooterFillAttributes(), maPageFillAttributes(), bFooter(false), bHeader(false), bTable(false), bHorz(false), bVert(false), eUsage(SVX_PAGE_ALL), aLeftText(), aRightText() { // Count in Twips by default SetMapMode(MapMode(MAP_TWIP)); aWinSize = GetOptimalSize(); aWinSize.Height() -= 4; aWinSize.Width() -= 4; aWinSize = PixelToLogic(aWinSize); SetBackground(); } SvxPageWindow::~SvxPageWindow() { delete pHdBorder; delete pFtBorder; } extern "C" SAL_DLLPUBLIC_EXPORT vcl::Window* SAL_CALL makeSvxPageWindow(vcl::Window *pParent, VclBuilder::stringmap &) { return new SvxPageWindow(pParent); } void SvxPageWindow::Paint(const Rectangle&) { boost::rational<long> aXScale(aWinSize.Width(),std::max((long)(aSize.Width() * 2 + aSize.Width() / 8),1L)); boost::rational<long> aYScale(aWinSize.Height(),std::max(aSize.Height(),1L)); MapMode aMapMode(GetMapMode()); if(aYScale < aXScale) { aMapMode.SetScaleX(aYScale); aMapMode.SetScaleY(aYScale); } else { aMapMode.SetScaleX(aXScale); aMapMode.SetScaleY(aXScale); } SetMapMode(aMapMode); Size aSz(PixelToLogic(GetSizePixel())); long nYPos = (aSz.Height() - aSize.Height()) / 2; if(eUsage == SVX_PAGE_ALL) { // all pages are equal -> draw one page if (aSize.Width() > aSize.Height()) { // Draw Landscape page of the same size boost::rational<long> aX = aMapMode.GetScaleX(); boost::rational<long> aY = aMapMode.GetScaleY(); boost::rational<long> a2(3, 2); aX *= a2; aY *= a2; aMapMode.SetScaleX(aX); aMapMode.SetScaleY(aY); SetMapMode(aMapMode); aSz = PixelToLogic(GetSizePixel()); nYPos = (aSz.Height() - aSize.Height()) / 2; long nXPos = (aSz.Width() - aSize.Width()) / 2; DrawPage(Point(nXPos,nYPos),true,true); } else // Portrait DrawPage(Point((aSz.Width() - aSize.Width()) / 2,nYPos),true,true); } else { // Left and right page are different -> draw two pages if possible DrawPage(Point(0,nYPos),false,(eUsage & SVX_PAGE_LEFT) != 0); DrawPage(Point(aSize.Width() + aSize.Width() / 8,nYPos),true, (eUsage & SVX_PAGE_RIGHT) != 0); } } void SvxPageWindow::DrawPage(const Point& rOrg, const bool bSecond, const bool bEnabled) { const StyleSettings& rStyleSettings = GetSettings().GetStyleSettings(); const Color& rFieldColor = rStyleSettings.GetFieldColor(); const Color& rFieldTextColor = rStyleSettings.GetFieldTextColor(); const Color& rDisableColor = rStyleSettings.GetDisableColor(); const Color& rDlgColor = rStyleSettings.GetDialogColor(); // background if(!bSecond || bResetBackground) { SetLineColor(Color(COL_TRANSPARENT)); SetFillColor(rDlgColor); Size winSize(GetOutputSize()); DrawRect(Rectangle(Point(0,0),winSize)); if(bResetBackground) bResetBackground = false; } SetLineColor(rFieldTextColor); // Shadow Size aTempSize = aSize; // Page if(!bEnabled) { SetFillColor(rDisableColor); DrawRect(Rectangle(rOrg,aTempSize)); return; } SetFillColor(rFieldColor); DrawRect(Rectangle(rOrg,aTempSize)); long nL = nLeft; long nR = nRight; if(eUsage == SVX_PAGE_MIRROR && !bSecond) { // turn for mirrored nL = nRight; nR = nLeft; } Rectangle aRect; aRect.Left() = rOrg.X() + nL; aRect.Right() = rOrg.X() + aTempSize.Width() - nR; aRect.Top() = rOrg.Y() + nTop; aRect.Bottom() = rOrg.Y() + aTempSize.Height() - nBottom; Rectangle aHdRect(aRect); Rectangle aFtRect(aRect); if(bHeader || bFooter) { //UUUU Header and/or footer used const Color aLineColor(GetLineColor()); //UUUU draw PageFill first and on the whole page, no outline SetLineColor(); drawFillAttributes(maPageFillAttributes, aRect, aRect); SetLineColor(aLineColor); if(bHeader) { // show headers if possible aHdRect.Left() += nHdLeft; aHdRect.Right() -= nHdRight; aHdRect.Bottom() = aRect.Top() + nHdHeight; aRect.Top() += nHdHeight + nHdDist; // draw header over PageFill, plus outline drawFillAttributes(maHeaderFillAttributes, aHdRect, aHdRect); } if(bFooter) { // show footer if possible aFtRect.Left() += nFtLeft; aFtRect.Right() -= nFtRight; aFtRect.Top() = aRect.Bottom() - nFtHeight; aRect.Bottom() -= nFtHeight + nFtDist; // draw footer over PageFill, plus outline drawFillAttributes(maFooterFillAttributes, aFtRect, aFtRect); } // draw page's reduced outline, only outline drawFillAttributes(drawinglayer::attribute::SdrAllFillAttributesHelperPtr(), aRect, aRect); } else { //UUUU draw PageFill and outline drawFillAttributes(maPageFillAttributes, aRect, aRect); } if(bFrameDirection && !bTable) { Point aPos; vcl::Font aFont(GetFont()); const Size aSaveSize = aFont.GetSize(); Size aDrawSize(0,aRect.GetHeight() / 6); aFont.SetSize(aDrawSize); SetFont(aFont); OUString sText("ABC"); Point aMove(1, GetTextHeight()); sal_Unicode cArrow = 0x2193; long nAWidth = GetTextWidth(sText.copy(0,1)); switch(nFrameDirection) { case FRMDIR_HORI_LEFT_TOP: aPos = aRect.TopLeft(); aPos.X() += PixelToLogic(Point(1,1)).X(); aMove.Y() = 0; cArrow = 0x2192; break; case FRMDIR_HORI_RIGHT_TOP: aPos = aRect.TopRight(); aPos.X() -= nAWidth; aMove.Y() = 0; aMove.X() *= -1; cArrow = 0x2190; break; case FRMDIR_VERT_TOP_LEFT: aPos = aRect.TopLeft(); aPos.X() += PixelToLogic(Point(1,1)).X(); aMove.X() = 0; break; case FRMDIR_VERT_TOP_RIGHT: aPos = aRect.TopRight(); aPos.X() -= nAWidth; aMove.X() = 0; break; } sText += OUString(cArrow); for(sal_uInt16 i = 0; i < sText.getLength(); i++) { OUString sDraw(sText.copy(i,1)); long nHDiff = 0; long nCharWidth = GetTextWidth(sDraw); bool bHorizontal = 0 == aMove.Y(); if(!bHorizontal) { nHDiff = (nAWidth - nCharWidth) / 2; aPos.X() += nHDiff; } DrawText(aPos,sDraw); if(bHorizontal) { aPos.X() += aMove.X() < 0 ? -nCharWidth : nCharWidth; } else { aPos.X() -= nHDiff; aPos.Y() += aMove.Y(); } } aFont.SetSize(aSaveSize); SetFont(aFont); } if(bTable) { // Paint Table, if necessary center it SetLineColor(Color(COL_LIGHTGRAY)); long nW = aRect.GetWidth(),nH = aRect.GetHeight(); long nTW = CELL_WIDTH * 3,nTH = CELL_HEIGHT * 3; long _nLeft = bHorz ? aRect.Left() + ((nW - nTW) / 2) : aRect.Left(); long _nTop = bVert ? aRect.Top() + ((nH - nTH) / 2) : aRect.Top(); Rectangle aCellRect(Point(_nLeft,_nTop),Size(CELL_WIDTH,CELL_HEIGHT)); for(sal_uInt16 i = 0; i < 3; ++i) { aCellRect.Left() = _nLeft; aCellRect.Right() = _nLeft + CELL_WIDTH; if(i > 0) aCellRect.Move(0,CELL_HEIGHT); for(sal_uInt16 j = 0; j < 3; ++j) { if(j > 0) aCellRect.Move(CELL_WIDTH,0); DrawRect(aCellRect); } } } } //UUUU void SvxPageWindow::drawFillAttributes( const drawinglayer::attribute::SdrAllFillAttributesHelperPtr& rFillAttributes, const Rectangle& rPaintRange, const Rectangle& rDefineRange) { const basegfx::B2DRange aPaintRange( rPaintRange.Left(), rPaintRange.Top(), rPaintRange.Right(), rPaintRange.Bottom()); if(!aPaintRange.isEmpty() && !basegfx::fTools::equalZero(aPaintRange.getWidth()) && !basegfx::fTools::equalZero(aPaintRange.getHeight())) { const basegfx::B2DRange aDefineRange( rDefineRange.Left(), rDefineRange.Top(), rDefineRange.Right(), rDefineRange.Bottom()); // prepare primitive sequence drawinglayer::primitive2d::Primitive2DSequence aSequence; // create fill geometry if there is something to fill if(rFillAttributes.get() && rFillAttributes->isUsed()) { aSequence = rFillAttributes->getPrimitive2DSequence( aPaintRange, aDefineRange); } // create line geometry if a LineColor is set at the target device if(IsLineColor()) { const drawinglayer::primitive2d::Primitive2DReference xOutline( new drawinglayer::primitive2d::PolygonHairlinePrimitive2D( basegfx::tools::createPolygonFromRect(aPaintRange), GetLineColor().getBColor())); drawinglayer::primitive2d::appendPrimitive2DReferenceToPrimitive2DSequence( aSequence, xOutline); } // draw that if we have something to draw if(aSequence.getLength()) { const drawinglayer::geometry::ViewInformation2D aViewInformation2D( basegfx::B2DHomMatrix(), GetViewTransformation(), aPaintRange, 0, 0.0, com::sun::star::uno::Sequence< com::sun::star::beans::PropertyValue >()); drawinglayer::processor2d::BaseProcessor2D* pProcessor = drawinglayer::processor2d::createProcessor2DFromOutputDevice( *this, aViewInformation2D); if(pProcessor) { pProcessor->process(aSequence); delete pProcessor; } } } } void SvxPageWindow::SetBorder(const SvxBoxItem& rNew) { delete pBorder; pBorder = new SvxBoxItem(rNew); } void SvxPageWindow::SetHdBorder(const SvxBoxItem& rNew) { delete pHdBorder; pHdBorder = new SvxBoxItem(rNew); } void SvxPageWindow::SetFtBorder(const SvxBoxItem& rNew) { delete pFtBorder; pFtBorder = new SvxBoxItem(rNew); } void SvxPageWindow::EnableFrameDirection(bool bEnable) { bFrameDirection = bEnable; } void SvxPageWindow::SetFrameDirection(sal_Int32 nDirection) { nFrameDirection = nDirection; } void SvxPageWindow::ResetBackground() { bResetBackground = true; } Size SvxPageWindow::GetOptimalSize() const { return LogicToPixel(Size(75, 46), MapMode(MAP_APPFONT)); } /* vim:set shiftwidth=4 softtabstop=4 expandtab: */ <commit_msg>Fraction: Revert "-Werror,-Wliteral-conversion (implicit conversion from double to long)"<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 <vcl/bitmap.hxx> #include <vcl/builder.hxx> #include <vcl/settings.hxx> #include <editeng/frmdiritem.hxx> #include <svx/pageitem.hxx> #include <svx/pagectrl.hxx> #include <editeng/boxitem.hxx> #include <algorithm> #include <basegfx/matrix/b2dhommatrix.hxx> #include <drawinglayer/geometry/viewinformation2d.hxx> #include <drawinglayer/processor2d/processor2dtools.hxx> #include <drawinglayer/primitive2d/polygonprimitive2d.hxx> #include <basegfx/polygon/b2dpolygontools.hxx> #define CELL_WIDTH 1600L #define CELL_HEIGHT 800L SvxPageWindow::SvxPageWindow(vcl::Window* pParent) : Window(pParent), aWinSize(), aSize(), nTop(0), nBottom(0), nLeft(0), nRight(0), //UUUU pBorder(0), bResetBackground(false), bFrameDirection(false), nFrameDirection(0), nHdLeft(0), nHdRight(0), nHdDist(0), nHdHeight(0), pHdBorder(0), nFtLeft(0), nFtRight(0), nFtDist(0), nFtHeight(0), pFtBorder(0), maHeaderFillAttributes(), maFooterFillAttributes(), maPageFillAttributes(), bFooter(false), bHeader(false), bTable(false), bHorz(false), bVert(false), eUsage(SVX_PAGE_ALL), aLeftText(), aRightText() { // Count in Twips by default SetMapMode(MapMode(MAP_TWIP)); aWinSize = GetOptimalSize(); aWinSize.Height() -= 4; aWinSize.Width() -= 4; aWinSize = PixelToLogic(aWinSize); SetBackground(); } SvxPageWindow::~SvxPageWindow() { delete pHdBorder; delete pFtBorder; } extern "C" SAL_DLLPUBLIC_EXPORT vcl::Window* SAL_CALL makeSvxPageWindow(vcl::Window *pParent, VclBuilder::stringmap &) { return new SvxPageWindow(pParent); } void SvxPageWindow::Paint(const Rectangle&) { boost::rational<long> aXScale(aWinSize.Width(),std::max((long)(aSize.Width() * 2 + aSize.Width() / 8),1L)); boost::rational<long> aYScale(aWinSize.Height(),std::max(aSize.Height(),1L)); MapMode aMapMode(GetMapMode()); if(aYScale < aXScale) { aMapMode.SetScaleX(aYScale); aMapMode.SetScaleY(aYScale); } else { aMapMode.SetScaleX(aXScale); aMapMode.SetScaleY(aXScale); } SetMapMode(aMapMode); Size aSz(PixelToLogic(GetSizePixel())); long nYPos = (aSz.Height() - aSize.Height()) / 2; if(eUsage == SVX_PAGE_ALL) { // all pages are equal -> draw one page if (aSize.Width() > aSize.Height()) { // Draw Landscape page of the same size boost::rational<long> aX = aMapMode.GetScaleX(); boost::rational<long> aY = aMapMode.GetScaleY(); boost::rational<long> a2(1.5); aX *= a2; aY *= a2; aMapMode.SetScaleX(aX); aMapMode.SetScaleY(aY); SetMapMode(aMapMode); aSz = PixelToLogic(GetSizePixel()); nYPos = (aSz.Height() - aSize.Height()) / 2; long nXPos = (aSz.Width() - aSize.Width()) / 2; DrawPage(Point(nXPos,nYPos),true,true); } else // Portrait DrawPage(Point((aSz.Width() - aSize.Width()) / 2,nYPos),true,true); } else { // Left and right page are different -> draw two pages if possible DrawPage(Point(0,nYPos),false,(eUsage & SVX_PAGE_LEFT) != 0); DrawPage(Point(aSize.Width() + aSize.Width() / 8,nYPos),true, (eUsage & SVX_PAGE_RIGHT) != 0); } } void SvxPageWindow::DrawPage(const Point& rOrg, const bool bSecond, const bool bEnabled) { const StyleSettings& rStyleSettings = GetSettings().GetStyleSettings(); const Color& rFieldColor = rStyleSettings.GetFieldColor(); const Color& rFieldTextColor = rStyleSettings.GetFieldTextColor(); const Color& rDisableColor = rStyleSettings.GetDisableColor(); const Color& rDlgColor = rStyleSettings.GetDialogColor(); // background if(!bSecond || bResetBackground) { SetLineColor(Color(COL_TRANSPARENT)); SetFillColor(rDlgColor); Size winSize(GetOutputSize()); DrawRect(Rectangle(Point(0,0),winSize)); if(bResetBackground) bResetBackground = false; } SetLineColor(rFieldTextColor); // Shadow Size aTempSize = aSize; // Page if(!bEnabled) { SetFillColor(rDisableColor); DrawRect(Rectangle(rOrg,aTempSize)); return; } SetFillColor(rFieldColor); DrawRect(Rectangle(rOrg,aTempSize)); long nL = nLeft; long nR = nRight; if(eUsage == SVX_PAGE_MIRROR && !bSecond) { // turn for mirrored nL = nRight; nR = nLeft; } Rectangle aRect; aRect.Left() = rOrg.X() + nL; aRect.Right() = rOrg.X() + aTempSize.Width() - nR; aRect.Top() = rOrg.Y() + nTop; aRect.Bottom() = rOrg.Y() + aTempSize.Height() - nBottom; Rectangle aHdRect(aRect); Rectangle aFtRect(aRect); if(bHeader || bFooter) { //UUUU Header and/or footer used const Color aLineColor(GetLineColor()); //UUUU draw PageFill first and on the whole page, no outline SetLineColor(); drawFillAttributes(maPageFillAttributes, aRect, aRect); SetLineColor(aLineColor); if(bHeader) { // show headers if possible aHdRect.Left() += nHdLeft; aHdRect.Right() -= nHdRight; aHdRect.Bottom() = aRect.Top() + nHdHeight; aRect.Top() += nHdHeight + nHdDist; // draw header over PageFill, plus outline drawFillAttributes(maHeaderFillAttributes, aHdRect, aHdRect); } if(bFooter) { // show footer if possible aFtRect.Left() += nFtLeft; aFtRect.Right() -= nFtRight; aFtRect.Top() = aRect.Bottom() - nFtHeight; aRect.Bottom() -= nFtHeight + nFtDist; // draw footer over PageFill, plus outline drawFillAttributes(maFooterFillAttributes, aFtRect, aFtRect); } // draw page's reduced outline, only outline drawFillAttributes(drawinglayer::attribute::SdrAllFillAttributesHelperPtr(), aRect, aRect); } else { //UUUU draw PageFill and outline drawFillAttributes(maPageFillAttributes, aRect, aRect); } if(bFrameDirection && !bTable) { Point aPos; vcl::Font aFont(GetFont()); const Size aSaveSize = aFont.GetSize(); Size aDrawSize(0,aRect.GetHeight() / 6); aFont.SetSize(aDrawSize); SetFont(aFont); OUString sText("ABC"); Point aMove(1, GetTextHeight()); sal_Unicode cArrow = 0x2193; long nAWidth = GetTextWidth(sText.copy(0,1)); switch(nFrameDirection) { case FRMDIR_HORI_LEFT_TOP: aPos = aRect.TopLeft(); aPos.X() += PixelToLogic(Point(1,1)).X(); aMove.Y() = 0; cArrow = 0x2192; break; case FRMDIR_HORI_RIGHT_TOP: aPos = aRect.TopRight(); aPos.X() -= nAWidth; aMove.Y() = 0; aMove.X() *= -1; cArrow = 0x2190; break; case FRMDIR_VERT_TOP_LEFT: aPos = aRect.TopLeft(); aPos.X() += PixelToLogic(Point(1,1)).X(); aMove.X() = 0; break; case FRMDIR_VERT_TOP_RIGHT: aPos = aRect.TopRight(); aPos.X() -= nAWidth; aMove.X() = 0; break; } sText += OUString(cArrow); for(sal_uInt16 i = 0; i < sText.getLength(); i++) { OUString sDraw(sText.copy(i,1)); long nHDiff = 0; long nCharWidth = GetTextWidth(sDraw); bool bHorizontal = 0 == aMove.Y(); if(!bHorizontal) { nHDiff = (nAWidth - nCharWidth) / 2; aPos.X() += nHDiff; } DrawText(aPos,sDraw); if(bHorizontal) { aPos.X() += aMove.X() < 0 ? -nCharWidth : nCharWidth; } else { aPos.X() -= nHDiff; aPos.Y() += aMove.Y(); } } aFont.SetSize(aSaveSize); SetFont(aFont); } if(bTable) { // Paint Table, if necessary center it SetLineColor(Color(COL_LIGHTGRAY)); long nW = aRect.GetWidth(),nH = aRect.GetHeight(); long nTW = CELL_WIDTH * 3,nTH = CELL_HEIGHT * 3; long _nLeft = bHorz ? aRect.Left() + ((nW - nTW) / 2) : aRect.Left(); long _nTop = bVert ? aRect.Top() + ((nH - nTH) / 2) : aRect.Top(); Rectangle aCellRect(Point(_nLeft,_nTop),Size(CELL_WIDTH,CELL_HEIGHT)); for(sal_uInt16 i = 0; i < 3; ++i) { aCellRect.Left() = _nLeft; aCellRect.Right() = _nLeft + CELL_WIDTH; if(i > 0) aCellRect.Move(0,CELL_HEIGHT); for(sal_uInt16 j = 0; j < 3; ++j) { if(j > 0) aCellRect.Move(CELL_WIDTH,0); DrawRect(aCellRect); } } } } //UUUU void SvxPageWindow::drawFillAttributes( const drawinglayer::attribute::SdrAllFillAttributesHelperPtr& rFillAttributes, const Rectangle& rPaintRange, const Rectangle& rDefineRange) { const basegfx::B2DRange aPaintRange( rPaintRange.Left(), rPaintRange.Top(), rPaintRange.Right(), rPaintRange.Bottom()); if(!aPaintRange.isEmpty() && !basegfx::fTools::equalZero(aPaintRange.getWidth()) && !basegfx::fTools::equalZero(aPaintRange.getHeight())) { const basegfx::B2DRange aDefineRange( rDefineRange.Left(), rDefineRange.Top(), rDefineRange.Right(), rDefineRange.Bottom()); // prepare primitive sequence drawinglayer::primitive2d::Primitive2DSequence aSequence; // create fill geometry if there is something to fill if(rFillAttributes.get() && rFillAttributes->isUsed()) { aSequence = rFillAttributes->getPrimitive2DSequence( aPaintRange, aDefineRange); } // create line geometry if a LineColor is set at the target device if(IsLineColor()) { const drawinglayer::primitive2d::Primitive2DReference xOutline( new drawinglayer::primitive2d::PolygonHairlinePrimitive2D( basegfx::tools::createPolygonFromRect(aPaintRange), GetLineColor().getBColor())); drawinglayer::primitive2d::appendPrimitive2DReferenceToPrimitive2DSequence( aSequence, xOutline); } // draw that if we have something to draw if(aSequence.getLength()) { const drawinglayer::geometry::ViewInformation2D aViewInformation2D( basegfx::B2DHomMatrix(), GetViewTransformation(), aPaintRange, 0, 0.0, com::sun::star::uno::Sequence< com::sun::star::beans::PropertyValue >()); drawinglayer::processor2d::BaseProcessor2D* pProcessor = drawinglayer::processor2d::createProcessor2DFromOutputDevice( *this, aViewInformation2D); if(pProcessor) { pProcessor->process(aSequence); delete pProcessor; } } } } void SvxPageWindow::SetBorder(const SvxBoxItem& rNew) { delete pBorder; pBorder = new SvxBoxItem(rNew); } void SvxPageWindow::SetHdBorder(const SvxBoxItem& rNew) { delete pHdBorder; pHdBorder = new SvxBoxItem(rNew); } void SvxPageWindow::SetFtBorder(const SvxBoxItem& rNew) { delete pFtBorder; pFtBorder = new SvxBoxItem(rNew); } void SvxPageWindow::EnableFrameDirection(bool bEnable) { bFrameDirection = bEnable; } void SvxPageWindow::SetFrameDirection(sal_Int32 nDirection) { nFrameDirection = nDirection; } void SvxPageWindow::ResetBackground() { bResetBackground = true; } Size SvxPageWindow::GetOptimalSize() const { return LogicToPixel(Size(75, 46), MapMode(MAP_APPFONT)); } /* vim:set shiftwidth=4 softtabstop=4 expandtab: */ <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: selector.hxx,v $ * * $Revision: 1.13 $ * * last change: $Author: kz $ $Date: 2007-10-09 15:18:31 $ * * 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 _SVXSELECTOR_HXX #define _SVXSELECTOR_HXX #ifndef _SV_LSTBOX_HXX //autogen #include <vcl/lstbox.hxx> #endif #ifndef _SV_FIXED_HXX //autogen #include <vcl/fixed.hxx> #endif #ifndef _SV_GROUP_HXX //autogen #include <vcl/group.hxx> #endif #ifndef _SV_MENUBTN_HXX //autogen #include <vcl/menubtn.hxx> #endif #ifndef _SVTREEBOX_HXX //autogen #include <svtools/svtreebx.hxx> #endif #include <com/sun/star/uno/XComponentContext.hpp> #include <com/sun/star/frame/XFrame.hpp> #include <com/sun/star/container/XNameAccess.hpp> #include <com/sun/star/script/browse/XBrowseNode.hpp> #ifndef INCLUDED_SVXDLLAPI_H #include "svx/svxdllapi.h" #endif #define _SVSTDARR_USHORTS #define _SVSTDARR_STRINGSDTOR #include <svtools/svstdarr.hxx> // SvUShorts #include <sfx2/minarray.hxx> #define SVX_CFGGROUP_FUNCTION 1 #define SVX_CFGFUNCTION_SLOT 2 #define SVX_CFGGROUP_SCRIPTCONTAINER 3 #define SVX_CFGFUNCTION_SCRIPT 4 struct SvxGroupInfo_Impl { USHORT nKind; USHORT nOrd; ::com::sun::star::uno::Reference< ::com::sun::star::script::browse::XBrowseNode > xBrowseNode; ::rtl::OUString sURL; ::rtl::OUString sHelpText; BOOL bWasOpened; SvxGroupInfo_Impl( USHORT n, USHORT nr ) :nKind( n ) ,nOrd( nr ) ,xBrowseNode() ,sURL() ,sHelpText() ,bWasOpened(FALSE) { } SvxGroupInfo_Impl( USHORT n, USHORT nr, const ::com::sun::star::uno::Reference< ::com::sun::star::script::browse::XBrowseNode >& _rxNode ) :nKind( n ) ,nOrd( nr ) ,xBrowseNode( _rxNode ) ,sURL() ,sHelpText() ,bWasOpened(FALSE) { } SvxGroupInfo_Impl( USHORT n, USHORT nr, const ::rtl::OUString& _rURL, const ::rtl::OUString& _rHelpText ) :nKind( n ) ,nOrd( nr ) ,xBrowseNode() ,sURL( _rURL ) ,sHelpText( _rHelpText ) ,bWasOpened(FALSE) { } }; typedef SvxGroupInfo_Impl* SvxGroupInfoPtr; SV_DECL_PTRARR_DEL(SvxGroupInfoArr_Impl, SvxGroupInfoPtr, 5, 5) DECL_2BYTEARRAY(USHORTArr, USHORT, 10, 10) class ImageProvider { public: virtual ~ImageProvider() {} virtual Image GetImage( const rtl::OUString& rCommandURL ) = 0; }; class SvxConfigFunctionListBox_Impl : public SvTreeListBox { friend class SvxConfigGroupListBox_Impl; Timer aTimer; SvLBoxEntry* pCurEntry; SvxGroupInfoArr_Impl aArr; SvLBoxEntry* m_pDraggingEntry; DECL_LINK( TimerHdl, Timer* ); virtual void MouseMove( const MouseEvent& rMEvt ); public: SvxConfigFunctionListBox_Impl( Window*, const ResId& ); ~SvxConfigFunctionListBox_Impl(); void ClearAll(); SvLBoxEntry* GetEntry_Impl( USHORT nId ); SvLBoxEntry* GetEntry_Impl( const String& ); USHORT GetId( SvLBoxEntry *pEntry ); String GetHelpText( SvLBoxEntry *pEntry ); using Window::GetHelpText; USHORT GetCurId() { return GetId( FirstSelected() ); } SvLBoxEntry* GetLastSelectedEntry(); void FunctionSelected(); // drag n drop methods virtual sal_Int8 AcceptDrop( const AcceptDropEvent& rEvt ); virtual DragDropMode NotifyStartDrag( TransferDataContainer&, SvLBoxEntry* ); virtual void DragFinished( sal_Int8 ); }; class SvxConfigGroupListBox_Impl : public SvTreeListBox { SvxGroupInfoArr_Impl aArr; bool m_bShowSlots; SvxConfigFunctionListBox_Impl* pFunctionListBox; ImageProvider* m_pImageProvider; ::com::sun::star::uno::Reference < ::com::sun::star::frame::XFrame > m_xFrame; ::com::sun::star::uno::Reference < ::com::sun::star::container::XNameAccess > m_xModuleCommands; Image m_hdImage; Image m_hdImage_hc; Image m_libImage; Image m_libImage_hc; Image m_macImage; Image m_macImage_hc; Image m_docImage; Image m_docImage_hc; ::rtl::OUString m_sMyMacros; ::rtl::OUString m_sProdMacros; Image GetImage( ::com::sun::star::uno::Reference< ::com::sun::star::script::browse::XBrowseNode > node, ::com::sun::star::uno::Reference< ::com::sun::star::uno::XComponentContext > xCtx, bool bIsRootNode, bool bHighContrast ); ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface > getDocumentModel( ::com::sun::star::uno::Reference< ::com::sun::star::uno::XComponentContext >& xCtx, ::rtl::OUString& docName ); private: void fillScriptList( const ::com::sun::star::uno::Reference< ::com::sun::star::script::browse::XBrowseNode >& _rxRootNode, SvLBoxEntry* _pParentEntry, bool _bCheapChildsOnDemand ); protected: virtual void RequestingChilds( SvLBoxEntry *pEntry); virtual BOOL Expand( SvLBoxEntry* pParent ); using SvListView::Expand; public: SvxConfigGroupListBox_Impl ( Window* pParent, const ResId&, bool _bShowSlots, const ::com::sun::star::uno::Reference < ::com::sun::star::frame::XFrame >& xFrame ); ~SvxConfigGroupListBox_Impl(); void Init(); void Open( SvLBoxEntry*, BOOL ); void ClearAll(); void GroupSelected(); void SetFunctionListBox( SvxConfigFunctionListBox_Impl *pBox ) { pFunctionListBox = pBox; } void SetImageProvider( ImageProvider* provider ) { m_pImageProvider = provider; } }; class SVX_DLLPUBLIC SvxScriptSelectorDialog : public ModelessDialog { FixedText aDialogDescription; FixedText aGroupText; SvxConfigGroupListBox_Impl aCategories; FixedText aFunctionText; SvxConfigFunctionListBox_Impl aCommands; OKButton aOKButton; CancelButton aCancelButton; HelpButton aHelpButton; FixedLine aDescription; FixedText aDescriptionText; BOOL m_bShowSlots; Link m_aAddHdl; DECL_LINK( ClickHdl, Button * ); DECL_LINK( SelectHdl, Control* ); void UpdateUI(); void ResizeControls(); public: SvxScriptSelectorDialog ( Window* pParent = NULL, BOOL bShowSlots = FALSE, const ::com::sun::star::uno::Reference < ::com::sun::star::frame::XFrame >& xFrame = 0 ); ~SvxScriptSelectorDialog ( ); void SetAddHdl( const Link& rLink ) { m_aAddHdl = rLink; } const Link& GetAddHdl() const { return m_aAddHdl; } void SetImageProvider( ImageProvider* provider ) { aCategories.SetImageProvider( provider ); } USHORT GetSelectedId(); String GetScriptURL(); String GetSelectedDisplayName(); String GetSelectedHelpText(); void SetRunLabel(); void SetDialogDescription(const String& rDescription); }; #endif <commit_msg>INTEGRATION: CWS odbmacros2 (1.13.90); FILE MERGED 2008/01/06 21:52:54 fs 1.13.90.2: #i49133# ContextDocument/WorkingDocument not needed anymore 2007/12/11 22:50:53 fs 1.13.90.1: #i49133# ScriptSelectorDialog now supports obtaining the document which it used as WorkingDocument<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: selector.hxx,v $ * * $Revision: 1.14 $ * * last change: $Author: kz $ $Date: 2008-03-06 17:30: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 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 _SVXSELECTOR_HXX #define _SVXSELECTOR_HXX #ifndef _SV_LSTBOX_HXX //autogen #include <vcl/lstbox.hxx> #endif #ifndef _SV_FIXED_HXX //autogen #include <vcl/fixed.hxx> #endif #ifndef _SV_GROUP_HXX //autogen #include <vcl/group.hxx> #endif #ifndef _SV_MENUBTN_HXX //autogen #include <vcl/menubtn.hxx> #endif #ifndef _SVTREEBOX_HXX //autogen #include <svtools/svtreebx.hxx> #endif #include <com/sun/star/uno/XComponentContext.hpp> #include <com/sun/star/frame/XFrame.hpp> #include <com/sun/star/container/XNameAccess.hpp> #include <com/sun/star/script/browse/XBrowseNode.hpp> #ifndef INCLUDED_SVXDLLAPI_H #include "svx/svxdllapi.h" #endif #define _SVSTDARR_USHORTS #define _SVSTDARR_STRINGSDTOR #include <svtools/svstdarr.hxx> // SvUShorts #include <sfx2/minarray.hxx> #define SVX_CFGGROUP_FUNCTION 1 #define SVX_CFGFUNCTION_SLOT 2 #define SVX_CFGGROUP_SCRIPTCONTAINER 3 #define SVX_CFGFUNCTION_SCRIPT 4 struct SvxGroupInfo_Impl { USHORT nKind; USHORT nOrd; ::com::sun::star::uno::Reference< ::com::sun::star::script::browse::XBrowseNode > xBrowseNode; ::rtl::OUString sURL; ::rtl::OUString sHelpText; BOOL bWasOpened; SvxGroupInfo_Impl( USHORT n, USHORT nr ) :nKind( n ) ,nOrd( nr ) ,xBrowseNode() ,sURL() ,sHelpText() ,bWasOpened(FALSE) { } SvxGroupInfo_Impl( USHORT n, USHORT nr, const ::com::sun::star::uno::Reference< ::com::sun::star::script::browse::XBrowseNode >& _rxNode ) :nKind( n ) ,nOrd( nr ) ,xBrowseNode( _rxNode ) ,sURL() ,sHelpText() ,bWasOpened(FALSE) { } SvxGroupInfo_Impl( USHORT n, USHORT nr, const ::rtl::OUString& _rURL, const ::rtl::OUString& _rHelpText ) :nKind( n ) ,nOrd( nr ) ,xBrowseNode() ,sURL( _rURL ) ,sHelpText( _rHelpText ) ,bWasOpened(FALSE) { } }; typedef SvxGroupInfo_Impl* SvxGroupInfoPtr; SV_DECL_PTRARR_DEL(SvxGroupInfoArr_Impl, SvxGroupInfoPtr, 5, 5) DECL_2BYTEARRAY(USHORTArr, USHORT, 10, 10) class ImageProvider { public: virtual ~ImageProvider() {} virtual Image GetImage( const rtl::OUString& rCommandURL ) = 0; }; class SvxConfigFunctionListBox_Impl : public SvTreeListBox { friend class SvxConfigGroupListBox_Impl; Timer aTimer; SvLBoxEntry* pCurEntry; SvxGroupInfoArr_Impl aArr; SvLBoxEntry* m_pDraggingEntry; DECL_LINK( TimerHdl, Timer* ); virtual void MouseMove( const MouseEvent& rMEvt ); public: SvxConfigFunctionListBox_Impl( Window*, const ResId& ); ~SvxConfigFunctionListBox_Impl(); void ClearAll(); SvLBoxEntry* GetEntry_Impl( USHORT nId ); SvLBoxEntry* GetEntry_Impl( const String& ); USHORT GetId( SvLBoxEntry *pEntry ); String GetHelpText( SvLBoxEntry *pEntry ); using Window::GetHelpText; USHORT GetCurId() { return GetId( FirstSelected() ); } SvLBoxEntry* GetLastSelectedEntry(); void FunctionSelected(); // drag n drop methods virtual sal_Int8 AcceptDrop( const AcceptDropEvent& rEvt ); virtual DragDropMode NotifyStartDrag( TransferDataContainer&, SvLBoxEntry* ); virtual void DragFinished( sal_Int8 ); }; class SvxConfigGroupListBox_Impl : public SvTreeListBox { SvxGroupInfoArr_Impl aArr; bool m_bShowSlots; SvxConfigFunctionListBox_Impl* pFunctionListBox; ImageProvider* m_pImageProvider; ::com::sun::star::uno::Reference < ::com::sun::star::frame::XFrame > m_xFrame; ::com::sun::star::uno::Reference < ::com::sun::star::container::XNameAccess > m_xModuleCommands; Image m_hdImage; Image m_hdImage_hc; Image m_libImage; Image m_libImage_hc; Image m_macImage; Image m_macImage_hc; Image m_docImage; Image m_docImage_hc; ::rtl::OUString m_sMyMacros; ::rtl::OUString m_sProdMacros; Image GetImage( ::com::sun::star::uno::Reference< ::com::sun::star::script::browse::XBrowseNode > node, ::com::sun::star::uno::Reference< ::com::sun::star::uno::XComponentContext > xCtx, bool bIsRootNode, bool bHighContrast ); ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface > getDocumentModel( ::com::sun::star::uno::Reference< ::com::sun::star::uno::XComponentContext >& xCtx, ::rtl::OUString& docName ); private: void fillScriptList( const ::com::sun::star::uno::Reference< ::com::sun::star::script::browse::XBrowseNode >& _rxRootNode, SvLBoxEntry* _pParentEntry, bool _bCheapChildsOnDemand ); protected: virtual void RequestingChilds( SvLBoxEntry *pEntry); virtual BOOL Expand( SvLBoxEntry* pParent ); using SvListView::Expand; public: SvxConfigGroupListBox_Impl ( Window* pParent, const ResId&, bool _bShowSlots, const ::com::sun::star::uno::Reference < ::com::sun::star::frame::XFrame >& xFrame ); ~SvxConfigGroupListBox_Impl(); void Init(); void Open( SvLBoxEntry*, BOOL ); void ClearAll(); void GroupSelected(); void SetFunctionListBox( SvxConfigFunctionListBox_Impl *pBox ) { pFunctionListBox = pBox; } void SetImageProvider( ImageProvider* provider ) { m_pImageProvider = provider; } }; class SVX_DLLPUBLIC SvxScriptSelectorDialog : public ModelessDialog { FixedText aDialogDescription; FixedText aGroupText; SvxConfigGroupListBox_Impl aCategories; FixedText aFunctionText; SvxConfigFunctionListBox_Impl aCommands; OKButton aOKButton; CancelButton aCancelButton; HelpButton aHelpButton; FixedLine aDescription; FixedText aDescriptionText; BOOL m_bShowSlots; Link m_aAddHdl; DECL_LINK( ClickHdl, Button * ); DECL_LINK( SelectHdl, Control* ); void UpdateUI(); void ResizeControls(); public: SvxScriptSelectorDialog ( Window* pParent = NULL, BOOL bShowSlots = FALSE, const ::com::sun::star::uno::Reference < ::com::sun::star::frame::XFrame >& xFrame = 0 ); ~SvxScriptSelectorDialog ( ); void SetAddHdl( const Link& rLink ) { m_aAddHdl = rLink; } const Link& GetAddHdl() const { return m_aAddHdl; } void SetImageProvider( ImageProvider* provider ) { aCategories.SetImageProvider( provider ); } USHORT GetSelectedId(); String GetScriptURL() const; String GetSelectedDisplayName(); String GetSelectedHelpText(); void SetRunLabel(); void SetDialogDescription(const String& rDescription); }; #endif <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: selector.hxx,v $ * * $Revision: 1.11 $ * * last change: $Author: rt $ $Date: 2005-09-08 22:01:43 $ * * 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 _SVXSELECTOR_HXX #define _SVXSELECTOR_HXX #ifndef _SV_LSTBOX_HXX //autogen #include <vcl/lstbox.hxx> #endif #ifndef _SV_FIXED_HXX //autogen #include <vcl/fixed.hxx> #endif #ifndef _SV_GROUP_HXX //autogen #include <vcl/group.hxx> #endif #ifndef _SV_MENUBTN_HXX //autogen #include <vcl/menubtn.hxx> #endif #ifndef _SVTREEBOX_HXX //autogen #include <svtools/svtreebx.hxx> #endif #include <com/sun/star/uno/XComponentContext.hpp> #include <com/sun/star/frame/XFrame.hpp> #include <com/sun/star/container/XNameAccess.hpp> #include <com/sun/star/script/browse/XBrowseNode.hpp> #ifndef INCLUDED_SVXDLLAPI_H #include "svx/svxdllapi.h" #endif #define _SVSTDARR_USHORTS #define _SVSTDARR_STRINGSDTOR #include <svtools/svstdarr.hxx> // SvUShorts #include <sfx2/minarray.hxx> #define SVX_CFGGROUP_FUNCTION 1 #define SVX_CFGFUNCTION_SLOT 2 #define SVX_CFGGROUP_SCRIPTCONTAINER 3 #define SVX_CFGFUNCTION_SCRIPT 4 struct SvxGroupInfo_Impl { USHORT nKind; USHORT nOrd; void* pObject; BOOL bWasOpened; SvxGroupInfo_Impl( USHORT n, USHORT nr, void* pObj = 0 ) : nKind( n ), nOrd( nr ), pObject( pObj ), bWasOpened(FALSE) {} }; typedef SvxGroupInfo_Impl* SvxGroupInfoPtr; SV_DECL_PTRARR_DEL(SvxGroupInfoArr_Impl, SvxGroupInfoPtr, 5, 5); DECL_2BYTEARRAY(USHORTArr, USHORT, 10, 10); class ImageProvider { public: virtual Image GetImage( const rtl::OUString& rCommandURL ) = 0; }; class SvxConfigFunctionListBox_Impl : public SvTreeListBox { friend class SvxConfigGroupListBox_Impl; Timer aTimer; SvLBoxEntry* pCurEntry; SvxGroupInfoArr_Impl aArr; SvLBoxEntry* m_pDraggingEntry; DECL_LINK( TimerHdl, Timer* ); virtual void MouseMove( const MouseEvent& rMEvt ); public: SvxConfigFunctionListBox_Impl( Window*, const ResId& ); ~SvxConfigFunctionListBox_Impl(); void ClearAll(); SvLBoxEntry* GetEntry_Impl( USHORT nId ); SvLBoxEntry* GetEntry_Impl( const String& ); USHORT GetId( SvLBoxEntry *pEntry ); String GetHelpText( SvLBoxEntry *pEntry ); USHORT GetCurId() { return GetId( FirstSelected() ); } SvLBoxEntry* GetLastSelectedEntry(); void FunctionSelected(); // drag n drop methods virtual sal_Int8 AcceptDrop( const AcceptDropEvent& rEvt ); virtual DragDropMode NotifyStartDrag( TransferDataContainer&, SvLBoxEntry* ); virtual void DragFinished( sal_Int8 ); }; class SvxConfigGroupListBox_Impl : public SvTreeListBox { SvxGroupInfoArr_Impl aArr; ULONG nMode; SvxConfigFunctionListBox_Impl* pFunctionListBox; ImageProvider* m_pImageProvider; ::com::sun::star::uno::Reference < ::com::sun::star::frame::XFrame > m_xFrame; ::com::sun::star::uno::Reference < ::com::sun::star::container::XNameAccess > m_xModuleCommands; // show Scripting Framework scripts? BOOL bShowSF; Image m_hdImage; Image m_hdImage_hc; Image m_libImage; Image m_libImage_hc; Image m_macImage; Image m_macImage_hc; Image m_docImage; Image m_docImage_hc; ::rtl::OUString m_sMyMacros; ::rtl::OUString m_sProdMacros; Image GetImage( ::com::sun::star::uno::Reference< ::com::sun::star::script::browse::XBrowseNode > node, ::com::sun::star::uno::Reference< ::com::sun::star::uno::XComponentContext > xCtx, bool bIsRootNode, bool bHighContrast ); ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface > getDocumentModel( ::com::sun::star::uno::Reference< ::com::sun::star::uno::XComponentContext >& xCtx, ::rtl::OUString& docName ); protected: virtual void RequestingChilds( SvLBoxEntry *pEntry); virtual BOOL Expand( SvLBoxEntry* pParent ); public: SvxConfigGroupListBox_Impl ( Window* pParent, const ResId&, ULONG nConfigMode = 0, const ::com::sun::star::uno::Reference < ::com::sun::star::frame::XFrame >& xFrame = 0 ); ~SvxConfigGroupListBox_Impl(); void Init( SvStringsDtor *pArr = 0 ); void Open( SvLBoxEntry*, BOOL ); void ClearAll(); void GroupSelected(); void SetFunctionListBox( SvxConfigFunctionListBox_Impl *pBox ) { pFunctionListBox = pBox; } void SetImageProvider( ImageProvider* provider ) { m_pImageProvider = provider; } }; class SVX_DLLPUBLIC SvxScriptSelectorDialog : public ModelessDialog { FixedText aDialogDescription; FixedText aGroupText; SvxConfigGroupListBox_Impl aCategories; FixedText aFunctionText; SvxConfigFunctionListBox_Impl aCommands; OKButton aOKButton; CancelButton aCancelButton; HelpButton aHelpButton; FixedLine aDescription; FixedText aDescriptionText; BOOL m_bShowSlots; Link m_aAddHdl; DECL_LINK( ClickHdl, Button * ); DECL_LINK( SelectHdl, Control* ); void UpdateUI(); void ResizeControls(); public: SvxScriptSelectorDialog ( Window* pParent = NULL, BOOL bShowSlots = FALSE, const ::com::sun::star::uno::Reference < ::com::sun::star::frame::XFrame >& xFrame = 0 ); ~SvxScriptSelectorDialog ( ); static void GetDocTitle( const ::com::sun::star::uno::Reference< ::com::sun::star::frame::XModel>& xModel, ::rtl::OUString& rTitle ); void SetAddHdl( const Link& rLink ) { m_aAddHdl = rLink; } const Link& GetAddHdl() const { return m_aAddHdl; } void SetImageProvider( ImageProvider* provider ) { aCategories.SetImageProvider( provider ); } USHORT GetSelectedId(); String GetScriptURL(); String GetSelectedDisplayName(); String GetSelectedHelpText(); void SetRunLabel(); void SetDialogDescription(const String& rDescription); }; #endif <commit_msg>INTEGRATION: CWS sb59 (1.11.488); FILE MERGED 2006/08/18 12:02:49 sb 1.11.488.2: #i67487# Made code warning-free (wntmsci10). 2006/08/03 13:51:35 cl 1.11.488.1: removed compiler warnings<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: selector.hxx,v $ * * $Revision: 1.12 $ * * last change: $Author: obo $ $Date: 2006-10-12 12:26: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 _SVXSELECTOR_HXX #define _SVXSELECTOR_HXX #ifndef _SV_LSTBOX_HXX //autogen #include <vcl/lstbox.hxx> #endif #ifndef _SV_FIXED_HXX //autogen #include <vcl/fixed.hxx> #endif #ifndef _SV_GROUP_HXX //autogen #include <vcl/group.hxx> #endif #ifndef _SV_MENUBTN_HXX //autogen #include <vcl/menubtn.hxx> #endif #ifndef _SVTREEBOX_HXX //autogen #include <svtools/svtreebx.hxx> #endif #include <com/sun/star/uno/XComponentContext.hpp> #include <com/sun/star/frame/XFrame.hpp> #include <com/sun/star/container/XNameAccess.hpp> #include <com/sun/star/script/browse/XBrowseNode.hpp> #ifndef INCLUDED_SVXDLLAPI_H #include "svx/svxdllapi.h" #endif #define _SVSTDARR_USHORTS #define _SVSTDARR_STRINGSDTOR #include <svtools/svstdarr.hxx> // SvUShorts #include <sfx2/minarray.hxx> #define SVX_CFGGROUP_FUNCTION 1 #define SVX_CFGFUNCTION_SLOT 2 #define SVX_CFGGROUP_SCRIPTCONTAINER 3 #define SVX_CFGFUNCTION_SCRIPT 4 struct SvxGroupInfo_Impl { USHORT nKind; USHORT nOrd; void* pObject; BOOL bWasOpened; SvxGroupInfo_Impl( USHORT n, USHORT nr, void* pObj = 0 ) : nKind( n ), nOrd( nr ), pObject( pObj ), bWasOpened(FALSE) {} }; typedef SvxGroupInfo_Impl* SvxGroupInfoPtr; SV_DECL_PTRARR_DEL(SvxGroupInfoArr_Impl, SvxGroupInfoPtr, 5, 5) DECL_2BYTEARRAY(USHORTArr, USHORT, 10, 10) class ImageProvider { public: virtual ~ImageProvider() {} virtual Image GetImage( const rtl::OUString& rCommandURL ) = 0; }; class SvxConfigFunctionListBox_Impl : public SvTreeListBox { friend class SvxConfigGroupListBox_Impl; Timer aTimer; SvLBoxEntry* pCurEntry; SvxGroupInfoArr_Impl aArr; SvLBoxEntry* m_pDraggingEntry; DECL_LINK( TimerHdl, Timer* ); virtual void MouseMove( const MouseEvent& rMEvt ); public: SvxConfigFunctionListBox_Impl( Window*, const ResId& ); ~SvxConfigFunctionListBox_Impl(); void ClearAll(); SvLBoxEntry* GetEntry_Impl( USHORT nId ); SvLBoxEntry* GetEntry_Impl( const String& ); USHORT GetId( SvLBoxEntry *pEntry ); String GetHelpText( SvLBoxEntry *pEntry ); using Window::GetHelpText; USHORT GetCurId() { return GetId( FirstSelected() ); } SvLBoxEntry* GetLastSelectedEntry(); void FunctionSelected(); // drag n drop methods virtual sal_Int8 AcceptDrop( const AcceptDropEvent& rEvt ); virtual DragDropMode NotifyStartDrag( TransferDataContainer&, SvLBoxEntry* ); virtual void DragFinished( sal_Int8 ); }; class SvxConfigGroupListBox_Impl : public SvTreeListBox { SvxGroupInfoArr_Impl aArr; ULONG nMode; SvxConfigFunctionListBox_Impl* pFunctionListBox; ImageProvider* m_pImageProvider; ::com::sun::star::uno::Reference < ::com::sun::star::frame::XFrame > m_xFrame; ::com::sun::star::uno::Reference < ::com::sun::star::container::XNameAccess > m_xModuleCommands; // show Scripting Framework scripts? BOOL bShowSF; Image m_hdImage; Image m_hdImage_hc; Image m_libImage; Image m_libImage_hc; Image m_macImage; Image m_macImage_hc; Image m_docImage; Image m_docImage_hc; ::rtl::OUString m_sMyMacros; ::rtl::OUString m_sProdMacros; Image GetImage( ::com::sun::star::uno::Reference< ::com::sun::star::script::browse::XBrowseNode > node, ::com::sun::star::uno::Reference< ::com::sun::star::uno::XComponentContext > xCtx, bool bIsRootNode, bool bHighContrast ); ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface > getDocumentModel( ::com::sun::star::uno::Reference< ::com::sun::star::uno::XComponentContext >& xCtx, ::rtl::OUString& docName ); protected: virtual void RequestingChilds( SvLBoxEntry *pEntry); virtual BOOL Expand( SvLBoxEntry* pParent ); using SvListView::Expand; public: SvxConfigGroupListBox_Impl ( Window* pParent, const ResId&, ULONG nConfigMode = 0, const ::com::sun::star::uno::Reference < ::com::sun::star::frame::XFrame >& xFrame = 0 ); ~SvxConfigGroupListBox_Impl(); void Init( SvStringsDtor *pArr = 0 ); void Open( SvLBoxEntry*, BOOL ); void ClearAll(); void GroupSelected(); void SetFunctionListBox( SvxConfigFunctionListBox_Impl *pBox ) { pFunctionListBox = pBox; } void SetImageProvider( ImageProvider* provider ) { m_pImageProvider = provider; } }; class SVX_DLLPUBLIC SvxScriptSelectorDialog : public ModelessDialog { FixedText aDialogDescription; FixedText aGroupText; SvxConfigGroupListBox_Impl aCategories; FixedText aFunctionText; SvxConfigFunctionListBox_Impl aCommands; OKButton aOKButton; CancelButton aCancelButton; HelpButton aHelpButton; FixedLine aDescription; FixedText aDescriptionText; BOOL m_bShowSlots; Link m_aAddHdl; DECL_LINK( ClickHdl, Button * ); DECL_LINK( SelectHdl, Control* ); void UpdateUI(); void ResizeControls(); public: SvxScriptSelectorDialog ( Window* pParent = NULL, BOOL bShowSlots = FALSE, const ::com::sun::star::uno::Reference < ::com::sun::star::frame::XFrame >& xFrame = 0 ); ~SvxScriptSelectorDialog ( ); static void GetDocTitle( const ::com::sun::star::uno::Reference< ::com::sun::star::frame::XModel>& xModel, ::rtl::OUString& rTitle ); void SetAddHdl( const Link& rLink ) { m_aAddHdl = rLink; } const Link& GetAddHdl() const { return m_aAddHdl; } void SetImageProvider( ImageProvider* provider ) { aCategories.SetImageProvider( provider ); } USHORT GetSelectedId(); String GetScriptURL(); String GetSelectedDisplayName(); String GetSelectedHelpText(); void SetRunLabel(); void SetDialogDescription(const String& rDescription); }; #endif <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: fntctl.cxx,v $ * * $Revision: 1.7 $ * * last change: $Author: hr $ $Date: 2007-06-27 18:32:27 $ * * 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_svx.hxx" #include <string> // HACK: prevent conflict between STLPORT and Workshop headern #ifndef _STDMENU_HXX //autogen #include <svtools/stdmenu.hxx> #endif #ifndef _SFXAPP_HXX //autogen #include <sfx2/app.hxx> #endif #ifndef _SFX_OBJSH_HXX //autogen #include <sfx2/objsh.hxx> #endif #ifndef _SFXDISPATCH_HXX //autogen #include <sfx2/dispatch.hxx> #endif #include <svx/fntctl.hxx> // #include <svx/svxids.hrc> #ifndef _SVX_FLSTITEM_HXX //autogen #include "flstitem.hxx" #endif #ifndef _SVX_FONTITEM_HXX //autogen #include "fontitem.hxx" #endif // STATIC DATA ----------------------------------------------------------- SFX_IMPL_MENU_CONTROL(SvxFontMenuControl, SvxFontItem); //-------------------------------------------------------------------- /* [Beschreibung] Ctor; setzt den Select-Handler am Men"u und tr"agt das Men"u in seinen Parent ein. */ SvxFontMenuControl::SvxFontMenuControl ( USHORT _nId, Menu& rMenu, SfxBindings& rBindings ) : pMenu ( new FontNameMenu ), rParent ( rMenu ) { rMenu.SetPopupMenu( _nId, pMenu ); pMenu->SetSelectHdl( LINK( this, SvxFontMenuControl, MenuSelect ) ); StartListening( rBindings ); FillMenu(); } //-------------------------------------------------------------------- /* [Beschreibung] F"ullt das Men"u mit den aktuellen Fonts aus der Fontlist der DocumentShell. */ void SvxFontMenuControl::FillMenu() { SfxObjectShell *pDoc = SfxObjectShell::Current(); if ( pDoc ) { const SvxFontListItem* pFonts = (const SvxFontListItem*)pDoc->GetItem( SID_ATTR_CHAR_FONTLIST ); const FontList* pList = pFonts ? pFonts->GetFontList(): 0; DBG_ASSERT( pList, "Kein Fonts gefunden" ); pMenu->Fill( pList ); } } //-------------------------------------------------------------------- /* [Beschreibung] Statusbenachrichtigung; f"ullt ggf. das Men"u mit den aktuellen Fonts aus der Fontlist der DocumentShell. Ist die Funktionalit"at disabled, wird der entsprechende Men"ueintrag im Parentmen"u disabled, andernfalls wird er enabled. Der aktuelle Font wird mit einer Checkmark versehen. */ void SvxFontMenuControl::StateChanged( USHORT, SfxItemState eState, const SfxPoolItem* pState ) { rParent.EnableItem( GetId(), SFX_ITEM_DISABLED != eState ); if ( SFX_ITEM_AVAILABLE == eState ) { if ( !pMenu->GetItemCount() ) FillMenu(); const SvxFontItem* pFontItem = PTR_CAST( SvxFontItem, pState ); String aFont; if ( pFontItem ) aFont = pFontItem->GetFamilyName(); pMenu->SetCurName( aFont ); } } //-------------------------------------------------------------------- /* [Beschreibung] Statusbenachrichtigung "uber Bindings; bei DOCCHANGED wird das Men"u mit den aktuellen Fonts aus der Fontlist der DocumentShell gef"ullt. */ void SvxFontMenuControl::SFX_NOTIFY( SfxBroadcaster&, const TypeId& rBCType, const SfxHint& rHint, const TypeId& rHintType ) { if ( rHint.Type() != TYPE(SfxSimpleHint) && ( (SfxSimpleHint&)rHint ).GetId() == SFX_HINT_DOCCHANGED ) FillMenu(); } //-------------------------------------------------------------------- /* [Beschreibung] Select-Handler des Men"us; der Name des selektierten Fonts wird in einem SvxFontItem verschickt. Das F"ullen mit den weiteren Fontinformationen mu\s durch die Applikation geschehen. */ IMPL_LINK_INLINE_START( SvxFontMenuControl, MenuSelect, FontNameMenu *, pMen ) { SvxFontItem aItem( GetId() ); aItem.GetFamilyName() = pMen->GetCurName(); GetBindings().GetDispatcher()->Execute( GetId(), SFX_CALLMODE_RECORD, &aItem, 0L ); return 0; } IMPL_LINK_INLINE_END( SvxFontMenuControl, MenuSelect, FontNameMenu *, pMen ) //-------------------------------------------------------------------- /* [Beschreibung] Dtor; gibt das Men"u frei. */ SvxFontMenuControl::~SvxFontMenuControl() { delete pMenu; } //-------------------------------------------------------------------- /* [Beschreibung] Gibt das Men"u zur"uck */ PopupMenu* SvxFontMenuControl::GetPopup() const { return pMenu; } <commit_msg>INTEGRATION: CWS changefileheader (1.7.368); FILE MERGED 2008/04/01 15:51:19 thb 1.7.368.3: #i85898# Stripping all external header guards 2008/04/01 12:49:17 thb 1.7.368.2: #i85898# Stripping all external header guards 2008/03/31 14:22:50 rt 1.7.368.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: fntctl.cxx,v $ * $Revision: 1.8 $ * * This file is part of OpenOffice.org. * * OpenOffice.org is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License version 3 * only, as published by the Free Software Foundation. * * OpenOffice.org is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License version 3 for more details * (a copy is included in the LICENSE file that accompanied this code). * * You should have received a copy of the GNU Lesser General Public License * version 3 along with OpenOffice.org. If not, see * <http://www.openoffice.org/license.html> * for a copy of the LGPLv3 License. * ************************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_svx.hxx" #include <string> // HACK: prevent conflict between STLPORT and Workshop headern #include <svtools/stdmenu.hxx> #include <sfx2/app.hxx> #include <sfx2/objsh.hxx> #include <sfx2/dispatch.hxx> #include <svx/fntctl.hxx> // #include <svx/svxids.hrc> #include "flstitem.hxx" #include "fontitem.hxx" // STATIC DATA ----------------------------------------------------------- SFX_IMPL_MENU_CONTROL(SvxFontMenuControl, SvxFontItem); //-------------------------------------------------------------------- /* [Beschreibung] Ctor; setzt den Select-Handler am Men"u und tr"agt das Men"u in seinen Parent ein. */ SvxFontMenuControl::SvxFontMenuControl ( USHORT _nId, Menu& rMenu, SfxBindings& rBindings ) : pMenu ( new FontNameMenu ), rParent ( rMenu ) { rMenu.SetPopupMenu( _nId, pMenu ); pMenu->SetSelectHdl( LINK( this, SvxFontMenuControl, MenuSelect ) ); StartListening( rBindings ); FillMenu(); } //-------------------------------------------------------------------- /* [Beschreibung] F"ullt das Men"u mit den aktuellen Fonts aus der Fontlist der DocumentShell. */ void SvxFontMenuControl::FillMenu() { SfxObjectShell *pDoc = SfxObjectShell::Current(); if ( pDoc ) { const SvxFontListItem* pFonts = (const SvxFontListItem*)pDoc->GetItem( SID_ATTR_CHAR_FONTLIST ); const FontList* pList = pFonts ? pFonts->GetFontList(): 0; DBG_ASSERT( pList, "Kein Fonts gefunden" ); pMenu->Fill( pList ); } } //-------------------------------------------------------------------- /* [Beschreibung] Statusbenachrichtigung; f"ullt ggf. das Men"u mit den aktuellen Fonts aus der Fontlist der DocumentShell. Ist die Funktionalit"at disabled, wird der entsprechende Men"ueintrag im Parentmen"u disabled, andernfalls wird er enabled. Der aktuelle Font wird mit einer Checkmark versehen. */ void SvxFontMenuControl::StateChanged( USHORT, SfxItemState eState, const SfxPoolItem* pState ) { rParent.EnableItem( GetId(), SFX_ITEM_DISABLED != eState ); if ( SFX_ITEM_AVAILABLE == eState ) { if ( !pMenu->GetItemCount() ) FillMenu(); const SvxFontItem* pFontItem = PTR_CAST( SvxFontItem, pState ); String aFont; if ( pFontItem ) aFont = pFontItem->GetFamilyName(); pMenu->SetCurName( aFont ); } } //-------------------------------------------------------------------- /* [Beschreibung] Statusbenachrichtigung "uber Bindings; bei DOCCHANGED wird das Men"u mit den aktuellen Fonts aus der Fontlist der DocumentShell gef"ullt. */ void SvxFontMenuControl::SFX_NOTIFY( SfxBroadcaster&, const TypeId& rBCType, const SfxHint& rHint, const TypeId& rHintType ) { if ( rHint.Type() != TYPE(SfxSimpleHint) && ( (SfxSimpleHint&)rHint ).GetId() == SFX_HINT_DOCCHANGED ) FillMenu(); } //-------------------------------------------------------------------- /* [Beschreibung] Select-Handler des Men"us; der Name des selektierten Fonts wird in einem SvxFontItem verschickt. Das F"ullen mit den weiteren Fontinformationen mu\s durch die Applikation geschehen. */ IMPL_LINK_INLINE_START( SvxFontMenuControl, MenuSelect, FontNameMenu *, pMen ) { SvxFontItem aItem( GetId() ); aItem.GetFamilyName() = pMen->GetCurName(); GetBindings().GetDispatcher()->Execute( GetId(), SFX_CALLMODE_RECORD, &aItem, 0L ); return 0; } IMPL_LINK_INLINE_END( SvxFontMenuControl, MenuSelect, FontNameMenu *, pMen ) //-------------------------------------------------------------------- /* [Beschreibung] Dtor; gibt das Men"u frei. */ SvxFontMenuControl::~SvxFontMenuControl() { delete pMenu; } //-------------------------------------------------------------------- /* [Beschreibung] Gibt das Men"u zur"uck */ PopupMenu* SvxFontMenuControl::GetPopup() const { return pMenu; } <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: svddrgm1.hxx,v $ * * $Revision: 1.10 $ * * last change: $Author: obo $ $Date: 2008-02-26 07:33:31 $ * * 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 _SVDDRGM1_HXX #define _SVDDRGM1_HXX #ifndef _XPOLY_HXX #include <svx/xpoly.hxx> #endif #ifndef _SVDHDL_HXX #include <svx/svdhdl.hxx> #endif #ifndef _SVDDRGV_HXX #include <svx/svddrgv.hxx> #endif #ifndef _SVDDRGMT_HXX #include <svx/svddrgmt.hxx> #endif //************************************************************ // Vorausdeklarationen //************************************************************ class SdrDragView; class SdrDragStat; //************************************************************ // SdrDragMovHdl //************************************************************ class SdrDragMovHdl : public SdrDragMethod { FASTBOOL bMirrObjShown; public: TYPEINFO(); SdrDragMovHdl(SdrDragView& rNewView): SdrDragMethod(rNewView), bMirrObjShown(FALSE) {} virtual void TakeComment(String& rStr) const; virtual FASTBOOL Beg(); virtual void Mov(const Point& rPnt); virtual FASTBOOL End(FASTBOOL bCopy); virtual void Brk(); virtual Pointer GetPointer() const; virtual void Show(); virtual void Hide(); }; //************************************************************ // SdrDragRotate //************************************************************ class SdrDragRotate : public SdrDragMethod { protected: double nSin; double nCos; long nWink0; long nWink; FASTBOOL bRight; public: TYPEINFO(); SdrDragRotate(SdrDragView& rNewView): SdrDragMethod(rNewView),nSin(0.0),nCos(1.0),nWink0(0),nWink(0),bRight(FALSE) {} virtual void TakeComment(String& rStr) const; virtual FASTBOOL Beg(); virtual void MovPoint(Point& rPnt); virtual void Mov(const Point& rPnt); virtual FASTBOOL End(FASTBOOL bCopy); virtual Pointer GetPointer() const; }; //************************************************************ // SdrDragShear //************************************************************ class SdrDragShear : public SdrDragMethod { Fraction aFact; long nWink0; long nWink; double nTan; FASTBOOL bVertical; // Vertikales verzerren FASTBOOL bResize; // Shear mit Resize FASTBOOL bUpSideDown; // Beim Shear/Slant gespiegelt FASTBOOL bSlant; public: TYPEINFO(); SdrDragShear(SdrDragView& rNewView,FASTBOOL bSlant1): SdrDragMethod(rNewView), aFact(1,1),nWink0(0),nWink(0), nTan(0.0), bVertical(FALSE),bResize(FALSE),bUpSideDown(FALSE), bSlant(bSlant1) {} virtual void TakeComment(String& rStr) const; virtual FASTBOOL Beg(); virtual void MovPoint(Point& rPnt); virtual void Mov(const Point& rPnt); virtual FASTBOOL End(FASTBOOL bCopy); virtual Pointer GetPointer() const; }; //************************************************************ // SdrDragMirror //************************************************************ class SdrDragMirror : public SdrDragMethod { Point aDif; long nWink; bool bMirrored; bool bSide0; private: FASTBOOL ImpCheckSide(const Point& rPnt) const; public: TYPEINFO(); SdrDragMirror(SdrDragView& rNewView): SdrDragMethod(rNewView),nWink(0),bMirrored(FALSE),bSide0(FALSE) { } virtual void TakeComment(String& rStr) const; virtual FASTBOOL Beg(); virtual void MovPoint(Point& rPnt); virtual void Mov(const Point& rPnt); virtual FASTBOOL End(FASTBOOL bCopy); virtual Pointer GetPointer() const; }; //************************************************************ // SdrDragGradient //************************************************************ class SdrDragGradient : public SdrDragMethod { // Handles to work on SdrHdlGradient* pIAOHandle; // is this for gradient (or for transparence) ? unsigned bIsGradient : 1; public: TYPEINFO(); SdrDragGradient(SdrDragView& rNewView, BOOL bGrad = TRUE); BOOL IsGradient() const { return bIsGradient; } virtual void TakeComment(String& rStr) const; virtual FASTBOOL Beg(); virtual void Mov(const Point& rPnt); virtual FASTBOOL End(FASTBOOL bCopy); virtual Pointer GetPointer() const; virtual void Brk(); }; //************************************************************ // SdrDragCrook //************************************************************ class SdrDragCrook : public SdrDragMethod { Rectangle aMarkRect; Point aMarkCenter; Point aCenter; Point aStart; Fraction aFact; Point aRad; bool bContortionAllowed; bool bNoContortionAllowed; bool bContortion; bool bResizeAllowed; bool bResize; bool bRotateAllowed; bool bRotate; bool bVertical; bool bValid; bool bLft; bool bRgt; bool bUpr; bool bLwr; bool bAtCenter; long nWink; long nMarkSize; SdrCrookMode eMode; public: TYPEINFO(); SdrDragCrook(SdrDragView& rNewView): SdrDragMethod(rNewView),aFact(1,1), bContortionAllowed(FALSE),bNoContortionAllowed(FALSE),bContortion(FALSE), bResizeAllowed(FALSE),bResize(FALSE),bRotateAllowed(FALSE),bRotate(FALSE), bVertical(FALSE),bValid(FALSE),bLft(FALSE),bRgt(FALSE),bUpr(FALSE),bLwr(FALSE),bAtCenter(FALSE), nWink(0),nMarkSize(0),eMode(SDRCROOK_ROTATE) {} virtual void TakeComment(String& rStr) const; virtual FASTBOOL Beg(); virtual void MovAllPoints(); void MovCrookPoint(Point& rPnt, Point* pC1, Point* pC2); virtual void Mov(const Point& rPnt); virtual FASTBOOL End(FASTBOOL bCopy); virtual Pointer GetPointer() const; }; //************************************************************ // SdrDragDistort //************************************************************ class SdrDragDistort : public SdrDragMethod { Rectangle aMarkRect; XPolygon aDistortedRect; USHORT nPolyPt; bool bContortionAllowed; bool bNoContortionAllowed; bool bContortion; public: TYPEINFO(); SdrDragDistort(SdrDragView& rNewView): SdrDragMethod(rNewView),nPolyPt(0), bContortionAllowed(FALSE),bNoContortionAllowed(FALSE),bContortion(FALSE) {} virtual void TakeComment(String& rStr) const; virtual FASTBOOL Beg(); virtual void MovAllPoints(); virtual void Mov(const Point& rPnt); virtual FASTBOOL End(FASTBOOL bCopy); virtual Pointer GetPointer() const; }; //************************************************************ // SdrDragCrop //************************************************************ class SdrDragCrop : public SdrDragResize { public: TYPEINFO(); SdrDragCrop(SdrDragView& rNewView); virtual void TakeComment(String& rStr) const; virtual FASTBOOL End(FASTBOOL bCopy); virtual Pointer GetPointer() const; }; //////////////////////////////////////////////////////////////////////////////////////////////////// #endif //_SVDDRGM1_HXX <commit_msg>INTEGRATION: CWS changefileheader (1.10.72); FILE MERGED 2008/04/01 12:49:50 thb 1.10.72.2: #i85898# Stripping all external header guards 2008/03/31 14:23:28 rt 1.10.72.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: svddrgm1.hxx,v $ * $Revision: 1.11 $ * * 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 _SVDDRGM1_HXX #define _SVDDRGM1_HXX #include <svx/xpoly.hxx> #include <svx/svdhdl.hxx> #include <svx/svddrgv.hxx> #include <svx/svddrgmt.hxx> //************************************************************ // Vorausdeklarationen //************************************************************ class SdrDragView; class SdrDragStat; //************************************************************ // SdrDragMovHdl //************************************************************ class SdrDragMovHdl : public SdrDragMethod { FASTBOOL bMirrObjShown; public: TYPEINFO(); SdrDragMovHdl(SdrDragView& rNewView): SdrDragMethod(rNewView), bMirrObjShown(FALSE) {} virtual void TakeComment(String& rStr) const; virtual FASTBOOL Beg(); virtual void Mov(const Point& rPnt); virtual FASTBOOL End(FASTBOOL bCopy); virtual void Brk(); virtual Pointer GetPointer() const; virtual void Show(); virtual void Hide(); }; //************************************************************ // SdrDragRotate //************************************************************ class SdrDragRotate : public SdrDragMethod { protected: double nSin; double nCos; long nWink0; long nWink; FASTBOOL bRight; public: TYPEINFO(); SdrDragRotate(SdrDragView& rNewView): SdrDragMethod(rNewView),nSin(0.0),nCos(1.0),nWink0(0),nWink(0),bRight(FALSE) {} virtual void TakeComment(String& rStr) const; virtual FASTBOOL Beg(); virtual void MovPoint(Point& rPnt); virtual void Mov(const Point& rPnt); virtual FASTBOOL End(FASTBOOL bCopy); virtual Pointer GetPointer() const; }; //************************************************************ // SdrDragShear //************************************************************ class SdrDragShear : public SdrDragMethod { Fraction aFact; long nWink0; long nWink; double nTan; FASTBOOL bVertical; // Vertikales verzerren FASTBOOL bResize; // Shear mit Resize FASTBOOL bUpSideDown; // Beim Shear/Slant gespiegelt FASTBOOL bSlant; public: TYPEINFO(); SdrDragShear(SdrDragView& rNewView,FASTBOOL bSlant1): SdrDragMethod(rNewView), aFact(1,1),nWink0(0),nWink(0), nTan(0.0), bVertical(FALSE),bResize(FALSE),bUpSideDown(FALSE), bSlant(bSlant1) {} virtual void TakeComment(String& rStr) const; virtual FASTBOOL Beg(); virtual void MovPoint(Point& rPnt); virtual void Mov(const Point& rPnt); virtual FASTBOOL End(FASTBOOL bCopy); virtual Pointer GetPointer() const; }; //************************************************************ // SdrDragMirror //************************************************************ class SdrDragMirror : public SdrDragMethod { Point aDif; long nWink; bool bMirrored; bool bSide0; private: FASTBOOL ImpCheckSide(const Point& rPnt) const; public: TYPEINFO(); SdrDragMirror(SdrDragView& rNewView): SdrDragMethod(rNewView),nWink(0),bMirrored(FALSE),bSide0(FALSE) { } virtual void TakeComment(String& rStr) const; virtual FASTBOOL Beg(); virtual void MovPoint(Point& rPnt); virtual void Mov(const Point& rPnt); virtual FASTBOOL End(FASTBOOL bCopy); virtual Pointer GetPointer() const; }; //************************************************************ // SdrDragGradient //************************************************************ class SdrDragGradient : public SdrDragMethod { // Handles to work on SdrHdlGradient* pIAOHandle; // is this for gradient (or for transparence) ? unsigned bIsGradient : 1; public: TYPEINFO(); SdrDragGradient(SdrDragView& rNewView, BOOL bGrad = TRUE); BOOL IsGradient() const { return bIsGradient; } virtual void TakeComment(String& rStr) const; virtual FASTBOOL Beg(); virtual void Mov(const Point& rPnt); virtual FASTBOOL End(FASTBOOL bCopy); virtual Pointer GetPointer() const; virtual void Brk(); }; //************************************************************ // SdrDragCrook //************************************************************ class SdrDragCrook : public SdrDragMethod { Rectangle aMarkRect; Point aMarkCenter; Point aCenter; Point aStart; Fraction aFact; Point aRad; bool bContortionAllowed; bool bNoContortionAllowed; bool bContortion; bool bResizeAllowed; bool bResize; bool bRotateAllowed; bool bRotate; bool bVertical; bool bValid; bool bLft; bool bRgt; bool bUpr; bool bLwr; bool bAtCenter; long nWink; long nMarkSize; SdrCrookMode eMode; public: TYPEINFO(); SdrDragCrook(SdrDragView& rNewView): SdrDragMethod(rNewView),aFact(1,1), bContortionAllowed(FALSE),bNoContortionAllowed(FALSE),bContortion(FALSE), bResizeAllowed(FALSE),bResize(FALSE),bRotateAllowed(FALSE),bRotate(FALSE), bVertical(FALSE),bValid(FALSE),bLft(FALSE),bRgt(FALSE),bUpr(FALSE),bLwr(FALSE),bAtCenter(FALSE), nWink(0),nMarkSize(0),eMode(SDRCROOK_ROTATE) {} virtual void TakeComment(String& rStr) const; virtual FASTBOOL Beg(); virtual void MovAllPoints(); void MovCrookPoint(Point& rPnt, Point* pC1, Point* pC2); virtual void Mov(const Point& rPnt); virtual FASTBOOL End(FASTBOOL bCopy); virtual Pointer GetPointer() const; }; //************************************************************ // SdrDragDistort //************************************************************ class SdrDragDistort : public SdrDragMethod { Rectangle aMarkRect; XPolygon aDistortedRect; USHORT nPolyPt; bool bContortionAllowed; bool bNoContortionAllowed; bool bContortion; public: TYPEINFO(); SdrDragDistort(SdrDragView& rNewView): SdrDragMethod(rNewView),nPolyPt(0), bContortionAllowed(FALSE),bNoContortionAllowed(FALSE),bContortion(FALSE) {} virtual void TakeComment(String& rStr) const; virtual FASTBOOL Beg(); virtual void MovAllPoints(); virtual void Mov(const Point& rPnt); virtual FASTBOOL End(FASTBOOL bCopy); virtual Pointer GetPointer() const; }; //************************************************************ // SdrDragCrop //************************************************************ class SdrDragCrop : public SdrDragResize { public: TYPEINFO(); SdrDragCrop(SdrDragView& rNewView); virtual void TakeComment(String& rStr) const; virtual FASTBOOL End(FASTBOOL bCopy); virtual Pointer GetPointer() const; }; //////////////////////////////////////////////////////////////////////////////////////////////////// #endif //_SVDDRGM1_HXX <|endoftext|>
<commit_before>/** * @file posix/wait.cpp * @brief POSIX event/timeout handling * * (c) 2013-2014 by Mega Limited, Wellsford, New Zealand * * This file is part of the MEGA SDK - Client Access Engine. * * Applications using the MEGA API must present a valid application key * and comply with the the rules set forth in the Terms of Service. * * The MEGA SDK 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. * * @copyright Simplified (2-clause) BSD License. * * You should have received a copy of the license along with this * program. * * This file is also distributed under the terms of the GNU General * Public License, see http://www.gnu.org/copyleft/gpl.txt for details. */ #include "mega/thread/posixthread.h" #include "mega/logging.h" #include <sys/time.h> #include <errno.h> #ifdef USE_PTHREAD // Apparently this is defined by pthread.h, if that header had been included. // __struct_timespec_defined is defined in time.h for MinGW on Windows #if defined (__MINGW32__) && !defined(_TIMESPEC_DEFINED) && ! __struct_timespec_defined struct timespec { long long tv_sec; /* seconds */ long tv_nsec; /* nanoseconds */ }; # define __struct_timespec_defined 1 #endif namespace mega { PosixThread::PosixThread() { thread = new pthread_t(); } void PosixThread::start(void *(*start_routine)(void*), void *parameter) { pthread_create(thread, NULL, start_routine, parameter); } void PosixThread::join() { pthread_join(*thread, NULL); } bool CppThread::isCurrentThread() { return thread == pthread_self(); } unsigned long long PosixThread::currentThreadId() { #if defined(_WIN32) && !defined(__WINPTHREADS_VERSION) return (unsigned long long) pthread_self().x; #else return (unsigned long long) pthread_self(); #endif } PosixThread::~PosixThread() { delete thread; } //PosixSemaphore PosixSemaphore::PosixSemaphore() { count = 0; pthread_mutexattr_t attr; pthread_mutexattr_init(&attr); pthread_mutex_init(&mtx, &attr); pthread_mutexattr_destroy(&attr); pthread_cond_init(&cv, NULL); } void PosixSemaphore::wait() { pthread_mutex_lock(&mtx); while (!count) { int ret = pthread_cond_wait(&cv,&mtx); if (ret) { pthread_mutex_unlock(&mtx); LOG_fatal << "Error in sem_wait: " << ret; return; } } count--; pthread_mutex_unlock(&mtx); } static inline void timespec_add_msec(struct timespec *tv, int milliseconds) { int seconds = milliseconds / 1000; int milliseconds_left = milliseconds % 1000; tv->tv_sec += seconds; tv->tv_nsec += milliseconds_left * 1000000; if (tv->tv_nsec >= 1000000000) { tv->tv_nsec -= 1000000000; tv->tv_sec++; } } int PosixSemaphore::timedwait(int milliseconds) { struct timespec ts; struct timeval now; int ret = gettimeofday(&now, NULL); //not Y2K38 safe :-D if (ret) { LOG_err << "Error in gettimeofday: " << ret; return -2; } ts.tv_sec = now.tv_sec; ts.tv_nsec = now.tv_usec * 1000; timespec_add_msec (&ts, milliseconds); pthread_mutex_lock(&mtx); while (!count) { int ret = pthread_cond_timedwait(&cv, &mtx, &ts); if (ret == ETIMEDOUT) { pthread_mutex_unlock(&mtx); return -1; } if (ret) { pthread_mutex_unlock(&mtx); LOG_err << "Unexpected error in pthread_cond_timedwait: " << ret; return -2; } } count--; pthread_mutex_unlock(&mtx); return 0; } void PosixSemaphore::release() { pthread_mutex_lock(&mtx); count++; int ret = pthread_cond_signal(&cv); if (ret) { LOG_fatal << "Unexpected error in pthread_cond_signal: " << ret; } pthread_mutex_unlock(&mtx); } PosixSemaphore::~PosixSemaphore() { pthread_mutex_destroy(&mtx); pthread_cond_destroy(&cv); } }// namespace #endif <commit_msg>fix on posix<commit_after>/** * @file posix/wait.cpp * @brief POSIX event/timeout handling * * (c) 2013-2014 by Mega Limited, Wellsford, New Zealand * * This file is part of the MEGA SDK - Client Access Engine. * * Applications using the MEGA API must present a valid application key * and comply with the the rules set forth in the Terms of Service. * * The MEGA SDK 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. * * @copyright Simplified (2-clause) BSD License. * * You should have received a copy of the license along with this * program. * * This file is also distributed under the terms of the GNU General * Public License, see http://www.gnu.org/copyleft/gpl.txt for details. */ #include "mega/thread/posixthread.h" #include "mega/logging.h" #include <sys/time.h> #include <errno.h> #ifdef USE_PTHREAD // Apparently this is defined by pthread.h, if that header had been included. // __struct_timespec_defined is defined in time.h for MinGW on Windows #if defined (__MINGW32__) && !defined(_TIMESPEC_DEFINED) && ! __struct_timespec_defined struct timespec { long long tv_sec; /* seconds */ long tv_nsec; /* nanoseconds */ }; # define __struct_timespec_defined 1 #endif namespace mega { PosixThread::PosixThread() { thread = new pthread_t(); } void PosixThread::start(void *(*start_routine)(void*), void *parameter) { pthread_create(thread, NULL, start_routine, parameter); } void PosixThread::join() { pthread_join(*thread, NULL); } bool PosixThread::isCurrentThread() { return thread == pthread_self(); } unsigned long long PosixThread::currentThreadId() { #if defined(_WIN32) && !defined(__WINPTHREADS_VERSION) return (unsigned long long) pthread_self().x; #else return (unsigned long long) pthread_self(); #endif } PosixThread::~PosixThread() { delete thread; } //PosixSemaphore PosixSemaphore::PosixSemaphore() { count = 0; pthread_mutexattr_t attr; pthread_mutexattr_init(&attr); pthread_mutex_init(&mtx, &attr); pthread_mutexattr_destroy(&attr); pthread_cond_init(&cv, NULL); } void PosixSemaphore::wait() { pthread_mutex_lock(&mtx); while (!count) { int ret = pthread_cond_wait(&cv,&mtx); if (ret) { pthread_mutex_unlock(&mtx); LOG_fatal << "Error in sem_wait: " << ret; return; } } count--; pthread_mutex_unlock(&mtx); } static inline void timespec_add_msec(struct timespec *tv, int milliseconds) { int seconds = milliseconds / 1000; int milliseconds_left = milliseconds % 1000; tv->tv_sec += seconds; tv->tv_nsec += milliseconds_left * 1000000; if (tv->tv_nsec >= 1000000000) { tv->tv_nsec -= 1000000000; tv->tv_sec++; } } int PosixSemaphore::timedwait(int milliseconds) { struct timespec ts; struct timeval now; int ret = gettimeofday(&now, NULL); //not Y2K38 safe :-D if (ret) { LOG_err << "Error in gettimeofday: " << ret; return -2; } ts.tv_sec = now.tv_sec; ts.tv_nsec = now.tv_usec * 1000; timespec_add_msec (&ts, milliseconds); pthread_mutex_lock(&mtx); while (!count) { int ret = pthread_cond_timedwait(&cv, &mtx, &ts); if (ret == ETIMEDOUT) { pthread_mutex_unlock(&mtx); return -1; } if (ret) { pthread_mutex_unlock(&mtx); LOG_err << "Unexpected error in pthread_cond_timedwait: " << ret; return -2; } } count--; pthread_mutex_unlock(&mtx); return 0; } void PosixSemaphore::release() { pthread_mutex_lock(&mtx); count++; int ret = pthread_cond_signal(&cv); if (ret) { LOG_fatal << "Unexpected error in pthread_cond_signal: " << ret; } pthread_mutex_unlock(&mtx); } PosixSemaphore::~PosixSemaphore() { pthread_mutex_destroy(&mtx); pthread_cond_destroy(&cv); } }// namespace #endif <|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 <svx/svdotext.hxx> #include <svx/svdmodel.hxx> // for GetMaxObjSize #include <svx/svdoutl.hxx> #include <editeng/editdata.hxx> #include <editeng/outliner.hxx> #include <editeng/editstat.hxx> #include <svl/itemset.hxx> #include <editeng/eeitem.hxx> #include <svx/sdtfchim.hxx> bool SdrTextObj::HasTextEdit() const { // linked text objects may be changed (no automatic reload) return true; } sal_Bool SdrTextObj::BegTextEdit(SdrOutliner& rOutl) { if (pEdtOutl!=NULL) return sal_False; // Textedit might already run in another View! pEdtOutl=&rOutl; mbInEditMode = sal_True; sal_uInt16 nOutlinerMode = OUTLINERMODE_OUTLINEOBJECT; if ( !IsOutlText() ) nOutlinerMode = OUTLINERMODE_TEXTOBJECT; rOutl.Init( nOutlinerMode ); rOutl.SetRefDevice( pModel->GetRefDevice() ); bool bFitToSize(IsFitToSize()); bool bContourFrame=IsContourTextFrame(); ImpSetTextEditParams(); if (!bContourFrame) { sal_uIntPtr nStat=rOutl.GetControlWord(); nStat|=EE_CNTRL_AUTOPAGESIZE; if (bFitToSize || IsAutoFit()) nStat|=EE_CNTRL_STRETCHING; else nStat&=~EE_CNTRL_STRETCHING; rOutl.SetControlWord(nStat); } OutlinerParaObject* pOutlinerParaObject = GetOutlinerParaObject(); if(pOutlinerParaObject!=NULL) { rOutl.SetText(*GetOutlinerParaObject()); rOutl.SetFixedCellHeight(((const SdrTextFixedCellHeightItem&)GetMergedItem(SDRATTR_TEXT_USEFIXEDCELLHEIGHT)).GetValue()); } // if necessary, set frame attributes for the first (new) paragraph of the // outliner if( !HasTextImpl( &rOutl ) ) { // Outliner has no text so we must set some // empty text so the outliner initialise itself rOutl.SetText( String(), rOutl.GetParagraph( 0 ) ); if(GetStyleSheet()) rOutl.SetStyleSheet( 0, GetStyleSheet()); // When setting the "hard" attributes for first paragraph, the Parent // pOutlAttr (i. e. the template) has to be removed temporarily. Else, // at SetParaAttribs(), all attributes contained in the parent become // attributed hard to the paragraph. const SfxItemSet& rSet = GetObjectItemSet(); SfxItemSet aFilteredSet(*rSet.GetPool(), EE_ITEMS_START, EE_ITEMS_END); aFilteredSet.Put(rSet); rOutl.SetParaAttribs(0, aFilteredSet); } if (bFitToSize) { Rectangle aAnchorRect; Rectangle aTextRect; TakeTextRect(rOutl, aTextRect, sal_False, &aAnchorRect); Fraction aFitXKorreg(1,1); ImpSetCharStretching(rOutl,aTextRect.GetSize(),aAnchorRect.GetSize(),aFitXKorreg); } else if (IsAutoFit()) { ImpAutoFitText(rOutl); } if(pOutlinerParaObject) { if(aGeo.nDrehWink || IsFontwork()) { // only repaint here, no real objectchange BroadcastObjectChange(); } } rOutl.UpdateFields(); rOutl.ClearModifyFlag(); return sal_True; } void SdrTextObj::TakeTextEditArea(Size* pPaperMin, Size* pPaperMax, Rectangle* pViewInit, Rectangle* pViewMin) const { bool bFitToSize(IsFitToSize()); Size aPaperMin,aPaperMax; Rectangle aViewInit; TakeTextAnchorRect(aViewInit); if (aGeo.nDrehWink!=0) { Point aCenter(aViewInit.Center()); aCenter-=aViewInit.TopLeft(); Point aCenter0(aCenter); RotatePoint(aCenter,Point(),aGeo.nSin,aGeo.nCos); aCenter-=aCenter0; aViewInit.Move(aCenter.X(),aCenter.Y()); } Size aAnkSiz(aViewInit.GetSize()); aAnkSiz.Width()--; aAnkSiz.Height()--; // because GetSize() adds 1 Size aMaxSiz(1000000,1000000); if (pModel!=NULL) { Size aTmpSiz(pModel->GetMaxObjSize()); if (aTmpSiz.Width()!=0) aMaxSiz.Width()=aTmpSiz.Width(); if (aTmpSiz.Height()!=0) aMaxSiz.Height()=aTmpSiz.Height(); } // Done earlier since used in else tree below SdrTextHorzAdjust eHAdj(GetTextHorizontalAdjust()); SdrTextVertAdjust eVAdj(GetTextVerticalAdjust()); if(IsTextFrame()) { long nMinWdt=GetMinTextFrameWidth(); long nMinHgt=GetMinTextFrameHeight(); long nMaxWdt=GetMaxTextFrameWidth(); long nMaxHgt=GetMaxTextFrameHeight(); if (nMinWdt<1) nMinWdt=1; if (nMinHgt<1) nMinHgt=1; if (!bFitToSize) { if (nMaxWdt==0 || nMaxWdt>aMaxSiz.Width()) nMaxWdt=aMaxSiz.Width(); if (nMaxHgt==0 || nMaxHgt>aMaxSiz.Height()) nMaxHgt=aMaxSiz.Height(); if (!IsAutoGrowWidth() ) { nMaxWdt=aAnkSiz.Width(); nMinWdt=nMaxWdt; } if (!IsAutoGrowHeight()) { nMaxHgt=aAnkSiz.Height(); nMinHgt=nMaxHgt; } SdrTextAniKind eAniKind=GetTextAniKind(); SdrTextAniDirection eAniDirection=GetTextAniDirection(); sal_Bool bInEditMode = IsInEditMode(); if (!bInEditMode && (eAniKind==SDRTEXTANI_SCROLL || eAniKind==SDRTEXTANI_ALTERNATE || eAniKind==SDRTEXTANI_SLIDE)) { // ticker text uses an unlimited paper size if (eAniDirection==SDRTEXTANI_LEFT || eAniDirection==SDRTEXTANI_RIGHT) nMaxWdt=1000000; if (eAniDirection==SDRTEXTANI_UP || eAniDirection==SDRTEXTANI_DOWN) nMaxHgt=1000000; } aPaperMax.Width()=nMaxWdt; aPaperMax.Height()=nMaxHgt; } else { aPaperMax=aMaxSiz; } aPaperMin.Width()=nMinWdt; aPaperMin.Height()=nMinHgt; } else { // aPaperMin needs to be set to object's size if full width is activated // for hor or ver writing respectively if((SDRTEXTHORZADJUST_BLOCK == eHAdj && !IsVerticalWriting()) || (SDRTEXTVERTADJUST_BLOCK == eVAdj && IsVerticalWriting())) { aPaperMin = aAnkSiz; } aPaperMax=aMaxSiz; } if (pViewMin!=NULL) { *pViewMin=aViewInit; long nXFree=aAnkSiz.Width()-aPaperMin.Width(); if (eHAdj==SDRTEXTHORZADJUST_LEFT) pViewMin->Right()-=nXFree; else if (eHAdj==SDRTEXTHORZADJUST_RIGHT) pViewMin->Left()+=nXFree; else { pViewMin->Left()+=nXFree/2; pViewMin->Right()=pViewMin->Left()+aPaperMin.Width(); } long nYFree=aAnkSiz.Height()-aPaperMin.Height(); if (eVAdj==SDRTEXTVERTADJUST_TOP) pViewMin->Bottom()-=nYFree; else if (eVAdj==SDRTEXTVERTADJUST_BOTTOM) pViewMin->Top()+=nYFree; else { pViewMin->Top()+=nYFree/2; pViewMin->Bottom()=pViewMin->Top()+aPaperMin.Height(); } } // PaperSize should grow automatically in most cases if(IsVerticalWriting()) aPaperMin.Width() = 0; else aPaperMin.Height() = 0; if(eHAdj!=SDRTEXTHORZADJUST_BLOCK || bFitToSize) { aPaperMin.Width()=0; } // For complete vertical adjustment support, set paper min height to 0, here. if(SDRTEXTVERTADJUST_BLOCK != eVAdj || bFitToSize) { aPaperMin.Height() = 0; } if (pPaperMin!=NULL) *pPaperMin=aPaperMin; if (pPaperMax!=NULL) *pPaperMax=aPaperMax; if (pViewInit!=NULL) *pViewInit=aViewInit; } void SdrTextObj::EndTextEdit(SdrOutliner& rOutl) { if(rOutl.IsModified()) { OutlinerParaObject* pNewText = NULL; if(HasTextImpl( &rOutl ) ) { // to make the gray field background vanish again rOutl.UpdateFields(); sal_uInt16 nParaAnz = static_cast< sal_uInt16 >( rOutl.GetParagraphCount() ); pNewText = rOutl.CreateParaObject( 0, nParaAnz ); } // need to end edit mode early since SetOutlinerParaObject already // uses GetCurrentBoundRect() which needs to take the text into account // to work correct mbInEditMode = sal_False; SetOutlinerParaObject(pNewText); } pEdtOutl = NULL; rOutl.Clear(); sal_uInt32 nStat = rOutl.GetControlWord(); nStat &= ~EE_CNTRL_AUTOPAGESIZE; rOutl.SetControlWord(nStat); mbInEditMode = sal_False; } sal_uInt16 SdrTextObj::GetOutlinerViewAnchorMode() const { SdrTextHorzAdjust eH=GetTextHorizontalAdjust(); SdrTextVertAdjust eV=GetTextVerticalAdjust(); EVAnchorMode eRet=ANCHOR_TOP_LEFT; if (IsContourTextFrame()) return (sal_uInt16)eRet; if (eH==SDRTEXTHORZADJUST_LEFT) { if (eV==SDRTEXTVERTADJUST_TOP) { eRet=ANCHOR_TOP_LEFT; } else if (eV==SDRTEXTVERTADJUST_BOTTOM) { eRet=ANCHOR_BOTTOM_LEFT; } else { eRet=ANCHOR_VCENTER_LEFT; } } else if (eH==SDRTEXTHORZADJUST_RIGHT) { if (eV==SDRTEXTVERTADJUST_TOP) { eRet=ANCHOR_TOP_RIGHT; } else if (eV==SDRTEXTVERTADJUST_BOTTOM) { eRet=ANCHOR_BOTTOM_RIGHT; } else { eRet=ANCHOR_VCENTER_RIGHT; } } else { if (eV==SDRTEXTVERTADJUST_TOP) { eRet=ANCHOR_TOP_HCENTER; } else if (eV==SDRTEXTVERTADJUST_BOTTOM) { eRet=ANCHOR_BOTTOM_HCENTER; } else { eRet=ANCHOR_VCENTER_HCENTER; } } return (sal_uInt16)eRet; } void SdrTextObj::ImpSetTextEditParams() const { if (pEdtOutl!=NULL) { bool bUpdMerk=pEdtOutl->GetUpdateMode(); if (bUpdMerk) pEdtOutl->SetUpdateMode(sal_False); Size aPaperMin; Size aPaperMax; Rectangle aEditArea; TakeTextEditArea(&aPaperMin,&aPaperMax,&aEditArea,NULL); bool bContourFrame=IsContourTextFrame(); pEdtOutl->SetMinAutoPaperSize(aPaperMin); pEdtOutl->SetMaxAutoPaperSize(aPaperMax); pEdtOutl->SetPaperSize(Size()); if (bContourFrame) { Rectangle aAnchorRect; TakeTextAnchorRect(aAnchorRect); ImpSetContourPolygon(*pEdtOutl,aAnchorRect, sal_True); } if (bUpdMerk) pEdtOutl->SetUpdateMode(sal_True); } } /* vim:set shiftwidth=4 softtabstop=4 expandtab: */ <commit_msg>fdo#63311: Unable to delete text from Shape.<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 <svx/svdotext.hxx> #include <svx/svdmodel.hxx> // for GetMaxObjSize #include <svx/svdoutl.hxx> #include <editeng/editdata.hxx> #include <editeng/outliner.hxx> #include <editeng/editstat.hxx> #include <svl/itemset.hxx> #include <editeng/eeitem.hxx> #include <svx/sdtfchim.hxx> bool SdrTextObj::HasTextEdit() const { // linked text objects may be changed (no automatic reload) return true; } sal_Bool SdrTextObj::BegTextEdit(SdrOutliner& rOutl) { if (pEdtOutl!=NULL) return sal_False; // Textedit might already run in another View! pEdtOutl=&rOutl; mbInEditMode = sal_True; sal_uInt16 nOutlinerMode = OUTLINERMODE_OUTLINEOBJECT; if ( !IsOutlText() ) nOutlinerMode = OUTLINERMODE_TEXTOBJECT; rOutl.Init( nOutlinerMode ); rOutl.SetRefDevice( pModel->GetRefDevice() ); bool bFitToSize(IsFitToSize()); bool bContourFrame=IsContourTextFrame(); ImpSetTextEditParams(); if (!bContourFrame) { sal_uIntPtr nStat=rOutl.GetControlWord(); nStat|=EE_CNTRL_AUTOPAGESIZE; if (bFitToSize || IsAutoFit()) nStat|=EE_CNTRL_STRETCHING; else nStat&=~EE_CNTRL_STRETCHING; rOutl.SetControlWord(nStat); } OutlinerParaObject* pOutlinerParaObject = GetOutlinerParaObject(); if(pOutlinerParaObject!=NULL) { rOutl.SetText(*GetOutlinerParaObject()); rOutl.SetFixedCellHeight(((const SdrTextFixedCellHeightItem&)GetMergedItem(SDRATTR_TEXT_USEFIXEDCELLHEIGHT)).GetValue()); } // if necessary, set frame attributes for the first (new) paragraph of the // outliner if( !HasTextImpl( &rOutl ) ) { // Outliner has no text so we must set some // empty text so the outliner initialise itself rOutl.SetText( String(), rOutl.GetParagraph( 0 ) ); if(GetStyleSheet()) rOutl.SetStyleSheet( 0, GetStyleSheet()); // When setting the "hard" attributes for first paragraph, the Parent // pOutlAttr (i. e. the template) has to be removed temporarily. Else, // at SetParaAttribs(), all attributes contained in the parent become // attributed hard to the paragraph. const SfxItemSet& rSet = GetObjectItemSet(); SfxItemSet aFilteredSet(*rSet.GetPool(), EE_ITEMS_START, EE_ITEMS_END); aFilteredSet.Put(rSet); rOutl.SetParaAttribs(0, aFilteredSet); } if (bFitToSize) { Rectangle aAnchorRect; Rectangle aTextRect; TakeTextRect(rOutl, aTextRect, sal_False, &aAnchorRect); Fraction aFitXKorreg(1,1); ImpSetCharStretching(rOutl,aTextRect.GetSize(),aAnchorRect.GetSize(),aFitXKorreg); } else if (IsAutoFit()) { ImpAutoFitText(rOutl); } if(pOutlinerParaObject) { if(aGeo.nDrehWink || IsFontwork()) { // only repaint here, no real objectchange BroadcastObjectChange(); } } rOutl.UpdateFields(); rOutl.ClearModifyFlag(); return sal_True; } void SdrTextObj::TakeTextEditArea(Size* pPaperMin, Size* pPaperMax, Rectangle* pViewInit, Rectangle* pViewMin) const { bool bFitToSize(IsFitToSize()); Size aPaperMin,aPaperMax; Rectangle aViewInit; TakeTextAnchorRect(aViewInit); if (aGeo.nDrehWink!=0) { Point aCenter(aViewInit.Center()); aCenter-=aViewInit.TopLeft(); Point aCenter0(aCenter); RotatePoint(aCenter,Point(),aGeo.nSin,aGeo.nCos); aCenter-=aCenter0; aViewInit.Move(aCenter.X(),aCenter.Y()); } Size aAnkSiz(aViewInit.GetSize()); aAnkSiz.Width()--; aAnkSiz.Height()--; // because GetSize() adds 1 Size aMaxSiz(1000000,1000000); if (pModel!=NULL) { Size aTmpSiz(pModel->GetMaxObjSize()); if (aTmpSiz.Width()!=0) aMaxSiz.Width()=aTmpSiz.Width(); if (aTmpSiz.Height()!=0) aMaxSiz.Height()=aTmpSiz.Height(); } // Done earlier since used in else tree below SdrTextHorzAdjust eHAdj(GetTextHorizontalAdjust()); SdrTextVertAdjust eVAdj(GetTextVerticalAdjust()); if(IsTextFrame()) { long nMinWdt=GetMinTextFrameWidth(); long nMinHgt=GetMinTextFrameHeight(); long nMaxWdt=GetMaxTextFrameWidth(); long nMaxHgt=GetMaxTextFrameHeight(); if (nMinWdt<1) nMinWdt=1; if (nMinHgt<1) nMinHgt=1; if (!bFitToSize) { if (nMaxWdt==0 || nMaxWdt>aMaxSiz.Width()) nMaxWdt=aMaxSiz.Width(); if (nMaxHgt==0 || nMaxHgt>aMaxSiz.Height()) nMaxHgt=aMaxSiz.Height(); if (!IsAutoGrowWidth() ) { nMaxWdt=aAnkSiz.Width(); nMinWdt=nMaxWdt; } if (!IsAutoGrowHeight()) { nMaxHgt=aAnkSiz.Height(); nMinHgt=nMaxHgt; } SdrTextAniKind eAniKind=GetTextAniKind(); SdrTextAniDirection eAniDirection=GetTextAniDirection(); sal_Bool bInEditMode = IsInEditMode(); if (!bInEditMode && (eAniKind==SDRTEXTANI_SCROLL || eAniKind==SDRTEXTANI_ALTERNATE || eAniKind==SDRTEXTANI_SLIDE)) { // ticker text uses an unlimited paper size if (eAniDirection==SDRTEXTANI_LEFT || eAniDirection==SDRTEXTANI_RIGHT) nMaxWdt=1000000; if (eAniDirection==SDRTEXTANI_UP || eAniDirection==SDRTEXTANI_DOWN) nMaxHgt=1000000; } aPaperMax.Width()=nMaxWdt; aPaperMax.Height()=nMaxHgt; } else { aPaperMax=aMaxSiz; } aPaperMin.Width()=nMinWdt; aPaperMin.Height()=nMinHgt; } else { // aPaperMin needs to be set to object's size if full width is activated // for hor or ver writing respectively if((SDRTEXTHORZADJUST_BLOCK == eHAdj && !IsVerticalWriting()) || (SDRTEXTVERTADJUST_BLOCK == eVAdj && IsVerticalWriting())) { aPaperMin = aAnkSiz; } aPaperMax=aMaxSiz; } if (pViewMin!=NULL) { *pViewMin=aViewInit; long nXFree=aAnkSiz.Width()-aPaperMin.Width(); if (eHAdj==SDRTEXTHORZADJUST_LEFT) pViewMin->Right()-=nXFree; else if (eHAdj==SDRTEXTHORZADJUST_RIGHT) pViewMin->Left()+=nXFree; else { pViewMin->Left()+=nXFree/2; pViewMin->Right()=pViewMin->Left()+aPaperMin.Width(); } long nYFree=aAnkSiz.Height()-aPaperMin.Height(); if (eVAdj==SDRTEXTVERTADJUST_TOP) pViewMin->Bottom()-=nYFree; else if (eVAdj==SDRTEXTVERTADJUST_BOTTOM) pViewMin->Top()+=nYFree; else { pViewMin->Top()+=nYFree/2; pViewMin->Bottom()=pViewMin->Top()+aPaperMin.Height(); } } // PaperSize should grow automatically in most cases if(IsVerticalWriting()) aPaperMin.Width() = 0; else aPaperMin.Height() = 0; if(eHAdj!=SDRTEXTHORZADJUST_BLOCK || bFitToSize) { aPaperMin.Width()=0; } // For complete vertical adjustment support, set paper min height to 0, here. if(SDRTEXTVERTADJUST_BLOCK != eVAdj || bFitToSize) { aPaperMin.Height() = 0; } if (pPaperMin!=NULL) *pPaperMin=aPaperMin; if (pPaperMax!=NULL) *pPaperMax=aPaperMax; if (pViewInit!=NULL) *pViewInit=aViewInit; } void SdrTextObj::EndTextEdit(SdrOutliner& rOutl) { if(rOutl.IsModified()) { OutlinerParaObject* pNewText = NULL; // to make the gray field background vanish again rOutl.UpdateFields(); sal_uInt16 nParaAnz = static_cast< sal_uInt16 >( rOutl.GetParagraphCount() ); pNewText = rOutl.CreateParaObject( 0, nParaAnz ); // need to end edit mode early since SetOutlinerParaObject already // uses GetCurrentBoundRect() which needs to take the text into account // to work correct mbInEditMode = sal_False; SetOutlinerParaObject(pNewText); } pEdtOutl = NULL; rOutl.Clear(); sal_uInt32 nStat = rOutl.GetControlWord(); nStat &= ~EE_CNTRL_AUTOPAGESIZE; rOutl.SetControlWord(nStat); mbInEditMode = sal_False; } sal_uInt16 SdrTextObj::GetOutlinerViewAnchorMode() const { SdrTextHorzAdjust eH=GetTextHorizontalAdjust(); SdrTextVertAdjust eV=GetTextVerticalAdjust(); EVAnchorMode eRet=ANCHOR_TOP_LEFT; if (IsContourTextFrame()) return (sal_uInt16)eRet; if (eH==SDRTEXTHORZADJUST_LEFT) { if (eV==SDRTEXTVERTADJUST_TOP) { eRet=ANCHOR_TOP_LEFT; } else if (eV==SDRTEXTVERTADJUST_BOTTOM) { eRet=ANCHOR_BOTTOM_LEFT; } else { eRet=ANCHOR_VCENTER_LEFT; } } else if (eH==SDRTEXTHORZADJUST_RIGHT) { if (eV==SDRTEXTVERTADJUST_TOP) { eRet=ANCHOR_TOP_RIGHT; } else if (eV==SDRTEXTVERTADJUST_BOTTOM) { eRet=ANCHOR_BOTTOM_RIGHT; } else { eRet=ANCHOR_VCENTER_RIGHT; } } else { if (eV==SDRTEXTVERTADJUST_TOP) { eRet=ANCHOR_TOP_HCENTER; } else if (eV==SDRTEXTVERTADJUST_BOTTOM) { eRet=ANCHOR_BOTTOM_HCENTER; } else { eRet=ANCHOR_VCENTER_HCENTER; } } return (sal_uInt16)eRet; } void SdrTextObj::ImpSetTextEditParams() const { if (pEdtOutl!=NULL) { bool bUpdMerk=pEdtOutl->GetUpdateMode(); if (bUpdMerk) pEdtOutl->SetUpdateMode(sal_False); Size aPaperMin; Size aPaperMax; Rectangle aEditArea; TakeTextEditArea(&aPaperMin,&aPaperMax,&aEditArea,NULL); bool bContourFrame=IsContourTextFrame(); pEdtOutl->SetMinAutoPaperSize(aPaperMin); pEdtOutl->SetMaxAutoPaperSize(aPaperMax); pEdtOutl->SetPaperSize(Size()); if (bContourFrame) { Rectangle aAnchorRect; TakeTextAnchorRect(aAnchorRect); ImpSetContourPolygon(*pEdtOutl,aAnchorRect, sal_True); } if (bUpdMerk) pEdtOutl->SetUpdateMode(sal_True); } } /* vim:set shiftwidth=4 softtabstop=4 expandtab: */ <|endoftext|>
<commit_before>/* * Client Key Exchange Message * (C) 2004-2010 Jack Lloyd * * Released under the terms of the Botan license */ #include <botan/internal/tls_messages.h> #include <botan/internal/tls_reader.h> #include <botan/internal/tls_extensions.h> #include <botan/internal/tls_handshake_io.h> #include <botan/internal/assert.h> #include <botan/credentials_manager.h> #include <botan/pubkey.h> #include <botan/dh.h> #include <botan/ecdh.h> #include <botan/rsa.h> #include <botan/srp6.h> #include <botan/rng.h> #include <botan/loadstor.h> #include <memory> namespace Botan { namespace TLS { namespace { secure_vector<byte> strip_leading_zeros(const secure_vector<byte>& input) { size_t leading_zeros = 0; for(size_t i = 0; i != input.size(); ++i) { if(input[i] != 0) break; ++leading_zeros; } secure_vector<byte> output(&input[leading_zeros], &input[input.size()]); return output; } } /* * Create a new Client Key Exchange message */ Client_Key_Exchange::Client_Key_Exchange(Handshake_IO& io, Handshake_State& state, const Policy& policy, Credentials_Manager& creds, const Public_Key* server_public_key, const std::string& hostname, RandomNumberGenerator& rng) { const std::string kex_algo = state.ciphersuite().kex_algo(); if(kex_algo == "PSK") { std::string identity_hint = ""; if(state.server_kex()) { TLS_Data_Reader reader(state.server_kex()->params()); identity_hint = reader.get_string(2, 0, 65535); } const std::string hostname = state.client_hello()->sni_hostname(); const std::string psk_identity = creds.psk_identity("tls-client", hostname, identity_hint); append_tls_length_value(m_key_material, psk_identity, 2); SymmetricKey psk = creds.psk("tls-client", hostname, psk_identity); std::vector<byte> zeros(psk.length()); append_tls_length_value(m_pre_master, zeros, 2); append_tls_length_value(m_pre_master, psk.bits_of(), 2); } else if(state.server_kex()) { TLS_Data_Reader reader(state.server_kex()->params()); SymmetricKey psk; if(kex_algo == "DHE_PSK" || kex_algo == "ECDHE_PSK") { std::string identity_hint = reader.get_string(2, 0, 65535); const std::string hostname = state.client_hello()->sni_hostname(); const std::string psk_identity = creds.psk_identity("tls-client", hostname, identity_hint); append_tls_length_value(m_key_material, psk_identity, 2); psk = creds.psk("tls-client", hostname, psk_identity); } if(kex_algo == "DH" || kex_algo == "DHE_PSK") { BigInt p = BigInt::decode(reader.get_range<byte>(2, 1, 65535)); BigInt g = BigInt::decode(reader.get_range<byte>(2, 1, 65535)); BigInt Y = BigInt::decode(reader.get_range<byte>(2, 1, 65535)); if(reader.remaining_bytes()) throw Decoding_Error("Bad params size for DH key exchange"); if(p.bits() < policy.minimum_dh_group_size()) throw TLS_Exception(Alert::INSUFFICIENT_SECURITY, "Server sent DH group of " + std::to_string(p.bits()) + " bits, policy requires at least " + std::to_string(policy.minimum_dh_group_size())); /* * A basic check for key validity. As we do not know q here we * cannot check that Y is in the right subgroup. However since * our key is ephemeral there does not seem to be any * advantage to bogus keys anyway. */ if(Y <= 1 || Y >= p - 1) throw TLS_Exception(Alert::INSUFFICIENT_SECURITY, "Server sent bad DH key for DHE exchange"); DL_Group group(p, g); if(!group.verify_group(rng, true)) throw Internal_Error("DH group failed validation, possible attack"); DH_PublicKey counterparty_key(group, Y); DH_PrivateKey priv_key(rng, group); PK_Key_Agreement ka(priv_key, "Raw"); secure_vector<byte> dh_secret = strip_leading_zeros( ka.derive_key(0, counterparty_key.public_value()).bits_of()); if(kex_algo == "DH") m_pre_master = dh_secret; else { append_tls_length_value(m_pre_master, dh_secret, 2); append_tls_length_value(m_pre_master, psk.bits_of(), 2); } append_tls_length_value(m_key_material, priv_key.public_value(), 2); } else if(kex_algo == "ECDH" || kex_algo == "ECDHE_PSK") { const byte curve_type = reader.get_byte(); if(curve_type != 3) throw Decoding_Error("Server sent non-named ECC curve"); const u16bit curve_id = reader.get_u16bit(); const std::string name = Supported_Elliptic_Curves::curve_id_to_name(curve_id); if(name == "") throw Decoding_Error("Server sent unknown named curve " + std::to_string(curve_id)); EC_Group group(name); std::vector<byte> ecdh_key = reader.get_range<byte>(1, 1, 255); ECDH_PublicKey counterparty_key(group, OS2ECP(ecdh_key, group.get_curve())); ECDH_PrivateKey priv_key(rng, group); PK_Key_Agreement ka(priv_key, "Raw"); secure_vector<byte> ecdh_secret = ka.derive_key(0, counterparty_key.public_value()).bits_of(); if(kex_algo == "ECDH") m_pre_master = ecdh_secret; else { append_tls_length_value(m_pre_master, ecdh_secret, 2); append_tls_length_value(m_pre_master, psk.bits_of(), 2); } append_tls_length_value(m_key_material, priv_key.public_value(), 1); } else if(kex_algo == "SRP_SHA") { const BigInt N = BigInt::decode(reader.get_range<byte>(2, 1, 65535)); const BigInt g = BigInt::decode(reader.get_range<byte>(2, 1, 65535)); std::vector<byte> salt = reader.get_range<byte>(1, 1, 255); const BigInt B = BigInt::decode(reader.get_range<byte>(2, 1, 65535)); const std::string srp_group = srp6_group_identifier(N, g); const std::string srp_identifier = creds.srp_identifier("tls-client", hostname); const std::string srp_password = creds.srp_password("tls-client", hostname, srp_identifier); std::pair<BigInt, SymmetricKey> srp_vals = srp6_client_agree(srp_identifier, srp_password, srp_group, "SHA-1", salt, B, rng); append_tls_length_value(m_key_material, BigInt::encode(srp_vals.first), 2); m_pre_master = srp_vals.second.bits_of(); } else { throw Internal_Error("Client_Key_Exchange: Unknown kex " + kex_algo); } reader.assert_done(); } else { // No server key exchange msg better mean RSA kex + RSA key in cert if(kex_algo != "RSA") throw Unexpected_Message("No server kex but negotiated kex " + kex_algo); if(!server_public_key) throw Internal_Error("No server public key for RSA exchange"); if(auto rsa_pub = dynamic_cast<const RSA_PublicKey*>(server_public_key)) { const Protocol_Version offered_version = state.client_hello()->version(); m_pre_master = rng.random_vec(48); m_pre_master[0] = offered_version.major_version(); m_pre_master[1] = offered_version.minor_version(); PK_Encryptor_EME encryptor(*rsa_pub, "PKCS1v15"); std::vector<byte> encrypted_key = encryptor.encrypt(m_pre_master, rng); if(state.version() == Protocol_Version::SSL_V3) m_key_material = encrypted_key; // no length field else append_tls_length_value(m_key_material, encrypted_key, 2); } else throw TLS_Exception(Alert::HANDSHAKE_FAILURE, "Expected a RSA key in server cert but got " + server_public_key->algo_name()); } state.hash().update(io.send(*this)); } /* * Read a Client Key Exchange message */ Client_Key_Exchange::Client_Key_Exchange(const std::vector<byte>& contents, const Handshake_State& state, const Private_Key* server_rsa_kex_key, Credentials_Manager& creds, const Policy& policy, RandomNumberGenerator& rng) { const std::string kex_algo = state.ciphersuite().kex_algo(); if(kex_algo == "RSA") { BOTAN_ASSERT(state.server_certs() && !state.server_certs()->cert_chain().empty(), "RSA key exchange negotiated so server sent a certificate"); if(!server_rsa_kex_key) throw Internal_Error("Expected RSA kex but no server kex key set"); if(!dynamic_cast<const RSA_PrivateKey*>(server_rsa_kex_key)) throw Internal_Error("Expected RSA key but got " + server_rsa_kex_key->algo_name()); PK_Decryptor_EME decryptor(*server_rsa_kex_key, "PKCS1v15"); Protocol_Version client_version = state.client_hello()->version(); try { if(state.version() == Protocol_Version::SSL_V3) { m_pre_master = decryptor.decrypt(contents); } else { TLS_Data_Reader reader(contents); m_pre_master = decryptor.decrypt(reader.get_range<byte>(2, 0, 65535)); } if(m_pre_master.size() != 48 || client_version.major_version() != m_pre_master[0] || client_version.minor_version() != m_pre_master[1]) { throw Decoding_Error("Client_Key_Exchange: Secret corrupted"); } } catch(...) { // Randomize to hide timing channel m_pre_master = rng.random_vec(48); m_pre_master[0] = client_version.major_version(); m_pre_master[1] = client_version.minor_version(); } } else { TLS_Data_Reader reader(contents); SymmetricKey psk; if(kex_algo == "PSK" || kex_algo == "DHE_PSK" || kex_algo == "ECDHE_PSK") { const std::string psk_identity = reader.get_string(2, 0, 65535); psk = creds.psk("tls-server", state.client_hello()->sni_hostname(), psk_identity); if(psk.length() == 0) { if(policy.hide_unknown_users()) psk = SymmetricKey(rng, 16); else throw TLS_Exception(Alert::UNKNOWN_PSK_IDENTITY, "No PSK for identifier " + psk_identity); } } if(kex_algo == "PSK") { std::vector<byte> zeros(psk.length()); append_tls_length_value(m_pre_master, zeros, 2); append_tls_length_value(m_pre_master, psk.bits_of(), 2); } else if(kex_algo == "SRP_SHA") { SRP6_Server_Session& srp = state.server_kex()->server_srp_params(); m_pre_master = srp.step2(BigInt::decode(reader.get_range<byte>(2, 0, 65535))).bits_of(); } else if(kex_algo == "DH" || kex_algo == "DHE_PSK" || kex_algo == "ECDH" || kex_algo == "ECDHE_PSK") { const Private_Key& private_key = state.server_kex()->server_kex_key(); const PK_Key_Agreement_Key* ka_key = dynamic_cast<const PK_Key_Agreement_Key*>(&private_key); if(!ka_key) throw Internal_Error("Expected key agreement key type but got " + private_key.algo_name()); try { PK_Key_Agreement ka(*ka_key, "Raw"); std::vector<byte> client_pubkey; if(ka_key->algo_name() == "DH") client_pubkey = reader.get_range<byte>(2, 0, 65535); else client_pubkey = reader.get_range<byte>(1, 0, 255); secure_vector<byte> shared_secret = ka.derive_key(0, client_pubkey).bits_of(); if(ka_key->algo_name() == "DH") shared_secret = strip_leading_zeros(shared_secret); if(kex_algo == "DHE_PSK" || kex_algo == "ECDHE_PSK") { append_tls_length_value(m_pre_master, shared_secret, 2); append_tls_length_value(m_pre_master, psk.bits_of(), 2); } else m_pre_master = shared_secret; } catch(std::exception &e) { /* * Something failed in the DH computation. To avoid possible * timing attacks, randomize the pre-master output and carry * on, allowing the protocol to fail later in the finished * checks. */ m_pre_master = rng.random_vec(ka_key->public_value().size()); } } else throw Internal_Error("Client_Key_Exchange: Unknown kex type " + kex_algo); } } } } <commit_msg>Generate the fake pre master needed if the RSA computation fails ahead of time. Otherwise we expose a timing channel WRT using the RNG.<commit_after>/* * Client Key Exchange Message * (C) 2004-2010 Jack Lloyd * * Released under the terms of the Botan license */ #include <botan/internal/tls_messages.h> #include <botan/internal/tls_reader.h> #include <botan/internal/tls_extensions.h> #include <botan/internal/tls_handshake_io.h> #include <botan/internal/assert.h> #include <botan/credentials_manager.h> #include <botan/pubkey.h> #include <botan/dh.h> #include <botan/ecdh.h> #include <botan/rsa.h> #include <botan/srp6.h> #include <botan/rng.h> #include <botan/loadstor.h> #include <memory> namespace Botan { namespace TLS { namespace { secure_vector<byte> strip_leading_zeros(const secure_vector<byte>& input) { size_t leading_zeros = 0; for(size_t i = 0; i != input.size(); ++i) { if(input[i] != 0) break; ++leading_zeros; } secure_vector<byte> output(&input[leading_zeros], &input[input.size()]); return output; } } /* * Create a new Client Key Exchange message */ Client_Key_Exchange::Client_Key_Exchange(Handshake_IO& io, Handshake_State& state, const Policy& policy, Credentials_Manager& creds, const Public_Key* server_public_key, const std::string& hostname, RandomNumberGenerator& rng) { const std::string kex_algo = state.ciphersuite().kex_algo(); if(kex_algo == "PSK") { std::string identity_hint = ""; if(state.server_kex()) { TLS_Data_Reader reader(state.server_kex()->params()); identity_hint = reader.get_string(2, 0, 65535); } const std::string hostname = state.client_hello()->sni_hostname(); const std::string psk_identity = creds.psk_identity("tls-client", hostname, identity_hint); append_tls_length_value(m_key_material, psk_identity, 2); SymmetricKey psk = creds.psk("tls-client", hostname, psk_identity); std::vector<byte> zeros(psk.length()); append_tls_length_value(m_pre_master, zeros, 2); append_tls_length_value(m_pre_master, psk.bits_of(), 2); } else if(state.server_kex()) { TLS_Data_Reader reader(state.server_kex()->params()); SymmetricKey psk; if(kex_algo == "DHE_PSK" || kex_algo == "ECDHE_PSK") { std::string identity_hint = reader.get_string(2, 0, 65535); const std::string hostname = state.client_hello()->sni_hostname(); const std::string psk_identity = creds.psk_identity("tls-client", hostname, identity_hint); append_tls_length_value(m_key_material, psk_identity, 2); psk = creds.psk("tls-client", hostname, psk_identity); } if(kex_algo == "DH" || kex_algo == "DHE_PSK") { BigInt p = BigInt::decode(reader.get_range<byte>(2, 1, 65535)); BigInt g = BigInt::decode(reader.get_range<byte>(2, 1, 65535)); BigInt Y = BigInt::decode(reader.get_range<byte>(2, 1, 65535)); if(reader.remaining_bytes()) throw Decoding_Error("Bad params size for DH key exchange"); if(p.bits() < policy.minimum_dh_group_size()) throw TLS_Exception(Alert::INSUFFICIENT_SECURITY, "Server sent DH group of " + std::to_string(p.bits()) + " bits, policy requires at least " + std::to_string(policy.minimum_dh_group_size())); /* * A basic check for key validity. As we do not know q here we * cannot check that Y is in the right subgroup. However since * our key is ephemeral there does not seem to be any * advantage to bogus keys anyway. */ if(Y <= 1 || Y >= p - 1) throw TLS_Exception(Alert::INSUFFICIENT_SECURITY, "Server sent bad DH key for DHE exchange"); DL_Group group(p, g); if(!group.verify_group(rng, true)) throw Internal_Error("DH group failed validation, possible attack"); DH_PublicKey counterparty_key(group, Y); DH_PrivateKey priv_key(rng, group); PK_Key_Agreement ka(priv_key, "Raw"); secure_vector<byte> dh_secret = strip_leading_zeros( ka.derive_key(0, counterparty_key.public_value()).bits_of()); if(kex_algo == "DH") m_pre_master = dh_secret; else { append_tls_length_value(m_pre_master, dh_secret, 2); append_tls_length_value(m_pre_master, psk.bits_of(), 2); } append_tls_length_value(m_key_material, priv_key.public_value(), 2); } else if(kex_algo == "ECDH" || kex_algo == "ECDHE_PSK") { const byte curve_type = reader.get_byte(); if(curve_type != 3) throw Decoding_Error("Server sent non-named ECC curve"); const u16bit curve_id = reader.get_u16bit(); const std::string name = Supported_Elliptic_Curves::curve_id_to_name(curve_id); if(name == "") throw Decoding_Error("Server sent unknown named curve " + std::to_string(curve_id)); EC_Group group(name); std::vector<byte> ecdh_key = reader.get_range<byte>(1, 1, 255); ECDH_PublicKey counterparty_key(group, OS2ECP(ecdh_key, group.get_curve())); ECDH_PrivateKey priv_key(rng, group); PK_Key_Agreement ka(priv_key, "Raw"); secure_vector<byte> ecdh_secret = ka.derive_key(0, counterparty_key.public_value()).bits_of(); if(kex_algo == "ECDH") m_pre_master = ecdh_secret; else { append_tls_length_value(m_pre_master, ecdh_secret, 2); append_tls_length_value(m_pre_master, psk.bits_of(), 2); } append_tls_length_value(m_key_material, priv_key.public_value(), 1); } else if(kex_algo == "SRP_SHA") { const BigInt N = BigInt::decode(reader.get_range<byte>(2, 1, 65535)); const BigInt g = BigInt::decode(reader.get_range<byte>(2, 1, 65535)); std::vector<byte> salt = reader.get_range<byte>(1, 1, 255); const BigInt B = BigInt::decode(reader.get_range<byte>(2, 1, 65535)); const std::string srp_group = srp6_group_identifier(N, g); const std::string srp_identifier = creds.srp_identifier("tls-client", hostname); const std::string srp_password = creds.srp_password("tls-client", hostname, srp_identifier); std::pair<BigInt, SymmetricKey> srp_vals = srp6_client_agree(srp_identifier, srp_password, srp_group, "SHA-1", salt, B, rng); append_tls_length_value(m_key_material, BigInt::encode(srp_vals.first), 2); m_pre_master = srp_vals.second.bits_of(); } else { throw Internal_Error("Client_Key_Exchange: Unknown kex " + kex_algo); } reader.assert_done(); } else { // No server key exchange msg better mean RSA kex + RSA key in cert if(kex_algo != "RSA") throw Unexpected_Message("No server kex but negotiated kex " + kex_algo); if(!server_public_key) throw Internal_Error("No server public key for RSA exchange"); if(auto rsa_pub = dynamic_cast<const RSA_PublicKey*>(server_public_key)) { const Protocol_Version offered_version = state.client_hello()->version(); m_pre_master = rng.random_vec(48); m_pre_master[0] = offered_version.major_version(); m_pre_master[1] = offered_version.minor_version(); PK_Encryptor_EME encryptor(*rsa_pub, "PKCS1v15"); std::vector<byte> encrypted_key = encryptor.encrypt(m_pre_master, rng); if(state.version() == Protocol_Version::SSL_V3) m_key_material = encrypted_key; // no length field else append_tls_length_value(m_key_material, encrypted_key, 2); } else throw TLS_Exception(Alert::HANDSHAKE_FAILURE, "Expected a RSA key in server cert but got " + server_public_key->algo_name()); } state.hash().update(io.send(*this)); } /* * Read a Client Key Exchange message */ Client_Key_Exchange::Client_Key_Exchange(const std::vector<byte>& contents, const Handshake_State& state, const Private_Key* server_rsa_kex_key, Credentials_Manager& creds, const Policy& policy, RandomNumberGenerator& rng) { const std::string kex_algo = state.ciphersuite().kex_algo(); if(kex_algo == "RSA") { BOTAN_ASSERT(state.server_certs() && !state.server_certs()->cert_chain().empty(), "RSA key exchange negotiated so server sent a certificate"); if(!server_rsa_kex_key) throw Internal_Error("Expected RSA kex but no server kex key set"); if(!dynamic_cast<const RSA_PrivateKey*>(server_rsa_kex_key)) throw Internal_Error("Expected RSA key but got " + server_rsa_kex_key->algo_name()); PK_Decryptor_EME decryptor(*server_rsa_kex_key, "PKCS1v15"); Protocol_Version client_version = state.client_hello()->version(); /* * This is used as the pre-master if RSA decryption fails. * Otherwise we can be used as an oracle. See Bleichenbacher * "Chosen Ciphertext Attacks against Protocols Based on RSA * Encryption Standard PKCS #1", Crypto 98 * * Create it here instead if in the catch clause as otherwise we * expose a timing channel WRT the generation of the fake value. * Some timing channel likely remains due to exception handling * and the like. */ secure_vector<byte> fake_pre_master = rng.random_vec(48); fake_pre_master[0] = client_version.major_version(); fake_pre_master[1] = client_version.minor_version(); try { if(state.version() == Protocol_Version::SSL_V3) { m_pre_master = decryptor.decrypt(contents); } else { TLS_Data_Reader reader(contents); m_pre_master = decryptor.decrypt(reader.get_range<byte>(2, 0, 65535)); } if(m_pre_master.size() != 48 || client_version.major_version() != m_pre_master[0] || client_version.minor_version() != m_pre_master[1]) { throw Decoding_Error("Client_Key_Exchange: Secret corrupted"); } } catch(...) { m_pre_master = fake_pre_master; } } else { TLS_Data_Reader reader(contents); SymmetricKey psk; if(kex_algo == "PSK" || kex_algo == "DHE_PSK" || kex_algo == "ECDHE_PSK") { const std::string psk_identity = reader.get_string(2, 0, 65535); psk = creds.psk("tls-server", state.client_hello()->sni_hostname(), psk_identity); if(psk.length() == 0) { if(policy.hide_unknown_users()) psk = SymmetricKey(rng, 16); else throw TLS_Exception(Alert::UNKNOWN_PSK_IDENTITY, "No PSK for identifier " + psk_identity); } } if(kex_algo == "PSK") { std::vector<byte> zeros(psk.length()); append_tls_length_value(m_pre_master, zeros, 2); append_tls_length_value(m_pre_master, psk.bits_of(), 2); } else if(kex_algo == "SRP_SHA") { SRP6_Server_Session& srp = state.server_kex()->server_srp_params(); m_pre_master = srp.step2(BigInt::decode(reader.get_range<byte>(2, 0, 65535))).bits_of(); } else if(kex_algo == "DH" || kex_algo == "DHE_PSK" || kex_algo == "ECDH" || kex_algo == "ECDHE_PSK") { const Private_Key& private_key = state.server_kex()->server_kex_key(); const PK_Key_Agreement_Key* ka_key = dynamic_cast<const PK_Key_Agreement_Key*>(&private_key); if(!ka_key) throw Internal_Error("Expected key agreement key type but got " + private_key.algo_name()); try { PK_Key_Agreement ka(*ka_key, "Raw"); std::vector<byte> client_pubkey; if(ka_key->algo_name() == "DH") client_pubkey = reader.get_range<byte>(2, 0, 65535); else client_pubkey = reader.get_range<byte>(1, 0, 255); secure_vector<byte> shared_secret = ka.derive_key(0, client_pubkey).bits_of(); if(ka_key->algo_name() == "DH") shared_secret = strip_leading_zeros(shared_secret); if(kex_algo == "DHE_PSK" || kex_algo == "ECDHE_PSK") { append_tls_length_value(m_pre_master, shared_secret, 2); append_tls_length_value(m_pre_master, psk.bits_of(), 2); } else m_pre_master = shared_secret; } catch(std::exception &e) { /* * Something failed in the DH computation. To avoid possible * timing attacks, randomize the pre-master output and carry * on, allowing the protocol to fail later in the finished * checks. */ m_pre_master = rng.random_vec(ka_key->public_value().size()); } } else throw Internal_Error("Client_Key_Exchange: Unknown kex type " + kex_algo); } } } } <|endoftext|>
<commit_before>/************************************************************************* * * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * Copyright 2000, 2010 Oracle and/or its affiliates. * * OpenOffice.org - a multi-platform office productivity suite * * 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 _DBGLOOP_HXX #define _DBGLOOP_HXX #ifdef DBG_UTIL #include <tools/solar.h> class SvStream; #define DBG_MAX_STACK 20 // Verschachtelungstiefe #define DBG_MAX_LOOP 1000 // das Abbruchkriterium class DbgLoopStack { sal_uInt16 aCount[DBG_MAX_STACK]; sal_uInt16 nPtr; const void *pDbg; void Reset(); public: DbgLoopStack(); void Push( const void *pThis ); void Pop(); void Print( SvStream &rOS ) const; //$ ostream }; class DbgLoop { friend inline void PrintLoopStack( SvStream &rOS ); //$ ostream static DbgLoopStack aDbgLoopStack; public: inline DbgLoop( const void *pThis ) { aDbgLoopStack.Push( pThis ); } inline ~DbgLoop() { aDbgLoopStack.Pop(); } }; inline void PrintLoopStack( SvStream &rOS ) //$ ostream { DbgLoop::aDbgLoopStack.Print( rOS ); } #define DBG_LOOP DbgLoop aDbgLoop( (const void*)this ); #define DBG_LOOP_RESET DbgLoop aDbgLoop( 0 ); #else #define DBG_LOOP #define DBG_LOOP_RESET #endif #endif <commit_msg>Remove unused dbgloop.hxx from repository<commit_after><|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: porfly.hxx,v $ * * $Revision: 1.1.1.1 $ * * last change: $Author: hr $ $Date: 2000-09-19 00:08:25 $ * * 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 _PORFLY_HXX #define _PORFLY_HXX #include "porglue.hxx" class SwDrawContact; class SwFrmFmt; class SwFlyInCntFrm; /************************************************************************* * class SwFlyPortion *************************************************************************/ class SwFlyPortion : public SwFixPortion { KSHORT nBlankWidth; public: inline SwFlyPortion( const SwRect &rFlyRect ) : SwFixPortion(rFlyRect), nBlankWidth( 0 ) { SetWhichPor( POR_FLY ); } inline const KSHORT GetBlankWidth( ) const { return nBlankWidth; } inline void SetBlankWidth( const KSHORT nNew ) { nBlankWidth = nNew; } virtual void Paint( const SwTxtPaintInfo &rInf ) const; virtual sal_Bool Format( SwTxtFormatInfo &rInf ); #ifdef OLDRECYCLE virtual sal_Bool MayRecycle() const; #endif OUTPUT_OPERATOR }; /************************************************************************* * class SwFlyCntPortion *************************************************************************/ #define SETBASE_NOFLAG 0 #define SETBASE_QUICK 1 #define SETBASE_ULSPACE 2 #define SETBASE_INIT 4 class SwFlyCntPortion : public SwLinePortion { void *pContact; // bDraw ? DrawContact : FlyInCntFrm Point aRef; // Relativ zu diesem Point wird die AbsPos berechnet. sal_Bool bDraw : 1; // DrawContact? sal_Bool bMax : 1; // Zeilenausrichtung und Hoehe == Zeilenhoehe sal_uInt8 nAlign : 3; // Zeilenausrichtung? Nein, oben, mitte, unten virtual xub_StrLen GetCrsrOfst( const KSHORT nOfst ) const; public: SwFlyCntPortion( SwFlyInCntFrm *pFly, const Point &rBase, long nAscent, long nDescent, long nFlyAsc, long nFlyDesc, sal_Bool bQuick = sal_False ); SwFlyCntPortion( SwDrawContact *pDrawContact, const Point &rBase, long nAscent, long nDescent, long nFlyAsc, long nFlyDesc, sal_Bool bQuick = sal_False ); inline const Point& GetRefPoint() const { return aRef; } inline SwFlyInCntFrm *GetFlyFrm() { return (SwFlyInCntFrm*)pContact; } inline const SwFlyInCntFrm *GetFlyFrm() const { return (SwFlyInCntFrm*)pContact; } inline SwDrawContact *GetDrawContact() { return (SwDrawContact*)pContact; } inline const SwDrawContact* GetDrawContact() const { return (SwDrawContact*)pContact; } inline const sal_Bool IsDraw() const { return bDraw; } inline const sal_Bool IsMax() const { return bMax; } inline const sal_uInt8 GetAlign() const { return nAlign; } inline void SetAlign( sal_uInt8 nNew ) { nAlign = nNew; } inline void SetMax( sal_Bool bNew ) { bMax = bNew; } void SetBase( const Point &rBase, long nLnAscent, long nLnDescent, long nFlyAscent, long nFlyDescent, sal_uInt8 nFlags ); const SwFrmFmt *GetFrmFmt() const; xub_StrLen GetFlyCrsrOfst( const KSHORT nOfst, const Point &rPoint, SwPosition *pPos, const SwCrsrMoveState* pCMS ) const; virtual sal_Bool Format( SwTxtFormatInfo &rInf ); virtual void Paint( const SwTxtPaintInfo &rInf ) const; OUTPUT_OPERATOR }; CLASSIO( SwFlyPortion ) CLASSIO( SwFlyCntPortion ) #endif <commit_msg>New: Rotated text with frame as character inside<commit_after>/************************************************************************* * * $RCSfile: porfly.hxx,v $ * * $Revision: 1.2 $ * * last change: $Author: ama $ $Date: 2001-02-01 14:11:20 $ * * 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 _PORFLY_HXX #define _PORFLY_HXX #include "porglue.hxx" class SwDrawContact; class SwFrmFmt; class SwFlyInCntFrm; /************************************************************************* * class SwFlyPortion *************************************************************************/ class SwFlyPortion : public SwFixPortion { KSHORT nBlankWidth; public: inline SwFlyPortion( const SwRect &rFlyRect ) : SwFixPortion(rFlyRect), nBlankWidth( 0 ) { SetWhichPor( POR_FLY ); } inline const KSHORT GetBlankWidth( ) const { return nBlankWidth; } inline void SetBlankWidth( const KSHORT nNew ) { nBlankWidth = nNew; } virtual void Paint( const SwTxtPaintInfo &rInf ) const; virtual sal_Bool Format( SwTxtFormatInfo &rInf ); #ifdef OLDRECYCLE virtual sal_Bool MayRecycle() const; #endif OUTPUT_OPERATOR }; /************************************************************************* * class SwFlyCntPortion *************************************************************************/ #define SETBASE_NOFLAG 0 #define SETBASE_QUICK 1 #define SETBASE_ULSPACE 2 #define SETBASE_INIT 4 #define SETBASE_ROTATE 8 #define SETBASE_REVERSE 16 class SwFlyCntPortion : public SwLinePortion { void *pContact; // bDraw ? DrawContact : FlyInCntFrm Point aRef; // Relativ zu diesem Point wird die AbsPos berechnet. sal_Bool bDraw : 1; // DrawContact? sal_Bool bMax : 1; // Zeilenausrichtung und Hoehe == Zeilenhoehe sal_uInt8 nAlign : 3; // Zeilenausrichtung? Nein, oben, mitte, unten virtual xub_StrLen GetCrsrOfst( const KSHORT nOfst ) const; public: SwFlyCntPortion( SwFlyInCntFrm *pFly, const Point &rBase, long nAscent, long nDescent, long nFlyAsc, long nFlyDesc, sal_uInt8 nFlags ); SwFlyCntPortion( SwDrawContact *pDrawContact, const Point &rBase, long nAscent, long nDescent, long nFlyAsc, long nFlyDesc, sal_uInt8 nFlags ); inline const Point& GetRefPoint() const { return aRef; } inline SwFlyInCntFrm *GetFlyFrm() { return (SwFlyInCntFrm*)pContact; } inline const SwFlyInCntFrm *GetFlyFrm() const { return (SwFlyInCntFrm*)pContact; } inline SwDrawContact *GetDrawContact() { return (SwDrawContact*)pContact; } inline const SwDrawContact* GetDrawContact() const { return (SwDrawContact*)pContact; } inline const sal_Bool IsDraw() const { return bDraw; } inline const sal_Bool IsMax() const { return bMax; } inline const sal_uInt8 GetAlign() const { return nAlign; } inline void SetAlign( sal_uInt8 nNew ) { nAlign = nNew; } inline void SetMax( sal_Bool bNew ) { bMax = bNew; } void SetBase( const Point &rBase, long nLnAscent, long nLnDescent, long nFlyAscent, long nFlyDescent, sal_uInt8 nFlags ); const SwFrmFmt *GetFrmFmt() const; xub_StrLen GetFlyCrsrOfst( const KSHORT nOfst, const Point &rPoint, SwPosition *pPos, const SwCrsrMoveState* pCMS ) const; virtual sal_Bool Format( SwTxtFormatInfo &rInf ); virtual void Paint( const SwTxtPaintInfo &rInf ) const; OUTPUT_OPERATOR }; CLASSIO( SwFlyPortion ) CLASSIO( SwFlyCntPortion ) #endif <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: porrst.hxx,v $ * * $Revision: 1.16 $ * * last change: $Author: rt $ $Date: 2005-09-09 05:02:07 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ #ifndef _PORRST_HXX #define _PORRST_HXX #ifndef _SVARRAY_HXX //autogen #include <svtools/svarray.hxx> #endif #include "porlay.hxx" #include "porexp.hxx" #ifdef VERTICAL_LAYOUT #define LINE_BREAK_WIDTH 150 #define SPECIAL_FONT_HEIGHT 200 #endif class SwTxtFormatInfo; /************************************************************************* * class SwTmpEndPortion *************************************************************************/ class SwTmpEndPortion : public SwLinePortion { public: SwTmpEndPortion( const SwLinePortion &rPortion ); virtual void Paint( const SwTxtPaintInfo &rInf ) const; OUTPUT_OPERATOR }; /************************************************************************* * class SwBreakPortion *************************************************************************/ class SwBreakPortion : public SwLinePortion { public: SwBreakPortion( const SwLinePortion &rPortion ); // liefert 0 zurueck, wenn keine Nutzdaten enthalten sind. virtual SwLinePortion *Compress(); virtual void Paint( const SwTxtPaintInfo &rInf ) const; virtual sal_Bool Format( SwTxtFormatInfo &rInf ); virtual KSHORT GetViewWidth( const SwTxtSizeInfo &rInf ) const; virtual xub_StrLen GetCrsrOfst( const MSHORT nOfst ) const; // Accessibility: pass information about this portion to the PortionHandler virtual void HandlePortion( SwPortionHandler& rPH ) const; OUTPUT_OPERATOR }; /************************************************************************* * class SwKernPortion *************************************************************************/ class SwKernPortion : public SwLinePortion { short nKern; sal_Bool bBackground; #ifdef VERTICAL_LAYOUT sal_Bool bGridKern; #endif public: #ifdef VERTICAL_LAYOUT // This constructor automatically appends the portion to rPortion // bBG indicates, that the background of the kerning portion has to // be painted, e.g., if the portion if positioned between to fields. // bGridKern indicates, that the kerning portion is used to provide // additional space in grid mode. SwKernPortion( SwLinePortion &rPortion, short nKrn, sal_Bool bBG = sal_False, sal_Bool bGridKern = sal_False ); // This constructor only sets the height and ascent to the values // of rPortion. It is only used for kerning portions for grid mode SwKernPortion( const SwLinePortion &rPortion ); #else SwKernPortion( SwLinePortion &rPortion, short nKrn, sal_Bool bBG = sal_False ); #endif virtual void FormatEOL( SwTxtFormatInfo &rInf ); virtual void Paint( const SwTxtPaintInfo &rInf ) const; OUTPUT_OPERATOR }; /************************************************************************* * class SwArrowPortion *************************************************************************/ class SwArrowPortion : public SwLinePortion { Point aPos; sal_Bool bLeft; public: SwArrowPortion( const SwLinePortion &rPortion ); SwArrowPortion( const SwTxtPaintInfo &rInf ); virtual void Paint( const SwTxtPaintInfo &rInf ) const; virtual SwLinePortion *Compress(); inline sal_Bool IsLeft() const { return bLeft; } inline const Point& GetPos() const { return aPos; } OUTPUT_OPERATOR }; /************************************************************************* * class SwHangingPortion * The characters which are forbidden at the start of a line like the dot and * other punctuation marks are allowed to display in the margin of the page * by a user option. * The SwHangingPortion is the corresponding textportion to do that. *************************************************************************/ class SwHangingPortion : public SwTxtPortion { KSHORT nInnerWidth; public: inline SwHangingPortion( SwPosSize aSize ) : nInnerWidth( aSize.Width() ) { SetWhichPor( POR_HNG ); SetLen( 1 ); Height( aSize.Height() ); } inline KSHORT GetInnerWidth() const { return nInnerWidth; } }; /************************************************************************* * class SwHiddenTextPortion * Is used to hide text *************************************************************************/ class SwHiddenTextPortion : public SwLinePortion { public: inline SwHiddenTextPortion( xub_StrLen nLen ) { SetWhichPor( POR_HIDDEN_TXT ); SetLen( nLen ); } virtual void Paint( const SwTxtPaintInfo &rInf ) const; virtual sal_Bool Format( SwTxtFormatInfo &rInf ); }; /************************************************************************* * inline - Implementations *************************************************************************/ CLASSIO( SwBreakPortion ) CLASSIO( SwEndPortion ) CLASSIO( SwKernPortion ) CLASSIO( SwArrowPortion ) #endif <commit_msg>INTEGRATION: CWS thaiissues (1.16.34); FILE MERGED 2005/10/25 06:46:21 fme 1.16.34.1: #i55716# Feature - Control characters<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: porrst.hxx,v $ * * $Revision: 1.17 $ * * last change: $Author: obo $ $Date: 2005-11-16 09:31:27 $ * * 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 _PORRST_HXX #define _PORRST_HXX #ifndef _SVARRAY_HXX //autogen #include <svtools/svarray.hxx> #endif #include "porlay.hxx" #include "porexp.hxx" #ifdef VERTICAL_LAYOUT #define LINE_BREAK_WIDTH 150 #define SPECIAL_FONT_HEIGHT 200 #endif class SwTxtFormatInfo; /************************************************************************* * class SwTmpEndPortion *************************************************************************/ class SwTmpEndPortion : public SwLinePortion { public: SwTmpEndPortion( const SwLinePortion &rPortion ); virtual void Paint( const SwTxtPaintInfo &rInf ) const; OUTPUT_OPERATOR }; /************************************************************************* * class SwBreakPortion *************************************************************************/ class SwBreakPortion : public SwLinePortion { public: SwBreakPortion( const SwLinePortion &rPortion ); // liefert 0 zurueck, wenn keine Nutzdaten enthalten sind. virtual SwLinePortion *Compress(); virtual void Paint( const SwTxtPaintInfo &rInf ) const; virtual sal_Bool Format( SwTxtFormatInfo &rInf ); virtual KSHORT GetViewWidth( const SwTxtSizeInfo &rInf ) const; virtual xub_StrLen GetCrsrOfst( const MSHORT nOfst ) const; // Accessibility: pass information about this portion to the PortionHandler virtual void HandlePortion( SwPortionHandler& rPH ) const; OUTPUT_OPERATOR }; /************************************************************************* * class SwKernPortion *************************************************************************/ class SwKernPortion : public SwLinePortion { short nKern; sal_Bool bBackground; #ifdef VERTICAL_LAYOUT sal_Bool bGridKern; #endif public: #ifdef VERTICAL_LAYOUT // This constructor automatically appends the portion to rPortion // bBG indicates, that the background of the kerning portion has to // be painted, e.g., if the portion if positioned between to fields. // bGridKern indicates, that the kerning portion is used to provide // additional space in grid mode. SwKernPortion( SwLinePortion &rPortion, short nKrn, sal_Bool bBG = sal_False, sal_Bool bGridKern = sal_False ); // This constructor only sets the height and ascent to the values // of rPortion. It is only used for kerning portions for grid mode SwKernPortion( const SwLinePortion &rPortion ); #else SwKernPortion( SwLinePortion &rPortion, short nKrn, sal_Bool bBG = sal_False ); #endif virtual void FormatEOL( SwTxtFormatInfo &rInf ); virtual void Paint( const SwTxtPaintInfo &rInf ) const; OUTPUT_OPERATOR }; /************************************************************************* * class SwArrowPortion *************************************************************************/ class SwArrowPortion : public SwLinePortion { Point aPos; sal_Bool bLeft; public: SwArrowPortion( const SwLinePortion &rPortion ); SwArrowPortion( const SwTxtPaintInfo &rInf ); virtual void Paint( const SwTxtPaintInfo &rInf ) const; virtual SwLinePortion *Compress(); inline sal_Bool IsLeft() const { return bLeft; } inline const Point& GetPos() const { return aPos; } OUTPUT_OPERATOR }; /************************************************************************* * class SwHangingPortion * The characters which are forbidden at the start of a line like the dot and * other punctuation marks are allowed to display in the margin of the page * by a user option. * The SwHangingPortion is the corresponding textportion to do that. *************************************************************************/ class SwHangingPortion : public SwTxtPortion { KSHORT nInnerWidth; public: inline SwHangingPortion( SwPosSize aSize ) : nInnerWidth( aSize.Width() ) { SetWhichPor( POR_HNG ); SetLen( 1 ); Height( aSize.Height() ); } inline KSHORT GetInnerWidth() const { return nInnerWidth; } }; /************************************************************************* * class SwHiddenTextPortion * Is used to hide text *************************************************************************/ class SwHiddenTextPortion : public SwLinePortion { public: inline SwHiddenTextPortion( xub_StrLen nLen ) { SetWhichPor( POR_HIDDEN_TXT ); SetLen( nLen ); } virtual void Paint( const SwTxtPaintInfo &rInf ) const; virtual sal_Bool Format( SwTxtFormatInfo &rInf ); }; /************************************************************************* * class SwControlCharPortion *************************************************************************/ class SwControlCharPortion : public SwLinePortion { private: mutable USHORT mnViewWidth; // used to cache a calculated value mutable USHORT mnHalfCharWidth; // used to cache a calculated value sal_Unicode mcChar; public: inline SwControlCharPortion( sal_Unicode cChar ) : mnViewWidth( 0 ), mnHalfCharWidth( 0 ), mcChar( cChar ) { SetWhichPor( POR_CONTROLCHAR ); SetLen( 1 ); } virtual void Paint( const SwTxtPaintInfo &rInf ) const; virtual sal_Bool Format( SwTxtFormatInfo &rInf ); virtual KSHORT GetViewWidth( const SwTxtSizeInfo& rInf ) const; }; /************************************************************************* * inline - Implementations *************************************************************************/ CLASSIO( SwBreakPortion ) CLASSIO( SwEndPortion ) CLASSIO( SwKernPortion ) CLASSIO( SwArrowPortion ) #endif <|endoftext|>
<commit_before>/* * Copyright 2012 Google Inc. * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include "SkNullCanvas.h" #include "SkCanvas.h" #include "SKNWayCanvas.h" SkCanvas* SkCreateNullCanvas() { // An N-Way canvas forwards calls to N canvas's. When N == 0 it's // effectively a null canvas. return SkNEW(SkNWayCanvas(0,0)); } <commit_msg>fix SkNWayCanvas cons call again.<commit_after>/* * Copyright 2012 Google Inc. * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include "SkNullCanvas.h" #include "SkCanvas.h" #include "SKNWayCanvas.h" SkCanvas* SkCreateNullCanvas() { // An N-Way canvas forwards calls to N canvas's. When N == 0 it's // effectively a null canvas. return SkNEW_ARGS(SkNWayCanvas, (0,0)); } <|endoftext|>
<commit_before>#ifndef __JSON_HPP__ #define __JSON_HPP__ #include <cctype> #include <string> #include <vector> #include <array> #include <regex> namespace JSON { using namespace std; struct Error {}; struct SyntaxError : public Error {}; struct LoadError : public Error {}; struct AccessError : public Error {}; template<typename _Value, char const ..._szName> struct Field { static char const s_szName; typedef _Value Type; }; template<char const ..._sz> struct FieldName {}; template<typename _Name, typename ..._Fields> struct FieldType {}; template<typename _Value, char const ..._szName, typename ..._OtherFields> struct FieldType<FieldName<_szName...>, Field<_Value, _szName...>, _OtherFields...> { typedef _Value Type; }; template<char const ..._szFieldName, typename _FirstField, typename ..._OtherFields> struct FieldType<FieldName<_szFieldName...>, _FirstField, _OtherFields...> { typedef typename FieldType<FieldName<_szFieldName...>, _OtherFields...>::Type Type; }; template<typename _Value, char const ..._szName> char const Field<_Value, _szName...>::s_szName = { _szName... }; template<typename ..._Fields> struct Object {}; template<typename _Field, typename ..._Fields> struct Getter {}; template<typename _Value, char const ..._szName, typename ..._OtherFields> struct Getter<Field<_Value, _szName...>, Field<_Value, _szName...>, _OtherFields...> { inline static _Value &Get(Object<Field<_Value, _szName...>, _OtherFields...> &rObject) { return rObject.m_Value; } inline static _Value const &Get(Object<Field<_Value, _szName...>, _OtherFields...> const &rObject) { return rObject.m_Value; } }; template<typename _Value, char const ..._szName, typename _FirstField, typename ..._OtherFields> struct Getter<Field<_Value, _szName...>, _FirstField, _OtherFields...> { inline static _Value &Get(Object<_FirstField, _OtherFields...> &rObject) { return Getter<Field<_Value, _szName...>, _OtherFields...>::Get(rObject); } inline static _Value const &Get(Object<_FirstField, _OtherFields...> const &rObject) { return Getter<Field<_Value, _szName...>, _FirstField, _OtherFields...>::Get(rObject); } }; template<> struct Object<> { Object() {} virtual ~Object() {} }; template<typename _Value, char const ..._szName, typename ..._OtherFields> struct Object<Field<_Value, _szName...>, _OtherFields...> : public Object<_OtherFields...> { static char const s_szName[]; _Value m_Value; Object() {} virtual ~Object() {} template<char const ..._szFieldName> inline typename FieldType<FieldName<_szFieldName...>, Field<_Value, _szName...>, _OtherFields...>::Type &Get() { return Getter< Field<typename FieldType< FieldName<_szFieldName...>, Field<_Value, _szName...>, _OtherFields... >::Type, _szFieldName...>, Field<_Value, _szName...>, _OtherFields... >::Get(*this); } template<char const ..._szFieldName> inline typename FieldType<FieldName<_szFieldName...>, Field<_Value, _szName...>, _OtherFields...>::Type const &Get() const { return Getter< Field<typename FieldType< FieldName<_szFieldName...>, Field<_Value, _szName...>, _OtherFields... >::Type, _szFieldName...>, Field<_Value, _szName...>, _OtherFields... >::Get(*this); } }; template<typename _Value, char const ..._szName, typename ..._OtherFields> char const Object<Field<_Value, _szName...>, _OtherFields...>::s_szName[] = { _szName... }; template<typename _Type> struct Serializer { static _Type Load(istream &ris); static ostream &Store(ostream &ros, _Type const &r); }; template<> struct Serializer<nullptr_t> { static nullptr_t Load(istream &ris) { // TODO throw Error(); } static ostream &Store(ostream &ros, nullptr_t const &r) { return ros << "null"; } }; template<> struct Serializer<bool> { static bool Load(istream &ris) { // TODO throw Error(); } static ostream &Store(ostream &ros, bool const &r) { if (r) { return ros << "true"; } else { return ros << "false"; } } }; template<> struct Serializer<int> { static int Load(istream &ris) { // TODO throw Error(); } static ostream &Store(ostream &ros, int const &r) { return ros << r; } }; template<> struct Serializer<unsigned int> { static unsigned int Load(istream &ris) { // TODO throw Error(); } static ostream &Store(ostream &ros, unsigned int const &r) { return ros << r; } }; template<> struct Serializer<double> { static double Load(istream &ris) { // TODO throw Error(); } static ostream &Store(ostream &ros, double const &r) { return ros << r; } }; template<> struct Serializer<string> { static string Load(istream &ris) { // TODO throw Error(); } static ostream &Store(ostream &ros, string const &r) { return ros << '\"' << r << '\"'; // FIXME escape special characters } }; template<typename ..._Fields> struct Serializer<Object<_Fields...>> { static Object<_Fields...> Load(istream &ris) { // TODO throw Error(); } }; template<typename _Element> struct Serializer<vector<_Element>> { static vector<_Element> Load(istream &ris) { // TODO throw Error(); } }; template<typename _Element, unsigned int _c> struct Serializer<array<_Element, _c>> { static array<_Element, _c> Load(istream &ris) { // TODO throw Error(); } }; template<typename _Type> inline _Type Load(istream &ris) { return Serializer<_Type>::Load(ris); } template<typename _Type> inline ostream &Store(ostream &ros, _Type const &r) { return Serializer<_Type>::Store(ros, r); } } #define UNPACK(sz) (sz)[0], ((sz)[0] > 0) ? UNPACK((sz) + 1) : 0 #endif <commit_msg>I/O shift operators<commit_after>#ifndef __JSON_HPP__ #define __JSON_HPP__ #include <cctype> #include <iostream> #include <string> #include <vector> #include <array> #include <regex> namespace JSON { using namespace std; struct Error {}; struct SyntaxError : public Error {}; struct LoadError : public Error {}; struct AccessError : public Error {}; template<typename _Value, char const ..._szName> struct Field { static char const s_szName; typedef _Value Type; }; template<char const ..._sz> struct FieldName {}; template<typename _Name, typename ..._Fields> struct FieldType {}; template<typename _Value, char const ..._szName, typename ..._OtherFields> struct FieldType<FieldName<_szName...>, Field<_Value, _szName...>, _OtherFields...> { typedef _Value Type; }; template<char const ..._szFieldName, typename _FirstField, typename ..._OtherFields> struct FieldType<FieldName<_szFieldName...>, _FirstField, _OtherFields...> { typedef typename FieldType<FieldName<_szFieldName...>, _OtherFields...>::Type Type; }; template<typename _Value, char const ..._szName> char const Field<_Value, _szName...>::s_szName = { _szName... }; template<typename ..._Fields> struct Object {}; template<typename _Field, typename ..._Fields> struct Getter {}; template<typename _Value, char const ..._szName, typename ..._OtherFields> struct Getter<Field<_Value, _szName...>, Field<_Value, _szName...>, _OtherFields...> { inline static _Value &Get(Object<Field<_Value, _szName...>, _OtherFields...> &rObject) { return rObject.m_Value; } inline static _Value const &Get(Object<Field<_Value, _szName...>, _OtherFields...> const &rObject) { return rObject.m_Value; } }; template<typename _Value, char const ..._szName, typename _FirstField, typename ..._OtherFields> struct Getter<Field<_Value, _szName...>, _FirstField, _OtherFields...> { inline static _Value &Get(Object<_FirstField, _OtherFields...> &rObject) { return Getter<Field<_Value, _szName...>, _OtherFields...>::Get(rObject); } inline static _Value const &Get(Object<_FirstField, _OtherFields...> const &rObject) { return Getter<Field<_Value, _szName...>, _FirstField, _OtherFields...>::Get(rObject); } }; template<> struct Object<> { Object() {} virtual ~Object() {} }; template<typename _Value, char const ..._szName, typename ..._OtherFields> struct Object<Field<_Value, _szName...>, _OtherFields...> : public Object<_OtherFields...> { static char const s_szName[]; _Value m_Value; Object() {} virtual ~Object() {} template<char const ..._szFieldName> inline typename FieldType<FieldName<_szFieldName...>, Field<_Value, _szName...>, _OtherFields...>::Type &Get() { return Getter< Field<typename FieldType< FieldName<_szFieldName...>, Field<_Value, _szName...>, _OtherFields... >::Type, _szFieldName...>, Field<_Value, _szName...>, _OtherFields... >::Get(*this); } template<char const ..._szFieldName> inline typename FieldType<FieldName<_szFieldName...>, Field<_Value, _szName...>, _OtherFields...>::Type const &Get() const { return Getter< Field<typename FieldType< FieldName<_szFieldName...>, Field<_Value, _szName...>, _OtherFields... >::Type, _szFieldName...>, Field<_Value, _szName...>, _OtherFields... >::Get(*this); } }; template<typename _Value, char const ..._szName, typename ..._OtherFields> char const Object<Field<_Value, _szName...>, _OtherFields...>::s_szName[] = { _szName... }; template<typename _Type> struct Serializer { static _Type Load(istream &ris); static ostream &Store(ostream &ros, _Type const &r); }; template<> struct Serializer<nullptr_t> { static nullptr_t Load(istream &ris) { // TODO throw Error(); } static ostream &Store(ostream &ros, nullptr_t const &r) { return ros << "null"; } }; template<> struct Serializer<bool> { static bool Load(istream &ris) { // TODO throw Error(); } static ostream &Store(ostream &ros, bool const &r) { if (r) { return ros << "true"; } else { return ros << "false"; } } }; template<> struct Serializer<int> { static int Load(istream &ris) { // TODO throw Error(); } static ostream &Store(ostream &ros, int const &r) { return ros << r; } }; template<> struct Serializer<unsigned int> { static unsigned int Load(istream &ris) { // TODO throw Error(); } static ostream &Store(ostream &ros, unsigned int const &r) { return ros << r; } }; template<> struct Serializer<double> { static double Load(istream &ris) { // TODO throw Error(); } static ostream &Store(ostream &ros, double const &r) { return ros << r; } }; template<> struct Serializer<string> { static string Load(istream &ris) { // TODO throw Error(); } static ostream &Store(ostream &ros, string const &r) { return ros << '\"' << r << '\"'; // FIXME escape special characters } }; template<typename ..._Fields> struct Serializer<Object<_Fields...>> { static Object<_Fields...> Load(istream &ris) { // TODO throw Error(); } }; template<typename _Element> struct Serializer<vector<_Element>> { static vector<_Element> Load(istream &ris) { // TODO throw Error(); } }; template<typename _Element, unsigned int _c> struct Serializer<array<_Element, _c>> { static array<_Element, _c> Load(istream &ris) { // TODO throw Error(); } }; template<typename _Type> inline _Type Load(istream &ris) { return Serializer<_Type>::Load(ris); } template<typename _Type> inline ostream &Store(ostream &ros, _Type const &r) { return Serializer<_Type>::Store(ros, r); } } template<typename ..._Fields> inline std::istream &operator >> (std::istream &ris, JSON::Object<_Fields...> &rObject) { rObject = JSON::Load<JSON::Object<_Fields...>>(ris); return ris; } template<typename ..._Fields> inline std::ostream &operator << (std::ostream &ros, JSON::Object<_Fields...> &rObject) { return JSON::Store<JSON::Object<_Fields...>>(ros, rObject); } #define UNPACK(sz) (sz)[0], ((sz)[0] > 0) ? UNPACK((sz) + 1) : 0 #endif <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: lateinitthread.cxx,v $ * * $Revision: 1.3 $ * * last change: $Author: rt $ $Date: 2004-05-12 08:00:08 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (the "License"); You may not use this file * except in compliance with the License. You may obtain a copy of the * License at http://www.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #include "lateinitthread.hxx" //_______________________________________________ // includes //_______________________________________________ // namespace namespace filter{ namespace config{ namespace css = ::com::sun::star; //_______________________________________________ // definitions /*----------------------------------------------- 14.08.2003 09:31 -----------------------------------------------*/ LateInitThread::LateInitThread() { } /*----------------------------------------------- 14.08.2003 08:42 -----------------------------------------------*/ LateInitThread::~LateInitThread() { } /*----------------------------------------------- 28.10.2003 09:30 -----------------------------------------------*/ void SAL_CALL LateInitThread::run() { try { // sal_True => It indicates using of this method by this thread // The filter cache use this information to show an assertion // for "optimization failure" in case the first calli of loadAll() // was not this thread ... ::salhelper::SingletonRef< FilterCache > rCache; rCache->load(FilterCache::E_CONTAINS_ALL); } catch(const css::uno::Exception&) { OSL_ENSURE(sal_False, "Filter cache could not be filled successfully! Might this office will run into some trouble ..."); } } } // namespace config } // namespace filter <commit_msg>INTEGRATION: CWS fwklhf01 (1.3.24); FILE MERGED 2004/06/18 13:14:50 as 1.3.24.1: #115305# make shure, that filter cache isnt created more then once ...<commit_after>/************************************************************************* * * $RCSfile: lateinitthread.cxx,v $ * * $Revision: 1.4 $ * * last change: $Author: hr $ $Date: 2004-07-23 11:12:10 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (the "License"); You may not use this file * except in compliance with the License. You may obtain a copy of the * License at http://www.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #include "lateinitthread.hxx" //_______________________________________________ // includes //_______________________________________________ // namespace namespace filter{ namespace config{ namespace css = ::com::sun::star; //_______________________________________________ // definitions /*----------------------------------------------- 14.08.2003 09:31 -----------------------------------------------*/ LateInitThread::LateInitThread() { } /*----------------------------------------------- 14.08.2003 08:42 -----------------------------------------------*/ LateInitThread::~LateInitThread() { } /*----------------------------------------------- 28.10.2003 09:30 -----------------------------------------------*/ void SAL_CALL LateInitThread::run() { // sal_True => It indicates using of this method by this thread // The filter cache use this information to show an assertion // for "optimization failure" in case the first calli of loadAll() // was not this thread ... // Further please dont catch any exception here. // May be they show the problem of a corrupted filter // configuration, which is handled inside our event loop or desktop.main()! ::salhelper::SingletonRef< FilterCache > rCache; rCache->load(FilterCache::E_CONTAINS_ALL, sal_True); } } // namespace config } // namespace filter <|endoftext|>
<commit_before>/************************************************************************** ** This file is part of LiteIDE ** ** Copyright (c) 2011-2016 LiteIDE Team. All rights reserved. ** ** This library is free software; you can redistribute it and/or ** modify it under the terms of the GNU Lesser General Public ** License as published by the Free Software Foundation; either ** version 2.1 of the License, or (at your option) any later version. ** ** This library is distributed in the hope that it will be useful, ** but WITHOUT ANY WARRANTY; without even the implied warranty of ** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU ** Lesser General Public License for more details. ** ** In addition, as a special exception, that plugins developed for LiteIDE, ** are allowed to remain closed sourced and can be distributed under any license . ** These rights are included in the file LGPL_EXCEPTION.txt in this package. ** **************************************************************************/ // Module: litetabwidget.cpp // Creator: visualfc <visualfc@gmail.com> #include "litetabwidget.h" #include "liteapi/liteapi.h" #include <QTabBar> #include <QHBoxLayout> #include <QVBoxLayout> #include <QStackedLayout> #include <QStackedWidget> #include <QToolButton> #include <QPushButton> #include <QToolBar> #include <QAction> #include <QActionGroup> #include <QMenu> #include <QKeyEvent> #include <QDebug> //lite_memory_check_begin #if defined(WIN32) && defined(_MSC_VER) && defined(_DEBUG) #define _CRTDBG_MAP_ALLOC #include <stdlib.h> #include <crtdbg.h> #define DEBUG_NEW new( _NORMAL_BLOCK, __FILE__, __LINE__ ) #define new DEBUG_NEW #endif //lite_memory_check_end LiteTabWidget::LiteTabWidget(QSize iconSize, QObject *parent) : QObject(parent) { m_tabBar = new TabBar; m_tabBar->setExpanding(false); m_tabBar->setDocumentMode(true); m_tabBar->setDrawBase(false); m_tabBar->setUsesScrollButtons(true); m_tabBar->setMovable(true); m_tabBar->setSelectionBehaviorOnRemove(QTabBar::SelectPreviousTab); m_dumpToolBar = new QToolBar; m_dumpToolBar->setObjectName("toolbar.tabs"); m_dumpToolBar->setIconSize(iconSize); m_tabBarWidget = new QWidget; m_addTabAct = new QAction(QIcon("icon:images/addpage.png"),tr("Open a new tab"),this); m_listButton = new QToolButton(m_dumpToolBar); m_listButton->setToolTip(tr("List All Tabs")); m_listButton->setIcon(QIcon("icon:images/listpage.png")); m_listButton->setPopupMode(QToolButton::InstantPopup); m_listButton->setStyleSheet( "QToolButton{border:none;}" "QToolButton::menu-indicator{image:none;}"); m_closeTabAct = new QAction(QIcon("icon:images/closetool.png"),tr("Close Tab"),this); m_closeButton = new QToolButton(m_dumpToolBar); m_closeButton->setDefaultAction(m_closeTabAct); m_closeButton->setStyleSheet( "QToolButton{border:none;}"); QHBoxLayout *layout = new QHBoxLayout; layout->setMargin(0); layout->setSpacing(0); layout->addWidget(m_tabBar,1); layout->addWidget(m_listButton); layout->addWidget(m_closeButton); m_tabBarWidget->setLayout(layout); m_stackedWidget = new QStackedWidget; connect(m_tabBar,SIGNAL(currentChanged(int)),this,SLOT(tabCurrentChanged(int))); connect(m_tabBar,SIGNAL(tabCloseRequested(int)),this,SIGNAL(tabCloseRequested(int))); connect(m_tabBar,SIGNAL(tabMoved(int,int)),this,SLOT(tabMoved(int,int))); connect(m_closeTabAct,SIGNAL(triggered()),this,SLOT(closeCurrentTab())); connect(m_addTabAct,SIGNAL(triggered()),this,SIGNAL(tabAddRequest())); m_listButton->setEnabled(false); } LiteTabWidget::~LiteTabWidget() { delete m_tabBarWidget; delete m_dumpToolBar; } void LiteTabWidget::closeCurrentTab() { int index = m_tabBar->currentIndex(); if (index < 0) { return; } emit tabCloseRequested(index); } int LiteTabWidget::addTab(QWidget *w,const QString & label, const QString &tip) { return addTab(w,QIcon(),label,tip); } int LiteTabWidget::addTab(QWidget *w,const QIcon & icon, const QString & label, const QString &tip) { if (!w) { return -1; } if (m_widgetList.size() == 0) { m_listButton->setEnabled(true); } int index = m_tabBar->addTab(icon,label); if (!tip.isEmpty()) { m_tabBar->setTabToolTip(index,tip); } m_stackedWidget->addWidget(w); m_widgetList.append(w); return index; } void LiteTabWidget::removeTab(int index) { if (index < 0) return; QWidget *w = widget(index); if (w) { m_stackedWidget->removeWidget(w); m_widgetList.removeAt(index); } if (m_widgetList.size() == 0) { m_listButton->setEnabled(false); } m_tabBar->removeTab(index); } QWidget *LiteTabWidget::currentWidget() { return m_stackedWidget->currentWidget(); } TabBar *LiteTabWidget::tabBar() { return m_tabBar; } QList<QWidget*> LiteTabWidget::widgetList() const { return m_widgetList; } QWidget *LiteTabWidget::stackedWidget() { return m_stackedWidget; } QWidget *LiteTabWidget::tabBarWidget() { return m_tabBarWidget; } void LiteTabWidget::setListMenu(QMenu *menu) { m_listButton->setMenu(menu); } void LiteTabWidget::setTabText(int index, const QString & text) { m_tabBar->setTabText(index,text); } int LiteTabWidget::indexOf(QWidget *w) { return m_widgetList.indexOf(w); } QWidget *LiteTabWidget::widget(int index) { return m_widgetList.value(index); } void LiteTabWidget::setCurrentWidget(QWidget *w) { int index = indexOf(w); if (index < 0) return; setCurrentIndex(index); } void LiteTabWidget::tabCurrentChanged(int index) { QWidget *w = m_widgetList.value(index); if (w) { m_stackedWidget->setCurrentWidget(w); } emit currentChanged(index); } void LiteTabWidget::setCurrentIndex(int index) { m_tabBar->setCurrentIndex(index); } void LiteTabWidget::tabMoved(int from, int to) { m_widgetList.swap(from,to); } <commit_msg>liteapp update css<commit_after>/************************************************************************** ** This file is part of LiteIDE ** ** Copyright (c) 2011-2016 LiteIDE Team. All rights reserved. ** ** This library is free software; you can redistribute it and/or ** modify it under the terms of the GNU Lesser General Public ** License as published by the Free Software Foundation; either ** version 2.1 of the License, or (at your option) any later version. ** ** This library is distributed in the hope that it will be useful, ** but WITHOUT ANY WARRANTY; without even the implied warranty of ** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU ** Lesser General Public License for more details. ** ** In addition, as a special exception, that plugins developed for LiteIDE, ** are allowed to remain closed sourced and can be distributed under any license . ** These rights are included in the file LGPL_EXCEPTION.txt in this package. ** **************************************************************************/ // Module: litetabwidget.cpp // Creator: visualfc <visualfc@gmail.com> #include "litetabwidget.h" #include "liteapi/liteapi.h" #include <QTabBar> #include <QHBoxLayout> #include <QVBoxLayout> #include <QStackedLayout> #include <QStackedWidget> #include <QToolButton> #include <QPushButton> #include <QToolBar> #include <QAction> #include <QActionGroup> #include <QMenu> #include <QKeyEvent> #include <QDebug> //lite_memory_check_begin #if defined(WIN32) && defined(_MSC_VER) && defined(_DEBUG) #define _CRTDBG_MAP_ALLOC #include <stdlib.h> #include <crtdbg.h> #define DEBUG_NEW new( _NORMAL_BLOCK, __FILE__, __LINE__ ) #define new DEBUG_NEW #endif //lite_memory_check_end LiteTabWidget::LiteTabWidget(QSize iconSize, QObject *parent) : QObject(parent) { m_tabBar = new TabBar; m_tabBar->setExpanding(false); m_tabBar->setDocumentMode(true); m_tabBar->setDrawBase(false); m_tabBar->setUsesScrollButtons(true); m_tabBar->setMovable(true); m_tabBar->setSelectionBehaviorOnRemove(QTabBar::SelectPreviousTab); m_dumpToolBar = new QToolBar; m_dumpToolBar->setObjectName("toolbar.tabs"); m_dumpToolBar->setIconSize(iconSize); m_tabBarWidget = new QWidget; m_addTabAct = new QAction(QIcon("icon:images/addpage.png"),tr("Open a new tab"),this); m_listButton = new QToolButton(m_dumpToolBar); m_listButton->setToolTip(tr("List All Tabs")); m_listButton->setIcon(QIcon("icon:images/listpage.png")); m_listButton->setPopupMode(QToolButton::InstantPopup); #ifdef Q_OS_MAC m_listButton->setStyleSheet( "QToolButton{border:none;}" "QToolButton::menu-indicator{image:none;}"); #else m_listButton->setStyleSheet( "QToolButton::menu-indicator{image:none;}"); #endif m_closeTabAct = new QAction(QIcon("icon:images/closetool.png"),tr("Close Tab"),this); m_closeButton = new QToolButton(m_dumpToolBar); m_closeButton->setDefaultAction(m_closeTabAct); #ifdef Q_OS_MAC m_closeButton->setStyleSheet( "QToolButton{border:none;}"); #endif QHBoxLayout *layout = new QHBoxLayout; layout->setMargin(0); layout->setSpacing(0); layout->addWidget(m_tabBar,1); layout->addWidget(m_listButton); layout->addWidget(m_closeButton); m_tabBarWidget->setLayout(layout); m_stackedWidget = new QStackedWidget; connect(m_tabBar,SIGNAL(currentChanged(int)),this,SLOT(tabCurrentChanged(int))); connect(m_tabBar,SIGNAL(tabCloseRequested(int)),this,SIGNAL(tabCloseRequested(int))); connect(m_tabBar,SIGNAL(tabMoved(int,int)),this,SLOT(tabMoved(int,int))); connect(m_closeTabAct,SIGNAL(triggered()),this,SLOT(closeCurrentTab())); connect(m_addTabAct,SIGNAL(triggered()),this,SIGNAL(tabAddRequest())); m_listButton->setEnabled(false); } LiteTabWidget::~LiteTabWidget() { delete m_tabBarWidget; delete m_dumpToolBar; } void LiteTabWidget::closeCurrentTab() { int index = m_tabBar->currentIndex(); if (index < 0) { return; } emit tabCloseRequested(index); } int LiteTabWidget::addTab(QWidget *w,const QString & label, const QString &tip) { return addTab(w,QIcon(),label,tip); } int LiteTabWidget::addTab(QWidget *w,const QIcon & icon, const QString & label, const QString &tip) { if (!w) { return -1; } if (m_widgetList.size() == 0) { m_listButton->setEnabled(true); } int index = m_tabBar->addTab(icon,label); if (!tip.isEmpty()) { m_tabBar->setTabToolTip(index,tip); } m_stackedWidget->addWidget(w); m_widgetList.append(w); return index; } void LiteTabWidget::removeTab(int index) { if (index < 0) return; QWidget *w = widget(index); if (w) { m_stackedWidget->removeWidget(w); m_widgetList.removeAt(index); } if (m_widgetList.size() == 0) { m_listButton->setEnabled(false); } m_tabBar->removeTab(index); } QWidget *LiteTabWidget::currentWidget() { return m_stackedWidget->currentWidget(); } TabBar *LiteTabWidget::tabBar() { return m_tabBar; } QList<QWidget*> LiteTabWidget::widgetList() const { return m_widgetList; } QWidget *LiteTabWidget::stackedWidget() { return m_stackedWidget; } QWidget *LiteTabWidget::tabBarWidget() { return m_tabBarWidget; } void LiteTabWidget::setListMenu(QMenu *menu) { m_listButton->setMenu(menu); } void LiteTabWidget::setTabText(int index, const QString & text) { m_tabBar->setTabText(index,text); } int LiteTabWidget::indexOf(QWidget *w) { return m_widgetList.indexOf(w); } QWidget *LiteTabWidget::widget(int index) { return m_widgetList.value(index); } void LiteTabWidget::setCurrentWidget(QWidget *w) { int index = indexOf(w); if (index < 0) return; setCurrentIndex(index); } void LiteTabWidget::tabCurrentChanged(int index) { QWidget *w = m_widgetList.value(index); if (w) { m_stackedWidget->setCurrentWidget(w); } emit currentChanged(index); } void LiteTabWidget::setCurrentIndex(int index) { m_tabBar->setCurrentIndex(index); } void LiteTabWidget::tabMoved(int from, int to) { m_widgetList.swap(from,to); } <|endoftext|>
<commit_before><commit_msg>Improve logging<commit_after><|endoftext|>
<commit_before><commit_msg>Fix regression introduced by swapping Close and Quit in the messagebox a few lines above. Quit is now KMessageBox::No<commit_after><|endoftext|>
<commit_before>/** * \file * \brief Scheduler class implementation * * \author Copyright (C) 2014 Kamil Szczygiel http://www.distortec.com http://www.freddiechopin.info * * \par License * 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/. * * \date 2014-09-16 */ #include "distortos/scheduler/Scheduler.hpp" #include "distortos/scheduler/Thread.hpp" #include "distortos/scheduler/SoftwareTimer.hpp" #include "distortos/scheduler/MainThreadControlBlock.hpp" #include "distortos/architecture/InterruptMaskingLock.hpp" #include "distortos/architecture/InterruptUnmaskingLock.hpp" #include <cerrno> namespace distortos { namespace scheduler { /*---------------------------------------------------------------------------------------------------------------------+ | public functions +---------------------------------------------------------------------------------------------------------------------*/ Scheduler::Scheduler(MainThreadControlBlock& mainThreadControlBlock, Thread<void (&)()>& idleThread) : currentThreadControlBlock_{}, threadControlBlockListAllocatorPool_{}, threadControlBlockListAllocator_{threadControlBlockListAllocatorPool_}, runnableList_{threadControlBlockListAllocator_, ThreadControlBlock::State::Runnable}, suspendedList_{threadControlBlockListAllocator_, ThreadControlBlock::State::Suspended}, softwareTimerControlBlockSupervisor_{}, tickCount_{0} { add(mainThreadControlBlock); currentThreadControlBlock_ = runnableList_.begin(); idleThread.start(); architecture::startScheduling(); } void Scheduler::add(ThreadControlBlock& threadControlBlock) { threadControlBlock.getRoundRobinQuantum().reset(); architecture::InterruptMaskingLock interruptMaskingLock; threadControlBlockListAllocatorPool_.feed(threadControlBlock.getLink()); runnableList_.sortedEmplace(threadControlBlock); maybeRequestContextSwitch(); } void Scheduler::block(ThreadControlBlockList& container) { block(container, currentThreadControlBlock_); } int Scheduler::block(ThreadControlBlockList& container, const ThreadControlBlockListIterator iterator) { { architecture::InterruptMaskingLock interruptMaskingLock; const auto ret = blockInternal(container, iterator); if (ret != 0) return ret; if (iterator != currentThreadControlBlock_) // blocked thread is not current thread - no forced switch required return 0; } forceContextSwitch(); return 0; } int Scheduler::blockUntil(ThreadControlBlockList& container, const TickClock::time_point timePoint) { architecture::InterruptMaskingLock interruptMaskingLock; const auto iterator = currentThreadControlBlock_; bool timedOut {}; // This lambda unblocks the thread only if it wasn't already unblocked - this is necessary because double unblock // should be avoided (it could mess the order of threads of the same priority). In that case it also marks the // "timed out" reason of unblocking. auto softwareTimer = makeSoftwareTimer( [this, iterator, &timedOut]() { if (iterator->get().getList() != &runnableList_) { unblockInternal(iterator); timedOut = true; } }); softwareTimer.start(timePoint); block(container); return timedOut == false ? 0 : ETIMEDOUT; } uint64_t Scheduler::getTickCount() const { architecture::InterruptMaskingLock interruptMaskingLock; return tickCount_; } int Scheduler::remove() { { architecture::InterruptMaskingLock interruptMaskingLock; ThreadControlBlockList terminatedList {threadControlBlockListAllocator_, ThreadControlBlock::State::Terminated}; const auto ret = blockInternal(terminatedList, currentThreadControlBlock_); if (ret != 0) return ret; terminatedList.begin()->get().terminationHook(); } forceContextSwitch(); return 0; } int Scheduler::resume(const ThreadControlBlockListIterator iterator) { architecture::InterruptMaskingLock interruptMaskingLock; if (iterator->get().getList() != &suspendedList_) return EINVAL; unblock(iterator); return 0; } void Scheduler::suspend() { suspend(currentThreadControlBlock_); } int Scheduler::suspend(const ThreadControlBlockListIterator iterator) { return block(suspendedList_, iterator); } void* Scheduler::switchContext(void* const stackPointer) { architecture::InterruptMaskingLock interruptMaskingLock; getCurrentThreadControlBlock().getStack().setStackPointer(stackPointer); currentThreadControlBlock_ = runnableList_.begin(); return getCurrentThreadControlBlock().getStack().getStackPointer(); } bool Scheduler::tickInterruptHandler() { architecture::InterruptMaskingLock interruptMaskingLock; ++tickCount_; getCurrentThreadControlBlock().getRoundRobinQuantum().decrement(); // if the object is on the "runnable" list and it used its round-robin quantum, then do the "rotation": move current // thread to the end of same-priority group to implement round-robin scheduling if (getCurrentThreadControlBlock().getList() == &runnableList_ && getCurrentThreadControlBlock().getRoundRobinQuantum().isZero() == true) runnableList_.sortedSplice(runnableList_, currentThreadControlBlock_); softwareTimerControlBlockSupervisor_.tickInterruptHandler(TickClock::time_point{TickClock::duration{tickCount_}}); return isContextSwitchRequired(); } void Scheduler::unblock(const ThreadControlBlockListIterator iterator) { architecture::InterruptMaskingLock interruptMaskingLock; unblockInternal(iterator); maybeRequestContextSwitch(); } void Scheduler::yield() { architecture::InterruptMaskingLock interruptMaskingLock; runnableList_.sortedSplice(runnableList_, currentThreadControlBlock_); maybeRequestContextSwitch(); } /*---------------------------------------------------------------------------------------------------------------------+ | private functions +---------------------------------------------------------------------------------------------------------------------*/ int Scheduler::blockInternal(ThreadControlBlockList& container, const ThreadControlBlockListIterator iterator) { if (iterator->get().getList() != &runnableList_) return EINVAL; container.sortedSplice(runnableList_, iterator); return 0; } void Scheduler::forceContextSwitch() const { architecture::InterruptUnmaskingLock interruptUnmaskingLock; architecture::requestContextSwitch(); } bool Scheduler::isContextSwitchRequired() const { // this check must be first, because during early startup currentThreadControlBlock_ is not yet initialized (so // futher conditions would dereference nullptr) and no threads are available if (runnableList_.size() <= 1) // no threads or single thread available? return false; // no context switch possible if (getCurrentThreadControlBlock().getList() != &runnableList_) return true; if (runnableList_.begin() != currentThreadControlBlock_) // is there a higher-priority thread available? return true; if (getCurrentThreadControlBlock().getRoundRobinQuantum().isZero() == true) { const auto nextThread = ++runnableList_.begin(); const auto nextThreadPriority = nextThread->get().getPriority(); // thread with same priority available? if (getCurrentThreadControlBlock().getPriority() == nextThreadPriority) return true; // switch context to do round-robin scheduling } return false; } void Scheduler::maybeRequestContextSwitch() const { if (isContextSwitchRequired() == true) architecture::requestContextSwitch(); } void Scheduler::unblockInternal(const ThreadControlBlockListIterator iterator) { runnableList_.sortedSplice(*iterator->get().getList(), iterator); iterator->get().getRoundRobinQuantum().reset(); } } // namespace scheduler } // namespace distortos <commit_msg>Scheduler: remove redundant call to RoundRobinQuantum::reset() in Scheduler::add()<commit_after>/** * \file * \brief Scheduler class implementation * * \author Copyright (C) 2014 Kamil Szczygiel http://www.distortec.com http://www.freddiechopin.info * * \par License * 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/. * * \date 2014-09-16 */ #include "distortos/scheduler/Scheduler.hpp" #include "distortos/scheduler/Thread.hpp" #include "distortos/scheduler/SoftwareTimer.hpp" #include "distortos/scheduler/MainThreadControlBlock.hpp" #include "distortos/architecture/InterruptMaskingLock.hpp" #include "distortos/architecture/InterruptUnmaskingLock.hpp" #include <cerrno> namespace distortos { namespace scheduler { /*---------------------------------------------------------------------------------------------------------------------+ | public functions +---------------------------------------------------------------------------------------------------------------------*/ Scheduler::Scheduler(MainThreadControlBlock& mainThreadControlBlock, Thread<void (&)()>& idleThread) : currentThreadControlBlock_{}, threadControlBlockListAllocatorPool_{}, threadControlBlockListAllocator_{threadControlBlockListAllocatorPool_}, runnableList_{threadControlBlockListAllocator_, ThreadControlBlock::State::Runnable}, suspendedList_{threadControlBlockListAllocator_, ThreadControlBlock::State::Suspended}, softwareTimerControlBlockSupervisor_{}, tickCount_{0} { add(mainThreadControlBlock); currentThreadControlBlock_ = runnableList_.begin(); idleThread.start(); architecture::startScheduling(); } void Scheduler::add(ThreadControlBlock& threadControlBlock) { architecture::InterruptMaskingLock interruptMaskingLock; threadControlBlockListAllocatorPool_.feed(threadControlBlock.getLink()); runnableList_.sortedEmplace(threadControlBlock); maybeRequestContextSwitch(); } void Scheduler::block(ThreadControlBlockList& container) { block(container, currentThreadControlBlock_); } int Scheduler::block(ThreadControlBlockList& container, const ThreadControlBlockListIterator iterator) { { architecture::InterruptMaskingLock interruptMaskingLock; const auto ret = blockInternal(container, iterator); if (ret != 0) return ret; if (iterator != currentThreadControlBlock_) // blocked thread is not current thread - no forced switch required return 0; } forceContextSwitch(); return 0; } int Scheduler::blockUntil(ThreadControlBlockList& container, const TickClock::time_point timePoint) { architecture::InterruptMaskingLock interruptMaskingLock; const auto iterator = currentThreadControlBlock_; bool timedOut {}; // This lambda unblocks the thread only if it wasn't already unblocked - this is necessary because double unblock // should be avoided (it could mess the order of threads of the same priority). In that case it also marks the // "timed out" reason of unblocking. auto softwareTimer = makeSoftwareTimer( [this, iterator, &timedOut]() { if (iterator->get().getList() != &runnableList_) { unblockInternal(iterator); timedOut = true; } }); softwareTimer.start(timePoint); block(container); return timedOut == false ? 0 : ETIMEDOUT; } uint64_t Scheduler::getTickCount() const { architecture::InterruptMaskingLock interruptMaskingLock; return tickCount_; } int Scheduler::remove() { { architecture::InterruptMaskingLock interruptMaskingLock; ThreadControlBlockList terminatedList {threadControlBlockListAllocator_, ThreadControlBlock::State::Terminated}; const auto ret = blockInternal(terminatedList, currentThreadControlBlock_); if (ret != 0) return ret; terminatedList.begin()->get().terminationHook(); } forceContextSwitch(); return 0; } int Scheduler::resume(const ThreadControlBlockListIterator iterator) { architecture::InterruptMaskingLock interruptMaskingLock; if (iterator->get().getList() != &suspendedList_) return EINVAL; unblock(iterator); return 0; } void Scheduler::suspend() { suspend(currentThreadControlBlock_); } int Scheduler::suspend(const ThreadControlBlockListIterator iterator) { return block(suspendedList_, iterator); } void* Scheduler::switchContext(void* const stackPointer) { architecture::InterruptMaskingLock interruptMaskingLock; getCurrentThreadControlBlock().getStack().setStackPointer(stackPointer); currentThreadControlBlock_ = runnableList_.begin(); return getCurrentThreadControlBlock().getStack().getStackPointer(); } bool Scheduler::tickInterruptHandler() { architecture::InterruptMaskingLock interruptMaskingLock; ++tickCount_; getCurrentThreadControlBlock().getRoundRobinQuantum().decrement(); // if the object is on the "runnable" list and it used its round-robin quantum, then do the "rotation": move current // thread to the end of same-priority group to implement round-robin scheduling if (getCurrentThreadControlBlock().getList() == &runnableList_ && getCurrentThreadControlBlock().getRoundRobinQuantum().isZero() == true) runnableList_.sortedSplice(runnableList_, currentThreadControlBlock_); softwareTimerControlBlockSupervisor_.tickInterruptHandler(TickClock::time_point{TickClock::duration{tickCount_}}); return isContextSwitchRequired(); } void Scheduler::unblock(const ThreadControlBlockListIterator iterator) { architecture::InterruptMaskingLock interruptMaskingLock; unblockInternal(iterator); maybeRequestContextSwitch(); } void Scheduler::yield() { architecture::InterruptMaskingLock interruptMaskingLock; runnableList_.sortedSplice(runnableList_, currentThreadControlBlock_); maybeRequestContextSwitch(); } /*---------------------------------------------------------------------------------------------------------------------+ | private functions +---------------------------------------------------------------------------------------------------------------------*/ int Scheduler::blockInternal(ThreadControlBlockList& container, const ThreadControlBlockListIterator iterator) { if (iterator->get().getList() != &runnableList_) return EINVAL; container.sortedSplice(runnableList_, iterator); return 0; } void Scheduler::forceContextSwitch() const { architecture::InterruptUnmaskingLock interruptUnmaskingLock; architecture::requestContextSwitch(); } bool Scheduler::isContextSwitchRequired() const { // this check must be first, because during early startup currentThreadControlBlock_ is not yet initialized (so // futher conditions would dereference nullptr) and no threads are available if (runnableList_.size() <= 1) // no threads or single thread available? return false; // no context switch possible if (getCurrentThreadControlBlock().getList() != &runnableList_) return true; if (runnableList_.begin() != currentThreadControlBlock_) // is there a higher-priority thread available? return true; if (getCurrentThreadControlBlock().getRoundRobinQuantum().isZero() == true) { const auto nextThread = ++runnableList_.begin(); const auto nextThreadPriority = nextThread->get().getPriority(); // thread with same priority available? if (getCurrentThreadControlBlock().getPriority() == nextThreadPriority) return true; // switch context to do round-robin scheduling } return false; } void Scheduler::maybeRequestContextSwitch() const { if (isContextSwitchRequired() == true) architecture::requestContextSwitch(); } void Scheduler::unblockInternal(const ThreadControlBlockListIterator iterator) { runnableList_.sortedSplice(*iterator->get().getList(), iterator); iterator->get().getRoundRobinQuantum().reset(); } } // namespace scheduler } // namespace distortos <|endoftext|>
<commit_before>// stress inversion of matrices with varios methods #include "Math/SMatrix.h" #include "TMatrixTSym.h" #include "TDecompChol.h" #include "TDecompBK.h" #include "TRandom.h" #include <vector> #include <string> #include <iostream> #include <cmath> #include <limits> #include "TStopwatch.h" // matrix size #ifndef N #define N 5 #endif bool doSelfTest = true; //timer namespace test { #ifdef REPORT_TIME void reportTime( std::string s, double time); #endif void printTime(TStopwatch & time, std::string s) { int pr = std::cout.precision(8); std::cout << s << "\t" << " time = " << time.RealTime() << "\t(sec)\t" // << time.CpuTime() << std::endl; std::cout.precision(pr); } class Timer { public: Timer(const std::string & s = "") : fName(s), fTime(0) { fWatch.Start(); } Timer(double & t, const std::string & s = "") : fName(s), fTime(&t) { fWatch.Start(); } ~Timer() { fWatch.Stop(); printTime(fWatch,fName); #ifdef REPORT_TIME // report time reportTime(fName, fWatch.RealTime() ); #endif if (fTime) *fTime += fWatch.RealTime(); } private: std::string fName; double * fTime; TStopwatch fWatch; }; } using namespace ROOT::Math; typedef SMatrix<double,N,N, MatRepSym<double,N> > SymMatrix; // create matrix template<class M> M * createMatrix() { return new M(); } // specialized for TMatrix template<> TMatrixTSym<double> * createMatrix<TMatrixTSym<double> >() { return new TMatrixTSym<double>(N); } //print matrix template<class M> void printMatrix(const M & m) { std::cout << m << std::endl; } template<> void printMatrix<TMatrixTSym<double> >(const TMatrixTSym<double> & m ) { m.Print(); } // generate matrices template<class M> void genMatrix(M & m ) { TRandom & r = *gRandom; // generate first diagonal elemets for (int i = 0; i < N; ++i) { double maxVal = i*10000/(N-1) + 1; // max condition is 10^4 m(i,i) = r.Uniform(0, maxVal); } for (int i = 0; i < N; ++i) { for (int j = 0; j < i; ++j) { double v = 0.3*std::sqrt( m(i,i) * m(j,j) ); // this makes the matrix pos defined m(i,j) = r.Uniform(0, v); m(j,i) = m(i,j); // needed for TMatrix } } } // generate all matrices template<class M> void generate(std::vector<M*> & v) { int n = v.size(); gRandom->SetSeed(111); for (int i = 0; i < n; ++i) { v[i] = createMatrix<M>(); genMatrix(*v[i] ); } } struct Choleski {}; struct BK {}; struct QR {}; struct Cramer {}; struct Default {}; template <class M, class Type> struct TestInverter { static bool Inv ( const M & , M & ) { return false;} static bool Inv2 ( M & ) { return false;} }; template <> struct TestInverter<SymMatrix, Choleski> { static bool Inv ( const SymMatrix & m, SymMatrix & result ) { int ifail = 0; result = m.InverseChol(ifail); return ifail == 0; } static bool Inv2 ( SymMatrix & m ) { return m.InvertChol(); } }; template <> struct TestInverter<SymMatrix, BK> { static bool Inv ( const SymMatrix & m, SymMatrix & result ) { int ifail = 0; result = m.Inverse(ifail); return ifail==0; } static bool Inv2 ( SymMatrix & m ) { return m.Invert(); } }; template <> struct TestInverter<SymMatrix, Cramer> { static bool Inv ( const SymMatrix & m, SymMatrix & result ) { int ifail = 0; result = m.InverseFast(ifail); return ifail==0; } static bool Inv2 ( SymMatrix & m ) { return m.InvertFast(); } }; #ifdef LATER template <> struct TestInverter<SymMatrix, QR> { static bool Inv ( const SymMatrix & m, SymMatrix & result ) { ROOT::Math::QRDecomposition<double> d; int ifail = 0; result = m.InverseFast(ifail); return ifail==0; } }; #endif //TMatrix functions template <> struct TestInverter<TMatrixDSym, Default> { static bool Inv ( const TMatrixDSym & m, TMatrixDSym & result ) { result = m; result.Invert(); return true; } static bool Inv2 ( TMatrixDSym & m ) { m.Invert(); return true; } }; template <> struct TestInverter<TMatrixDSym, Cramer> { static bool Inv ( const TMatrixDSym & m, TMatrixDSym & result ) { result = m; result.InvertFast(); return true; } static bool Inv2 ( TMatrixDSym & m ) { m.InvertFast(); return true; } }; template <> struct TestInverter<TMatrixDSym, Choleski> { static bool Inv ( const TMatrixDSym & m, TMatrixDSym & result ) { TDecompChol chol(m); if (!chol.Decompose() ) return false; chol.Invert(result); return true; } }; template <> struct TestInverter<TMatrixDSym, BK> { static bool Inv ( const TMatrixDSym & m, TMatrixDSym & result ) { TDecompBK d(m); if (!d.Decompose() ) return false; d.Invert(result); return true; } }; template<class M, class T> double invert( const std::vector<M* > & matlist, double & time,std::string s) { M result = *(matlist.front()); test::Timer t(time,s); int nloop = matlist.size(); double sum = 0; for (int l = 0; l < nloop; l++) { const M & m = *(matlist[l]); bool ok = TestInverter<M,T>::Inv(m,result); if (!ok) { std::cout << "inv failed for matrix " << l << std::endl; printMatrix<M>( m); return -1; } sum += result(0,1); } return sum; } // invert without copying the matrices (une INv2) template<class M, class T> double invert2( const std::vector<M* > & matlist, double & time,std::string s) { // copy vector of matrices int nloop = matlist.size(); std::vector<M *> vmat(nloop); for (int l = 0; l < nloop; l++) { vmat[l] = new M( *matlist[l] ); } test::Timer t(time,s); double sum = 0; for (int l = 0; l < nloop; l++) { M & m = *(vmat[l]); bool ok = TestInverter<M,T>::Inv2(m); if (!ok) { std::cout << "inv failed for matrix " << l << std::endl; printMatrix<M>( m); return -1; } sum += m(0,1); } return sum; } bool equal(double d1, double d2, double stol = 10000) { std::cout.precision(12); // tolerance is 1E-12 double eps = stol * std::numeric_limits<double>::epsilon(); if ( std::abs(d1) > 0 && std::abs(d2) > 0 ) return ( std::abs( d1-d2) < eps * std::max(std::abs(d1), std::abs(d2) ) ); else if ( d1 == 0 ) return std::abs(d2) < eps; else // d2 = 0 return std::abs(d1) < eps; } // test matrices symmetric and positive defines bool stressSymPosInversion(int n, bool selftest ) { // test smatrix std::vector<SymMatrix *> v1(n); generate(v1); std::vector<TMatrixDSym *> v2(n); generate(v2); bool iret = true; double time = 0; double s1 = invert<SymMatrix, Choleski> (v1, time,"SMatrix Chol"); double s2 = invert<SymMatrix, BK> (v1, time,"SMatrix BK"); double s3 = invert<SymMatrix, Cramer> (v1, time,"SMatrix Cram"); bool ok = ( equal(s1,s2) && equal(s1,s3) ); if (!ok) { std::cout << "result SMatrix choleski " << s1 << " BK " << s2 << " cramer " << s3 << std::endl; std::cerr <<"Error: inversion test for SMatrix FAILED ! " << std::endl; } iret &= ok; std::cout << std::endl; double m1 = invert<TMatrixDSym, Choleski> (v2, time,"TMatrix Chol"); double m2 = invert<TMatrixDSym, BK> (v2, time,"TMatrix BK"); double m3 = invert<TMatrixDSym, Cramer> (v2, time,"TMatrix Cram"); double m4 = invert<TMatrixDSym, Default> (v2, time,"TMatrix Def"); ok = ( equal(m1,m2) && equal(m1,m3) && equal(m1,m4) ); if (!ok) { std::cout << "result TMatrix choleski " << m1 << " BK " << m2 << " cramer " << m3 << " default " << m4 << std::endl; std::cerr <<"Error: inversion test for TMatrix FAILED ! " << std::endl; } iret &= ok; std::cout << std::endl; // test using self inversion if (selftest) { std::cout << "\n - self inversion test \n"; double s11 = invert2<SymMatrix, Choleski> (v1, time,"SMatrix Chol"); double s12 = invert2<SymMatrix, BK> (v1, time,"SMatrix BK"); double s13 = invert2<SymMatrix, Cramer> (v1, time,"SMatrix Cram"); ok = ( equal(s11,s12) && equal(s11,s13) ); if (!ok) { std::cout << "result SMatrix choleski " << s11 << " BK " << s12 << " cramer " << s13 << std::endl; std::cerr <<"Error: self inversion test for SMatrix FAILED ! " << std::endl; } iret &= ok; std::cout << std::endl; double m13 = invert2<TMatrixDSym, Cramer> (v2, time,"TMatrix Cram"); double m14 = invert2<TMatrixDSym, Default> (v2, time,"TMatrix Def"); ok = ( equal(m13,m14) ); if (!ok) { std::cout << "result TMatrix cramer " << m13 << " default " << m14 << std::endl; std::cerr <<"Error: self inversion test for TMatrix FAILED ! " << std::endl; } iret &= ok; std::cout << std::endl; } return iret; } int testInversion(int n = 100000) { bool ok = stressSymPosInversion(n, doSelfTest); std::cerr << "Test inversion of positive defined matrix ( N = " << N << " ) ........ "; if (ok) std::cerr << "OK \n"; else std::cerr << "FAILED \n"; return (ok) ? 0 : -1; } int main() { return testInversion(); } <commit_msg>fix test error message<commit_after>// stress inversion of matrices with varios methods #include "Math/SMatrix.h" #include "TMatrixTSym.h" #include "TDecompChol.h" #include "TDecompBK.h" #include "TRandom.h" #include <vector> #include <string> #include <iostream> #include <cmath> #include <limits> #include "TStopwatch.h" // matrix size #ifndef N #define N 5 #endif bool doSelfTest = true; //timer namespace test { #ifdef REPORT_TIME void reportTime( std::string s, double time); #endif void printTime(TStopwatch & time, std::string s) { int pr = std::cout.precision(8); std::cout << s << "\t" << " time = " << time.RealTime() << "\t(sec)\t" // << time.CpuTime() << std::endl; std::cout.precision(pr); } class Timer { public: Timer(const std::string & s = "") : fName(s), fTime(0) { fWatch.Start(); } Timer(double & t, const std::string & s = "") : fName(s), fTime(&t) { fWatch.Start(); } ~Timer() { fWatch.Stop(); printTime(fWatch,fName); #ifdef REPORT_TIME // report time reportTime(fName, fWatch.RealTime() ); #endif if (fTime) *fTime += fWatch.RealTime(); } private: std::string fName; double * fTime; TStopwatch fWatch; }; } using namespace ROOT::Math; typedef SMatrix<double,N,N, MatRepSym<double,N> > SymMatrix; // create matrix template<class M> M * createMatrix() { return new M(); } // specialized for TMatrix template<> TMatrixTSym<double> * createMatrix<TMatrixTSym<double> >() { return new TMatrixTSym<double>(N); } //print matrix template<class M> void printMatrix(const M & m) { std::cout << m << std::endl; } template<> void printMatrix<TMatrixTSym<double> >(const TMatrixTSym<double> & m ) { m.Print(); } // generate matrices template<class M> void genMatrix(M & m ) { TRandom & r = *gRandom; // generate first diagonal elemets for (int i = 0; i < N; ++i) { double maxVal = i*10000/(N-1) + 1; // max condition is 10^4 m(i,i) = r.Uniform(0, maxVal); } for (int i = 0; i < N; ++i) { for (int j = 0; j < i; ++j) { double v = 0.3*std::sqrt( m(i,i) * m(j,j) ); // this makes the matrix pos defined m(i,j) = r.Uniform(0, v); m(j,i) = m(i,j); // needed for TMatrix } } } // generate all matrices template<class M> void generate(std::vector<M*> & v) { int n = v.size(); gRandom->SetSeed(111); for (int i = 0; i < n; ++i) { v[i] = createMatrix<M>(); genMatrix(*v[i] ); } } struct Choleski {}; struct BK {}; struct QR {}; struct Cramer {}; struct Default {}; template <class M, class Type> struct TestInverter { static bool Inv ( const M & , M & ) { return false;} static bool Inv2 ( M & ) { return false;} }; template <> struct TestInverter<SymMatrix, Choleski> { static bool Inv ( const SymMatrix & m, SymMatrix & result ) { int ifail = 0; result = m.InverseChol(ifail); return ifail == 0; } static bool Inv2 ( SymMatrix & m ) { return m.InvertChol(); } }; template <> struct TestInverter<SymMatrix, BK> { static bool Inv ( const SymMatrix & m, SymMatrix & result ) { int ifail = 0; result = m.Inverse(ifail); return ifail==0; } static bool Inv2 ( SymMatrix & m ) { return m.Invert(); } }; template <> struct TestInverter<SymMatrix, Cramer> { static bool Inv ( const SymMatrix & m, SymMatrix & result ) { int ifail = 0; result = m.InverseFast(ifail); return ifail==0; } static bool Inv2 ( SymMatrix & m ) { return m.InvertFast(); } }; #ifdef LATER template <> struct TestInverter<SymMatrix, QR> { static bool Inv ( const SymMatrix & m, SymMatrix & result ) { ROOT::Math::QRDecomposition<double> d; int ifail = 0; result = m.InverseFast(ifail); return ifail==0; } }; #endif //TMatrix functions template <> struct TestInverter<TMatrixDSym, Default> { static bool Inv ( const TMatrixDSym & m, TMatrixDSym & result ) { result = m; result.Invert(); return true; } static bool Inv2 ( TMatrixDSym & m ) { m.Invert(); return true; } }; template <> struct TestInverter<TMatrixDSym, Cramer> { static bool Inv ( const TMatrixDSym & m, TMatrixDSym & result ) { result = m; result.InvertFast(); return true; } static bool Inv2 ( TMatrixDSym & m ) { m.InvertFast(); return true; } }; template <> struct TestInverter<TMatrixDSym, Choleski> { static bool Inv ( const TMatrixDSym & m, TMatrixDSym & result ) { TDecompChol chol(m); if (!chol.Decompose() ) return false; chol.Invert(result); return true; } }; template <> struct TestInverter<TMatrixDSym, BK> { static bool Inv ( const TMatrixDSym & m, TMatrixDSym & result ) { TDecompBK d(m); if (!d.Decompose() ) return false; d.Invert(result); return true; } }; template<class M, class T> double invert( const std::vector<M* > & matlist, double & time,std::string s) { M result = *(matlist.front()); test::Timer t(time,s); int nloop = matlist.size(); double sum = 0; for (int l = 0; l < nloop; l++) { const M & m = *(matlist[l]); bool ok = TestInverter<M,T>::Inv(m,result); if (!ok) { std::cout << "inv failed for matrix " << l << std::endl; printMatrix<M>( m); return -1; } sum += result(0,1); } return sum; } // invert without copying the matrices (une INv2) template<class M, class T> double invert2( const std::vector<M* > & matlist, double & time,std::string s) { // copy vector of matrices int nloop = matlist.size(); std::vector<M *> vmat(nloop); for (int l = 0; l < nloop; l++) { vmat[l] = new M( *matlist[l] ); } test::Timer t(time,s); double sum = 0; for (int l = 0; l < nloop; l++) { M & m = *(vmat[l]); bool ok = TestInverter<M,T>::Inv2(m); if (!ok) { std::cout << "inv failed for matrix " << l << std::endl; printMatrix<M>( m); return -1; } sum += m(0,1); } return sum; } bool equal(double d1, double d2, double stol = 10000) { std::cout.precision(12); // tolerance is 1E-12 double eps = stol * std::numeric_limits<double>::epsilon(); if ( std::abs(d1) > 0 && std::abs(d2) > 0 ) return ( std::abs( d1-d2) < eps * std::max(std::abs(d1), std::abs(d2) ) ); else if ( d1 == 0 ) return std::abs(d2) < eps; else // d2 = 0 return std::abs(d1) < eps; } // test matrices symmetric and positive defines bool stressSymPosInversion(int n, bool selftest ) { // test smatrix std::vector<SymMatrix *> v1(n); generate(v1); std::vector<TMatrixDSym *> v2(n); generate(v2); bool iret = true; double time = 0; double s1 = invert<SymMatrix, Choleski> (v1, time,"SMatrix Chol"); double s2 = invert<SymMatrix, BK> (v1, time,"SMatrix BK"); double s3 = invert<SymMatrix, Cramer> (v1, time,"SMatrix Cram"); bool ok = ( equal(s1,s2) && equal(s1,s3) ); if (!ok) { std::cout << "result SMatrix choleski " << s1 << " BK " << s2 << " cramer " << s3 << std::endl; std::cerr <<"Error: inversion test for SMatrix FAILED ! " << std::endl; } iret &= ok; std::cout << std::endl; double m1 = invert<TMatrixDSym, Choleski> (v2, time,"TMatrix Chol"); double m2 = invert<TMatrixDSym, BK> (v2, time,"TMatrix BK"); double m3 = invert<TMatrixDSym, Cramer> (v2, time,"TMatrix Cram"); double m4 = invert<TMatrixDSym, Default> (v2, time,"TMatrix Def"); ok = ( equal(m1,m2) && equal(m1,m3) && equal(m1,m4) ); if (!ok) { std::cout << "result TMatrix choleski " << m1 << " BK " << m2 << " cramer " << m3 << " default " << m4 << std::endl; std::cerr <<"Error: inversion test for TMatrix FAILED ! " << std::endl; } iret &= ok; std::cout << std::endl; // test using self inversion if (selftest) { std::cout << "\n - self inversion test \n"; double s11 = invert2<SymMatrix, Choleski> (v1, time,"SMatrix Chol"); double s12 = invert2<SymMatrix, BK> (v1, time,"SMatrix BK"); double s13 = invert2<SymMatrix, Cramer> (v1, time,"SMatrix Cram"); ok = ( equal(s11,s12) && equal(s11,s13) ); if (!ok) { std::cout << "result SMatrix choleski " << s11 << " BK " << s12 << " cramer " << s13 << std::endl; std::cerr <<"Error: self inversion test for SMatrix FAILED ! " << std::endl; } iret &= ok; std::cout << std::endl; double m13 = invert2<TMatrixDSym, Cramer> (v2, time,"TMatrix Cram"); double m14 = invert2<TMatrixDSym, Default> (v2, time,"TMatrix Def"); ok = ( equal(m13,m14) ); if (!ok) { std::cout << "result TMatrix cramer " << m13 << " default " << m14 << std::endl; std::cerr <<"Error: self inversion test for TMatrix FAILED ! " << std::endl; } iret &= ok; std::cout << std::endl; } return iret; } int testInversion(int n = 100000) { std::cout << "Test Inversion for matrix with N = " << N << std::endl; bool ok = stressSymPosInversion(n, doSelfTest); std::cerr << "Test inversion of positive defined matrix ....... "; if (ok) std::cerr << "OK \n"; else std::cerr << "FAILED \n"; return (ok) ? 0 : -1; } int main() { return testInversion(); } <|endoftext|>
<commit_before>// Project specific #include <Server.hpp> #include <Doremi/Core/Include/GameCore.hpp> #include <Doremi/Core/Include/EntityComponent/Components/TransformComponent.hpp> #include <Doremi/Core/Include/EntityComponent/EntityHandlerServer.hpp> #include <Doremi/Core/Include/EventHandler/EventHandler.hpp> #include <Doremi/Core/Include/EventHandler/Events/EntityCreatedEvent.hpp> #include <Doremi/Core/Include/PlayerHandler.hpp> #include <Doremi/Core/Include/Manager/Manager.hpp> #include <Doremi/Core/Include/Manager/Network/ServerNetworkManager.hpp> #include <Doremi/Core/Include/Manager/MovementManager.hpp> #include <Doremi/Core/Include/Manager/RigidTransformSyncManager.hpp> #include <DoremiEngine/Core/Include/Subsystem/EngineModuleEnum.hpp> #include <Doremi/Core/Include/TemplateCreator.hpp> #include <Doremi/Core/Include/EntityComponent/Components/PhysicsMaterialComponent.hpp> #include <Doremi/Core/Include/EntityComponent/Components/RigidBodyComponent.hpp> #include <DoremiEngine/Physics/Include/PhysicsModule.hpp> #include <DoremiEngine/Physics/Include/RigidBodyManager.hpp> #include <DoremiEngine/Physics/Include/CharacterControlManager.hpp> #include <Doremi/Core/Include/Manager/AI/AIPathManager.hpp> #include <Doremi/Core/Include/Manager/CharacterControlSyncManager.hpp> #include <Doremi/Core/Include/InputHandlerClient.hpp> #include <Doremi/Core/Include/EntityComponent/Components/PotentialFieldComponent.hpp> #include <DoremiEngine/AI/Include/Interface/SubModule/PotentialFieldSubModule.hpp> #include <DoremiEngine/AI/Include/AIModule.hpp> #include <Doremi/Core/Include/Manager/JumpManager.hpp> #include <Doremi/Core/Include/Manager/GravityManager.hpp> #include <Doremi/Core/Include/EntityComponent/EntityFactory.hpp> #include <Doremi/Core/Include/LevelLoaderServer.hpp> #include <DoremiEngine/Physics/Include/FluidManager.hpp> // Timer #include <Utility/Timer/Include/Measure/MeasureTimer.hpp> // Third party #include <DirectXMath.h> // Standard libraries #include <stdexcept> #include <exception> #include <chrono> namespace Doremi { ServerMain::ServerMain() {} ServerMain::~ServerMain() {} void ServerMain::Initialize() { TIME_FUNCTION_START const DoremiEngine::Core::SharedContext& sharedContext = InitializeEngine( DoremiEngine::Core::EngineModuleEnum::NETWORK | DoremiEngine::Core::EngineModuleEnum::PHYSICS | DoremiEngine::Core::EngineModuleEnum::AI); /* This starts the physics handler. Should not be done here, but since this is the general code dump, it'll work for now TODOJB*/ Core::EntityHandlerServer::StartupEntityHandlerServer(); Core::PlayerHandler::StartPlayerHandler(sharedContext); ////////////////Example only//////////////// // Create manager // Manager* t_physicsManager = new ExampleManager(sharedContext); Core::Manager* t_serverNetworkManager = new Core::ServerNetworkManager(sharedContext); Core::Manager* t_movementManager = new Core::MovementManager(sharedContext); Core::Manager* t_rigidTransSyndManager = new Core::RigidTransformSyncManager(sharedContext); Core::Manager* t_aiPathManager = new Core::AIPathManager(sharedContext); Core::Manager* t_charSyncManager = new Core::CharacterControlSyncManager(sharedContext); // TODO check if needed Core::Manager* t_jumpManager = new Core::JumpManager(sharedContext); Core::Manager* t_gravManager = new Core::GravityManager(sharedContext); // Add manager to list of managers // Remember to put server last (cause we want on same frame as we update to send data, or at least close togeather) // m_managers.push_back(t_physicsManager); m_managers.push_back(t_serverNetworkManager); m_managers.push_back(t_rigidTransSyndManager); m_managers.push_back(t_movementManager); m_managers.push_back(t_aiPathManager); m_managers.push_back(t_charSyncManager); m_managers.push_back(t_jumpManager); m_managers.push_back(t_gravManager); // GenerateWorld(sharedContext); // GenerateWorldServerJawsTest(sharedContext); Core::TemplateCreator::GetInstance()->CreateTemplatesForServer(sharedContext); SpawnDebugWorld(sharedContext); ////////////////End Example//////////////// // Remove later, needed to see something when we play solo cause of camera interactions with input // Doremi::Core::InputHandlerClient* inputHandler = new Doremi::Core::InputHandlerClient(sharedContext); // Core::PlayerHandler::GetInstance()->CreateNewPlayer(300, (Doremi::Core::InputHandler*)inputHandler); TIME_FUNCTION_STOP } void ServerMain::SpawnDebugWorld(const DoremiEngine::Core::SharedContext& sharedContext) { TIME_FUNCTION_START Core::EntityFactory& t_entityFactory = *Core::EntityFactory::GetInstance(); Core::LevelLoaderServer* t_levelLoader = new Core::LevelLoaderServer(sharedContext); t_levelLoader->LoadLevel("Levels/test.drm"); // Create entity // int playerID = t_entityHandler.CreateEntity(Blueprints::PlayerEntity); //// Create the rigid body // int materialID = t_entityHandler.GetComponentFromStorage<Core::PhysicsMaterialComponent>(playerID)->p_materialID; // DirectX::XMFLOAT3 position = DirectX::XMFLOAT3(0, 10, 0); // DirectX::XMFLOAT4 orientation = DirectX::XMFLOAT4(0, 0, 0, 1); // Core::RigidBodyComponent* bodyComp = t_entityHandler.GetComponentFromStorage<Core::RigidBodyComponent>(playerID); /*bodyComp->p_bodyID = sharedContext.GetPhysicsModule().GetRigidBodyManager().AddBoxBodyDynamic(playerID, position, orientation, DirectX::XMFLOAT3(0.5, 0.5, 0.5), materialID);*/ // sharedContext.GetPhysicsModule().GetCharacterControlManager().AddController(playerID, materialID, position, XMFLOAT2(1, 1)); // Core::EntityHandler::GetInstance().AddComponent(playerID, (int)ComponentType::CharacterController); int entityDebugJaws = t_entityFactory.CreateEntity(Blueprints::JawsDebugEntity); Core::TransformComponent* trans = GetComponent<Core::TransformComponent>(entityDebugJaws); trans->position = DirectX::XMFLOAT3(-10, 5, 0); // TODOKO REMOVE Create debug potentialfields for(size_t i = 0; i < 1; i++) { int entityID = t_entityHandler.CreateEntity(Blueprints::DebugPotentialFieldActor); DirectX::XMFLOAT3 position = DirectX::XMFLOAT3(0, 0, 0); DirectX::XMFLOAT4 orientation = XMFLOAT4(0, 0, 0, 1); int matID = Core::EntityHandler::GetInstance().GetComponentFromStorage<Core::PhysicsMaterialComponent>(entityID)->p_materialID; Core::RigidBodyComponent* rigidComp = Core::EntityHandler::GetInstance().GetComponentFromStorage<Core::RigidBodyComponent>(entityID); rigidComp->p_bodyID = sharedContext.GetPhysicsModule().GetRigidBodyManager().AddBoxBodyStatic(entityID, position, orientation, XMFLOAT3(0.5, 0.5, 0.5), matID); Core::PotentialFieldComponent* actor = Core::EntityHandler::GetInstance().GetComponentFromStorage<Core::PotentialFieldComponent>(entityID); actor->ChargedActor = sharedContext.GetAIModule().GetPotentialFieldSubModule().CreateNewActor(position, 10, 10, true); } for(size_t i = 0; i < 5; i++) { int entityID = t_entityFactory.CreateEntity(Blueprints::PlatformEntity); DirectX::XMFLOAT3 position = DirectX::XMFLOAT3(0, 10 - (int)i, i * 5); DirectX::XMFLOAT4 orientation = XMFLOAT4(0, 0, 0, 1); int matID = Core::EntityHandler::GetInstance().GetComponentFromStorage<Core::PhysicsMaterialComponent>(entityID)->p_materialID; Core::RigidBodyComponent* rigidComp = Core::EntityHandler::GetInstance().GetComponentFromStorage<Core::RigidBodyComponent>(entityID); rigidComp->p_bodyID = sharedContext.GetPhysicsModule().GetRigidBodyManager().AddBoxBodyDynamic(entityID, position, orientation, XMFLOAT3(2, 0.05, 2), matID); } // Create some enemies for(size_t i = 0; i < 8; i++) { int entityID = t_entityFactory.CreateEntity(Blueprints::EnemyEntity); XMFLOAT3 position = DirectX::XMFLOAT3(0, 7 - (int)i, i * 5); XMFLOAT4 orientation = XMFLOAT4(0, 0, 0, 1); int matID = Core::EntityHandler::GetInstance().GetComponentFromStorage<Core::PhysicsMaterialComponent>(entityID)->p_materialID; // RigidBodyComponent* rigidComp = EntityHandler::GetInstance().GetComponentFromStorage<RigidBodyComponent>(entityID); // rigidComp->p_bodyID = sharedContext.GetPhysicsModule().GetRigidBodyManager().AddBoxBodyDynamic(entityID, position, orientation, // XMFLOAT3(0.5, 0.5, 0.5), matID); sharedContext.GetPhysicsModule().GetCharacterControlManager().AddController(entityID, matID, position, XMFLOAT2(0.1, 0.5)); Core::PotentialFieldComponent* potentialComponent = Core::EntityHandler::GetInstance().GetComponentFromStorage<Core::PotentialFieldComponent>(entityID); potentialComponent->ChargedActor = sharedContext.GetAIModule().GetPotentialFieldSubModule().CreateNewActor(DirectX::XMFLOAT3(0, 0, 0), -1, 3, false); Core::EntityCreatedEvent* AIGroupActorCreated = new Core::EntityCreatedEvent(entityID, Core::EventType::AiGroupActorCreation); Core::EventHandler::GetInstance()->BroadcastEvent(AIGroupActorCreated); } int entityID = t_entityFactory.CreateEntity(Blueprints::ExperimentalPressureParticleEntity); DoremiEngine::Physics::ParticleEmitterData emitterData; emitterData.m_density = 3; emitterData.m_dimensions = XMFLOAT2(0, 0); emitterData.m_direction = XMFLOAT4(0, 0, 0, 1); emitterData.m_emissionAreaDimensions = XMFLOAT2(0.1, 0.4); emitterData.m_emissionRate = 1; emitterData.m_launchPressure = 2; emitterData.m_position = Core::EntityHandler::GetInstance().GetComponentFromStorage<Core::TransformComponent>(entityID)->position; // sharedContext.GetPhysicsModule().GetFluidManager().CreateParticleEmitter(entityID, emitterData); // TODO Not using this event atm, because of refac, will need to find some solution /*PlayerCreationEvent* playerCreationEvent = new PlayerCreationEvent(); playerCreationEvent->eventType = Events::PlayerCreation; playerCreationEvent->playerEntityID = playerID;*/ // EventHandler::GetInstance()->BroadcastEvent(playerCreationEvent); // for(size_t i = 0; i < 1; i++) //{ // int entityID = t_entityHandler.CreateEntity(Blueprints::PlatformEntity); // XMFLOAT3 position = DirectX::XMFLOAT3(0, -2 - (int)i, i * 5); // XMFLOAT4 orientation = XMFLOAT4(0, 0, 0, 1); // int matID = EntityHandler::GetInstance().GetComponentFromStorage<PhysicsMaterialComponent>(entityID)->p_materialID; // RigidBodyComponent* rigidComp = EntityHandler::GetInstance().GetComponentFromStorage<RigidBodyComponent>(entityID);/* // rigidComp->p_bodyID = // sharedContext.GetPhysicsModule().GetRigidBodyManager().AddBoxBodyStatic(position, orientation, XMFLOAT3(2, 0.05, 2), matID);*/ // rigidComp->p_bodyID = // sharedContext.GetPhysicsModule().GetRigidBodyManager().AddBoxBodyStatic(position, orientation, XMFLOAT3(200, 0.05, 200), matID); //} TIME_FUNCTION_STOP } void JawsSimulatePhysicsDebug(double deltaTime) { TIME_FUNCTION_START Core::TransformComponent* trans = Core::EntityHandler::GetInstance().GetComponentFromStorage<Core::TransformComponent>(0); if(trans->position.x == -10) { trans->position.y += deltaTime; if(trans->position.y > 5) { trans->position.x = -11; } } else { trans->position.y -= deltaTime; if(trans->position.y < -5) { trans->position.x = -10; } } DirectX::XMStoreFloat4(&trans->rotation, DirectX::XMQuaternionRotationRollPitchYaw(0, 0, trans->position.y * 1.0f)); TIME_FUNCTION_STOP } void ServerMain::Run() { TIME_FUNCTION_START std::chrono::time_point<std::chrono::high_resolution_clock> CurrentClock, PreviousClock; PreviousClock = std::chrono::high_resolution_clock::now(); double Frame = 0; double Offset = 0; double Accum = 0; double GameTime = 0; double UpdateStepLen = 0.017; while(true) { CurrentClock = std::chrono::high_resolution_clock::now(); std::chrono::duration<double> duration = (CurrentClock - PreviousClock); Frame = duration.count() + Offset; Offset = 0; // We simulate maximum 250 milliseconds each frame // If we would let it be alone we would get mayor stops instead of lesser ones that will slowly catch up if(Frame > 0.25f) { Offset = Frame - 0.25f; Frame = 0.25f; } // Update the previous position with frametime so we can catch up if we slow down PreviousClock = CurrentClock; // Update Accumulator (how much we will work this frame) Accum += Frame; // Loop as many update-steps we will take this frame while(Accum >= UpdateStepLen) { // Update Game logic JawsSimulatePhysicsDebug(UpdateStepLen); // TODOCM remove // Update Game logic UpdateGame(UpdateStepLen); // Remove time from accumulator // Accumulator -= UpdateTimeStepLength; Accum -= UpdateStepLen; // Add time to start GameTime += UpdateStepLen; } } TIME_FUNCTION_STOP } void ServerMain::UpdateGame(double p_deltaTime) { TIME_FUNCTION_START Core::EventHandler::GetInstance()->DeliverEvents(); Core::PlayerHandler::GetInstance()->UpdateServer(); Utility::Timer::MeasureTimer& timer = Utility::Timer::MeasureTimer::GetInstance(); // Have all managers update size_t length = m_managers.size(); for(size_t i = 0; i < length; i++) { Utility::Timer::MeasureInfo& info = timer.GetTimer(m_managers.at(i)->GetName()); info.Reset().Start(); m_managers.at(i)->Update(p_deltaTime); info.Stop(); } TIME_FUNCTION_STOP } void ServerMain::Start() { TIME_FUNCTION_START Initialize(); Run(); TIME_FUNCTION_STOP } }<commit_msg>Entity factory instead of entity manager<commit_after>// Project specific #include <Server.hpp> #include <Doremi/Core/Include/GameCore.hpp> #include <Doremi/Core/Include/EntityComponent/Components/TransformComponent.hpp> #include <Doremi/Core/Include/EntityComponent/EntityHandlerServer.hpp> #include <Doremi/Core/Include/EventHandler/EventHandler.hpp> #include <Doremi/Core/Include/EventHandler/Events/EntityCreatedEvent.hpp> #include <Doremi/Core/Include/PlayerHandler.hpp> #include <Doremi/Core/Include/Manager/Manager.hpp> #include <Doremi/Core/Include/Manager/Network/ServerNetworkManager.hpp> #include <Doremi/Core/Include/Manager/MovementManager.hpp> #include <Doremi/Core/Include/Manager/RigidTransformSyncManager.hpp> #include <DoremiEngine/Core/Include/Subsystem/EngineModuleEnum.hpp> #include <Doremi/Core/Include/TemplateCreator.hpp> #include <Doremi/Core/Include/EntityComponent/Components/PhysicsMaterialComponent.hpp> #include <Doremi/Core/Include/EntityComponent/Components/RigidBodyComponent.hpp> #include <DoremiEngine/Physics/Include/PhysicsModule.hpp> #include <DoremiEngine/Physics/Include/RigidBodyManager.hpp> #include <DoremiEngine/Physics/Include/CharacterControlManager.hpp> #include <Doremi/Core/Include/Manager/AI/AIPathManager.hpp> #include <Doremi/Core/Include/Manager/CharacterControlSyncManager.hpp> #include <Doremi/Core/Include/InputHandlerClient.hpp> #include <Doremi/Core/Include/EntityComponent/Components/PotentialFieldComponent.hpp> #include <DoremiEngine/AI/Include/Interface/SubModule/PotentialFieldSubModule.hpp> #include <DoremiEngine/AI/Include/AIModule.hpp> #include <Doremi/Core/Include/Manager/JumpManager.hpp> #include <Doremi/Core/Include/Manager/GravityManager.hpp> #include <Doremi/Core/Include/EntityComponent/EntityFactory.hpp> #include <Doremi/Core/Include/LevelLoaderServer.hpp> #include <DoremiEngine/Physics/Include/FluidManager.hpp> // Timer #include <Utility/Timer/Include/Measure/MeasureTimer.hpp> // Third party #include <DirectXMath.h> // Standard libraries #include <stdexcept> #include <exception> #include <chrono> namespace Doremi { ServerMain::ServerMain() {} ServerMain::~ServerMain() {} void ServerMain::Initialize() { TIME_FUNCTION_START const DoremiEngine::Core::SharedContext& sharedContext = InitializeEngine( DoremiEngine::Core::EngineModuleEnum::NETWORK | DoremiEngine::Core::EngineModuleEnum::PHYSICS | DoremiEngine::Core::EngineModuleEnum::AI); /* This starts the physics handler. Should not be done here, but since this is the general code dump, it'll work for now TODOJB*/ Core::EntityHandlerServer::StartupEntityHandlerServer(); Core::PlayerHandler::StartPlayerHandler(sharedContext); ////////////////Example only//////////////// // Create manager // Manager* t_physicsManager = new ExampleManager(sharedContext); Core::Manager* t_serverNetworkManager = new Core::ServerNetworkManager(sharedContext); Core::Manager* t_movementManager = new Core::MovementManager(sharedContext); Core::Manager* t_rigidTransSyndManager = new Core::RigidTransformSyncManager(sharedContext); Core::Manager* t_aiPathManager = new Core::AIPathManager(sharedContext); Core::Manager* t_charSyncManager = new Core::CharacterControlSyncManager(sharedContext); // TODO check if needed Core::Manager* t_jumpManager = new Core::JumpManager(sharedContext); Core::Manager* t_gravManager = new Core::GravityManager(sharedContext); // Add manager to list of managers // Remember to put server last (cause we want on same frame as we update to send data, or at least close togeather) // m_managers.push_back(t_physicsManager); m_managers.push_back(t_serverNetworkManager); m_managers.push_back(t_rigidTransSyndManager); m_managers.push_back(t_movementManager); m_managers.push_back(t_aiPathManager); m_managers.push_back(t_charSyncManager); m_managers.push_back(t_jumpManager); m_managers.push_back(t_gravManager); // GenerateWorld(sharedContext); // GenerateWorldServerJawsTest(sharedContext); Core::TemplateCreator::GetInstance()->CreateTemplatesForServer(sharedContext); SpawnDebugWorld(sharedContext); ////////////////End Example//////////////// // Remove later, needed to see something when we play solo cause of camera interactions with input // Doremi::Core::InputHandlerClient* inputHandler = new Doremi::Core::InputHandlerClient(sharedContext); // Core::PlayerHandler::GetInstance()->CreateNewPlayer(300, (Doremi::Core::InputHandler*)inputHandler); TIME_FUNCTION_STOP } void ServerMain::SpawnDebugWorld(const DoremiEngine::Core::SharedContext& sharedContext) { TIME_FUNCTION_START Core::EntityFactory& t_entityFactory = *Core::EntityFactory::GetInstance(); Core::LevelLoaderServer* t_levelLoader = new Core::LevelLoaderServer(sharedContext); t_levelLoader->LoadLevel("Levels/test.drm"); // Create entity // int playerID = t_entityHandler.CreateEntity(Blueprints::PlayerEntity); //// Create the rigid body // int materialID = t_entityHandler.GetComponentFromStorage<Core::PhysicsMaterialComponent>(playerID)->p_materialID; // DirectX::XMFLOAT3 position = DirectX::XMFLOAT3(0, 10, 0); // DirectX::XMFLOAT4 orientation = DirectX::XMFLOAT4(0, 0, 0, 1); // Core::RigidBodyComponent* bodyComp = t_entityHandler.GetComponentFromStorage<Core::RigidBodyComponent>(playerID); /*bodyComp->p_bodyID = sharedContext.GetPhysicsModule().GetRigidBodyManager().AddBoxBodyDynamic(playerID, position, orientation, DirectX::XMFLOAT3(0.5, 0.5, 0.5), materialID);*/ // sharedContext.GetPhysicsModule().GetCharacterControlManager().AddController(playerID, materialID, position, XMFLOAT2(1, 1)); // Core::EntityHandler::GetInstance().AddComponent(playerID, (int)ComponentType::CharacterController); int entityDebugJaws = t_entityFactory.CreateEntity(Blueprints::JawsDebugEntity); Core::TransformComponent* trans = GetComponent<Core::TransformComponent>(entityDebugJaws); trans->position = DirectX::XMFLOAT3(-10, 5, 0); // TODOKO REMOVE Create debug potentialfields for(size_t i = 0; i < 1; i++) { int entityID = t_entityFactory.CreateEntity(Blueprints::DebugPotentialFieldActor); DirectX::XMFLOAT3 position = DirectX::XMFLOAT3(0, 0, 0); DirectX::XMFLOAT4 orientation = XMFLOAT4(0, 0, 0, 1); int matID = Core::EntityHandler::GetInstance().GetComponentFromStorage<Core::PhysicsMaterialComponent>(entityID)->p_materialID; Core::RigidBodyComponent* rigidComp = Core::EntityHandler::GetInstance().GetComponentFromStorage<Core::RigidBodyComponent>(entityID); rigidComp->p_bodyID = sharedContext.GetPhysicsModule().GetRigidBodyManager().AddBoxBodyStatic(entityID, position, orientation, XMFLOAT3(0.5, 0.5, 0.5), matID); Core::PotentialFieldComponent* actor = Core::EntityHandler::GetInstance().GetComponentFromStorage<Core::PotentialFieldComponent>(entityID); actor->ChargedActor = sharedContext.GetAIModule().GetPotentialFieldSubModule().CreateNewActor(position, 10, 10, true); } for(size_t i = 0; i < 5; i++) { int entityID = t_entityFactory.CreateEntity(Blueprints::PlatformEntity); DirectX::XMFLOAT3 position = DirectX::XMFLOAT3(0, 10 - (int)i, i * 5); DirectX::XMFLOAT4 orientation = XMFLOAT4(0, 0, 0, 1); int matID = Core::EntityHandler::GetInstance().GetComponentFromStorage<Core::PhysicsMaterialComponent>(entityID)->p_materialID; Core::RigidBodyComponent* rigidComp = Core::EntityHandler::GetInstance().GetComponentFromStorage<Core::RigidBodyComponent>(entityID); rigidComp->p_bodyID = sharedContext.GetPhysicsModule().GetRigidBodyManager().AddBoxBodyDynamic(entityID, position, orientation, XMFLOAT3(2, 0.05, 2), matID); } // Create some enemies for(size_t i = 0; i < 8; i++) { int entityID = t_entityFactory.CreateEntity(Blueprints::EnemyEntity); XMFLOAT3 position = DirectX::XMFLOAT3(0, 7 - (int)i, i * 5); XMFLOAT4 orientation = XMFLOAT4(0, 0, 0, 1); int matID = Core::EntityHandler::GetInstance().GetComponentFromStorage<Core::PhysicsMaterialComponent>(entityID)->p_materialID; // RigidBodyComponent* rigidComp = EntityHandler::GetInstance().GetComponentFromStorage<RigidBodyComponent>(entityID); // rigidComp->p_bodyID = sharedContext.GetPhysicsModule().GetRigidBodyManager().AddBoxBodyDynamic(entityID, position, orientation, // XMFLOAT3(0.5, 0.5, 0.5), matID); sharedContext.GetPhysicsModule().GetCharacterControlManager().AddController(entityID, matID, position, XMFLOAT2(0.1, 0.5)); Core::PotentialFieldComponent* potentialComponent = Core::EntityHandler::GetInstance().GetComponentFromStorage<Core::PotentialFieldComponent>(entityID); potentialComponent->ChargedActor = sharedContext.GetAIModule().GetPotentialFieldSubModule().CreateNewActor(DirectX::XMFLOAT3(0, 0, 0), -1, 3, false); Core::EntityCreatedEvent* AIGroupActorCreated = new Core::EntityCreatedEvent(entityID, Core::EventType::AiGroupActorCreation); Core::EventHandler::GetInstance()->BroadcastEvent(AIGroupActorCreated); } int entityID = t_entityFactory.CreateEntity(Blueprints::ExperimentalPressureParticleEntity); DoremiEngine::Physics::ParticleEmitterData emitterData; emitterData.m_density = 3; emitterData.m_dimensions = XMFLOAT2(0, 0); emitterData.m_direction = XMFLOAT4(0, 0, 0, 1); emitterData.m_emissionAreaDimensions = XMFLOAT2(0.1, 0.4); emitterData.m_emissionRate = 1; emitterData.m_launchPressure = 2; emitterData.m_position = Core::EntityHandler::GetInstance().GetComponentFromStorage<Core::TransformComponent>(entityID)->position; // sharedContext.GetPhysicsModule().GetFluidManager().CreateParticleEmitter(entityID, emitterData); // TODO Not using this event atm, because of refac, will need to find some solution /*PlayerCreationEvent* playerCreationEvent = new PlayerCreationEvent(); playerCreationEvent->eventType = Events::PlayerCreation; playerCreationEvent->playerEntityID = playerID;*/ // EventHandler::GetInstance()->BroadcastEvent(playerCreationEvent); // for(size_t i = 0; i < 1; i++) //{ // int entityID = t_entityHandler.CreateEntity(Blueprints::PlatformEntity); // XMFLOAT3 position = DirectX::XMFLOAT3(0, -2 - (int)i, i * 5); // XMFLOAT4 orientation = XMFLOAT4(0, 0, 0, 1); // int matID = EntityHandler::GetInstance().GetComponentFromStorage<PhysicsMaterialComponent>(entityID)->p_materialID; // RigidBodyComponent* rigidComp = EntityHandler::GetInstance().GetComponentFromStorage<RigidBodyComponent>(entityID);/* // rigidComp->p_bodyID = // sharedContext.GetPhysicsModule().GetRigidBodyManager().AddBoxBodyStatic(position, orientation, XMFLOAT3(2, 0.05, 2), matID);*/ // rigidComp->p_bodyID = // sharedContext.GetPhysicsModule().GetRigidBodyManager().AddBoxBodyStatic(position, orientation, XMFLOAT3(200, 0.05, 200), matID); //} TIME_FUNCTION_STOP } void JawsSimulatePhysicsDebug(double deltaTime) { TIME_FUNCTION_START Core::TransformComponent* trans = Core::EntityHandler::GetInstance().GetComponentFromStorage<Core::TransformComponent>(0); if(trans->position.x == -10) { trans->position.y += deltaTime; if(trans->position.y > 5) { trans->position.x = -11; } } else { trans->position.y -= deltaTime; if(trans->position.y < -5) { trans->position.x = -10; } } DirectX::XMStoreFloat4(&trans->rotation, DirectX::XMQuaternionRotationRollPitchYaw(0, 0, trans->position.y * 1.0f)); TIME_FUNCTION_STOP } void ServerMain::Run() { TIME_FUNCTION_START std::chrono::time_point<std::chrono::high_resolution_clock> CurrentClock, PreviousClock; PreviousClock = std::chrono::high_resolution_clock::now(); double Frame = 0; double Offset = 0; double Accum = 0; double GameTime = 0; double UpdateStepLen = 0.017; while(true) { CurrentClock = std::chrono::high_resolution_clock::now(); std::chrono::duration<double> duration = (CurrentClock - PreviousClock); Frame = duration.count() + Offset; Offset = 0; // We simulate maximum 250 milliseconds each frame // If we would let it be alone we would get mayor stops instead of lesser ones that will slowly catch up if(Frame > 0.25f) { Offset = Frame - 0.25f; Frame = 0.25f; } // Update the previous position with frametime so we can catch up if we slow down PreviousClock = CurrentClock; // Update Accumulator (how much we will work this frame) Accum += Frame; // Loop as many update-steps we will take this frame while(Accum >= UpdateStepLen) { // Update Game logic JawsSimulatePhysicsDebug(UpdateStepLen); // TODOCM remove // Update Game logic UpdateGame(UpdateStepLen); // Remove time from accumulator // Accumulator -= UpdateTimeStepLength; Accum -= UpdateStepLen; // Add time to start GameTime += UpdateStepLen; } } TIME_FUNCTION_STOP } void ServerMain::UpdateGame(double p_deltaTime) { TIME_FUNCTION_START Core::EventHandler::GetInstance()->DeliverEvents(); Core::PlayerHandler::GetInstance()->UpdateServer(); Utility::Timer::MeasureTimer& timer = Utility::Timer::MeasureTimer::GetInstance(); // Have all managers update size_t length = m_managers.size(); for(size_t i = 0; i < length; i++) { Utility::Timer::MeasureInfo& info = timer.GetTimer(m_managers.at(i)->GetName()); info.Reset().Start(); m_managers.at(i)->Update(p_deltaTime); info.Stop(); } TIME_FUNCTION_STOP } void ServerMain::Start() { TIME_FUNCTION_START Initialize(); Run(); TIME_FUNCTION_STOP } }<|endoftext|>
<commit_before>#include "postprocessing.h" //osg #include <osg/Texture2D> #include <osg/TexEnv> #include <osg/TexGen> #include <osg/TextureCubeMap> #include <osg/TexMat> #include <osg/Material> #include <osg/Geode> #include <osgDB/WriteFile> #include <osg/CullFace> #include <osg/TexGenNode> #include <osgUtil/CullVisitor> #include <osgGA/StateSetManipulator> #include <osgDB/FileNameUtils> #include <stdio.h> // troen #include "shaders.h" #define HALF_PINGPONGTEXTURE_WIDTH true //for performance improvement, set to true using namespace troen; // ugly but convenient global statics for shaders static osg::ref_ptr<osg::Uniform> g_nearFarUniform = new osg::Uniform("nearFar", osg::Vec2(0.0, 1.0)); PostProcessing::PostProcessing(osg::ref_ptr<osg::Group> rootNode, int width, int height) :m_root(rootNode), m_sceneNode(new osg::Group()), m_width(width), m_height(height) { // init textures, will be recreated when screen size changes setupTextures(m_width, m_height); // create shaders shaders::reloadShaders(); //////////////////////////////////////// // Multi pass rendering and Ping Pong // //////////////////////////////////////// // 1. gBuffer pass: render color, normal&depth, id buffer unsigned int pass = 0; m_allCameras.push_back(gBufferPass()); m_root->addChild(m_allCameras[pass++]); // 2. prepare pass: render id buffer as seeds into PONG texture TEXTURE_CONTENT pingPong[] = { PING, PONG }; // start writing into PONG buffer (pass == 1 ) m_allCameras.push_back(pingPongPass(pass, COLOR, PONG, shaders::SELECT_GLOW_OBJECTS, -1.0)); m_root->addChild(m_allCameras[pass++]); m_allCameras.push_back(pingPongPass(pass, PONG, PING, shaders::HBLUR, -1.0)); m_root->addChild(m_allCameras[pass++]); m_allCameras.push_back(pingPongPass(pass, PING, PONG, shaders::VBLUR, -1.0)); m_root->addChild(m_allCameras[pass++]); m_allCameras.push_back(postProcessingPass()); m_root->addChild(m_allCameras[m_allCameras.size() - 1]); } // sets up textures void PostProcessing::setupTextures(const unsigned int & width, const unsigned int &height) { ////////////////////////////////////////////////////////////////////////// // 2D textures as render targets ////////////////////////////////////////////////////////////////////////// int halfedWidth = width / 2; int halfedHeight = height / 2; // store color, normal & Depth, id in textures m_fboTextures.resize(TEXTURE_CONTENT_SIZE); for (int i = 0; i<m_fboTextures.size(); i++) { // only create textures on first run if (!m_fboTextures[i].get()) { m_fboTextures[i] = new osg::Texture2D(); } if ((i == PING || i == PONG) && HALF_PINGPONGTEXTURE_WIDTH) { m_fboTextures[i]->setTextureWidth(halfedWidth); m_fboTextures[i]->setTextureHeight(halfedHeight); } else { m_fboTextures[i]->setTextureWidth(width); m_fboTextures[i]->setTextureHeight(height); } // higher resolution if (i == ID) { m_fboTextures[i]->setInternalFormat(GL_RG); m_fboTextures[i]->setSourceFormat(GL_RG); m_fboTextures[i]->setSourceType(GL_FLOAT); } else { m_fboTextures[i]->setInternalFormat(GL_RGBA); m_fboTextures[i]->setSourceFormat(GL_RGBA); m_fboTextures[i]->setSourceType(GL_FLOAT); } m_fboTextures[i]->setBorderWidth(0); m_fboTextures[i]->setFilter(osg::Texture::MIN_FILTER, osg::Texture::NEAREST); m_fboTextures[i]->setFilter(osg::Texture::MAG_FILTER, osg::Texture::NEAREST); m_fboTextures[i]->setWrap(osg::Texture::WRAP_S, osg::Texture::CLAMP_TO_BORDER); m_fboTextures[i]->setWrap(osg::Texture::WRAP_T, osg::Texture::CLAMP_TO_BORDER); m_fboTextures[i]->setBorderColor(osg::Vec4d(0.0, 0.0, 0.0, 1.0)); m_fboTextures[i]->setResizeNonPowerOfTwoHint(true); // important to reflect the change in size m_fboTextures[i]->dirtyTextureObject(); } // important to reflect the change in size for the FBO if (m_allCameras.size() > 0) { for (size_t i = 0, iEnd = m_allCameras.size(); i<iEnd; i++) { m_allCameras[i]->setRenderingCache(0); if (i != 0 && i != iEnd - 1 && HALF_PINGPONGTEXTURE_WIDTH) // only draw with halfed resolution, if we process the gbuffer + postprocessing pass m_allCameras[i]->setViewport(new osg::Viewport(0, 0, halfedWidth, halfedHeight)); } } } class NearFarCallback : public osg::NodeCallback { virtual void operator()(osg::Node* node, osg::NodeVisitor* nv) { traverse(node, nv); osgUtil::CullVisitor * cv = dynamic_cast<osgUtil::CullVisitor*> (nv); if (cv) { double n = cv->getCalculatedNearPlane(); double f = cv->getCalculatedFarPlane(); osg::Matrixd m = *cv->getProjectionMatrix(); cv->clampProjectionMatrix(m, n, f); if (n != m_oldNear || f != m_oldFar) { m_oldNear = n; m_oldFar = f; g_nearFarUniform->set(osg::Vec2(n, f)); } } } private: double m_oldNear; double m_oldFar; }; // create gbuffer creation camera osg::ref_ptr<osg::Camera> PostProcessing::gBufferPass() { osg::ref_ptr<osg::Camera> cam = new osg::Camera(); // output textures cam->attach((osg::Camera::BufferComponent)(osg::Camera::COLOR_BUFFER0 + COLOR), m_fboTextures[COLOR]); //cam->attach((osg::Camera::BufferComponent)(osg::Camera::COLOR_BUFFER0 + NORMALDEPTH), m_fboTextures[NORMALDEPTH]); cam->attach((osg::Camera::BufferComponent)(osg::Camera::COLOR_BUFFER0 + ID), m_fboTextures[ID]); // Configure fboCamera to draw fullscreen textured quad // black clear color cam->setClearColor(osg::Vec4(0.0, 0.0, 0.5, 1.0)); cam->setRenderTargetImplementation(osg::Camera::FRAME_BUFFER_OBJECT); cam->setReferenceFrame(osg::Camera::RELATIVE_RF); cam->setRenderOrder(osg::Camera::PRE_RENDER, 0); // need to know about near far changes for correct depth cam->setCullCallback(new NearFarCallback()); cam->addChild(m_sceneNode); // attach shader program //cam->getOrCreateStateSet()->setMode(GL_DEPTH_TEST, osg::StateAttribute::ON); //cam->getOrCreateStateSet()->addUniform(new osg::Uniform("colorTex", COLOR)); //cam->getOrCreateStateSet()->setAttributeAndModes(shaders::m_allShaderPrograms[shaders::GBUFFER], osg::StateAttribute::ON); //cam->getOrCreateStateSet()->setTextureAttributeAndModes(COLOR, m_fboTextures[COLOR], osg::StateAttribute::ON); //cam->getOrCreateStateSet()->setTextureAttributeAndModes(NORMALDEPTH, m_fboTextures[NORMALDEPTH], osg::StateAttribute::ON); <<<<<<< HEAD cam->getOrCreateStateSet()->setTextureAttributeAndModes(ID, m_fboTextures[ID], osg::StateAttribute::ON); ======= //cam->getOrCreateStateSet()->setTextureAttributeAndModes(ID, m_fboTextures[ID], osg::StateAttribute::ON); g_nearFarUniform = new osg::Uniform("nearFar", osg::Vec2(0.0, 1.0)); >>>>>>> 7cb382183590906ebf637ff0b0806e97b150fde0 cam->getOrCreateStateSet()->addUniform(g_nearFarUniform); return cam; } class timeUpdate : public osg::Uniform::Callback { public: virtual void operator() (osg::Uniform* uniform, osg::NodeVisitor* nv) { float time = nv->getFrameStamp()->getReferenceTime(); uniform->set(time); } }; // create skeleton creation camera osg::ref_ptr<osg::Camera> PostProcessing::pingPongPass(int order, TEXTURE_CONTENT inputTexture, TEXTURE_CONTENT outputTexture, int shader, int step) { osg::ref_ptr<osg::Camera> camera(new osg::Camera()); // output textures camera->attach((osg::Camera::BufferComponent) (osg::Camera::COLOR_BUFFER0), m_fboTextures[outputTexture]); // Configure fboCamera to draw fullscreen textured quad camera->setClearColor(osg::Vec4(0.0, float(float(order) / float(m_allCameras.size())), 0.0, 1.0)); camera->setRenderTargetImplementation(osg::Camera::FRAME_BUFFER_OBJECT); camera->setReferenceFrame(osg::Camera::ABSOLUTE_RF); camera->setRenderOrder(osg::Camera::PRE_RENDER, order); // geometry osg::Geode* geode(new osg::Geode()); geode->addDrawable(osg::createTexturedQuadGeometry(osg::Vec3(-1, -1, 0), osg::Vec3(2, 0, 0), osg::Vec3(0, 2, 0))); geode->getOrCreateStateSet()->setMode(GL_LIGHTING, osg::StateAttribute::OFF); camera->addChild(geode); // attach shader program osg::ref_ptr<osg::StateSet> state = camera->getOrCreateStateSet(); state->setMode(GL_DEPTH_TEST, osg::StateAttribute::ON); state->setAttributeAndModes(shaders::m_allShaderPrograms[shader], osg::StateAttribute::ON); // add sampler textures state->addUniform(new osg::Uniform("inputLayer", inputTexture)); state->addUniform(new osg::Uniform("idLayer", ID)); if (step != -1) state->addUniform(new osg::Uniform("currentStep", step)); // add time uniform osg::Uniform* timeU = new osg::Uniform("time", 0.f); state->addUniform(timeU); timeU->setUpdateCallback(new timeUpdate()); state->setTextureAttributeAndModes(inputTexture, m_fboTextures[inputTexture], osg::StateAttribute::ON); state->setTextureAttributeAndModes(ID, m_fboTextures[ID], osg::StateAttribute::ON); return camera.release(); } // create post processing pass to put it all together osg::ref_ptr<osg::Camera> PostProcessing::postProcessingPass() { osg::ref_ptr<osg::Camera> postRenderCamera(new osg::Camera()); // input textures //postRenderCamera->attach((osg::Camera::BufferComponent) (osg::Camera::COLOR_BUFFER0 + COLOR), m_fboTextures[COLOR]); //postRenderCamera->attach((osg::Camera::BufferComponent) (osg::Camera::COLOR_BUFFER0 + NORMALDEPTH), m_fboTextures[NORMALDEPTH]); //postRenderCamera->attach((osg::Camera::BufferComponent) (osg::Camera::COLOR_BUFFER0 + ID), m_fboTextures[ID]); //postRenderCamera->attach((osg::Camera::BufferComponent) (osg::Camera::COLOR_BUFFER0 + PONG), m_fboTextures[PONG]); // configure postRenderCamera to draw fullscreen textured quad postRenderCamera->setClearColor(osg::Vec4(0.0, 0.5, 0.0, 1)); // should never see this. postRenderCamera->setReferenceFrame(osg::Camera::ABSOLUTE_RF); postRenderCamera->setRenderOrder(osg::Camera::POST_RENDER); // geometry osg::Geode* geode(new osg::Geode()); geode->addDrawable(osg::createTexturedQuadGeometry(osg::Vec3(-1, -1, 0), osg::Vec3(2, 0, 0), osg::Vec3(0, 2, 0))); //geode->getOrCreateStateSet()->setTextureAttributeAndModes(COLOR, m_fboTextures[COLOR], osg::StateAttribute::ON); //geode->getOrCreateStateSet()->setTextureAttributeAndModes(NORMALDEPTH, m_fboTextures[NORMALDEPTH], osg::StateAttribute::ON); /*geode->getOrCreateStateSet()->setTextureAttributeAndModes(ID, m_fboTextures[ID], osg::StateAttribute::ON); geode->getOrCreateStateSet()->setTextureAttributeAndModes(PONG, m_fboTextures[PONG], osg::StateAttribute::ON);*/ geode->getOrCreateStateSet()->setMode(GL_LIGHTING, osg::StateAttribute::OFF); postRenderCamera->addChild(geode); // attach shader program osg::ref_ptr<osg::StateSet> state = postRenderCamera->getOrCreateStateSet(); state->setMode(GL_DEPTH_TEST, osg::StateAttribute::ON); state->setAttributeAndModes(shaders::m_allShaderPrograms[shaders::POST_PROCESSING], osg::StateAttribute::ON); // add samplers state->addUniform(new osg::Uniform("sceneLayer", COLOR)); //state->addUniform(new osg::Uniform("normalDepthLayer", NORMALDEPTH)); state->addUniform(new osg::Uniform("idLayer", ID)); state->addUniform(new osg::Uniform("pongLayer", PONG)); state->setTextureAttributeAndModes(COLOR, m_fboTextures[COLOR], osg::StateAttribute::ON); //state->setTextureAttributeAndModes(NORMALDEPTH, m_fboTextures[NORMALDEPTH], osg::StateAttribute::ON); state->setTextureAttributeAndModes(ID, m_fboTextures[ID], osg::StateAttribute::ON); state->setTextureAttributeAndModes(PONG, m_fboTextures[PONG], osg::StateAttribute::ON); return postRenderCamera; } bool PostProcessing::handleGuiEvents(const osgGA::GUIEventAdapter& ea, osgGA::GUIActionAdapter&, osg::Object*, osg::NodeVisitor*) { if (ea.getEventType() == osgGA::GUIEventAdapter::RESIZE) { // re setup textures to new size setupTextures(ea.getWindowWidth(), ea.getWindowHeight()); return true; } else return false; } <commit_msg>resolve merge conflict<commit_after>#include "postprocessing.h" //osg #include <osg/Texture2D> #include <osg/TexEnv> #include <osg/TexGen> #include <osg/TextureCubeMap> #include <osg/TexMat> #include <osg/Material> #include <osg/Geode> #include <osgDB/WriteFile> #include <osg/CullFace> #include <osg/TexGenNode> #include <osgUtil/CullVisitor> #include <osgGA/StateSetManipulator> #include <osgDB/FileNameUtils> #include <stdio.h> // troen #include "shaders.h" #define HALF_PINGPONGTEXTURE_WIDTH true //for performance improvement, set to true using namespace troen; // ugly but convenient global statics for shaders static osg::ref_ptr<osg::Uniform> g_nearFarUniform = new osg::Uniform("nearFar", osg::Vec2(0.0, 1.0)); PostProcessing::PostProcessing(osg::ref_ptr<osg::Group> rootNode, int width, int height) :m_root(rootNode), m_sceneNode(new osg::Group()), m_width(width), m_height(height) { // init textures, will be recreated when screen size changes setupTextures(m_width, m_height); // create shaders shaders::reloadShaders(); //////////////////////////////////////// // Multi pass rendering and Ping Pong // //////////////////////////////////////// // 1. gBuffer pass: render color, normal&depth, id buffer unsigned int pass = 0; m_allCameras.push_back(gBufferPass()); m_root->addChild(m_allCameras[pass++]); // 2. prepare pass: render id buffer as seeds into PONG texture TEXTURE_CONTENT pingPong[] = { PING, PONG }; // start writing into PONG buffer (pass == 1 ) m_allCameras.push_back(pingPongPass(pass, COLOR, PONG, shaders::SELECT_GLOW_OBJECTS, -1.0)); m_root->addChild(m_allCameras[pass++]); m_allCameras.push_back(pingPongPass(pass, PONG, PING, shaders::HBLUR, -1.0)); m_root->addChild(m_allCameras[pass++]); m_allCameras.push_back(pingPongPass(pass, PING, PONG, shaders::VBLUR, -1.0)); m_root->addChild(m_allCameras[pass++]); m_allCameras.push_back(postProcessingPass()); m_root->addChild(m_allCameras[m_allCameras.size() - 1]); } // sets up textures void PostProcessing::setupTextures(const unsigned int & width, const unsigned int &height) { ////////////////////////////////////////////////////////////////////////// // 2D textures as render targets ////////////////////////////////////////////////////////////////////////// int halfedWidth = width / 2; int halfedHeight = height / 2; // store color, normal & Depth, id in textures m_fboTextures.resize(TEXTURE_CONTENT_SIZE); for (int i = 0; i<m_fboTextures.size(); i++) { // only create textures on first run if (!m_fboTextures[i].get()) { m_fboTextures[i] = new osg::Texture2D(); } if ((i == PING || i == PONG) && HALF_PINGPONGTEXTURE_WIDTH) { m_fboTextures[i]->setTextureWidth(halfedWidth); m_fboTextures[i]->setTextureHeight(halfedHeight); } else { m_fboTextures[i]->setTextureWidth(width); m_fboTextures[i]->setTextureHeight(height); } // higher resolution if (i == ID) { m_fboTextures[i]->setInternalFormat(GL_RG); m_fboTextures[i]->setSourceFormat(GL_RG); m_fboTextures[i]->setSourceType(GL_FLOAT); } else { m_fboTextures[i]->setInternalFormat(GL_RGBA); m_fboTextures[i]->setSourceFormat(GL_RGBA); m_fboTextures[i]->setSourceType(GL_FLOAT); } m_fboTextures[i]->setBorderWidth(0); m_fboTextures[i]->setFilter(osg::Texture::MIN_FILTER, osg::Texture::NEAREST); m_fboTextures[i]->setFilter(osg::Texture::MAG_FILTER, osg::Texture::NEAREST); m_fboTextures[i]->setWrap(osg::Texture::WRAP_S, osg::Texture::CLAMP_TO_BORDER); m_fboTextures[i]->setWrap(osg::Texture::WRAP_T, osg::Texture::CLAMP_TO_BORDER); m_fboTextures[i]->setBorderColor(osg::Vec4d(0.0, 0.0, 0.0, 1.0)); m_fboTextures[i]->setResizeNonPowerOfTwoHint(true); // important to reflect the change in size m_fboTextures[i]->dirtyTextureObject(); } // important to reflect the change in size for the FBO if (m_allCameras.size() > 0) { for (size_t i = 0, iEnd = m_allCameras.size(); i<iEnd; i++) { m_allCameras[i]->setRenderingCache(0); if (i != 0 && i != iEnd - 1 && HALF_PINGPONGTEXTURE_WIDTH) // only draw with halfed resolution, if we process the gbuffer + postprocessing pass m_allCameras[i]->setViewport(new osg::Viewport(0, 0, halfedWidth, halfedHeight)); } } } class NearFarCallback : public osg::NodeCallback { virtual void operator()(osg::Node* node, osg::NodeVisitor* nv) { traverse(node, nv); osgUtil::CullVisitor * cv = dynamic_cast<osgUtil::CullVisitor*> (nv); if (cv) { double n = cv->getCalculatedNearPlane(); double f = cv->getCalculatedFarPlane(); osg::Matrixd m = *cv->getProjectionMatrix(); cv->clampProjectionMatrix(m, n, f); if (n != m_oldNear || f != m_oldFar) { m_oldNear = n; m_oldFar = f; g_nearFarUniform->set(osg::Vec2(n, f)); } } } private: double m_oldNear; double m_oldFar; }; // create gbuffer creation camera osg::ref_ptr<osg::Camera> PostProcessing::gBufferPass() { osg::ref_ptr<osg::Camera> cam = new osg::Camera(); // output textures cam->attach((osg::Camera::BufferComponent)(osg::Camera::COLOR_BUFFER0 + COLOR), m_fboTextures[COLOR]); //cam->attach((osg::Camera::BufferComponent)(osg::Camera::COLOR_BUFFER0 + NORMALDEPTH), m_fboTextures[NORMALDEPTH]); cam->attach((osg::Camera::BufferComponent)(osg::Camera::COLOR_BUFFER0 + ID), m_fboTextures[ID]); // Configure fboCamera to draw fullscreen textured quad // black clear color cam->setClearColor(osg::Vec4(0.0, 0.0, 0.5, 1.0)); cam->setRenderTargetImplementation(osg::Camera::FRAME_BUFFER_OBJECT); cam->setReferenceFrame(osg::Camera::RELATIVE_RF); cam->setRenderOrder(osg::Camera::PRE_RENDER, 0); // need to know about near far changes for correct depth cam->setCullCallback(new NearFarCallback()); cam->addChild(m_sceneNode); // attach shader program //cam->getOrCreateStateSet()->setMode(GL_DEPTH_TEST, osg::StateAttribute::ON); //cam->getOrCreateStateSet()->addUniform(new osg::Uniform("colorTex", COLOR)); //cam->getOrCreateStateSet()->setAttributeAndModes(shaders::m_allShaderPrograms[shaders::GBUFFER], osg::StateAttribute::ON); //cam->getOrCreateStateSet()->setTextureAttributeAndModes(COLOR, m_fboTextures[COLOR], osg::StateAttribute::ON); //cam->getOrCreateStateSet()->setTextureAttributeAndModes(NORMALDEPTH, m_fboTextures[NORMALDEPTH], osg::StateAttribute::ON); //cam->getOrCreateStateSet()->setTextureAttributeAndModes(ID, m_fboTextures[ID], osg::StateAttribute::ON); g_nearFarUniform = new osg::Uniform("nearFar", osg::Vec2(0.0, 1.0)); cam->getOrCreateStateSet()->addUniform(g_nearFarUniform); return cam; } class timeUpdate : public osg::Uniform::Callback { public: virtual void operator() (osg::Uniform* uniform, osg::NodeVisitor* nv) { float time = nv->getFrameStamp()->getReferenceTime(); uniform->set(time); } }; // create skeleton creation camera osg::ref_ptr<osg::Camera> PostProcessing::pingPongPass(int order, TEXTURE_CONTENT inputTexture, TEXTURE_CONTENT outputTexture, int shader, int step) { osg::ref_ptr<osg::Camera> camera(new osg::Camera()); // output textures camera->attach((osg::Camera::BufferComponent) (osg::Camera::COLOR_BUFFER0), m_fboTextures[outputTexture]); // Configure fboCamera to draw fullscreen textured quad camera->setClearColor(osg::Vec4(0.0, float(float(order) / float(m_allCameras.size())), 0.0, 1.0)); camera->setRenderTargetImplementation(osg::Camera::FRAME_BUFFER_OBJECT); camera->setReferenceFrame(osg::Camera::ABSOLUTE_RF); camera->setRenderOrder(osg::Camera::PRE_RENDER, order); // geometry osg::Geode* geode(new osg::Geode()); geode->addDrawable(osg::createTexturedQuadGeometry(osg::Vec3(-1, -1, 0), osg::Vec3(2, 0, 0), osg::Vec3(0, 2, 0))); geode->getOrCreateStateSet()->setMode(GL_LIGHTING, osg::StateAttribute::OFF); camera->addChild(geode); // attach shader program osg::ref_ptr<osg::StateSet> state = camera->getOrCreateStateSet(); state->setMode(GL_DEPTH_TEST, osg::StateAttribute::ON); state->setAttributeAndModes(shaders::m_allShaderPrograms[shader], osg::StateAttribute::ON); // add sampler textures state->addUniform(new osg::Uniform("inputLayer", inputTexture)); state->addUniform(new osg::Uniform("idLayer", ID)); if (step != -1) state->addUniform(new osg::Uniform("currentStep", step)); // add time uniform osg::Uniform* timeU = new osg::Uniform("time", 0.f); state->addUniform(timeU); timeU->setUpdateCallback(new timeUpdate()); state->setTextureAttributeAndModes(inputTexture, m_fboTextures[inputTexture], osg::StateAttribute::ON); state->setTextureAttributeAndModes(ID, m_fboTextures[ID], osg::StateAttribute::ON); return camera.release(); } // create post processing pass to put it all together osg::ref_ptr<osg::Camera> PostProcessing::postProcessingPass() { osg::ref_ptr<osg::Camera> postRenderCamera(new osg::Camera()); // input textures //postRenderCamera->attach((osg::Camera::BufferComponent) (osg::Camera::COLOR_BUFFER0 + COLOR), m_fboTextures[COLOR]); //postRenderCamera->attach((osg::Camera::BufferComponent) (osg::Camera::COLOR_BUFFER0 + NORMALDEPTH), m_fboTextures[NORMALDEPTH]); //postRenderCamera->attach((osg::Camera::BufferComponent) (osg::Camera::COLOR_BUFFER0 + ID), m_fboTextures[ID]); //postRenderCamera->attach((osg::Camera::BufferComponent) (osg::Camera::COLOR_BUFFER0 + PONG), m_fboTextures[PONG]); // configure postRenderCamera to draw fullscreen textured quad postRenderCamera->setClearColor(osg::Vec4(0.0, 0.5, 0.0, 1)); // should never see this. postRenderCamera->setReferenceFrame(osg::Camera::ABSOLUTE_RF); postRenderCamera->setRenderOrder(osg::Camera::POST_RENDER); // geometry osg::Geode* geode(new osg::Geode()); geode->addDrawable(osg::createTexturedQuadGeometry(osg::Vec3(-1, -1, 0), osg::Vec3(2, 0, 0), osg::Vec3(0, 2, 0))); //geode->getOrCreateStateSet()->setTextureAttributeAndModes(COLOR, m_fboTextures[COLOR], osg::StateAttribute::ON); //geode->getOrCreateStateSet()->setTextureAttributeAndModes(NORMALDEPTH, m_fboTextures[NORMALDEPTH], osg::StateAttribute::ON); /*geode->getOrCreateStateSet()->setTextureAttributeAndModes(ID, m_fboTextures[ID], osg::StateAttribute::ON); geode->getOrCreateStateSet()->setTextureAttributeAndModes(PONG, m_fboTextures[PONG], osg::StateAttribute::ON);*/ geode->getOrCreateStateSet()->setMode(GL_LIGHTING, osg::StateAttribute::OFF); postRenderCamera->addChild(geode); // attach shader program osg::ref_ptr<osg::StateSet> state = postRenderCamera->getOrCreateStateSet(); state->setMode(GL_DEPTH_TEST, osg::StateAttribute::ON); state->setAttributeAndModes(shaders::m_allShaderPrograms[shaders::POST_PROCESSING], osg::StateAttribute::ON); // add samplers state->addUniform(new osg::Uniform("sceneLayer", COLOR)); //state->addUniform(new osg::Uniform("normalDepthLayer", NORMALDEPTH)); state->addUniform(new osg::Uniform("idLayer", ID)); state->addUniform(new osg::Uniform("pongLayer", PONG)); state->setTextureAttributeAndModes(COLOR, m_fboTextures[COLOR], osg::StateAttribute::ON); //state->setTextureAttributeAndModes(NORMALDEPTH, m_fboTextures[NORMALDEPTH], osg::StateAttribute::ON); state->setTextureAttributeAndModes(ID, m_fboTextures[ID], osg::StateAttribute::ON); state->setTextureAttributeAndModes(PONG, m_fboTextures[PONG], osg::StateAttribute::ON); return postRenderCamera; } bool PostProcessing::handleGuiEvents(const osgGA::GUIEventAdapter& ea, osgGA::GUIActionAdapter&, osg::Object*, osg::NodeVisitor*) { if (ea.getEventType() == osgGA::GUIEventAdapter::RESIZE) { // re setup textures to new size setupTextures(ea.getWindowWidth(), ea.getWindowHeight()); return true; } else return false; } <|endoftext|>
<commit_before>#include "coursestablemanager.h" coursesTableManager::coursesTableManager(QTableWidget *ptr, user *usrPtr) { this->gp = NULL; this->us = usrPtr; this->courseTBL = ptr; /* * Initilizing Table */ courseTBL->setRowCount(0); courseTBL->setColumnCount(COURSE_FIELDS); QStringList mz; mz << QObject::tr("Number") << QObject::tr("Year") << QObject::tr("Semester") << QObject::tr("Serial") << QObject::tr("Name") << QObject::tr("Type") << QObject::tr("Points") << QObject::tr("Hours") << QObject::tr("Grade") << QObject::tr("Additions"); courseTBL->setHorizontalHeaderLabels(mz); courseTBL->verticalHeader()->setVisible(false); courseTBL->setSelectionMode(QAbstractItemView::SingleSelection); courseTBL->setShowGrid(true); courseTBL->setStyleSheet("QTableView {selection-background-color: red;}"); /* * */ graph = new gradegraph(NULL,gp); } coursesTableManager::~coursesTableManager() { courseTBL = NULL; delete gp; gp = NULL; } /** * @brief coursesTableManager::insertJceCoursesIntoTable phrasing the course list to rows in table */ void coursesTableManager::insertJceCoursesIntoTable() { for (gradeCourse *c: *gp->getCourses()) { if (us->getInfluenceCourseOnly()) { if (isCourseInfluence(c)) addRow(c); } else addRow(c); } } /** * @brief coursesTableManager::setCoursesList creating courses list with given html page * @param html */ void coursesTableManager::setCoursesList(QString &html) { if (gp != NULL) gp->~GradePage(); gp = new GradePage(html); } /** * @brief coursesTableManager::changes when user changes the table manually it updates it * @param change string change * @param row row index * @param col col index * @return if change has been done */ bool coursesTableManager::changes(QString change, int row, int col) { bool isNumFlag = true; if (courseTBL->item(row,gradeCourse::CourseScheme::SERIAL) == NULL) return true; int serialCourse = courseTBL->item(row,gradeCourse::CourseScheme::SERIAL)->text().toInt(); for (gradeCourse *c: *gp->getCourses()) { if (c->getSerialNum() == serialCourse) { switch (col) { case (gradeCourse::CourseScheme::COURSE_NUMBER_IN_LIST): c->setCourseNumInList(change.toInt()); break; case (gradeCourse::CourseScheme::YEAR): c->setYear(change.toInt()); break; case (gradeCourse::CourseScheme::SEMESTER): c->setSemester(change.toInt()); break; case (gradeCourse::CourseScheme::NAME): c->setName(change); break; case (gradeCourse::CourseScheme::TYPE): c->setType(change); break; case (gradeCourse::CourseScheme::POINTS): { change.toDouble(&isNumFlag); if (!isNumFlag) { courseTBL->item(row,col)->setText(QString::number(c->getPoints())); } else c->setPoints(change.toDouble()); break; } case (gradeCourse::CourseScheme::HOURS): { change.toDouble(&isNumFlag); if (!isNumFlag) { courseTBL->item(row,col)->setText(QString::number(c->getHours())); } else c->setHours(change.toDouble()); break; } case (gradeCourse::CourseScheme::GRADE): { change.toDouble(&isNumFlag); if (!isNumFlag) { courseTBL->item(row,col)->setText(QString::number(c->getGrade())); } else { if ((change.toDouble() >= 0) && (change.toDouble() <= 100)) c->setGrade(change.toDouble()); else courseTBL->item(row,col)->setText(QString::number(c->getGrade())); } break; } case (gradeCourse::CourseScheme::ADDITION): c->setAdditions(change); break; } break; } } return isNumFlag; } /** * @brief coursesTableManager::addRow adds row with given information * @param courseToAdd if exists, add its information to table */ void coursesTableManager::addRow(const gradeCourse *courseToAdd) { int i=1,j=1; j = 0; QTableWidgetItem *number,*year,*semester,*serial,*name,*type,*points,*hours,*grade,*addition; const gradeCourse * c; if (courseToAdd != NULL) { c = courseToAdd; if (!isCourseAlreadyInserted(c->getSerialNum())) { courseTBL->setRowCount(courseTBL->rowCount() + 1); i = courseTBL->rowCount()-1; number = new QTableWidgetItem(); number->setData(Qt::EditRole, c->getCourseNumInList()); number->setFlags(number->flags() & ~Qt::ItemIsEditable); year = new QTableWidgetItem(); year->setData(Qt::EditRole,c->getYear()); year->setFlags(year->flags() & ~Qt::ItemIsEditable); semester = new QTableWidgetItem(); semester->setData(Qt::EditRole,c->getSemester()); semester->setFlags(semester->flags() & ~Qt::ItemIsEditable); serial = new QTableWidgetItem(); serial->setData(Qt::EditRole,c->getSerialNum()); serial->setFlags(serial->flags() & ~Qt::ItemIsEditable); name = new QTableWidgetItem(); name->setData(Qt::EditRole,c->getName()); name->setFlags(name->flags() & ~Qt::ItemIsEditable); type = new QTableWidgetItem(); type->setData(Qt::EditRole, c->getType()); type->setFlags(type->flags() & ~Qt::ItemIsEditable); points = new QTableWidgetItem(); points->setData(Qt::EditRole, c->getPoints()); points->setFlags(points->flags() & ~Qt::ItemIsEditable); hours = new QTableWidgetItem(); hours->setData(Qt::EditRole, c->getHours()); hours->setFlags(hours->flags() & ~Qt::ItemIsEditable); grade = new QTableWidgetItem(); grade->setData(Qt::EditRole,c->getGrade()); addition = new QTableWidgetItem(); addition->setData(Qt::EditRole,c->getAddidtions()); courseTBL->setItem(i,j++,number); courseTBL->setItem(i,j++,year); courseTBL->setItem(i,j++,semester); courseTBL->setItem(i,j++,serial); courseTBL->setItem(i,j++,name); courseTBL->setItem(i,j++,type); courseTBL->setItem(i,j++,points); courseTBL->setItem(i,j++,hours); courseTBL->setItem(i,j++,grade); courseTBL->setItem(i,j,addition); } } else { qCritical() << Q_FUNC_INFO << "no course to load!"; } courseTBL->resizeColumnsToContents(); } double coursesTableManager::getAvg() { if (this->gp != NULL) return gp->getAvg(); return 0; } void coursesTableManager::showGraph() { if (gp != NULL) { qDebug() << "Graph Dialog Opened. gp != NULL"; this->graph->showGraph(gp); } } void coursesTableManager::influnceCourseChanged(bool ignoreCourseStatus) { if (ignoreCourseStatus) { int i = 0; while (i < courseTBL->rowCount()) { if (courseTBL->item(i,gradeCourse::CourseScheme::POINTS)->text().compare("0") == 0) courseTBL->removeRow(i--); i++; } } else { if (this->gp != NULL) for (gradeCourse *c: *gp->getCourses()) { if (!(isCourseAlreadyInserted(c->getSerialNum()))) if (c->getPoints() == 0) addRow(c); } } } void coursesTableManager::clearTable() { if (courseTBL->rowCount() == 0) return; int i = 0; //starting point while (courseTBL->rowCount() > i) { gp->removeCourse(courseTBL->item(i,gradeCourse::CourseScheme::SERIAL)->text()); courseTBL->removeRow(i); } gp = NULL; courseTBL->repaint(); } gradeCourse *coursesTableManager::getCourseByRow(int row) { QString courseSerial = courseTBL->item(row,gradeCourse::CourseScheme::SERIAL)->text(); for (gradeCourse *c: *gp->getCourses()) { if (c->getSerialNum() == courseSerial.toDouble()) return c; } return NULL; } bool coursesTableManager::isCourseAlreadyInserted(double courseID) { int i; for (i = courseTBL->rowCount(); i >= 0; --i) { if (courseTBL->item(i,gradeCourse::CourseScheme::SERIAL) != NULL) { QString courseSerial = courseTBL->item(i,gradeCourse::CourseScheme::SERIAL)->text(); if (QString::number(courseID) == courseSerial) return true; } } return false; } bool coursesTableManager::isCourseInfluence(const gradeCourse *courseToCheck) { if (courseToCheck->getPoints() > 0) return true; return false; } <commit_msg>added feature #26<commit_after>#include "coursestablemanager.h" coursesTableManager::coursesTableManager(QTableWidget *ptr, user *usrPtr) { this->gp = NULL; this->us = usrPtr; this->courseTBL = ptr; /* * Initilizing Table */ courseTBL->setRowCount(0); courseTBL->setColumnCount(COURSE_FIELDS); QStringList mz; mz << QObject::tr("Number") << QObject::tr("Year") << QObject::tr("Semester") << QObject::tr("Serial") << QObject::tr("Name") << QObject::tr("Type") << QObject::tr("Points") << QObject::tr("Hours") << QObject::tr("Grade") << QObject::tr("Additions"); courseTBL->setHorizontalHeaderLabels(mz); courseTBL->verticalHeader()->setVisible(false); courseTBL->setSelectionMode(QAbstractItemView::SingleSelection); courseTBL->setShowGrid(true); courseTBL->setStyleSheet("QTableView {selection-background-color: red;}"); /* * */ graph = new gradegraph(NULL,gp); } coursesTableManager::~coursesTableManager() { courseTBL = NULL; delete gp; gp = NULL; } /** * @brief coursesTableManager::insertJceCoursesIntoTable phrasing the course list to rows in table */ void coursesTableManager::insertJceCoursesIntoTable() { for (gradeCourse *c: *gp->getCourses()) { if (us->getInfluenceCourseOnly()) { if (isCourseInfluence(c)) addRow(c); } else addRow(c); } } /** * @brief coursesTableManager::setCoursesList creating courses list with given html page * @param html */ void coursesTableManager::setCoursesList(QString &html) { if (gp != NULL) gp->~GradePage(); gp = new GradePage(html); } /** * @brief coursesTableManager::changes when user changes the table manually it updates it * @param change string change * @param row row index * @param col col index * @return if change has been done */ bool coursesTableManager::changes(QString change, int row, int col) { bool isNumFlag = true; if (courseTBL->item(row,gradeCourse::CourseScheme::SERIAL) == NULL) return true; int serialCourse = courseTBL->item(row,gradeCourse::CourseScheme::SERIAL)->text().toInt(); for (gradeCourse *c: *gp->getCourses()) { if (c->getSerialNum() == serialCourse) { switch (col) { case (gradeCourse::CourseScheme::COURSE_NUMBER_IN_LIST): c->setCourseNumInList(change.toInt()); break; case (gradeCourse::CourseScheme::YEAR): c->setYear(change.toInt()); break; case (gradeCourse::CourseScheme::SEMESTER): c->setSemester(change.toInt()); break; case (gradeCourse::CourseScheme::NAME): c->setName(change); break; case (gradeCourse::CourseScheme::TYPE): c->setType(change); break; case (gradeCourse::CourseScheme::POINTS): { change.toDouble(&isNumFlag); if (!isNumFlag) { courseTBL->item(row,col)->setText(QString::number(c->getPoints())); } else c->setPoints(change.toDouble()); break; } case (gradeCourse::CourseScheme::HOURS): { change.toDouble(&isNumFlag); if (!isNumFlag) { courseTBL->item(row,col)->setText(QString::number(c->getHours())); } else c->setHours(change.toDouble()); break; } case (gradeCourse::CourseScheme::GRADE): { change.toDouble(&isNumFlag); if (!isNumFlag) { courseTBL->item(row,col)->setText(QString::number(c->getGrade())); } else { if ((change.toDouble() >= 0) && (change.toDouble() <= 100)) c->setGrade(change.toDouble()); else courseTBL->item(row,col)->setText(QString::number(c->getGrade())); } break; } case (gradeCourse::CourseScheme::ADDITION): c->setAdditions(change); break; } break; } } return isNumFlag; } /** * @brief coursesTableManager::addRow adds row with given information * @param courseToAdd if exists, add its information to table */ void coursesTableManager::addRow(const gradeCourse *courseToAdd) { int i=1,j=1; j = 0; QTableWidgetItem *number,*year,*semester,*serial,*name,*type,*points,*hours,*grade,*addition; const gradeCourse * c; if (courseToAdd != NULL) { c = courseToAdd; if (!isCourseAlreadyInserted(c->getSerialNum())) { courseTBL->setRowCount(courseTBL->rowCount() + 1); i = courseTBL->rowCount()-1; number = new QTableWidgetItem(); number->setData(Qt::EditRole, c->getCourseNumInList()); number->setFlags(number->flags() & ~Qt::ItemIsEditable); year = new QTableWidgetItem(); year->setData(Qt::EditRole,c->getYear()); year->setFlags(year->flags() & ~Qt::ItemIsEditable); semester = new QTableWidgetItem(); semester->setData(Qt::EditRole,c->getSemester()); semester->setFlags(semester->flags() & ~Qt::ItemIsEditable); serial = new QTableWidgetItem(); serial->setData(Qt::EditRole,c->getSerialNum()); serial->setFlags(serial->flags() & ~Qt::ItemIsEditable); name = new QTableWidgetItem(); name->setData(Qt::EditRole,c->getName()); name->setFlags(name->flags() & ~Qt::ItemIsEditable); type = new QTableWidgetItem(); type->setData(Qt::EditRole, c->getType()); type->setFlags(type->flags() & ~Qt::ItemIsEditable); points = new QTableWidgetItem(); points->setData(Qt::EditRole, c->getPoints()); points->setFlags(points->flags() & ~Qt::ItemIsEditable); hours = new QTableWidgetItem(); hours->setData(Qt::EditRole, c->getHours()); hours->setFlags(hours->flags() & ~Qt::ItemIsEditable); grade = new QTableWidgetItem(); grade->setData(Qt::EditRole,c->getGrade()); addition = new QTableWidgetItem(); addition->setData(Qt::EditRole,c->getAddidtions()); courseTBL->setItem(i,j++,number); courseTBL->setItem(i,j++,year); courseTBL->setItem(i,j++,semester); courseTBL->setItem(i,j++,serial); courseTBL->setItem(i,j++,name); courseTBL->setItem(i,j++,type); courseTBL->setItem(i,j++,points); courseTBL->setItem(i,j++,hours); courseTBL->setItem(i,j,grade); if(c->getGrade() < 55 && c->getGrade() != 0) { courseTBL->item(i, j)->setBackground(Qt::darkRed); courseTBL->item(i,j)->setTextColor(Qt::white); } else if(55 <= c->getGrade() && c->getGrade() < 70 ) { courseTBL->item(i, j)->setBackground(Qt::darkYellow); courseTBL->item(i,j)->setTextColor(Qt::white); } // else if(70 < c->getGrade() && c->getGrade() <= 80 ) // courseTBL->item(i, j)->setBackground(Qt::darkGreen); //They Look Bad!! // else if(c->getGrade() > 80) // courseTBL->item(i, j)->setBackground(Qt::green); j++; courseTBL->setItem(i,j,addition); } } else { qCritical() << Q_FUNC_INFO << "no course to load!"; } courseTBL->resizeColumnsToContents(); } double coursesTableManager::getAvg() { if (this->gp != NULL) return gp->getAvg(); return 0; } void coursesTableManager::showGraph() { if (gp != NULL) { qDebug() << "Graph Dialog Opened. gp != NULL"; this->graph->showGraph(gp); } } void coursesTableManager::influnceCourseChanged(bool ignoreCourseStatus) { if (ignoreCourseStatus) { int i = 0; while (i < courseTBL->rowCount()) { if (courseTBL->item(i,gradeCourse::CourseScheme::POINTS)->text().compare("0") == 0) courseTBL->removeRow(i--); i++; } } else { if (this->gp != NULL) for (gradeCourse *c: *gp->getCourses()) { if (!(isCourseAlreadyInserted(c->getSerialNum()))) if (c->getPoints() == 0) addRow(c); } } } void coursesTableManager::clearTable() { if (courseTBL->rowCount() == 0) return; int i = 0; //starting point while (courseTBL->rowCount() > i) { gp->removeCourse(courseTBL->item(i,gradeCourse::CourseScheme::SERIAL)->text()); courseTBL->removeRow(i); } gp = NULL; courseTBL->repaint(); } gradeCourse *coursesTableManager::getCourseByRow(int row) { QString courseSerial = courseTBL->item(row,gradeCourse::CourseScheme::SERIAL)->text(); for (gradeCourse *c: *gp->getCourses()) { if (c->getSerialNum() == courseSerial.toDouble()) return c; } return NULL; } bool coursesTableManager::isCourseAlreadyInserted(double courseID) { int i; for (i = courseTBL->rowCount(); i >= 0; --i) { if (courseTBL->item(i,gradeCourse::CourseScheme::SERIAL) != NULL) { QString courseSerial = courseTBL->item(i,gradeCourse::CourseScheme::SERIAL)->text(); if (QString::number(courseID) == courseSerial) return true; } } return false; } bool coursesTableManager::isCourseInfluence(const gradeCourse *courseToCheck) { if (courseToCheck->getPoints() > 0) return true; return false; } <|endoftext|>
<commit_before>// ***************************************************************************** // // Copyright (c) 2014, Southwest Research Institute® (SwRI®) // 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 Southwest Research Institute® (SwRI®) 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 <COPYRIGHT HOLDER> 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 <mapviz_plugins/tf_frame_plugin.h> // C++ standard libraries #include <cstdio> #include <algorithm> #include <vector> // QT libraries #include <QGLWidget> #include <QPalette> // ROS libraries #include <ros/master.h> #include <mapviz/select_frame_dialog.h> // Declare plugin #include <pluginlib/class_list_macros.h> PLUGINLIB_EXPORT_CLASS(mapviz_plugins::TfFramePlugin, mapviz::MapvizPlugin) namespace mapviz_plugins { TfFramePlugin::TfFramePlugin() : config_widget_(new QWidget()) { ui_.setupUi(config_widget_); ui_.color->setColor(Qt::green); // Set background white QPalette p(config_widget_->palette()); p.setColor(QPalette::Background, Qt::white); config_widget_->setPalette(p); // Set status text red QPalette p3(ui_.status->palette()); p3.setColor(QPalette::Text, Qt::red); ui_.status->setPalette(p3); QObject::connect(ui_.selectframe, SIGNAL(clicked()), this, SLOT(SelectFrame())); QObject::connect(ui_.frame, SIGNAL(editingFinished()), this, SLOT(FrameEdited())); QObject::connect(ui_.positiontolerance, SIGNAL(valueChanged(double)), this, SLOT(PositionToleranceChanged(double))); QObject::connect(ui_.buffersize, SIGNAL(valueChanged(int)), this, SLOT(BufferSizeChanged(int))); QObject::connect(ui_.drawstyle, SIGNAL(activated(QString)), this, SLOT(SetDrawStyle(QString))); QObject::connect(ui_.static_arrow_sizes, SIGNAL(clicked(bool)), this, SLOT(SetStaticArrowSizes(bool))); QObject::connect(ui_.arrow_size, SIGNAL(valueChanged(int)), this, SLOT(SetArrowSize(int))); connect(ui_.color, SIGNAL(colorEdited(const QColor&)), this, SLOT(SetColor(const QColor&))); } TfFramePlugin::~TfFramePlugin() { } void TfFramePlugin::SelectFrame() { std::string frame = mapviz::SelectFrameDialog::selectFrame(tf_); if (!frame.empty()) { ui_.frame->setText(QString::fromStdString(frame)); FrameEdited(); } } void TfFramePlugin::FrameEdited() { source_frame_ = ui_.frame->text().toStdString(); PrintWarning("Waiting for transform."); ROS_INFO("Setting target frame to to %s", source_frame_.c_str()); initialized_ = true; } void TfFramePlugin::TimerCallback(const ros::TimerEvent& event) { swri_transform_util::Transform transform; if (GetTransform(ros::Time(), transform)) { StampedPoint stamped_point; stamped_point.point = transform.GetOrigin(); stamped_point.orientation = transform.GetOrientation(); stamped_point.source_frame = target_frame_; stamped_point.stamp = transform.GetStamp(); stamped_point.transformed = false; double distance = std::sqrt( std::pow(stamped_point.point.x() - points_.back().point.x(), 2) + std::pow(stamped_point.point.y() - points_.back().point.y(), 2)); if (points_.empty() || distance >= position_tolerance_) { points_.push_back(stamped_point); } if (buffer_size_ > 0) { while (static_cast<int>(points_.size()) > buffer_size_) { points_.pop_front(); } } cur_point_ = stamped_point; } } void TfFramePlugin::PrintError(const std::string& message) { PrintErrorHelper(ui_.status, message); } void TfFramePlugin::PrintInfo(const std::string& message) { PrintInfoHelper(ui_.status, message); } void TfFramePlugin::PrintWarning(const std::string& message) { PrintWarningHelper(ui_.status, message); } QWidget* TfFramePlugin::GetConfigWidget(QWidget* parent) { config_widget_->setParent(parent); return config_widget_; } bool TfFramePlugin::Initialize(QGLWidget* canvas) { canvas_ = canvas; timer_ = node_.createTimer(ros::Duration(0.1), &TfFramePlugin::TimerCallback, this); SetColor(ui_.color->color()); return true; } void TfFramePlugin::Draw(double x, double y, double scale) { if (DrawPoints(scale)) { PrintInfo("OK"); } } void TfFramePlugin::LoadConfig(const YAML::Node& node, const std::string& path) { if (node["frame"]) { node["frame"] >> source_frame_; ui_.frame->setText(source_frame_.c_str()); } if (node["color"]) { std::string color; node["color"] >> color; SetColor(QColor(color.c_str())); ui_.color->setColor(color_); } if (node["draw_style"]) { std::string draw_style; node["draw_style"] >> draw_style; if (draw_style == "lines") { draw_style_ = LINES; ui_.drawstyle->setCurrentIndex(0); } else if (draw_style == "points") { draw_style_ = POINTS; ui_.drawstyle->setCurrentIndex(1); } } if (node["position_tolerance"]) { node["position_tolerance"] >> position_tolerance_; ui_.positiontolerance->setValue(position_tolerance_); } if (node["buffer_size"]) { node["buffer_size"] >> buffer_size_; ui_.buffersize->setValue(buffer_size_); } if (node["static_arrow_sizes"]) { bool static_arrow_sizes = node["static_arrow_sizes"].as<bool>(); ui_.static_arrow_sizes->setChecked(static_arrow_sizes); SetStaticArrowSizes(static_arrow_sizes); } if (node["arrow_size"]) { ui_.arrow_size->setValue(node["arrow_size"].as<int>()); } FrameEdited(); } void TfFramePlugin::SaveConfig(YAML::Emitter& emitter, const std::string& path) { emitter << YAML::Key << "frame" << YAML::Value << ui_.frame->text().toStdString(); emitter << YAML::Key << "color" << YAML::Value << ui_.color->color().name().toStdString(); std::string draw_style = ui_.drawstyle->currentText().toStdString(); emitter << YAML::Key << "draw_style" << YAML::Value << draw_style; emitter << YAML::Key << "position_tolerance" << YAML::Value << position_tolerance_; emitter << YAML::Key << "buffer_size" << YAML::Value << buffer_size_; emitter << YAML::Key << "static_arrow_sizes" << YAML::Value << ui_.static_arrow_sizes->isChecked(); emitter << YAML::Key << "arrow_size" << YAML::Value << ui_.arrow_size->value(); } } <commit_msg>the option "arrow" was not loaded correctly<commit_after>// ***************************************************************************** // // Copyright (c) 2014, Southwest Research Institute® (SwRI®) // 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 Southwest Research Institute® (SwRI®) 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 <COPYRIGHT HOLDER> 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 <mapviz_plugins/tf_frame_plugin.h> // C++ standard libraries #include <cstdio> #include <algorithm> #include <vector> // QT libraries #include <QGLWidget> #include <QPalette> // ROS libraries #include <ros/master.h> #include <mapviz/select_frame_dialog.h> // Declare plugin #include <pluginlib/class_list_macros.h> PLUGINLIB_EXPORT_CLASS(mapviz_plugins::TfFramePlugin, mapviz::MapvizPlugin) namespace mapviz_plugins { TfFramePlugin::TfFramePlugin() : config_widget_(new QWidget()) { ui_.setupUi(config_widget_); ui_.color->setColor(Qt::green); // Set background white QPalette p(config_widget_->palette()); p.setColor(QPalette::Background, Qt::white); config_widget_->setPalette(p); // Set status text red QPalette p3(ui_.status->palette()); p3.setColor(QPalette::Text, Qt::red); ui_.status->setPalette(p3); QObject::connect(ui_.selectframe, SIGNAL(clicked()), this, SLOT(SelectFrame())); QObject::connect(ui_.frame, SIGNAL(editingFinished()), this, SLOT(FrameEdited())); QObject::connect(ui_.positiontolerance, SIGNAL(valueChanged(double)), this, SLOT(PositionToleranceChanged(double))); QObject::connect(ui_.buffersize, SIGNAL(valueChanged(int)), this, SLOT(BufferSizeChanged(int))); QObject::connect(ui_.drawstyle, SIGNAL(activated(QString)), this, SLOT(SetDrawStyle(QString))); QObject::connect(ui_.static_arrow_sizes, SIGNAL(clicked(bool)), this, SLOT(SetStaticArrowSizes(bool))); QObject::connect(ui_.arrow_size, SIGNAL(valueChanged(int)), this, SLOT(SetArrowSize(int))); QObject::connect(ui_.color, SIGNAL(colorEdited(const QColor&)), this, SLOT(SetColor(const QColor&))); } TfFramePlugin::~TfFramePlugin() { } void TfFramePlugin::SelectFrame() { std::string frame = mapviz::SelectFrameDialog::selectFrame(tf_); if (!frame.empty()) { ui_.frame->setText(QString::fromStdString(frame)); FrameEdited(); } } void TfFramePlugin::FrameEdited() { source_frame_ = ui_.frame->text().toStdString(); PrintWarning("Waiting for transform."); ROS_INFO("Setting target frame to to %s", source_frame_.c_str()); initialized_ = true; } void TfFramePlugin::TimerCallback(const ros::TimerEvent& event) { swri_transform_util::Transform transform; if (GetTransform(ros::Time(), transform)) { StampedPoint stamped_point; stamped_point.point = transform.GetOrigin(); stamped_point.orientation = transform.GetOrientation(); stamped_point.source_frame = target_frame_; stamped_point.stamp = transform.GetStamp(); stamped_point.transformed = false; double distance = std::sqrt( std::pow(stamped_point.point.x() - points_.back().point.x(), 2) + std::pow(stamped_point.point.y() - points_.back().point.y(), 2)); if (points_.empty() || distance >= position_tolerance_) { points_.push_back(stamped_point); } if (buffer_size_ > 0) { while (static_cast<int>(points_.size()) > buffer_size_) { points_.pop_front(); } } cur_point_ = stamped_point; } } void TfFramePlugin::PrintError(const std::string& message) { PrintErrorHelper(ui_.status, message); } void TfFramePlugin::PrintInfo(const std::string& message) { PrintInfoHelper(ui_.status, message); } void TfFramePlugin::PrintWarning(const std::string& message) { PrintWarningHelper(ui_.status, message); } QWidget* TfFramePlugin::GetConfigWidget(QWidget* parent) { config_widget_->setParent(parent); return config_widget_; } bool TfFramePlugin::Initialize(QGLWidget* canvas) { canvas_ = canvas; timer_ = node_.createTimer(ros::Duration(0.1), &TfFramePlugin::TimerCallback, this); SetColor(ui_.color->color()); return true; } void TfFramePlugin::Draw(double x, double y, double scale) { if (DrawPoints(scale)) { PrintInfo("OK"); } } void TfFramePlugin::LoadConfig(const YAML::Node& node, const std::string& path) { if (node["frame"]) { node["frame"] >> source_frame_; ui_.frame->setText(source_frame_.c_str()); } if (node["color"]) { std::string color; node["color"] >> color; SetColor(QColor(color.c_str())); ui_.color->setColor(color_); } if (node["draw_style"]) { std::string draw_style; node["draw_style"] >> draw_style; if (draw_style == "lines") { draw_style_ = LINES; ui_.drawstyle->setCurrentIndex(0); } else if (draw_style == "points") { draw_style_ = POINTS; ui_.drawstyle->setCurrentIndex(1); } else if (draw_style == "arrows") { draw_style_ = ARROWS; ui_.drawstyle->setCurrentIndex(2); } } if (node["position_tolerance"]) { node["position_tolerance"] >> position_tolerance_; ui_.positiontolerance->setValue(position_tolerance_); } if (node["buffer_size"]) { node["buffer_size"] >> buffer_size_; ui_.buffersize->setValue(buffer_size_); } if (node["static_arrow_sizes"]) { bool static_arrow_sizes = node["static_arrow_sizes"].as<bool>(); ui_.static_arrow_sizes->setChecked(static_arrow_sizes); SetStaticArrowSizes(static_arrow_sizes); } if (node["arrow_size"]) { ui_.arrow_size->setValue(node["arrow_size"].as<int>()); } FrameEdited(); } void TfFramePlugin::SaveConfig(YAML::Emitter& emitter, const std::string& path) { emitter << YAML::Key << "frame" << YAML::Value << ui_.frame->text().toStdString(); emitter << YAML::Key << "color" << YAML::Value << ui_.color->color().name().toStdString(); std::string draw_style = ui_.drawstyle->currentText().toStdString(); emitter << YAML::Key << "draw_style" << YAML::Value << draw_style; emitter << YAML::Key << "position_tolerance" << YAML::Value << position_tolerance_; emitter << YAML::Key << "buffer_size" << YAML::Value << buffer_size_; emitter << YAML::Key << "static_arrow_sizes" << YAML::Value << ui_.static_arrow_sizes->isChecked(); emitter << YAML::Key << "arrow_size" << YAML::Value << ui_.arrow_size->value(); } } <|endoftext|>
<commit_before>#include "enemy.h" Enemy::Enemy(Player* player, float lineOfSight, float forceTowardsPlayer, float forceFromAbstacles, float health, float speed, float damage, int width, int height, unsigned int textureID, b2World * world) : Person::Person(health, speed, damage, width, height, textureID, world) { this->player = player; this->lineOfSight = lineOfSight; this->forceTowardsPlayer = forceTowardsPlayer; this->forceFromObstacles = forceFromAbstacles; raycast = new Raycast(world); distanceObjects = new B2Entity(width, height, 0, world); distanceObjects->CreateCircleCollider(65, true, true); distanceObjects->SetDebugColor(glm::vec3(1, 0, 0)); this->AddChild(distanceObjects); /*mirror = new Mirror(false, 45.0f, 120.0f, ResourceManager::GetTexture("mirror")->GetId(), world); mirror->localPosition.x = 100; mirror->CreateBoxCollider(45.0f, 120.0f, glm::vec2(0.0f, 0.0f), false, false); mirror->SetFilter(2); AddChild(mirror);*/ attackRadius = 150.0f; sword = new B2Entity(75, 120, ResourceManager::GetTexture("sword")->GetId(), world); sword->SetPivot(glm::vec2(0.0f, -0.5f)); sword->CreateBoxCollider(40, 120, glm::vec2(0, -0.5f), true, true); sword->localPosition = glm::vec2(20,34); sword->localAngle = glm::radians(110.0f); sword->SetFilter(2); AddChild(sword); redHealthbar = new Sprite(150, 15, 0); redHealthbar->SetColor(glm::vec4(1, 0, 0, 1)); redHealthbar->SetPivot(glm::vec2(0.5f, 0.0f)); AddChild(redHealthbar); greenHealthbar = new Sprite(150, 15, 0); greenHealthbar->SetColor(glm::vec4(0, 1, 0, 1)); greenHealthbar->SetPivot(glm::vec2(0.5f, 0.0f)); AddChild(greenHealthbar); } Enemy::~Enemy() { delete raycast; delete distanceObjects; //delete mirror; delete sword; delete redHealthbar; delete greenHealthbar; } void Enemy::Update(double deltaTime) { glm::vec2 rayDestination = player->GetGlobalPosition() - position; rayDestination = glm::normalize(rayDestination); rayDestination *= lineOfSight; rayDestination += position; raycast->Update(position, rayDestination); raycast->Draw(glm::vec3(0,1,0)); glm::vec2 acceleration; bool playerHit = false; // Check if the first object hitted by the raycast is the player std::vector<RaycastHit> hits = raycast->GetHits(); for (int i = 0; i < hits.size(); i++) { B2Entity* b = static_cast<B2Entity*>(hits[i].fixture->GetUserData()); if (b == player) { // hitted player lastPositionPlayer = player->GetGlobalPosition(); if (glm::length(lastPositionPlayer - position) < attackRadius) { sword->localAngle -= glm::radians(180.0f) * deltaTime; if (sword->localAngle < 0) {//glm::radians(90.0f) * -1) { sword->localAngle = glm::radians(110.0f); } if (sword->Contact(player)) { player->Damage(damage * deltaTime); } } else { sword->localAngle = glm::radians(110.0f); acceleration += (glm::normalize(lastPositionPlayer - position) * forceTowardsPlayer); } playerHit = true; glm::vec2 diff = player->GetGlobalPosition() - position; diff = glm::normalize(diff); float _angle = glm::atan(diff.y, diff.x); localAngle = _angle; continue; } // If the raycast hit is a enemy or a sensor continue with the for loop otheriwse break it else if (dynamic_cast<Enemy*>(b) != NULL || hits[i].fixture->IsSensor() || b->GetFilter() == 2) { continue; } break; } if (!playerHit && glm::length(position - lastPositionPlayer) > 75.0f) { acceleration += (glm::normalize(lastPositionPlayer - position) * forceTowardsPlayer); glm::vec2 diff = lastPositionPlayer - position; diff = glm::normalize(diff); float _angle = glm::atan(diff.y, diff.x); localAngle = _angle; } std::vector<B2Entity*> inRangeObjects = distanceObjects->GetAllContacts(); for (int i = 0; i < inRangeObjects.size(); i++) { if (inRangeObjects[i] != this && inRangeObjects[i] != player && inRangeObjects[i]->GetFilter() != 2) { // hitted a wall or something acceleration += (glm::normalize(position - inRangeObjects[i]->GetGlobalPosition()) * forceFromObstacles); } } if (acceleration.x != 0 || acceleration.y != 0) { velocity += acceleration; velocity = glm::normalize(velocity); velocity *= speed; this->localPosition = this->ApplyVelocityB2body(velocity); } } void Enemy::Draw() { // Update the healthbars redHealthbar->UpdateChilderen(NULL, 0); greenHealthbar->UpdateChilderen(NULL, 0); redHealthbar->localPosition = glm::vec2(position.x - 75, position.y + 125); greenHealthbar->localPosition = glm::vec2(position.x - 75, position.y + 125); greenHealthbar->SetWidth(currentHealth / maxHealth * 150); // Render renderer->Submit(this); if (body != nullptr) { DebugRenderer::Submit(this); } } <commit_msg>removed unnecesary lines<commit_after>#include "enemy.h" Enemy::Enemy(Player* player, float lineOfSight, float forceTowardsPlayer, float forceFromAbstacles, float health, float speed, float damage, int width, int height, unsigned int textureID, b2World * world) : Person::Person(health, speed, damage, width, height, textureID, world) { this->player = player; this->lineOfSight = lineOfSight; this->forceTowardsPlayer = forceTowardsPlayer; this->forceFromObstacles = forceFromAbstacles; raycast = new Raycast(world); distanceObjects = new B2Entity(width, height, 0, world); distanceObjects->CreateCircleCollider(65, true, true); this->AddChild(distanceObjects); attackRadius = 150.0f; sword = new B2Entity(75, 120, ResourceManager::GetTexture("sword")->GetId(), world); sword->SetPivot(glm::vec2(0.0f, -0.5f)); sword->CreateBoxCollider(40, 120, glm::vec2(0, -0.5f), true, true); sword->localPosition = glm::vec2(20,34); sword->localAngle = glm::radians(110.0f); sword->SetFilter(2); AddChild(sword); redHealthbar = new Sprite(150, 15, 0); redHealthbar->SetColor(glm::vec4(1, 0, 0, 1)); redHealthbar->SetPivot(glm::vec2(0.5f, 0.0f)); AddChild(redHealthbar); greenHealthbar = new Sprite(150, 15, 0); greenHealthbar->SetColor(glm::vec4(0, 1, 0, 1)); greenHealthbar->SetPivot(glm::vec2(0.5f, 0.0f)); AddChild(greenHealthbar); } Enemy::~Enemy() { delete raycast; delete distanceObjects; //delete mirror; delete sword; delete redHealthbar; delete greenHealthbar; } void Enemy::Update(double deltaTime) { glm::vec2 rayDestination = player->GetGlobalPosition() - position; rayDestination = glm::normalize(rayDestination); rayDestination *= lineOfSight; rayDestination += position; raycast->Update(position, rayDestination); raycast->Draw(glm::vec3(0,1,0)); glm::vec2 acceleration; bool playerHit = false; // Check if the first object hitted by the raycast is the player std::vector<RaycastHit> hits = raycast->GetHits(); for (int i = 0; i < hits.size(); i++) { B2Entity* b = static_cast<B2Entity*>(hits[i].fixture->GetUserData()); if (b == player) { // hitted player lastPositionPlayer = player->GetGlobalPosition(); if (glm::length(lastPositionPlayer - position) < attackRadius) { sword->localAngle -= glm::radians(180.0f) * deltaTime; if (sword->localAngle < 0) {//glm::radians(90.0f) * -1) { sword->localAngle = glm::radians(110.0f); } if (sword->Contact(player)) { player->Damage(damage * deltaTime); } } else { sword->localAngle = glm::radians(110.0f); acceleration += (glm::normalize(lastPositionPlayer - position) * forceTowardsPlayer); } playerHit = true; glm::vec2 diff = player->GetGlobalPosition() - position; diff = glm::normalize(diff); float _angle = glm::atan(diff.y, diff.x); localAngle = _angle; continue; } // If the raycast hit is a enemy or a sensor continue with the for loop otheriwse break it else if (dynamic_cast<Enemy*>(b) != NULL || hits[i].fixture->IsSensor() || b->GetFilter() == 2) { continue; } break; } if (!playerHit && glm::length(position - lastPositionPlayer) > 75.0f) { acceleration += (glm::normalize(lastPositionPlayer - position) * forceTowardsPlayer); glm::vec2 diff = lastPositionPlayer - position; diff = glm::normalize(diff); float _angle = glm::atan(diff.y, diff.x); localAngle = _angle; } std::vector<B2Entity*> inRangeObjects = distanceObjects->GetAllContacts(); for (int i = 0; i < inRangeObjects.size(); i++) { if (inRangeObjects[i] != this && inRangeObjects[i] != player && inRangeObjects[i]->GetFilter() != 2) { // hitted a wall or something acceleration += (glm::normalize(position - inRangeObjects[i]->GetGlobalPosition()) * forceFromObstacles); } } if (acceleration.x != 0 || acceleration.y != 0) { velocity += acceleration; velocity = glm::normalize(velocity); velocity *= speed; this->localPosition = this->ApplyVelocityB2body(velocity); } } void Enemy::Draw() { // Update the healthbars redHealthbar->UpdateChilderen(NULL, 0); greenHealthbar->UpdateChilderen(NULL, 0); redHealthbar->localPosition = glm::vec2(position.x - 75, position.y + 125); greenHealthbar->localPosition = glm::vec2(position.x - 75, position.y + 125); greenHealthbar->SetWidth(currentHealth / maxHealth * 150); // Render renderer->Submit(this); if (body != nullptr) { DebugRenderer::Submit(this); } } <|endoftext|>
<commit_before>/* * Copyright (C) 2005-2019 Centre National d'Etudes Spatiales (CNES) * * This file is part of Orfeo Toolbox * * https://www.orfeo-toolbox.org/ * * 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 otbFastICAImageFilter_hxx #define otbFastICAImageFilter_hxx #include "otbFastICAImageFilter.h" #include "itkNumericTraits.h" #include "itkProgressReporter.h" #include <vnl/vnl_matrix.h> #include <vnl/algo/vnl_matrix_inverse.h> #include <vnl/algo/vnl_generalized_eigensystem.h> namespace otb { template < class TInputImage, class TOutputImage, Transform::TransformDirection TDirectionOfTransformation > FastICAImageFilter< TInputImage, TOutputImage, TDirectionOfTransformation > ::FastICAImageFilter () { this->SetNumberOfRequiredInputs(1); m_NumberOfPrincipalComponentsRequired = 0; m_GivenTransformationMatrix = false; m_IsTransformationForward = true; m_NumberOfIterations = 50; m_ConvergenceThreshold = 1E-4; m_NonLinearity = [](double x) {return std::tanh(x);}; m_NonLinearityDerivative = [](double x) {return 1-std::pow( std::tanh(x), 2. );}; m_Mu = 1.; m_PCAFilter = PCAFilterType::New(); m_PCAFilter->SetUseNormalization(true); m_PCAFilter->SetUseVarianceForNormalization(false); m_TransformFilter = TransformFilterType::New(); } template < class TInputImage, class TOutputImage, Transform::TransformDirection TDirectionOfTransformation > void FastICAImageFilter< TInputImage, TOutputImage, TDirectionOfTransformation > ::GenerateOutputInformation() // throw itk::ExceptionObject { Superclass::GenerateOutputInformation(); switch ( static_cast<int>(DirectionOfTransformation) ) { case static_cast<int>(Transform::FORWARD): { if ( m_NumberOfPrincipalComponentsRequired == 0 || m_NumberOfPrincipalComponentsRequired > this->GetInput()->GetNumberOfComponentsPerPixel() ) { m_NumberOfPrincipalComponentsRequired = this->GetInput()->GetNumberOfComponentsPerPixel(); } this->GetOutput()->SetNumberOfComponentsPerPixel( m_NumberOfPrincipalComponentsRequired ); break; } case static_cast<int>(Transform::INVERSE): { unsigned int theOutputDimension = 0; if ( m_GivenTransformationMatrix ) { theOutputDimension = m_TransformationMatrix.Rows() >= m_TransformationMatrix.Cols() ? m_TransformationMatrix.Rows() : m_TransformationMatrix.Cols(); } else { throw itk::ExceptionObject(__FILE__, __LINE__, "Mixture matrix is required to know the output size", ITK_LOCATION); } this->GetOutput()->SetNumberOfComponentsPerPixel( theOutputDimension ); break; } default: throw itk::ExceptionObject(__FILE__, __LINE__, "Class should be templeted with FORWARD or INVERSE only...", ITK_LOCATION ); } switch ( static_cast<int>(DirectionOfTransformation) ) { case static_cast<int>(Transform::FORWARD): { ForwardGenerateOutputInformation(); break; } case static_cast<int>(Transform::INVERSE): { ReverseGenerateOutputInformation(); break; } } } template < class TInputImage, class TOutputImage, Transform::TransformDirection TDirectionOfTransformation > void FastICAImageFilter< TInputImage, TOutputImage, TDirectionOfTransformation > ::ForwardGenerateOutputInformation() { typename InputImageType::Pointer inputImgPtr = const_cast<InputImageType*>( this->GetInput() ); m_PCAFilter->SetInput( inputImgPtr ); m_PCAFilter->GetOutput()->UpdateOutputInformation(); if ( !m_GivenTransformationMatrix ) { GenerateTransformationMatrix(); } else if ( !m_IsTransformationForward ) { // prevent from multiple inversion in the pipelines m_IsTransformationForward = true; vnl_svd< MatrixElementType > invertor ( m_TransformationMatrix.GetVnlMatrix() ); m_TransformationMatrix = invertor.pinverse(); } if ( m_TransformationMatrix.GetVnlMatrix().empty() ) { throw itk::ExceptionObject( __FILE__, __LINE__, "Empty transformation matrix", ITK_LOCATION); } m_TransformFilter->SetInput( m_PCAFilter->GetOutput() ); m_TransformFilter->SetMatrix( m_TransformationMatrix.GetVnlMatrix() ); } template < class TInputImage, class TOutputImage, Transform::TransformDirection TDirectionOfTransformation > void FastICAImageFilter< TInputImage, TOutputImage, TDirectionOfTransformation > ::ReverseGenerateOutputInformation() { if ( !m_GivenTransformationMatrix ) { throw itk::ExceptionObject( __FILE__, __LINE__, "No Transformation matrix given", ITK_LOCATION ); } if ( m_TransformationMatrix.GetVnlMatrix().empty() ) { throw itk::ExceptionObject( __FILE__, __LINE__, "Empty transformation matrix", ITK_LOCATION); } if ( m_IsTransformationForward ) { // prevent from multiple inversion in the pipelines m_IsTransformationForward = false; vnl_svd< MatrixElementType > invertor ( m_TransformationMatrix.GetVnlMatrix() ); m_TransformationMatrix = invertor.pinverse(); } m_TransformFilter->SetInput( this->GetInput() ); m_TransformFilter->SetMatrix( m_TransformationMatrix.GetVnlMatrix() ); /* * PCA filter may throw exception if * the mean, stdDev and transformation matrix * have not been given at this point */ m_PCAFilter->SetInput( m_TransformFilter->GetOutput() ); } template < class TInputImage, class TOutputImage, Transform::TransformDirection TDirectionOfTransformation > void FastICAImageFilter< TInputImage, TOutputImage, TDirectionOfTransformation > ::GenerateData () { switch ( static_cast<int>(DirectionOfTransformation) ) { case static_cast<int>(Transform::FORWARD): return ForwardGenerateData(); case static_cast<int>(Transform::INVERSE): return ReverseGenerateData(); default: throw itk::ExceptionObject(__FILE__, __LINE__, "Class should be templated with FORWARD or INVERSE only...", ITK_LOCATION ); } } template < class TInputImage, class TOutputImage, Transform::TransformDirection TDirectionOfTransformation > void FastICAImageFilter< TInputImage, TOutputImage, TDirectionOfTransformation > ::ForwardGenerateData () { m_TransformFilter->GraftOutput( this->GetOutput() ); m_TransformFilter->Update(); this->GraftOutput( m_TransformFilter->GetOutput() ); } template < class TInputImage, class TOutputImage, Transform::TransformDirection TDirectionOfTransformation > void FastICAImageFilter< TInputImage, TOutputImage, TDirectionOfTransformation > ::ReverseGenerateData () { m_PCAFilter->GraftOutput( this->GetOutput() ); m_PCAFilter->Update(); this->GraftOutput( m_PCAFilter->GetOutput() ); } template < class TInputImage, class TOutputImage, Transform::TransformDirection TDirectionOfTransformation > void FastICAImageFilter< TInputImage, TOutputImage, TDirectionOfTransformation > ::GenerateTransformationMatrix () { itk::ProgressReporter reporter ( this, 0, GetNumberOfIterations(), GetNumberOfIterations() ); double convergence = itk::NumericTraits<double>::max(); unsigned int iteration = 0; const unsigned int size = this->GetInput()->GetNumberOfComponentsPerPixel(); // transformation matrix InternalMatrixType W ( size, size, vnl_matrix_identity ); while ( iteration++ < GetNumberOfIterations() && convergence > GetConvergenceThreshold() ) { InternalMatrixType W_old ( W ); typename InputImageType::Pointer img = const_cast<InputImageType*>( m_PCAFilter->GetOutput() ); TransformFilterPointerType transformer = TransformFilterType::New(); if ( !W.is_identity() ) { transformer->SetInput( GetPCAFilter()->GetOutput() ); transformer->SetMatrix( W ); transformer->Update(); img = const_cast<InputImageType*>( transformer->GetOutput() ); } for ( unsigned int band = 0; band < size; band++ ) { otbMsgDebugMacro( << "Iteration " << iteration << ", bande " << band << ", convergence " << convergence ); InternalOptimizerPointerType optimizer = InternalOptimizerType::New(); optimizer->SetInput( 0, m_PCAFilter->GetOutput() ); optimizer->SetInput( 1, img ); optimizer->SetW( W ); optimizer->SetNonLinearity( this->GetNonLinearity(), this->GetNonLinearityDerivative() ); optimizer->SetCurrentBandForLoop( band ); MeanEstimatorFilterPointerType estimator = MeanEstimatorFilterType::New(); estimator->SetInput( optimizer->GetOutput() ); // Here we have a pipeline of two persistent filters, we have to manually // call Reset() and Synthetize () on the first one (optimizer). optimizer->Reset(); estimator->Update(); optimizer->Synthetize(); double norm = 0.; for ( unsigned int bd = 0; bd < size; bd++ ) { W(bd, band) -= m_Mu * ( estimator->GetMean()[bd] - optimizer->GetBeta() * W(bd, band) ) / optimizer->GetDen(); norm += std::pow( W(bd, band), 2. ); } for ( unsigned int bd = 0; bd < size; bd++ ) W(bd, band) /= std::sqrt( norm ); } // Decorrelation of the W vectors InternalMatrixType W_tmp = W * W.transpose(); vnl_svd< MatrixElementType > solver ( W_tmp ); InternalMatrixType valP = solver.W(); for ( unsigned int i = 0; i < valP.rows(); ++i ) valP(i, i) = 1. / std::sqrt( static_cast<double>( valP(i, i) ) ); // Watch for 0 or neg InternalMatrixType transf = solver.U(); W_tmp = transf * valP * transf.transpose(); W = W_tmp * W; // Convergence evaluation convergence = 0.; for ( unsigned int i = 0; i < W.rows(); ++i ) for ( unsigned int j = 0; j < W.cols(); ++j ) convergence += std::abs( W(i, j) - W_old(i, j) ); reporter.CompletedPixel(); } // end of while loop if ( size != this->GetNumberOfPrincipalComponentsRequired() ) { this->m_TransformationMatrix = W.get_n_columns( 0, this->GetNumberOfPrincipalComponentsRequired() ); } else { this->m_TransformationMatrix = W; } otbMsgDebugMacro( << "Final convergence " << convergence << " after " << iteration << " iterations" ); } } // end of namespace otb #endif <commit_msg>ENH: the dimensioality reduction is now done in the pca step<commit_after>/* * Copyright (C) 2005-2019 Centre National d'Etudes Spatiales (CNES) * * This file is part of Orfeo Toolbox * * https://www.orfeo-toolbox.org/ * * 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 otbFastICAImageFilter_hxx #define otbFastICAImageFilter_hxx #include "otbFastICAImageFilter.h" #include "itkNumericTraits.h" #include "itkProgressReporter.h" #include <vnl/vnl_matrix.h> #include <vnl/algo/vnl_matrix_inverse.h> #include <vnl/algo/vnl_generalized_eigensystem.h> namespace otb { template < class TInputImage, class TOutputImage, Transform::TransformDirection TDirectionOfTransformation > FastICAImageFilter< TInputImage, TOutputImage, TDirectionOfTransformation > ::FastICAImageFilter () { this->SetNumberOfRequiredInputs(1); m_NumberOfPrincipalComponentsRequired = 0; m_GivenTransformationMatrix = false; m_IsTransformationForward = true; m_NumberOfIterations = 50; m_ConvergenceThreshold = 1E-4; m_NonLinearity = [](double x) {return std::tanh(x);}; m_NonLinearityDerivative = [](double x) {return 1-std::pow( std::tanh(x), 2. );}; m_Mu = 1.; m_PCAFilter = PCAFilterType::New(); m_PCAFilter->SetUseNormalization(true); m_PCAFilter->SetUseVarianceForNormalization(false); m_TransformFilter = TransformFilterType::New(); } template < class TInputImage, class TOutputImage, Transform::TransformDirection TDirectionOfTransformation > void FastICAImageFilter< TInputImage, TOutputImage, TDirectionOfTransformation > ::GenerateOutputInformation() // throw itk::ExceptionObject { Superclass::GenerateOutputInformation(); switch ( static_cast<int>(DirectionOfTransformation) ) { case static_cast<int>(Transform::FORWARD): { if ( m_NumberOfPrincipalComponentsRequired == 0 || m_NumberOfPrincipalComponentsRequired > this->GetInput()->GetNumberOfComponentsPerPixel() ) { m_NumberOfPrincipalComponentsRequired = this->GetInput()->GetNumberOfComponentsPerPixel(); } m_PCAFilter->SetNumberOfPrincipalComponentsRequired( m_NumberOfPrincipalComponentsRequired); this->GetOutput()->SetNumberOfComponentsPerPixel( m_NumberOfPrincipalComponentsRequired ); break; } case static_cast<int>(Transform::INVERSE): { unsigned int theOutputDimension = 0; if ( m_GivenTransformationMatrix ) { theOutputDimension = m_TransformationMatrix.Rows() >= m_TransformationMatrix.Cols() ? m_TransformationMatrix.Rows() : m_TransformationMatrix.Cols(); } else { throw itk::ExceptionObject(__FILE__, __LINE__, "Mixture matrix is required to know the output size", ITK_LOCATION); } this->GetOutput()->SetNumberOfComponentsPerPixel( theOutputDimension ); break; } default: throw itk::ExceptionObject(__FILE__, __LINE__, "Class should be templeted with FORWARD or INVERSE only...", ITK_LOCATION ); } switch ( static_cast<int>(DirectionOfTransformation) ) { case static_cast<int>(Transform::FORWARD): { ForwardGenerateOutputInformation(); break; } case static_cast<int>(Transform::INVERSE): { ReverseGenerateOutputInformation(); break; } } } template < class TInputImage, class TOutputImage, Transform::TransformDirection TDirectionOfTransformation > void FastICAImageFilter< TInputImage, TOutputImage, TDirectionOfTransformation > ::ForwardGenerateOutputInformation() { typename InputImageType::Pointer inputImgPtr = const_cast<InputImageType*>( this->GetInput() ); m_PCAFilter->SetInput( inputImgPtr ); m_PCAFilter->GetOutput()->UpdateOutputInformation(); if ( !m_GivenTransformationMatrix ) { GenerateTransformationMatrix(); } else if ( !m_IsTransformationForward ) { // prevent from multiple inversion in the pipelines m_IsTransformationForward = true; vnl_svd< MatrixElementType > invertor ( m_TransformationMatrix.GetVnlMatrix() ); m_TransformationMatrix = invertor.pinverse(); } if ( m_TransformationMatrix.GetVnlMatrix().empty() ) { throw itk::ExceptionObject( __FILE__, __LINE__, "Empty transformation matrix", ITK_LOCATION); } m_TransformFilter->SetInput( m_PCAFilter->GetOutput() ); m_TransformFilter->SetMatrix( m_TransformationMatrix.GetVnlMatrix() ); } template < class TInputImage, class TOutputImage, Transform::TransformDirection TDirectionOfTransformation > void FastICAImageFilter< TInputImage, TOutputImage, TDirectionOfTransformation > ::ReverseGenerateOutputInformation() { if ( !m_GivenTransformationMatrix ) { throw itk::ExceptionObject( __FILE__, __LINE__, "No Transformation matrix given", ITK_LOCATION ); } if ( m_TransformationMatrix.GetVnlMatrix().empty() ) { throw itk::ExceptionObject( __FILE__, __LINE__, "Empty transformation matrix", ITK_LOCATION); } if ( m_IsTransformationForward ) { // prevent from multiple inversion in the pipelines m_IsTransformationForward = false; vnl_svd< MatrixElementType > invertor ( m_TransformationMatrix.GetVnlMatrix() ); m_TransformationMatrix = invertor.pinverse(); } m_TransformFilter->SetInput( this->GetInput() ); m_TransformFilter->SetMatrix( m_TransformationMatrix.GetVnlMatrix() ); /* * PCA filter may throw exception if * the mean, stdDev and transformation matrix * have not been given at this point */ m_PCAFilter->SetInput( m_TransformFilter->GetOutput() ); } template < class TInputImage, class TOutputImage, Transform::TransformDirection TDirectionOfTransformation > void FastICAImageFilter< TInputImage, TOutputImage, TDirectionOfTransformation > ::GenerateData () { switch ( static_cast<int>(DirectionOfTransformation) ) { case static_cast<int>(Transform::FORWARD): return ForwardGenerateData(); case static_cast<int>(Transform::INVERSE): return ReverseGenerateData(); default: throw itk::ExceptionObject(__FILE__, __LINE__, "Class should be templated with FORWARD or INVERSE only...", ITK_LOCATION ); } } template < class TInputImage, class TOutputImage, Transform::TransformDirection TDirectionOfTransformation > void FastICAImageFilter< TInputImage, TOutputImage, TDirectionOfTransformation > ::ForwardGenerateData () { m_TransformFilter->GraftOutput( this->GetOutput() ); m_TransformFilter->Update(); this->GraftOutput( m_TransformFilter->GetOutput() ); } template < class TInputImage, class TOutputImage, Transform::TransformDirection TDirectionOfTransformation > void FastICAImageFilter< TInputImage, TOutputImage, TDirectionOfTransformation > ::ReverseGenerateData () { m_PCAFilter->GraftOutput( this->GetOutput() ); m_PCAFilter->Update(); this->GraftOutput( m_PCAFilter->GetOutput() ); } template < class TInputImage, class TOutputImage, Transform::TransformDirection TDirectionOfTransformation > void FastICAImageFilter< TInputImage, TOutputImage, TDirectionOfTransformation > ::GenerateTransformationMatrix () { itk::ProgressReporter reporter ( this, 0, GetNumberOfIterations(), GetNumberOfIterations() ); double convergence = itk::NumericTraits<double>::max(); unsigned int iteration = 0; const unsigned int size = this->GetNumberOfPrincipalComponentsRequired(); // transformation matrix InternalMatrixType W ( size, size, vnl_matrix_identity ); while ( iteration++ < GetNumberOfIterations() && convergence > GetConvergenceThreshold() ) { InternalMatrixType W_old ( W ); typename InputImageType::Pointer img = const_cast<InputImageType*>( m_PCAFilter->GetOutput() ); TransformFilterPointerType transformer = TransformFilterType::New(); if ( !W.is_identity() ) { transformer->SetInput( GetPCAFilter()->GetOutput() ); transformer->SetMatrix( W ); transformer->Update(); img = const_cast<InputImageType*>( transformer->GetOutput() ); } for ( unsigned int band = 0; band < size; band++ ) { otbMsgDebugMacro( << "Iteration " << iteration << ", bande " << band << ", convergence " << convergence ); InternalOptimizerPointerType optimizer = InternalOptimizerType::New(); optimizer->SetInput( 0, m_PCAFilter->GetOutput() ); optimizer->SetInput( 1, img ); optimizer->SetW( W ); optimizer->SetNonLinearity( this->GetNonLinearity(), this->GetNonLinearityDerivative() ); optimizer->SetCurrentBandForLoop( band ); MeanEstimatorFilterPointerType estimator = MeanEstimatorFilterType::New(); estimator->SetInput( optimizer->GetOutput() ); // Here we have a pipeline of two persistent filters, we have to manually // call Reset() and Synthetize () on the first one (optimizer). optimizer->Reset(); estimator->Update(); optimizer->Synthetize(); double norm = 0.; for ( unsigned int bd = 0; bd < size; bd++ ) { W(bd, band) -= m_Mu * ( estimator->GetMean()[bd] - optimizer->GetBeta() * W(bd, band) ) / optimizer->GetDen(); norm += std::pow( W(bd, band), 2. ); } for ( unsigned int bd = 0; bd < size; bd++ ) W(bd, band) /= std::sqrt( norm ); } // Decorrelation of the W vectors InternalMatrixType W_tmp = W * W.transpose(); vnl_svd< MatrixElementType > solver ( W_tmp ); InternalMatrixType valP = solver.W(); for ( unsigned int i = 0; i < valP.rows(); ++i ) valP(i, i) = 1. / std::sqrt( static_cast<double>( valP(i, i) ) ); // Watch for 0 or neg InternalMatrixType transf = solver.U(); W_tmp = transf * valP * transf.transpose(); W = W_tmp * W; // Convergence evaluation convergence = 0.; for ( unsigned int i = 0; i < W.rows(); ++i ) for ( unsigned int j = 0; j < W.cols(); ++j ) convergence += std::abs( W(i, j) - W_old(i, j) ); reporter.CompletedPixel(); } // end of while loop this->m_TransformationMatrix = W; otbMsgDebugMacro( << "Final convergence " << convergence << " after " << iteration << " iterations" ); } } // end of namespace otb #endif <|endoftext|>
<commit_before>/*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include "mitkPASpectralUnmixingFilterBase.h" // Includes for AddEnmemberMatrix #include "mitkPAPropertyCalculator.h" #include <eigen3/Eigen/Dense> // ImageAccessor #include <mitkImageReadAccessor.h> #include <mitkImageWriteAccessor.h> mitk::pa::SpectralUnmixingFilterBase::SpectralUnmixingFilterBase() { m_PropertyCalculatorEigen = mitk::pa::PropertyCalculator::New(); } mitk::pa::SpectralUnmixingFilterBase::~SpectralUnmixingFilterBase() { } void mitk::pa::SpectralUnmixingFilterBase::AddOutputs(unsigned int outputs) { this->SetNumberOfIndexedOutputs(outputs); for (unsigned int i = 0; i<GetNumberOfIndexedOutputs(); i++) this->SetNthOutput(i, mitk::Image::New()); } void mitk::pa::SpectralUnmixingFilterBase::AddWavelength(int wavelength) { m_Wavelength.push_back(wavelength); } void mitk::pa::SpectralUnmixingFilterBase::AddChromophore(mitk::pa::PropertyCalculator::ChromophoreType chromophore) { m_Chromophore.push_back(chromophore); } void mitk::pa::SpectralUnmixingFilterBase::Verbose(bool verbose) { m_Verbose = verbose; } void mitk::pa::SpectralUnmixingFilterBase::RelativeError(bool relativeError) { m_RelativeError = relativeError; } void mitk::pa::SpectralUnmixingFilterBase::GenerateData() { MITK_INFO(m_Verbose) << "GENERATING DATA.."; mitk::Image::Pointer input = GetInput(0); unsigned int xDim = input->GetDimensions()[0]; unsigned int yDim = input->GetDimensions()[1]; unsigned int numberOfInputImages = input->GetDimensions()[2]; MITK_INFO(m_Verbose) << "x dimension: " << xDim; MITK_INFO(m_Verbose) << "y dimension: " << yDim; MITK_INFO(m_Verbose) << "z dimension: " << numberOfInputImages; unsigned int sequenceSize = m_Wavelength.size(); unsigned int totalNumberOfSequences = numberOfInputImages / sequenceSize; if (totalNumberOfSequences == 0) //means that more chromophores then wavelengths mitkThrow() << "ERROR! REMOVE WAVELENGTHS!"; MITK_INFO(m_Verbose) << "TotalNumberOfSequences: " << totalNumberOfSequences; InitializeOutputs(totalNumberOfSequences); auto endmemberMatrix = CalculateEndmemberMatrix(m_Chromophore, m_Wavelength); // Copy input image into array mitk::ImageReadAccessor readAccess(input); const float* inputDataArray = ((const float*)readAccess.GetData()); CheckPreConditions(numberOfInputImages, inputDataArray); // test to see pixel values @ txt file myfile.open("SimplexNormalisation.txt"); unsigned int outputCounter = GetNumberOfIndexedOutputs(); std::vector<float*> writteBufferVector; for (unsigned int i = 0; i < outputCounter; ++i) { auto output = GetOutput(i); mitk::ImageWriteAccessor writeOutput(output); float* writeBuffer = (float *)writeOutput.GetData(); writteBufferVector.push_back(writeBuffer); } if (m_RelativeError == true) { // -1 because rel error is output[IndexedOutputs() - 1] and loop over chromophore outputs has to end at [IndexedOutputs() - 2] outputCounter -= 1; } for (unsigned int sequenceCounter = 0; sequenceCounter < totalNumberOfSequences; ++sequenceCounter) { MITK_INFO(m_Verbose) << "SequenceCounter: " << sequenceCounter; //loop over every pixel in XY-plane for (unsigned int x = 0; x < xDim; x++) { for (unsigned int y = 0; y < yDim; y++) { Eigen::VectorXf inputVector(sequenceSize); for (unsigned int z = 0; z < sequenceSize; z++) { /** * 'sequenceCounter*sequenceSize' has to be added to 'z' to ensure that one accesses the * correct pixel, because the inputDataArray contains the information of all sequences and * not just the one of the current sequence. */ unsigned int pixelNumber = (xDim*yDim*(z+sequenceCounter*sequenceSize)) + x * yDim + y; auto pixel = inputDataArray[pixelNumber]; inputVector[z] = pixel; } Eigen::VectorXf resultVector = SpectralUnmixingAlgorithm(endmemberMatrix, inputVector); unsigned int outputCounter = GetNumberOfIndexedOutputs(); if (m_RelativeError == true) { float relativeError = (endmemberMatrix*resultVector - inputVector).norm() / inputVector.norm(); // norm() is L2 norm writteBufferVector[outputCounter][(xDim*yDim * sequenceCounter) + x * yDim + y] = relativeError; } for (unsigned int outputIdx = 0; outputIdx < outputCounter; ++outputIdx) { writteBufferVector[outputIdx][(xDim*yDim * sequenceCounter) + x * yDim + y] = resultVector[outputIdx]; } } } } MITK_INFO(m_Verbose) << "GENERATING DATA...[DONE]"; myfile.close(); } void mitk::pa::SpectralUnmixingFilterBase::CheckPreConditions(unsigned int numberOfInputImages, const float* inputDataArray) { MITK_INFO(m_Verbose) << "CHECK PRECONDITIONS ..."; if (m_Wavelength.size() < numberOfInputImages) MITK_WARN << "NUMBER OF WAVELENGTHS < NUMBER OF INPUT IMAGES"; if (m_Chromophore.size() > m_Wavelength.size()) mitkThrow() << "ADD MORE WAVELENGTHS OR REMOVE ENDMEMBERS!"; if (typeid(inputDataArray[0]).name() != typeid(float).name()) mitkThrow() << "PIXELTYPE ERROR! FLOAT 32 REQUIRED"; MITK_INFO(m_Verbose) << "...[DONE]"; } void mitk::pa::SpectralUnmixingFilterBase::InitializeOutputs(unsigned int totalNumberOfSequences) { MITK_INFO(m_Verbose) << "Initialize Outputs ..."; unsigned int numberOfInputs = GetNumberOfIndexedInputs(); unsigned int numberOfOutputs = GetNumberOfIndexedOutputs(); MITK_INFO(m_Verbose) << "Inputs: " << numberOfInputs << " Outputs: " << numberOfOutputs; mitk::PixelType pixelType = mitk::MakeScalarPixelType<float>(); const int NUMBER_OF_SPATIAL_DIMENSIONS = 3; auto* dimensions = new unsigned int[NUMBER_OF_SPATIAL_DIMENSIONS]; for (unsigned int dimIdx = 0; dimIdx < 2; dimIdx++) dimensions[dimIdx] = GetInput()->GetDimensions()[dimIdx]; dimensions[2] = totalNumberOfSequences; for (unsigned int outputIdx = 0; outputIdx < numberOfOutputs; outputIdx++) GetOutput(outputIdx)->Initialize(pixelType, NUMBER_OF_SPATIAL_DIMENSIONS, dimensions); MITK_INFO(m_Verbose) << "...[DONE]"; } Eigen::Matrix<float, Eigen::Dynamic, Eigen::Dynamic> mitk::pa::SpectralUnmixingFilterBase::CalculateEndmemberMatrix( std::vector<mitk::pa::PropertyCalculator::ChromophoreType> m_Chromophore, std::vector<int> m_Wavelength) { unsigned int numberOfChromophores = m_Chromophore.size(); //columns unsigned int numberOfWavelengths = m_Wavelength.size(); //rows Eigen::Matrix<float, Eigen::Dynamic, Eigen::Dynamic> endmemberMatrixEigen(numberOfWavelengths, numberOfChromophores); for (unsigned int j = 0; j < numberOfChromophores; ++j) { for (unsigned int i = 0; i < numberOfWavelengths; ++i) endmemberMatrixEigen(i, j) = PropertyElement(m_Chromophore[j], m_Wavelength[i]); } MITK_INFO(m_Verbose) << "GENERATING ENMEMBERMATRIX [DONE]"; return endmemberMatrixEigen; } float mitk::pa::SpectralUnmixingFilterBase::PropertyElement(mitk::pa::PropertyCalculator::ChromophoreType chromophore, int wavelength) { if (chromophore == mitk::pa::PropertyCalculator::ChromophoreType::ONEENDMEMBER) return 1; else { float value = m_PropertyCalculatorEigen->GetAbsorptionForWavelength(chromophore, wavelength); if (value == 0) mitkThrow() << "WAVELENGTH " << wavelength << "nm NOT SUPPORTED!"; else return value; } } <commit_msg>fixed a implementation bug from refacotring the write buffer.<commit_after>/*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include "mitkPASpectralUnmixingFilterBase.h" // Includes for AddEnmemberMatrix #include "mitkPAPropertyCalculator.h" #include <eigen3/Eigen/Dense> // ImageAccessor #include <mitkImageReadAccessor.h> #include <mitkImageWriteAccessor.h> mitk::pa::SpectralUnmixingFilterBase::SpectralUnmixingFilterBase() { m_PropertyCalculatorEigen = mitk::pa::PropertyCalculator::New(); } mitk::pa::SpectralUnmixingFilterBase::~SpectralUnmixingFilterBase() { } void mitk::pa::SpectralUnmixingFilterBase::AddOutputs(unsigned int outputs) { this->SetNumberOfIndexedOutputs(outputs); for (unsigned int i = 0; i<GetNumberOfIndexedOutputs(); i++) this->SetNthOutput(i, mitk::Image::New()); } void mitk::pa::SpectralUnmixingFilterBase::AddWavelength(int wavelength) { m_Wavelength.push_back(wavelength); } void mitk::pa::SpectralUnmixingFilterBase::AddChromophore(mitk::pa::PropertyCalculator::ChromophoreType chromophore) { m_Chromophore.push_back(chromophore); } void mitk::pa::SpectralUnmixingFilterBase::Verbose(bool verbose) { m_Verbose = verbose; } void mitk::pa::SpectralUnmixingFilterBase::RelativeError(bool relativeError) { m_RelativeError = relativeError; } void mitk::pa::SpectralUnmixingFilterBase::GenerateData() { MITK_INFO(m_Verbose) << "GENERATING DATA.."; mitk::Image::Pointer input = GetInput(0); unsigned int xDim = input->GetDimensions()[0]; unsigned int yDim = input->GetDimensions()[1]; unsigned int numberOfInputImages = input->GetDimensions()[2]; MITK_INFO(m_Verbose) << "x dimension: " << xDim; MITK_INFO(m_Verbose) << "y dimension: " << yDim; MITK_INFO(m_Verbose) << "z dimension: " << numberOfInputImages; unsigned int sequenceSize = m_Wavelength.size(); unsigned int totalNumberOfSequences = numberOfInputImages / sequenceSize; if (totalNumberOfSequences == 0) //means that more chromophores then wavelengths mitkThrow() << "ERROR! REMOVE WAVELENGTHS!"; MITK_INFO(m_Verbose) << "TotalNumberOfSequences: " << totalNumberOfSequences; InitializeOutputs(totalNumberOfSequences); auto endmemberMatrix = CalculateEndmemberMatrix(m_Chromophore, m_Wavelength); // Copy input image into array mitk::ImageReadAccessor readAccess(input); const float* inputDataArray = ((const float*)readAccess.GetData()); CheckPreConditions(numberOfInputImages, inputDataArray); // test to see pixel values @ txt file myfile.open("SimplexNormalisation.txt"); unsigned int outputCounter = GetNumberOfIndexedOutputs(); std::vector<float*> writteBufferVector; for (unsigned int i = 0; i < outputCounter; ++i) { auto output = GetOutput(i); mitk::ImageWriteAccessor writeOutput(output); float* writeBuffer = (float *)writeOutput.GetData(); writteBufferVector.push_back(writeBuffer); } if (m_RelativeError == true) { // -1 because rel error is output[IndexedOutputs() - 1] and loop over chromophore outputs has to end at [IndexedOutputs() - 2] outputCounter -= 1; } for (unsigned int sequenceCounter = 0; sequenceCounter < totalNumberOfSequences; ++sequenceCounter) { MITK_INFO(m_Verbose) << "SequenceCounter: " << sequenceCounter; //loop over every pixel in XY-plane for (unsigned int x = 0; x < xDim; x++) { for (unsigned int y = 0; y < yDim; y++) { Eigen::VectorXf inputVector(sequenceSize); for (unsigned int z = 0; z < sequenceSize; z++) { /** * 'sequenceCounter*sequenceSize' has to be added to 'z' to ensure that one accesses the * correct pixel, because the inputDataArray contains the information of all sequences and * not just the one of the current sequence. */ unsigned int pixelNumber = (xDim*yDim*(z+sequenceCounter*sequenceSize)) + x * yDim + y; auto pixel = inputDataArray[pixelNumber]; inputVector[z] = pixel; } Eigen::VectorXf resultVector = SpectralUnmixingAlgorithm(endmemberMatrix, inputVector); if (m_RelativeError == true) { float relativeError = (endmemberMatrix*resultVector - inputVector).norm() / inputVector.norm(); // norm() is L2 norm writteBufferVector[outputCounter][(xDim*yDim * sequenceCounter) + x * yDim + y] = relativeError; } for (unsigned int outputIdx = 0; outputIdx < outputCounter; ++outputIdx) { writteBufferVector[outputIdx][(xDim*yDim * sequenceCounter) + x * yDim + y] = resultVector[outputIdx]; } } } } MITK_INFO(m_Verbose) << "GENERATING DATA...[DONE]"; myfile.close(); } void mitk::pa::SpectralUnmixingFilterBase::CheckPreConditions(unsigned int numberOfInputImages, const float* inputDataArray) { MITK_INFO(m_Verbose) << "CHECK PRECONDITIONS ..."; if (m_Wavelength.size() < numberOfInputImages) MITK_WARN << "NUMBER OF WAVELENGTHS < NUMBER OF INPUT IMAGES"; if (m_Chromophore.size() > m_Wavelength.size()) mitkThrow() << "ADD MORE WAVELENGTHS OR REMOVE ENDMEMBERS!"; if (typeid(inputDataArray[0]).name() != typeid(float).name()) mitkThrow() << "PIXELTYPE ERROR! FLOAT 32 REQUIRED"; MITK_INFO(m_Verbose) << "...[DONE]"; } void mitk::pa::SpectralUnmixingFilterBase::InitializeOutputs(unsigned int totalNumberOfSequences) { MITK_INFO(m_Verbose) << "Initialize Outputs ..."; unsigned int numberOfInputs = GetNumberOfIndexedInputs(); unsigned int numberOfOutputs = GetNumberOfIndexedOutputs(); MITK_INFO(m_Verbose) << "Inputs: " << numberOfInputs << " Outputs: " << numberOfOutputs; mitk::PixelType pixelType = mitk::MakeScalarPixelType<float>(); const int NUMBER_OF_SPATIAL_DIMENSIONS = 3; auto* dimensions = new unsigned int[NUMBER_OF_SPATIAL_DIMENSIONS]; for (unsigned int dimIdx = 0; dimIdx < 2; dimIdx++) dimensions[dimIdx] = GetInput()->GetDimensions()[dimIdx]; dimensions[2] = totalNumberOfSequences; for (unsigned int outputIdx = 0; outputIdx < numberOfOutputs; outputIdx++) GetOutput(outputIdx)->Initialize(pixelType, NUMBER_OF_SPATIAL_DIMENSIONS, dimensions); MITK_INFO(m_Verbose) << "...[DONE]"; } Eigen::Matrix<float, Eigen::Dynamic, Eigen::Dynamic> mitk::pa::SpectralUnmixingFilterBase::CalculateEndmemberMatrix( std::vector<mitk::pa::PropertyCalculator::ChromophoreType> m_Chromophore, std::vector<int> m_Wavelength) { unsigned int numberOfChromophores = m_Chromophore.size(); //columns unsigned int numberOfWavelengths = m_Wavelength.size(); //rows Eigen::Matrix<float, Eigen::Dynamic, Eigen::Dynamic> endmemberMatrixEigen(numberOfWavelengths, numberOfChromophores); for (unsigned int j = 0; j < numberOfChromophores; ++j) { for (unsigned int i = 0; i < numberOfWavelengths; ++i) endmemberMatrixEigen(i, j) = PropertyElement(m_Chromophore[j], m_Wavelength[i]); } MITK_INFO(m_Verbose) << "GENERATING ENMEMBERMATRIX [DONE]"; return endmemberMatrixEigen; } float mitk::pa::SpectralUnmixingFilterBase::PropertyElement(mitk::pa::PropertyCalculator::ChromophoreType chromophore, int wavelength) { if (chromophore == mitk::pa::PropertyCalculator::ChromophoreType::ONEENDMEMBER) return 1; else { float value = m_PropertyCalculatorEigen->GetAbsorptionForWavelength(chromophore, wavelength); if (value == 0) mitkThrow() << "WAVELENGTH " << wavelength << "nm NOT SUPPORTED!"; else return value; } } <|endoftext|>
<commit_before>#pragma once #include <src/batchringbuffer.h> #include <time.h> #include <sys/time.h> #include <gtest/gtest.h> #ifdef __MACH__ #include <mach/clock.h> #include <mach/mach.h> #endif #define MILLIS 1000000LL #define NANOS 1000000000LL class Bench_4_4_1024_buffer : public testing::Test { protected: brb_buffer * buffer; }; timespec diff(timespec start, timespec end) { timespec temp; if ((end.tv_nsec-start.tv_nsec)<0) { temp.tv_sec = end.tv_sec-start.tv_sec-1; temp.tv_nsec = 1000000000+end.tv_nsec-start.tv_nsec; } else { temp.tv_sec = end.tv_sec-start.tv_sec; temp.tv_nsec = end.tv_nsec-start.tv_nsec; } return temp; } void get_timespec(timespec * ts) { #ifdef __MACH__ /* OS X does not have clock_gettime, use clock_get_time */ clock_serv_t cclock; mach_timespec_t mts; host_get_clock_service(mach_host_self(), CALENDAR_CLOCK, &cclock); clock_get_time(cclock, &mts); mach_port_deallocate(mach_task_self(), cclock); ts->tv_sec = mts.tv_sec; ts->tv_nsec = mts.tv_nsec; #else clock_gettime(CLOCK_REALTIME, ts); #endif } double bench(int n) { timespec time1, time2; brb_buffer * buffer; brb_batch * batch; char cancel; brb_init_buffer(&buffer, 4, 4, 1024); get_timespec(&time1); for (int i = 0; i< n; i++) { brb_claim(buffer, &batch, 1, &cancel); brb_publish(buffer, batch); brb_release(buffer, batch); } get_timespec(&time2); brb_free_buffer(&buffer); return (double)diff(time1,time2).tv_nsec / (double)n; } TEST_F(Bench_4_4_1024_buffer, _claim_publish_release) { double ns_per_op; double ops_per_ms; double ops_per_s; int count; /* warmup */ bench(1000); for(count = 1000; count <= 10000000; count *= 10) { ns_per_op = bench(count); ops_per_ms = MILLIS / ns_per_op; ops_per_s = NANOS / ns_per_op; printf("[%10d]\t%8.4f ns/op\t\t%12.4f op/ms\t\t%12.4f op/s\n", count, ns_per_op, ops_per_ms, ops_per_s); } } <commit_msg>Added iostream include for ubuntu<commit_after>#pragma once #include <src/batchringbuffer.h> #include <iostream> #include <time.h> #include <sys/time.h> #include <gtest/gtest.h> #ifdef __MACH__ #include <mach/clock.h> #include <mach/mach.h> #endif #define MILLIS 1000000LL #define NANOS 1000000000LL class Bench_4_4_1024_buffer : public testing::Test { protected: brb_buffer * buffer; }; timespec diff(timespec start, timespec end) { timespec temp; if ((end.tv_nsec-start.tv_nsec)<0) { temp.tv_sec = end.tv_sec-start.tv_sec-1; temp.tv_nsec = 1000000000+end.tv_nsec-start.tv_nsec; } else { temp.tv_sec = end.tv_sec-start.tv_sec; temp.tv_nsec = end.tv_nsec-start.tv_nsec; } return temp; } void get_timespec(timespec * ts) { #ifdef __MACH__ /* OS X does not have clock_gettime, use clock_get_time */ clock_serv_t cclock; mach_timespec_t mts; host_get_clock_service(mach_host_self(), CALENDAR_CLOCK, &cclock); clock_get_time(cclock, &mts); mach_port_deallocate(mach_task_self(), cclock); ts->tv_sec = mts.tv_sec; ts->tv_nsec = mts.tv_nsec; #else clock_gettime(CLOCK_REALTIME, ts); #endif } double bench(int n) { timespec time1, time2; brb_buffer * buffer; brb_batch * batch; char cancel; brb_init_buffer(&buffer, 4, 4, 1024); get_timespec(&time1); for (int i = 0; i< n; i++) { brb_claim(buffer, &batch, 1, &cancel); brb_publish(buffer, batch); brb_release(buffer, batch); } get_timespec(&time2); brb_free_buffer(&buffer); return (double)diff(time1,time2).tv_nsec / (double)n; } TEST_F(Bench_4_4_1024_buffer, _claim_publish_release) { double ns_per_op; double ops_per_ms; double ops_per_s; int count; /* warmup */ bench(1000); for(count = 1000; count <= 10000000; count *= 10) { ns_per_op = bench(count); ops_per_ms = MILLIS / ns_per_op; ops_per_s = NANOS / ns_per_op; printf("[%10d]\t%8.4f ns/op\t\t%12.4f op/ms\t\t%12.4f op/s\n", count, ns_per_op, ops_per_ms, ops_per_s); } } <|endoftext|>
<commit_before>/* * Copyright (c) 2017, Tier IV, 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 Autoware nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include <ros/ros.h> #include <ros/package.h> #include <std_msgs/String.h> #include <std_msgs/Float64MultiArray.h> #include <geometry_msgs/TwistStamped.h> #include <unordered_map> #include <stdlib.h> #include <string.h> #include <vector> #include <boost/algorithm/string.hpp> #include <mosquitto.h> #include <yaml-cpp/yaml.h> using namespace std; #include "mqtt_socket/mqtt_setting.hpp" #include "autoware_msgs/CanInfo.h" class MqttSender { public: MqttSender(); ~MqttSender(); void canInfoCallback(const autoware_msgs::CanInfoConstPtr &msg); static void on_connect(struct mosquitto *mosq, void *obj, int result); static void on_disconnect(struct mosquitto *mosq, void *obj, int rc); static void on_publish(struct mosquitto *mosq, void *userdata, int mid); static void load_config(); private: void targetVelocityArrayCallback(const std_msgs::Float64MultiArray &msg); void twistCmdCallback(const geometry_msgs::TwistStamped &msg); void stateCallback(const std_msgs::String &msg); unordered_map<string, ros::Subscriber> Subs; ros::NodeHandle node_handle_; // MQTT TOPIC string mqtt_topic_can_info_; string mqtt_topic_state_; string mqtt_topic_target_velocity_; string mqtt_topic_current_target_velocity_; // current behavior/status std_msgs::Float64MultiArray current_target_velocity_array_; //kmph geometry_msgs::TwistStamped current_twist_cmd_; //mps double current_target_velocity_; // mps2kmph(current_twist_cmd_.twist.twist.linear.x); std_msgs::String current_state_; int callback_counter_ = 0; }; inline double mps2kmph(double _mpsval) { return (_mpsval * 60 * 60) / 1000; // mps * 60sec * 60 minute / 1000m } MqttSender::MqttSender() : node_handle_("~") { // ROS Subscriber Subs["can_info"] = node_handle_.subscribe("/can_info", 100, &MqttSender::canInfoCallback, this); Subs["target_velocity_array"] = node_handle_.subscribe("/target_velocity_array", 1, &MqttSender::targetVelocityArrayCallback, this); Subs["twist_cmd"] = node_handle_.subscribe("/twist_cmd", 1, &MqttSender::twistCmdCallback, this); Subs["state"] = node_handle_.subscribe("/state", 1, &MqttSender::stateCallback, this); // MQTT PARAMS mosquitto_lib_init(); // Load Config MqttSender::load_config(); mqtt_topic_can_info_ = "vehicle/" + to_string(vehicle_id) + "/can_info"; mqtt_topic_state_ = "vehicle/" + to_string(vehicle_id) + "/state"; mqtt_topic_target_velocity_ = "vehicle/" + to_string(vehicle_id) + "/target_velocity"; mqtt_topic_current_target_velocity_ = "vehicle/" + to_string(vehicle_id) + "/current_velocity"; mqtt_client = mosquitto_new(mqtt_client_id.c_str(), true, NULL); mosquitto_connect_callback_set(mqtt_client, &MqttSender::on_connect); mosquitto_disconnect_callback_set(mqtt_client, &MqttSender::on_disconnect); if(mosquitto_connect_bind(mqtt_client, mqtt_address.c_str(), mqtt_port, mqtt_timeout, NULL)){ ROS_INFO("Failed to connect broker.\n"); mosquitto_lib_cleanup(); exit(EXIT_FAILURE); } } MqttSender::~MqttSender() { mosquitto_destroy(mqtt_client); mosquitto_lib_cleanup(); } void MqttSender::on_connect(struct mosquitto *mosq, void *obj, int result) { ROS_INFO("on_connect: %s(%d)\n", __FUNCTION__, __LINE__); } void MqttSender::on_disconnect(struct mosquitto *mosq, void *obj, int rc) { ROS_INFO("on_disconnect: %s(%d)\n", __FUNCTION__, __LINE__); } static void MqttSender::load_config() { string config_file_path = ros::package::getPath(MQTT_NODE_NAME) + MQTT_CONFIG_FILE_NAME; ROS_INFO("Load Config File: %s %s(%d)\n", config_file_path.c_str(), __FUNCTION__, __LINE__); YAML::Node config = YAML::LoadFile(config_file_path); vehicle_id = config["mqtt"]["VEHICLEID"].as<int>(); mqtt_client_id = "vehicle_" + to_string(vehicle_id) + "_snd"; mqtt_address = config["mqtt"]["ADDRESS"].as<string>(); mqtt_port = config["mqtt"]["PORT"].as<int>(); mqtt_qos = config["mqtt"]["QOS"].as<int>(); mqtt_timeout = config["mqtt"]["TIMEOUT"].as<int>(); caninfo_downsample = config["mqtt"]["CANINFO_DOWNSAMPLE"].as<float>(); gear_d = config["mqtt"]["GEAR_D"].as<int>(); gear_n = config["mqtt"]["GEAR_N"].as<int>(); gear_r = config["mqtt"]["GEAR_R"].as<int>(); gear_p = config["mqtt"]["GEAR_P"].as<int>(); ROS_INFO("MQTT Sender ADDR: %s:%d, ID: %s\n", mqtt_address.c_str(), mqtt_port, mqtt_client_id.c_str()); ROS_INFO( "[MQTT Receiver Settings] vehicle_id: %d, \ caninfo_downsample: %f, gear_d: %d, gear_n: %d, gear_r: %d, \ gear_p: %d", vehicle_id, caninfo_downsample, gear_d, gear_n, gear_r, gear_p); } void MqttSender::targetVelocityArrayCallback(const std_msgs::Float64MultiArray &msg) { ostringstream publish_msg; current_target_velocity_array_ = msg; for(int i = 0; i < sizeof(msg.data); i++) { publish_msg << to_string(msg.data[i]) << ","; } string publish_msg_str = publish_msg.str(); int ret = mosquitto_publish( mqtt_client, NULL, mqtt_topic_target_velocity_.c_str(), strlen(publish_msg_str.c_str()), publish_msg_str.c_str(), mqtt_qos, false ); } void MqttSender::twistCmdCallback(const geometry_msgs::TwistStamped &msg) { ostringstream publish_msg; current_twist_cmd_ = msg; current_target_velocity_ = mps2kmph(msg.twist.linear.x); publish_msg << to_string(current_target_velocity_); string publish_msg_str = publish_msg.str(); int ret = mosquitto_publish( mqtt_client, NULL, mqtt_topic_current_target_velocity_.c_str(), strlen(publish_msg_str.c_str()), publish_msg_str.c_str(), mqtt_qos, false ); } void MqttSender::stateCallback(const std_msgs::String &msg) { ROS_INFO("State: %s\n", msg.data.c_str()); int ret = mosquitto_publish( mqtt_client, NULL, mqtt_topic_state_.c_str(), strlen(msg.data.c_str()), msg.data.c_str(), mqtt_qos, false ); } void MqttSender::canInfoCallback(const autoware_msgs::CanInfoConstPtr &msg) { if(callback_counter_ > caninfo_downsample * 100) { ostringstream publish_msg; publish_msg << msg->tm << ","; publish_msg << to_string(msg->devmode) << ","; publish_msg << to_string(msg->drvcontmode) << ","; publish_msg << to_string(msg->drvoverridemode) << ","; publish_msg << to_string(msg->drvservo) << ","; publish_msg << to_string(msg->drivepedal) << ","; publish_msg << to_string(msg->targetpedalstr) << ","; publish_msg << to_string(msg->inputpedalstr) << ","; publish_msg << to_string(msg->targetveloc) << ","; publish_msg << to_string(msg->speed) << ","; if (msg->driveshift == gear_d) publish_msg << "D,"; else if (msg->driveshift == gear_n) publish_msg << "N,"; else if (msg->driveshift == gear_r) publish_msg << "R,"; else if (msg->driveshift == gear_p) publish_msg << "P,"; else publish_msg << "Unkwown,"; publish_msg << to_string(msg->targetshift) << ","; publish_msg << to_string(msg->inputshift) << ","; publish_msg << to_string(msg->strmode) << ","; publish_msg << to_string(msg->strcontmode) << ","; publish_msg << to_string(msg->stroverridemode) << ","; publish_msg << to_string(msg->strservo) << ","; publish_msg << to_string(msg->targettorque) << ","; publish_msg << to_string(msg->torque) << ","; publish_msg << to_string(msg->angle) << ","; publish_msg << to_string(msg->targetangle) << ","; publish_msg << to_string(msg->bbrakepress) << ","; publish_msg << to_string(msg->brakepedal) << ","; publish_msg << to_string(msg->brtargetpedalstr) << ","; publish_msg << to_string(msg->brinputpedalstr) << ","; publish_msg << to_string(msg->battery) << ","; publish_msg << to_string(msg->voltage) << ","; publish_msg << to_string(msg->anp) << ","; publish_msg << to_string(msg->battmaxtemparature) << ","; publish_msg << to_string(msg->battmintemparature) << ","; publish_msg << to_string(msg->maxchgcurrent) << ","; publish_msg << to_string(msg->maxdischgcurrent) << ","; publish_msg << to_string(msg->sideacc) << ","; publish_msg << to_string(msg->accellfromp) << ","; publish_msg << to_string(msg->anglefromp) << ","; publish_msg << to_string(msg->brakepedalfromp) << ","; publish_msg << to_string(msg->speedfr) << ","; publish_msg << to_string(msg->speedfl) << ","; publish_msg << to_string(msg->speedrr) << ","; publish_msg << to_string(msg->speedrl) << ","; publish_msg << to_string(msg->velocfromp2) << ","; publish_msg << to_string(msg->drvmode) << ","; publish_msg << to_string(msg->devpedalstrfromp) << ","; publish_msg << to_string(msg->rpm) << ","; publish_msg << to_string(msg->velocflfromp) << ","; publish_msg << to_string(msg->ev_mode) << ","; publish_msg << to_string(msg->temp) << ","; publish_msg << to_string(msg->shiftfrmprius) << ","; publish_msg << to_string(msg->light) << ","; publish_msg << to_string(msg->gaslevel) << ","; publish_msg << to_string(msg->door) << ","; publish_msg << to_string(msg->cluise); // ostringstream publish_msg = create_message(msg); string publish_msg_str = publish_msg.str(); int ret = mosquitto_publish( mqtt_client, NULL, mqtt_topic_can_info_.c_str(), strlen(publish_msg_str.c_str()), publish_msg_str.c_str(), mqtt_qos, false ); callback_counter_ = 0; } else { callback_counter_++; } } int main(int argc, char **argv) { ros::init(argc, argv, "mqtt_sender"); MqttSender node; ros::spin(); return 0; } <commit_msg>add current_pose topic to mqtt msg<commit_after>/* * Copyright (c) 2017, Tier IV, 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 Autoware nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include <ros/ros.h> #include <ros/package.h> #include <std_msgs/String.h> #include <std_msgs/Float64MultiArray.h> #include <geometry_msgs/TwistStamped.h> #include <geometry_msgs/PoseStamped.h> #include <unordered_map> #include <stdlib.h> #include <string.h> #include <vector> #include <boost/algorithm/string.hpp> #include <mosquitto.h> #include <yaml-cpp/yaml.h> using namespace std; #include "mqtt_socket/mqtt_setting.hpp" #include "autoware_msgs/CanInfo.h" class MqttSender { public: MqttSender(); ~MqttSender(); void canInfoCallback(const autoware_msgs::CanInfoConstPtr &msg); static void on_connect(struct mosquitto *mosq, void *obj, int result); static void on_disconnect(struct mosquitto *mosq, void *obj, int rc); static void on_publish(struct mosquitto *mosq, void *userdata, int mid); static void load_config(); private: void targetVelocityArrayCallback(const std_msgs::Float64MultiArray &msg); void twistCmdCallback(const geometry_msgs::TwistStamped &msg); void stateCallback(const std_msgs::String &msg); void currentPoseCallback(const geometry_msgs::PoseStamped& msg); unordered_map<string, ros::Subscriber> Subs; ros::NodeHandle node_handle_; // MQTT TOPIC string mqtt_topic_can_info_; string mqtt_topic_state_; string mqtt_topic_target_velocity_; string mqtt_topic_current_target_velocity_; string mqtt_topic_current_pose_; // current behavior/status std_msgs::Float64MultiArray current_target_velocity_array_; //kmph geometry_msgs::TwistStamped current_twist_cmd_; //mps double current_target_velocity_; // mps2kmph(current_twist_cmd_.twist.twist.linear.x); std_msgs::String current_state_; int callback_counter_ = 0; }; inline double mps2kmph(double _mpsval) { return (_mpsval * 60 * 60) / 1000; // mps * 60sec * 60 minute / 1000m } MqttSender::MqttSender() : node_handle_("~") { // ROS Subscriber Subs["can_info"] = node_handle_.subscribe("/can_info", 100, &MqttSender::canInfoCallback, this); Subs["target_velocity_array"] = node_handle_.subscribe("/target_velocity_array", 1, &MqttSender::targetVelocityArrayCallback, this); Subs["twist_cmd"] = node_handle_.subscribe("/twist_cmd", 1, &MqttSender::twistCmdCallback, this); Subs["state"] = node_handle_.subscribe("/state", 1, &MqttSender::stateCallback, this); Subs["current_pose"] = node_handle_.subscribe("/current_pose", 1, &MqttSender::currentPoseCallback, this); // MQTT PARAMS mosquitto_lib_init(); // Load Config MqttSender::load_config(); mqtt_topic_can_info_ = "vehicle/" + to_string(vehicle_id) + "/can_info"; mqtt_topic_state_ = "vehicle/" + to_string(vehicle_id) + "/state"; mqtt_topic_target_velocity_ = "vehicle/" + to_string(vehicle_id) + "/target_velocity"; mqtt_topic_current_target_velocity_ = "vehicle/" + to_string(vehicle_id) + "/current_velocity"; mqtt_topic_current_pose_ = "vehicle/" + to_string(vehicle_id) + "/current_pose"; mqtt_client = mosquitto_new(mqtt_client_id.c_str(), true, NULL); mosquitto_connect_callback_set(mqtt_client, &MqttSender::on_connect); mosquitto_disconnect_callback_set(mqtt_client, &MqttSender::on_disconnect); if(mosquitto_connect_bind(mqtt_client, mqtt_address.c_str(), mqtt_port, mqtt_timeout, NULL)){ ROS_INFO("Failed to connect broker.\n"); mosquitto_lib_cleanup(); exit(EXIT_FAILURE); } } MqttSender::~MqttSender() { mosquitto_destroy(mqtt_client); mosquitto_lib_cleanup(); } void MqttSender::on_connect(struct mosquitto *mosq, void *obj, int result) { ROS_INFO("on_connect: %s(%d)\n", __FUNCTION__, __LINE__); } void MqttSender::on_disconnect(struct mosquitto *mosq, void *obj, int rc) { ROS_INFO("on_disconnect: %s(%d)\n", __FUNCTION__, __LINE__); } static void MqttSender::load_config() { string config_file_path = ros::package::getPath(MQTT_NODE_NAME) + MQTT_CONFIG_FILE_NAME; ROS_INFO("Load Config File: %s %s(%d)\n", config_file_path.c_str(), __FUNCTION__, __LINE__); YAML::Node config = YAML::LoadFile(config_file_path); vehicle_id = config["mqtt"]["VEHICLEID"].as<int>(); mqtt_client_id = "vehicle_" + to_string(vehicle_id) + "_snd"; mqtt_address = config["mqtt"]["ADDRESS"].as<string>(); mqtt_port = config["mqtt"]["PORT"].as<int>(); mqtt_qos = config["mqtt"]["QOS"].as<int>(); mqtt_timeout = config["mqtt"]["TIMEOUT"].as<int>(); caninfo_downsample = config["mqtt"]["CANINFO_DOWNSAMPLE"].as<float>(); gear_d = config["mqtt"]["GEAR_D"].as<int>(); gear_n = config["mqtt"]["GEAR_N"].as<int>(); unordered_map<string, ros::Subscriber> Subs; gear_r = config["mqtt"]["GEAR_R"].as<int>(); gear_p = config["mqtt"]["GEAR_P"].as<int>(); ROS_INFO("MQTT Sender ADDR: %s:%d, ID: %s\n", mqtt_address.c_str(), mqtt_port, mqtt_client_id.c_str()); ROS_INFO( "[MQTT Receiver Settings] vehicle_id: %d, \ caninfo_downsample: %f, gear_d: %d, gear_n: %d, gear_r: %d, \ gear_p: %d", vehicle_id, caninfo_downsample, gear_d, gear_n, gear_r, gear_p); } void MqttSender::targetVelocityArrayCallback(const std_msgs::Float64MultiArray &msg) { ostringstream publish_msg; current_target_velocity_array_ = msg; for(int i = 0; i < sizeof(msg.data); i++) { publish_msg << to_string(msg.data[i]) << ","; } string publish_msg_str = publish_msg.str(); int ret = mosquitto_publish( mqtt_client, NULL, mqtt_topic_target_velocity_.c_str(), strlen(publish_msg_str.c_str()), publish_msg_str.c_str(), mqtt_qos, false ); } void MqttSender::twistCmdCallback(const geometry_msgs::TwistStamped &msg) { ostringstream publish_msg; current_twist_cmd_ = msg; current_target_velocity_ = mps2kmph(msg.twist.linear.x); publish_msg << to_string(current_target_velocity_); string publish_msg_str = publish_msg.str(); int ret = mosquitto_publish( mqtt_client, NULL, mqtt_topic_current_target_velocity_.c_str(), strlen(publish_msg_str.c_str()), publish_msg_str.c_str(), mqtt_qos, false ); } void MqttSender::stateCallback(const std_msgs::String &msg) { ROS_INFO("State: %s\n", msg.data.c_str()); int ret = mosquitto_publish( mqtt_client, NULL, mqtt_topic_state_.c_str(), strlen(msg.data.c_str()), msg.data.c_str(), mqtt_qos, false ); } void MqttSender::currentPoseCallback(const geometry_msgs::PoseStamped& msg) { ostringstream publish_msg; publish_msg << to_string(msg.pose.position.x) << ","; publish_msg << to_string(msg.pose.position.y) << ","; publish_msg << to_string(msg.pose.position.z) << ","; publish_msg << to_string(msg.pose.orientation.x) << ","; publish_msg << to_string(msg.pose.orientation.y) << ","; publish_msg << to_string(msg.pose.orientation.z) << ","; publish_msg << to_string(msg.pose.orientation.w) << ","; string publish_msg_str = publish_msg.str(); int ret = mosquitto_publish( mqtt_client, NULL, mqtt_topic_current_pose_.c_str(), strlen(publish_msg_str.c_str()), publish_msg_str.c_str(), mqtt_qos, false ); } void MqttSender::canInfoCallback(const autoware_msgs::CanInfoConstPtr &msg) { if(callback_counter_ > caninfo_downsample * 100) { ostringstream publish_msg; publish_msg << msg->tm << ","; publish_msg << to_string(msg->devmode) << ","; publish_msg << to_string(msg->drvcontmode) << ","; publish_msg << to_string(msg->drvoverridemode) << ","; publish_msg << to_string(msg->drvservo) << ","; publish_msg << to_string(msg->drivepedal) << ","; publish_msg << to_string(msg->targetpedalstr) << ","; publish_msg << to_string(msg->inputpedalstr) << ","; publish_msg << to_string(msg->targetveloc) << ","; publish_msg << to_string(msg->speed) << ","; if (msg->driveshift == gear_d) publish_msg << "D,"; else if (msg->driveshift == gear_n) publish_msg << "N,"; else if (msg->driveshift == gear_r) publish_msg << "R,"; else if (msg->driveshift == gear_p) publish_msg << "P,"; else publish_msg << "Unkwown,"; publish_msg << to_string(msg->targetshift) << ","; publish_msg << to_string(msg->inputshift) << ","; publish_msg << to_string(msg->strmode) << ","; publish_msg << to_string(msg->strcontmode) << ","; publish_msg << to_string(msg->stroverridemode) << ","; publish_msg << to_string(msg->strservo) << ","; publish_msg << to_string(msg->targettorque) << ","; publish_msg << to_string(msg->torque) << ","; publish_msg << to_string(msg->angle) << ","; publish_msg << to_string(msg->targetangle) << ","; publish_msg << to_string(msg->bbrakepress) << ","; publish_msg << to_string(msg->brakepedal) << ","; publish_msg << to_string(msg->brtargetpedalstr) << ","; publish_msg << to_string(msg->brinputpedalstr) << ","; publish_msg << to_string(msg->battery) << ","; publish_msg << to_string(msg->voltage) << ","; publish_msg << to_string(msg->anp) << ","; publish_msg << to_string(msg->battmaxtemparature) << ","; publish_msg << to_string(msg->battmintemparature) << ","; publish_msg << to_string(msg->maxchgcurrent) << ","; publish_msg << to_string(msg->maxdischgcurrent) << ","; publish_msg << to_string(msg->sideacc) << ","; publish_msg << to_string(msg->accellfromp) << ","; publish_msg << to_string(msg->anglefromp) << ","; publish_msg << to_string(msg->brakepedalfromp) << ","; publish_msg << to_string(msg->speedfr) << ","; publish_msg << to_string(msg->speedfl) << ","; publish_msg << to_string(msg->speedrr) << ","; publish_msg << to_string(msg->speedrl) << ","; publish_msg << to_string(msg->velocfromp2) << ","; publish_msg << to_string(msg->drvmode) << ","; publish_msg << to_string(msg->devpedalstrfromp) << ","; publish_msg << to_string(msg->rpm) << ","; publish_msg << to_string(msg->velocflfromp) << ","; publish_msg << to_string(msg->ev_mode) << ","; publish_msg << to_string(msg->temp) << ","; publish_msg << to_string(msg->shiftfrmprius) << ","; publish_msg << to_string(msg->light) << ","; publish_msg << to_string(msg->gaslevel) << ","; publish_msg << to_string(msg->door) << ","; publish_msg << to_string(msg->cluise); // ostringstream publish_msg = create_message(msg); string publish_msg_str = publish_msg.str(); int ret = mosquitto_publish( mqtt_client, NULL, mqtt_topic_can_info_.c_str(), strlen(publish_msg_str.c_str()), publish_msg_str.c_str(), mqtt_qos, false ); callback_counter_ = 0; } else { callback_counter_++; } } int main(int argc, char **argv) { ros::init(argc, argv, "mqtt_sender"); MqttSender node; ros::spin(); return 0; } <|endoftext|>
<commit_before>/* ############################################################################### # # EGSnrc egs++ shape collection # Copyright (C) 2015 National Research Council Canada # # This file is part of EGSnrc. # # EGSnrc is free software: you can redistribute it and/or modify it under # the terms of the GNU Affero General Public License as published by the # Free Software Foundation, either version 3 of the License, or (at your # option) any later version. # # EGSnrc is distributed in the hope that it will be useful, but WITHOUT ANY # WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS # FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for # more details. # # You should have received a copy of the GNU Affero General Public License # along with EGSnrc. If not, see <http://www.gnu.org/licenses/>. # ############################################################################### # # Author: Iwan Kawrakow, 2005 # # Contributors: # ############################################################################### */ /*! \file egs_shape_collection.cpp * \brief A shape collection * \IK */ #include "egs_shape_collection.h" #include "egs_input.h" #include "egs_functions.h" EGS_ShapeCollection::EGS_ShapeCollection(const vector<EGS_BaseShape *> &Shapes, const vector<EGS_Float> &Probs, const string &Name, EGS_ObjectFactory *f) : EGS_BaseShape(Name,f), nshape(0) { int n1 = Shapes.size(), n2 = Probs.size(); if (n1 < 2 || n2 < 2 || n1 != n2) { egsWarning("EGS_ShapeCollection::EGS_ShapeCollection: invalid input\n"); return; } nshape = n1; shapes = new EGS_BaseShape* [nshape]; EGS_Float *dum = new EGS_Float [nshape], *p = new EGS_Float [nshape]; for (int j=0; j<nshape; j++) { shapes[j] = Shapes[j]; shapes[j]->ref(); p[j] = Probs[j]; dum[j] = 1; } table = new EGS_AliasTable(nshape,dum,p,0); delete [] dum; delete [] p; } extern "C" { EGS_SHAPE_COLLECTION_EXPORT EGS_BaseShape *createShape(EGS_Input *input, EGS_ObjectFactory *f) { if (!input) { egsWarning("createShape(shape collection): null input?\n"); return 0; } vector<EGS_BaseShape *> shapes; vector<EGS_Float> probs; EGS_Input *ishape; while ((ishape = input->takeInputItem("shape",false))) { EGS_BaseShape *shape = EGS_BaseShape::createShape(ishape); if (!shape) { egsWarning("createShape(shape collection): got null shape\n"); } else { shapes.push_back(shape); } delete ishape; } vector<string> snames; int err = input->getInput("shape names",snames); if (!err && snames.size() > 0) { for (unsigned int j=0; j<snames.size(); j++) { EGS_BaseShape *shape = EGS_BaseShape::getShape(snames[j]); if (!shape) egsWarning("createShape(shape collection): no shape " "named %s exists\n",snames[j].c_str()); else { shapes.push_back(shape); } } } err = input->getInput("probabilities",probs); bool ok = true; if (err) { egsWarning("createShape(shape collection): no 'probabilities' input\n"); ok = false; } if (shapes.size() < 2) { egsWarning("createShape(shape collection): at least 2 shapes are " "needed for a shape collection, you defined %s\n",shapes.size()); ok = false; } if (shapes.size() != probs.size()) { egsWarning("createShape(shape collection): the number of shapes (%d)" " is not the same as the number of input probabilities (%d)\n"); ok = false; } for (unsigned int i=0; i<probs.size(); i++) { if (probs[i] < 0) { egsWarning("createShape(shape collection): probabilities must not" " be negative, but your input probability %d is %g\n", i,probs[i]); ok = false; } } if (!ok) { for (unsigned int j=0; j<shapes.size(); j++) { EGS_Object::deleteObject(shapes[j]); } return 0; } EGS_ShapeCollection *s = new EGS_ShapeCollection(shapes,probs,"",f); s->setName(input); s->setTransformation(input); return s; } } <commit_msg>Fix format specifier in shape collection warning<commit_after>/* ############################################################################### # # EGSnrc egs++ shape collection # Copyright (C) 2015 National Research Council Canada # # This file is part of EGSnrc. # # EGSnrc is free software: you can redistribute it and/or modify it under # the terms of the GNU Affero General Public License as published by the # Free Software Foundation, either version 3 of the License, or (at your # option) any later version. # # EGSnrc is distributed in the hope that it will be useful, but WITHOUT ANY # WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS # FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for # more details. # # You should have received a copy of the GNU Affero General Public License # along with EGSnrc. If not, see <http://www.gnu.org/licenses/>. # ############################################################################### # # Author: Iwan Kawrakow, 2005 # # Contributors: # ############################################################################### */ /*! \file egs_shape_collection.cpp * \brief A shape collection * \IK */ #include "egs_shape_collection.h" #include "egs_input.h" #include "egs_functions.h" EGS_ShapeCollection::EGS_ShapeCollection(const vector<EGS_BaseShape *> &Shapes, const vector<EGS_Float> &Probs, const string &Name, EGS_ObjectFactory *f) : EGS_BaseShape(Name,f), nshape(0) { int n1 = Shapes.size(), n2 = Probs.size(); if (n1 < 2 || n2 < 2 || n1 != n2) { egsWarning("EGS_ShapeCollection::EGS_ShapeCollection: invalid input\n"); return; } nshape = n1; shapes = new EGS_BaseShape* [nshape]; EGS_Float *dum = new EGS_Float [nshape], *p = new EGS_Float [nshape]; for (int j=0; j<nshape; j++) { shapes[j] = Shapes[j]; shapes[j]->ref(); p[j] = Probs[j]; dum[j] = 1; } table = new EGS_AliasTable(nshape,dum,p,0); delete [] dum; delete [] p; } extern "C" { EGS_SHAPE_COLLECTION_EXPORT EGS_BaseShape *createShape(EGS_Input *input, EGS_ObjectFactory *f) { if (!input) { egsWarning("createShape(shape collection): null input?\n"); return 0; } vector<EGS_BaseShape *> shapes; vector<EGS_Float> probs; EGS_Input *ishape; while ((ishape = input->takeInputItem("shape",false))) { EGS_BaseShape *shape = EGS_BaseShape::createShape(ishape); if (!shape) { egsWarning("createShape(shape collection): got null shape\n"); } else { shapes.push_back(shape); } delete ishape; } vector<string> snames; int err = input->getInput("shape names",snames); if (!err && snames.size() > 0) { for (unsigned int j=0; j<snames.size(); j++) { EGS_BaseShape *shape = EGS_BaseShape::getShape(snames[j]); if (!shape) egsWarning("createShape(shape collection): no shape " "named %s exists\n",snames[j].c_str()); else { shapes.push_back(shape); } } } err = input->getInput("probabilities",probs); bool ok = true; if (err) { egsWarning("createShape(shape collection): no 'probabilities' input\n"); ok = false; } if (shapes.size() < 2) { egsWarning("createShape(shape collection): at least 2 shapes are " "needed for a shape collection, you defined %d\n",shapes.size()); ok = false; } if (shapes.size() != probs.size()) { egsWarning("createShape(shape collection): the number of shapes (%d)" " is not the same as the number of input probabilities (%d)\n"); ok = false; } for (unsigned int i=0; i<probs.size(); i++) { if (probs[i] < 0) { egsWarning("createShape(shape collection): probabilities must not" " be negative, but your input probability %d is %g\n", i,probs[i]); ok = false; } } if (!ok) { for (unsigned int j=0; j<shapes.size(); j++) { EGS_Object::deleteObject(shapes[j]); } return 0; } EGS_ShapeCollection *s = new EGS_ShapeCollection(shapes,probs,"",f); s->setName(input); s->setTransformation(input); return s; } } <|endoftext|>
<commit_before>/* * Software License Agreement (BSD License) * * Point Cloud Library (PCL) - www.pointclouds.org * Copyright (c) 2009, Willow Garage, Inc. * Copyright (c) 2012-, Open Perception, 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 the copyright holder(s) nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * $Id$ * */ #ifndef PCL_SAMPLE_CONSENSUS_IMPL_SAC_MODEL_LINE_H_ #define PCL_SAMPLE_CONSENSUS_IMPL_SAC_MODEL_LINE_H_ #include <pcl/sample_consensus/sac_model_line.h> #include <pcl/common/centroid.h> #include <pcl/common/concatenate.h> ////////////////////////////////////////////////////////////////////////// template <typename PointT> bool pcl::SampleConsensusModelLine<PointT>::isSampleGood (const std::vector<int> &samples) const { if ( (input_->points[samples[0]].x != input_->points[samples[1]].x) && (input_->points[samples[0]].y != input_->points[samples[1]].y) && (input_->points[samples[0]].z != input_->points[samples[1]].z)) return (true); return (false); } ////////////////////////////////////////////////////////////////////////// template <typename PointT> bool pcl::SampleConsensusModelLine<PointT>::computeModelCoefficients ( const std::vector<int> &samples, Eigen::VectorXf &model_coefficients) const { // Need 2 samples if (samples.size () != 2) { PCL_ERROR ("[pcl::SampleConsensusModelLine::computeModelCoefficients] Invalid set of samples given (%lu)!\n", samples.size ()); return (false); } if (fabs (input_->points[samples[0]].x - input_->points[samples[1]].x) <= std::numeric_limits<float>::epsilon () && fabs (input_->points[samples[0]].y - input_->points[samples[1]].y) <= std::numeric_limits<float>::epsilon () && fabs (input_->points[samples[0]].z - input_->points[samples[1]].z) <= std::numeric_limits<float>::epsilon ()) { return (false); } model_coefficients.resize (6); model_coefficients[0] = input_->points[samples[0]].x; model_coefficients[1] = input_->points[samples[0]].y; model_coefficients[2] = input_->points[samples[0]].z; model_coefficients[3] = input_->points[samples[1]].x - model_coefficients[0]; model_coefficients[4] = input_->points[samples[1]].y - model_coefficients[1]; model_coefficients[5] = input_->points[samples[1]].z - model_coefficients[2]; model_coefficients.template tail<3> ().normalize (); return (true); } ////////////////////////////////////////////////////////////////////////// template <typename PointT> void pcl::SampleConsensusModelLine<PointT>::getDistancesToModel ( const Eigen::VectorXf &model_coefficients, std::vector<double> &distances) const { // Needs a valid set of model coefficients if (!isModelValid (model_coefficients)) return; distances.resize (indices_->size ()); // Obtain the line point and direction Eigen::Vector4f line_pt (model_coefficients[0], model_coefficients[1], model_coefficients[2], 0); Eigen::Vector4f line_dir (model_coefficients[3], model_coefficients[4], model_coefficients[5], 0); line_dir.normalize (); // Iterate through the 3d points and calculate the distances from them to the line for (size_t i = 0; i < indices_->size (); ++i) { // Calculate the distance from the point to the line // D = ||(P2-P1) x (P1-P0)|| / ||P2-P1|| = norm (cross (p2-p1, p2-p0)) / norm(p2-p1) // Need to estimate sqrt here to keep MSAC and friends general distances[i] = sqrt ((line_pt - input_->points[(*indices_)[i]].getVector4fMap ()).cross3 (line_dir).squaredNorm ()); } } ////////////////////////////////////////////////////////////////////////// template <typename PointT> void pcl::SampleConsensusModelLine<PointT>::selectWithinDistance ( const Eigen::VectorXf &model_coefficients, const double threshold, std::vector<int> &inliers) { // Needs a valid set of model coefficients if (!isModelValid (model_coefficients)) return; double sqr_threshold = threshold * threshold; int nr_p = 0; inliers.resize (indices_->size ()); error_sqr_dists_.resize (indices_->size ()); // Obtain the line point and direction Eigen::Vector4f line_pt (model_coefficients[0], model_coefficients[1], model_coefficients[2], 0); Eigen::Vector4f line_dir (model_coefficients[3], model_coefficients[4], model_coefficients[5], 0); line_dir.normalize (); // Iterate through the 3d points and calculate the distances from them to the line for (size_t i = 0; i < indices_->size (); ++i) { // Calculate the distance from the point to the line // D = ||(P2-P1) x (P1-P0)|| / ||P2-P1|| = norm (cross (p2-p1, p2-p0)) / norm(p2-p1) double sqr_distance = (line_pt - input_->points[(*indices_)[i]].getVector4fMap ()).cross3 (line_dir).squaredNorm (); if (sqr_distance < sqr_threshold) { // Returns the indices of the points whose squared distances are smaller than the threshold inliers[nr_p] = (*indices_)[i]; error_sqr_dists_[nr_p] = sqr_distance; ++nr_p; } } inliers.resize (nr_p); error_sqr_dists_.resize (nr_p); } ////////////////////////////////////////////////////////////////////////// template <typename PointT> int pcl::SampleConsensusModelLine<PointT>::countWithinDistance ( const Eigen::VectorXf &model_coefficients, const double threshold) const { // Needs a valid set of model coefficients if (!isModelValid (model_coefficients)) return (0); double sqr_threshold = threshold * threshold; int nr_p = 0; // Obtain the line point and direction Eigen::Vector4f line_pt (model_coefficients[0], model_coefficients[1], model_coefficients[2], 0); Eigen::Vector4f line_dir (model_coefficients[3], model_coefficients[4], model_coefficients[5], 0); line_dir.normalize (); // Iterate through the 3d points and calculate the distances from them to the line for (size_t i = 0; i < indices_->size (); ++i) { // Calculate the distance from the point to the line // D = ||(P2-P1) x (P1-P0)|| / ||P2-P1|| = norm (cross (p2-p1, p2-p0)) / norm(p2-p1) double sqr_distance = (line_pt - input_->points[(*indices_)[i]].getVector4fMap ()).cross3 (line_dir).squaredNorm (); if (sqr_distance < sqr_threshold) nr_p++; } return (nr_p); } ////////////////////////////////////////////////////////////////////////// template <typename PointT> void pcl::SampleConsensusModelLine<PointT>::optimizeModelCoefficients ( const std::vector<int> &inliers, const Eigen::VectorXf &model_coefficients, Eigen::VectorXf &optimized_coefficients) const { // Needs a valid set of model coefficients if (!isModelValid (model_coefficients)) { optimized_coefficients = model_coefficients; return; } // Need at least 2 points to estimate a line if (inliers.size () <= 2) { PCL_ERROR ("[pcl::SampleConsensusModelLine::optimizeModelCoefficients] Not enough inliers found to support a model (%lu)! Returning the same coefficients.\n", inliers.size ()); optimized_coefficients = model_coefficients; return; } optimized_coefficients.resize (6); // Compute the 3x3 covariance matrix Eigen::Vector4f centroid; compute3DCentroid (*input_, inliers, centroid); Eigen::Matrix3f covariance_matrix; computeCovarianceMatrix (*input_, inliers, centroid, covariance_matrix); optimized_coefficients[0] = centroid[0]; optimized_coefficients[1] = centroid[1]; optimized_coefficients[2] = centroid[2]; // Extract the eigenvalues and eigenvectors EIGEN_ALIGN16 Eigen::Vector3f eigen_values; EIGEN_ALIGN16 Eigen::Vector3f eigen_vector; pcl::eigen33 (covariance_matrix, eigen_values); pcl::computeCorrespondingEigenVector (covariance_matrix, eigen_values [2], eigen_vector); //pcl::eigen33 (covariance_matrix, eigen_vectors, eigen_values); optimized_coefficients.template tail<3> ().matrix () = eigen_vector; } ////////////////////////////////////////////////////////////////////////// template <typename PointT> void pcl::SampleConsensusModelLine<PointT>::projectPoints ( const std::vector<int> &inliers, const Eigen::VectorXf &model_coefficients, PointCloud &projected_points, bool copy_data_fields) const { // Needs a valid model coefficients if (!isModelValid (model_coefficients)) return; // Obtain the line point and direction Eigen::Vector4f line_pt (model_coefficients[0], model_coefficients[1], model_coefficients[2], 0); Eigen::Vector4f line_dir (model_coefficients[3], model_coefficients[4], model_coefficients[5], 0); projected_points.header = input_->header; projected_points.is_dense = input_->is_dense; // Copy all the data fields from the input cloud to the projected one? if (copy_data_fields) { // Allocate enough space and copy the basics projected_points.points.resize (input_->points.size ()); projected_points.width = input_->width; projected_points.height = input_->height; typedef typename pcl::traits::fieldList<PointT>::type FieldList; // Iterate over each point for (size_t i = 0; i < projected_points.points.size (); ++i) // Iterate over each dimension pcl::for_each_type <FieldList> (NdConcatenateFunctor <PointT, PointT> (input_->points[i], projected_points.points[i])); // Iterate through the 3d points and calculate the distances from them to the line for (size_t i = 0; i < inliers.size (); ++i) { Eigen::Vector4f pt (input_->points[inliers[i]].x, input_->points[inliers[i]].y, input_->points[inliers[i]].z, 0); // double k = (DOT_PROD_3D (points[i], p21) - dotA_B) / dotB_B; float k = (pt.dot (line_dir) - line_pt.dot (line_dir)) / line_dir.dot (line_dir); Eigen::Vector4f pp = line_pt + k * line_dir; // Calculate the projection of the point on the line (pointProj = A + k * B) projected_points.points[inliers[i]].x = pp[0]; projected_points.points[inliers[i]].y = pp[1]; projected_points.points[inliers[i]].z = pp[2]; } } else { // Allocate enough space and copy the basics projected_points.points.resize (inliers.size ()); projected_points.width = static_cast<uint32_t> (inliers.size ()); projected_points.height = 1; typedef typename pcl::traits::fieldList<PointT>::type FieldList; // Iterate over each point for (size_t i = 0; i < inliers.size (); ++i) // Iterate over each dimension pcl::for_each_type <FieldList> (NdConcatenateFunctor <PointT, PointT> (input_->points[inliers[i]], projected_points.points[i])); // Iterate through the 3d points and calculate the distances from them to the line for (size_t i = 0; i < inliers.size (); ++i) { Eigen::Vector4f pt (input_->points[inliers[i]].x, input_->points[inliers[i]].y, input_->points[inliers[i]].z, 0); // double k = (DOT_PROD_3D (points[i], p21) - dotA_B) / dotB_B; float k = (pt.dot (line_dir) - line_pt.dot (line_dir)) / line_dir.dot (line_dir); Eigen::Vector4f pp = line_pt + k * line_dir; // Calculate the projection of the point on the line (pointProj = A + k * B) projected_points.points[i].x = pp[0]; projected_points.points[i].y = pp[1]; projected_points.points[i].z = pp[2]; } } } ////////////////////////////////////////////////////////////////////////// template <typename PointT> bool pcl::SampleConsensusModelLine<PointT>::doSamplesVerifyModel ( const std::set<int> &indices, const Eigen::VectorXf &model_coefficients, const double threshold) const { // Needs a valid set of model coefficients if (!isModelValid (model_coefficients)) return (false); // Obtain the line point and direction Eigen::Vector4f line_pt (model_coefficients[0], model_coefficients[1], model_coefficients[2], 0); Eigen::Vector4f line_dir (model_coefficients[3], model_coefficients[4], model_coefficients[5], 0); line_dir.normalize (); double sqr_threshold = threshold * threshold; // Iterate through the 3d points and calculate the distances from them to the line for (std::set<int>::const_iterator it = indices.begin (); it != indices.end (); ++it) { // Calculate the distance from the point to the line // D = ||(P2-P1) x (P1-P0)|| / ||P2-P1|| = norm (cross (p2-p1, p2-p0)) / norm(p2-p1) if ((line_pt - input_->points[*it].getVector4fMap ()).cross3 (line_dir).squaredNorm () > sqr_threshold) return (false); } return (true); } #define PCL_INSTANTIATE_SampleConsensusModelLine(T) template class PCL_EXPORTS pcl::SampleConsensusModelLine<T>; #endif // PCL_SAMPLE_CONSENSUS_IMPL_SAC_MODEL_LINE_H_ <commit_msg>Fix regression in pcl::SACSegmentation line fitting<commit_after>/* * Software License Agreement (BSD License) * * Point Cloud Library (PCL) - www.pointclouds.org * Copyright (c) 2009, Willow Garage, Inc. * Copyright (c) 2012-, Open Perception, 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 the copyright holder(s) nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * $Id$ * */ #ifndef PCL_SAMPLE_CONSENSUS_IMPL_SAC_MODEL_LINE_H_ #define PCL_SAMPLE_CONSENSUS_IMPL_SAC_MODEL_LINE_H_ #include <pcl/sample_consensus/sac_model_line.h> #include <pcl/common/centroid.h> #include <pcl/common/concatenate.h> ////////////////////////////////////////////////////////////////////////// template <typename PointT> bool pcl::SampleConsensusModelLine<PointT>::isSampleGood (const std::vector<int> &samples) const { // Make sure that the two sample points are not identical if ( (input_->points[samples[0]].x != input_->points[samples[1]].x) || (input_->points[samples[0]].y != input_->points[samples[1]].y) || (input_->points[samples[0]].z != input_->points[samples[1]].z)) { return (true); } return (false); } ////////////////////////////////////////////////////////////////////////// template <typename PointT> bool pcl::SampleConsensusModelLine<PointT>::computeModelCoefficients ( const std::vector<int> &samples, Eigen::VectorXf &model_coefficients) const { // Need 2 samples if (samples.size () != 2) { PCL_ERROR ("[pcl::SampleConsensusModelLine::computeModelCoefficients] Invalid set of samples given (%lu)!\n", samples.size ()); return (false); } if (fabs (input_->points[samples[0]].x - input_->points[samples[1]].x) <= std::numeric_limits<float>::epsilon () && fabs (input_->points[samples[0]].y - input_->points[samples[1]].y) <= std::numeric_limits<float>::epsilon () && fabs (input_->points[samples[0]].z - input_->points[samples[1]].z) <= std::numeric_limits<float>::epsilon ()) { return (false); } model_coefficients.resize (6); model_coefficients[0] = input_->points[samples[0]].x; model_coefficients[1] = input_->points[samples[0]].y; model_coefficients[2] = input_->points[samples[0]].z; model_coefficients[3] = input_->points[samples[1]].x - model_coefficients[0]; model_coefficients[4] = input_->points[samples[1]].y - model_coefficients[1]; model_coefficients[5] = input_->points[samples[1]].z - model_coefficients[2]; model_coefficients.template tail<3> ().normalize (); return (true); } ////////////////////////////////////////////////////////////////////////// template <typename PointT> void pcl::SampleConsensusModelLine<PointT>::getDistancesToModel ( const Eigen::VectorXf &model_coefficients, std::vector<double> &distances) const { // Needs a valid set of model coefficients if (!isModelValid (model_coefficients)) return; distances.resize (indices_->size ()); // Obtain the line point and direction Eigen::Vector4f line_pt (model_coefficients[0], model_coefficients[1], model_coefficients[2], 0); Eigen::Vector4f line_dir (model_coefficients[3], model_coefficients[4], model_coefficients[5], 0); line_dir.normalize (); // Iterate through the 3d points and calculate the distances from them to the line for (size_t i = 0; i < indices_->size (); ++i) { // Calculate the distance from the point to the line // D = ||(P2-P1) x (P1-P0)|| / ||P2-P1|| = norm (cross (p2-p1, p2-p0)) / norm(p2-p1) // Need to estimate sqrt here to keep MSAC and friends general distances[i] = sqrt ((line_pt - input_->points[(*indices_)[i]].getVector4fMap ()).cross3 (line_dir).squaredNorm ()); } } ////////////////////////////////////////////////////////////////////////// template <typename PointT> void pcl::SampleConsensusModelLine<PointT>::selectWithinDistance ( const Eigen::VectorXf &model_coefficients, const double threshold, std::vector<int> &inliers) { // Needs a valid set of model coefficients if (!isModelValid (model_coefficients)) return; double sqr_threshold = threshold * threshold; int nr_p = 0; inliers.resize (indices_->size ()); error_sqr_dists_.resize (indices_->size ()); // Obtain the line point and direction Eigen::Vector4f line_pt (model_coefficients[0], model_coefficients[1], model_coefficients[2], 0); Eigen::Vector4f line_dir (model_coefficients[3], model_coefficients[4], model_coefficients[5], 0); line_dir.normalize (); // Iterate through the 3d points and calculate the distances from them to the line for (size_t i = 0; i < indices_->size (); ++i) { // Calculate the distance from the point to the line // D = ||(P2-P1) x (P1-P0)|| / ||P2-P1|| = norm (cross (p2-p1, p2-p0)) / norm(p2-p1) double sqr_distance = (line_pt - input_->points[(*indices_)[i]].getVector4fMap ()).cross3 (line_dir).squaredNorm (); if (sqr_distance < sqr_threshold) { // Returns the indices of the points whose squared distances are smaller than the threshold inliers[nr_p] = (*indices_)[i]; error_sqr_dists_[nr_p] = sqr_distance; ++nr_p; } } inliers.resize (nr_p); error_sqr_dists_.resize (nr_p); } ////////////////////////////////////////////////////////////////////////// template <typename PointT> int pcl::SampleConsensusModelLine<PointT>::countWithinDistance ( const Eigen::VectorXf &model_coefficients, const double threshold) const { // Needs a valid set of model coefficients if (!isModelValid (model_coefficients)) return (0); double sqr_threshold = threshold * threshold; int nr_p = 0; // Obtain the line point and direction Eigen::Vector4f line_pt (model_coefficients[0], model_coefficients[1], model_coefficients[2], 0); Eigen::Vector4f line_dir (model_coefficients[3], model_coefficients[4], model_coefficients[5], 0); line_dir.normalize (); // Iterate through the 3d points and calculate the distances from them to the line for (size_t i = 0; i < indices_->size (); ++i) { // Calculate the distance from the point to the line // D = ||(P2-P1) x (P1-P0)|| / ||P2-P1|| = norm (cross (p2-p1, p2-p0)) / norm(p2-p1) double sqr_distance = (line_pt - input_->points[(*indices_)[i]].getVector4fMap ()).cross3 (line_dir).squaredNorm (); if (sqr_distance < sqr_threshold) nr_p++; } return (nr_p); } ////////////////////////////////////////////////////////////////////////// template <typename PointT> void pcl::SampleConsensusModelLine<PointT>::optimizeModelCoefficients ( const std::vector<int> &inliers, const Eigen::VectorXf &model_coefficients, Eigen::VectorXf &optimized_coefficients) const { // Needs a valid set of model coefficients if (!isModelValid (model_coefficients)) { optimized_coefficients = model_coefficients; return; } // Need at least 2 points to estimate a line if (inliers.size () <= 2) { PCL_ERROR ("[pcl::SampleConsensusModelLine::optimizeModelCoefficients] Not enough inliers found to support a model (%lu)! Returning the same coefficients.\n", inliers.size ()); optimized_coefficients = model_coefficients; return; } optimized_coefficients.resize (6); // Compute the 3x3 covariance matrix Eigen::Vector4f centroid; compute3DCentroid (*input_, inliers, centroid); Eigen::Matrix3f covariance_matrix; computeCovarianceMatrix (*input_, inliers, centroid, covariance_matrix); optimized_coefficients[0] = centroid[0]; optimized_coefficients[1] = centroid[1]; optimized_coefficients[2] = centroid[2]; // Extract the eigenvalues and eigenvectors EIGEN_ALIGN16 Eigen::Vector3f eigen_values; EIGEN_ALIGN16 Eigen::Vector3f eigen_vector; pcl::eigen33 (covariance_matrix, eigen_values); pcl::computeCorrespondingEigenVector (covariance_matrix, eigen_values [2], eigen_vector); //pcl::eigen33 (covariance_matrix, eigen_vectors, eigen_values); optimized_coefficients.template tail<3> ().matrix () = eigen_vector; } ////////////////////////////////////////////////////////////////////////// template <typename PointT> void pcl::SampleConsensusModelLine<PointT>::projectPoints ( const std::vector<int> &inliers, const Eigen::VectorXf &model_coefficients, PointCloud &projected_points, bool copy_data_fields) const { // Needs a valid model coefficients if (!isModelValid (model_coefficients)) return; // Obtain the line point and direction Eigen::Vector4f line_pt (model_coefficients[0], model_coefficients[1], model_coefficients[2], 0); Eigen::Vector4f line_dir (model_coefficients[3], model_coefficients[4], model_coefficients[5], 0); projected_points.header = input_->header; projected_points.is_dense = input_->is_dense; // Copy all the data fields from the input cloud to the projected one? if (copy_data_fields) { // Allocate enough space and copy the basics projected_points.points.resize (input_->points.size ()); projected_points.width = input_->width; projected_points.height = input_->height; typedef typename pcl::traits::fieldList<PointT>::type FieldList; // Iterate over each point for (size_t i = 0; i < projected_points.points.size (); ++i) // Iterate over each dimension pcl::for_each_type <FieldList> (NdConcatenateFunctor <PointT, PointT> (input_->points[i], projected_points.points[i])); // Iterate through the 3d points and calculate the distances from them to the line for (size_t i = 0; i < inliers.size (); ++i) { Eigen::Vector4f pt (input_->points[inliers[i]].x, input_->points[inliers[i]].y, input_->points[inliers[i]].z, 0); // double k = (DOT_PROD_3D (points[i], p21) - dotA_B) / dotB_B; float k = (pt.dot (line_dir) - line_pt.dot (line_dir)) / line_dir.dot (line_dir); Eigen::Vector4f pp = line_pt + k * line_dir; // Calculate the projection of the point on the line (pointProj = A + k * B) projected_points.points[inliers[i]].x = pp[0]; projected_points.points[inliers[i]].y = pp[1]; projected_points.points[inliers[i]].z = pp[2]; } } else { // Allocate enough space and copy the basics projected_points.points.resize (inliers.size ()); projected_points.width = static_cast<uint32_t> (inliers.size ()); projected_points.height = 1; typedef typename pcl::traits::fieldList<PointT>::type FieldList; // Iterate over each point for (size_t i = 0; i < inliers.size (); ++i) // Iterate over each dimension pcl::for_each_type <FieldList> (NdConcatenateFunctor <PointT, PointT> (input_->points[inliers[i]], projected_points.points[i])); // Iterate through the 3d points and calculate the distances from them to the line for (size_t i = 0; i < inliers.size (); ++i) { Eigen::Vector4f pt (input_->points[inliers[i]].x, input_->points[inliers[i]].y, input_->points[inliers[i]].z, 0); // double k = (DOT_PROD_3D (points[i], p21) - dotA_B) / dotB_B; float k = (pt.dot (line_dir) - line_pt.dot (line_dir)) / line_dir.dot (line_dir); Eigen::Vector4f pp = line_pt + k * line_dir; // Calculate the projection of the point on the line (pointProj = A + k * B) projected_points.points[i].x = pp[0]; projected_points.points[i].y = pp[1]; projected_points.points[i].z = pp[2]; } } } ////////////////////////////////////////////////////////////////////////// template <typename PointT> bool pcl::SampleConsensusModelLine<PointT>::doSamplesVerifyModel ( const std::set<int> &indices, const Eigen::VectorXf &model_coefficients, const double threshold) const { // Needs a valid set of model coefficients if (!isModelValid (model_coefficients)) return (false); // Obtain the line point and direction Eigen::Vector4f line_pt (model_coefficients[0], model_coefficients[1], model_coefficients[2], 0); Eigen::Vector4f line_dir (model_coefficients[3], model_coefficients[4], model_coefficients[5], 0); line_dir.normalize (); double sqr_threshold = threshold * threshold; // Iterate through the 3d points and calculate the distances from them to the line for (std::set<int>::const_iterator it = indices.begin (); it != indices.end (); ++it) { // Calculate the distance from the point to the line // D = ||(P2-P1) x (P1-P0)|| / ||P2-P1|| = norm (cross (p2-p1, p2-p0)) / norm(p2-p1) if ((line_pt - input_->points[*it].getVector4fMap ()).cross3 (line_dir).squaredNorm () > sqr_threshold) return (false); } return (true); } #define PCL_INSTANTIATE_SampleConsensusModelLine(T) template class PCL_EXPORTS pcl::SampleConsensusModelLine<T>; #endif // PCL_SAMPLE_CONSENSUS_IMPL_SAC_MODEL_LINE_H_ <|endoftext|>
<commit_before>#include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include <sqlite3.h> #include <getopt.h> #include <string> #include <vector> #include <map> #include <set> #include <zlib.h> #include <math.h> #include <fcntl.h> #include <sys/stat.h> #include <sys/mman.h> #include <protozero/pbf_reader.hpp> #include "mvt.hpp" #include "projection.hpp" #include "geometry.hpp" #include "write_json.hpp" int minzoom = 0; int maxzoom = 32; bool force = false; void do_stats(mvt_tile &tile, size_t size, bool compressed, int z, unsigned x, unsigned y) { printf("{ \"zoom\": %d, \"x\": %u, \"y\": %u, \"bytes\": %zu, \"compressed\": %s", z, x, y, size, compressed ? "true" : "false"); printf(", \"layers\": { "); for (size_t i = 0; i < tile.layers.size(); i++) { if (i != 0) { printf(", "); } fprintq(stdout, tile.layers[i].name.c_str()); int points = 0, lines = 0, polygons = 0; for (size_t j = 0; j < tile.layers[i].features.size(); j++) { if (tile.layers[i].features[j].type == mvt_point) { points++; } else if (tile.layers[i].features[j].type == mvt_linestring) { lines++; } else if (tile.layers[i].features[j].type == mvt_polygon) { polygons++; } } printf(": { \"points\": %d, \"lines\": %d, \"polygons\": %d, \"extent\": %lld }", points, lines, polygons, tile.layers[i].extent); } printf(" } }\n"); } void handle(std::string message, int z, unsigned x, unsigned y, int describe, std::set<std::string> const &to_decode, bool pipeline, bool stats) { mvt_tile tile; bool was_compressed; try { if (!tile.decode(message, was_compressed)) { fprintf(stderr, "Couldn't parse tile %d/%u/%u\n", z, x, y); exit(EXIT_FAILURE); } } catch (protozero::unknown_pbf_wire_type_exception e) { fprintf(stderr, "PBF decoding error in tile %d/%u/%u\n", z, x, y); exit(EXIT_FAILURE); } if (stats) { do_stats(tile, message.size(), was_compressed, z, x, y); return; } if (!pipeline) { printf("{ \"type\": \"FeatureCollection\""); if (describe) { printf(", \"properties\": { \"zoom\": %d, \"x\": %d, \"y\": %d", z, x, y); if (!was_compressed) { printf(", \"compressed\": false"); } printf(" }"); if (projection != projections) { printf(", \"crs\": { \"type\": \"name\", \"properties\": { \"name\": "); fprintq(stdout, projection->alias); printf(" } }"); } } printf(", \"features\": [\n"); } bool first_layer = true; for (size_t l = 0; l < tile.layers.size(); l++) { mvt_layer &layer = tile.layers[l]; if (to_decode.size() != 0 && !to_decode.count(layer.name)) { continue; } if (!pipeline) { if (describe) { if (!first_layer) { printf(",\n"); } printf("{ \"type\": \"FeatureCollection\""); printf(", \"properties\": { \"layer\": "); fprintq(stdout, layer.name.c_str()); printf(", \"version\": %d, \"extent\": %lld", layer.version, layer.extent); printf(" }"); printf(", \"features\": [\n"); first_layer = false; } } layer_to_geojson(stdout, layer, z, x, y, !pipeline, pipeline, pipeline, 0, 0, 0, !force); if (!pipeline) { if (describe) { printf("] }\n"); } } } if (!pipeline) { printf("] }\n"); } } void decode(char *fname, int z, unsigned x, unsigned y, std::set<std::string> const &to_decode, bool pipeline, bool stats) { sqlite3 *db; int oz = z; unsigned ox = x, oy = y; int fd = open(fname, O_RDONLY | O_CLOEXEC); if (fd >= 0) { struct stat st; if (fstat(fd, &st) == 0) { if (st.st_size < 50 * 1024 * 1024) { char *map = (char *) mmap(NULL, st.st_size, PROT_READ, MAP_PRIVATE, fd, 0); if (map != NULL && map != MAP_FAILED) { if (strcmp(map, "SQLite format 3") != 0) { if (z >= 0) { std::string s = std::string(map, st.st_size); handle(s, z, x, y, 1, to_decode, pipeline, stats); munmap(map, st.st_size); return; } else { fprintf(stderr, "Must specify zoom/x/y to decode a single pbf file\n"); exit(EXIT_FAILURE); } } } munmap(map, st.st_size); } } else { perror("fstat"); } if (close(fd) != 0) { perror("close"); exit(EXIT_FAILURE); } } else { perror(fname); } if (sqlite3_open(fname, &db) != SQLITE_OK) { fprintf(stderr, "%s: %s\n", fname, sqlite3_errmsg(db)); exit(EXIT_FAILURE); } if (z < 0) { int within = 0; if (!pipeline && !stats) { printf("{ \"type\": \"FeatureCollection\", \"properties\": {\n"); const char *sql2 = "SELECT name, value from metadata order by name;"; sqlite3_stmt *stmt2; if (sqlite3_prepare_v2(db, sql2, -1, &stmt2, NULL) != SQLITE_OK) { fprintf(stderr, "%s: select failed: %s\n", fname, sqlite3_errmsg(db)); exit(EXIT_FAILURE); } while (sqlite3_step(stmt2) == SQLITE_ROW) { if (within) { printf(",\n"); } within = 1; const unsigned char *name = sqlite3_column_text(stmt2, 0); const unsigned char *value = sqlite3_column_text(stmt2, 1); if (name == NULL || value == NULL) { fprintf(stderr, "Corrupt mbtiles file: null metadata\n"); exit(EXIT_FAILURE); } fprintq(stdout, (char *) name); printf(": "); fprintq(stdout, (char *) value); } sqlite3_finalize(stmt2); } if (stats) { printf("[\n"); } const char *sql = "SELECT tile_data, zoom_level, tile_column, tile_row from tiles where zoom_level between ? and ? order by zoom_level, tile_column, tile_row;"; sqlite3_stmt *stmt; if (sqlite3_prepare_v2(db, sql, -1, &stmt, NULL) != SQLITE_OK) { fprintf(stderr, "%s: select failed: %s\n", fname, sqlite3_errmsg(db)); exit(EXIT_FAILURE); } sqlite3_bind_int(stmt, 1, minzoom); sqlite3_bind_int(stmt, 2, maxzoom); if (!pipeline && !stats) { printf("\n}, \"features\": [\n"); } within = 0; while (sqlite3_step(stmt) == SQLITE_ROW) { if (!pipeline && !stats) { if (within) { printf(",\n"); } within = 1; } if (stats) { if (within) { printf(",\n"); } within = 1; } int len = sqlite3_column_bytes(stmt, 0); int tz = sqlite3_column_int(stmt, 1); int tx = sqlite3_column_int(stmt, 2); int ty = sqlite3_column_int(stmt, 3); ty = (1LL << tz) - 1 - ty; const char *s = (const char *) sqlite3_column_blob(stmt, 0); handle(std::string(s, len), tz, tx, ty, 1, to_decode, pipeline, stats); } if (!pipeline && !stats) { printf("] }\n"); } if (stats) { printf("]\n"); } sqlite3_finalize(stmt); } else { int handled = 0; while (z >= 0 && !handled) { const char *sql = "SELECT tile_data from tiles where zoom_level = ? and tile_column = ? and tile_row = ?;"; sqlite3_stmt *stmt; if (sqlite3_prepare_v2(db, sql, -1, &stmt, NULL) != SQLITE_OK) { fprintf(stderr, "%s: select failed: %s\n", fname, sqlite3_errmsg(db)); exit(EXIT_FAILURE); } sqlite3_bind_int(stmt, 1, z); sqlite3_bind_int(stmt, 2, x); sqlite3_bind_int(stmt, 3, (1LL << z) - 1 - y); while (sqlite3_step(stmt) == SQLITE_ROW) { int len = sqlite3_column_bytes(stmt, 0); const char *s = (const char *) sqlite3_column_blob(stmt, 0); if (z != oz) { fprintf(stderr, "%s: Warning: using tile %d/%u/%u instead of %d/%u/%u\n", fname, z, x, y, oz, ox, oy); } handle(std::string(s, len), z, x, y, 0, to_decode, pipeline, stats); handled = 1; } sqlite3_finalize(stmt); z--; x /= 2; y /= 2; } } if (sqlite3_close(db) != SQLITE_OK) { fprintf(stderr, "%s: could not close database: %s\n", fname, sqlite3_errmsg(db)); exit(EXIT_FAILURE); } } void usage(char **argv) { fprintf(stderr, "Usage: %s [-s projection] [-Z minzoom] [-z maxzoom] [-l layer ...] file.mbtiles [zoom x y]\n", argv[0]); exit(EXIT_FAILURE); } int main(int argc, char **argv) { extern int optind; extern char *optarg; int i; std::set<std::string> to_decode; bool pipeline = false; bool stats = false; struct option long_options[] = { {"projection", required_argument, 0, 's'}, {"maximum-zoom", required_argument, 0, 'z'}, {"minimum-zoom", required_argument, 0, 'Z'}, {"layer", required_argument, 0, 'l'}, {"tag-layer-and-zoom", no_argument, 0, 'c'}, {"stats", no_argument, 0, 'S'}, {"force", no_argument, 0, 'f'}, {0, 0, 0, 0}, }; std::string getopt_str; for (size_t lo = 0; long_options[lo].name != NULL; lo++) { if (long_options[lo].val > ' ') { getopt_str.push_back(long_options[lo].val); if (long_options[lo].has_arg == required_argument) { getopt_str.push_back(':'); } } } while ((i = getopt_long(argc, argv, getopt_str.c_str(), long_options, NULL)) != -1) { switch (i) { case 0: break; case 's': set_projection_or_exit(optarg); break; case 'z': maxzoom = atoi(optarg); break; case 'Z': minzoom = atoi(optarg); break; case 'l': to_decode.insert(optarg); break; case 'c': pipeline = true; break; case 'S': stats = true; break; case 'f': force = true; break; default: usage(argv); } } if (argc == optind + 4) { decode(argv[optind], atoi(argv[optind + 1]), atoi(argv[optind + 2]), atoi(argv[optind + 3]), to_decode, pipeline, stats); } else if (argc == optind + 1) { decode(argv[optind], -1, -1, -1, to_decode, pipeline, stats); } else { usage(argv); } return 0; } <commit_msg>Guard against decoding tiles with an impossible extent<commit_after>#include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include <sqlite3.h> #include <getopt.h> #include <string> #include <vector> #include <map> #include <set> #include <zlib.h> #include <math.h> #include <fcntl.h> #include <sys/stat.h> #include <sys/mman.h> #include <protozero/pbf_reader.hpp> #include "mvt.hpp" #include "projection.hpp" #include "geometry.hpp" #include "write_json.hpp" int minzoom = 0; int maxzoom = 32; bool force = false; void do_stats(mvt_tile &tile, size_t size, bool compressed, int z, unsigned x, unsigned y) { printf("{ \"zoom\": %d, \"x\": %u, \"y\": %u, \"bytes\": %zu, \"compressed\": %s", z, x, y, size, compressed ? "true" : "false"); printf(", \"layers\": { "); for (size_t i = 0; i < tile.layers.size(); i++) { if (i != 0) { printf(", "); } fprintq(stdout, tile.layers[i].name.c_str()); int points = 0, lines = 0, polygons = 0; for (size_t j = 0; j < tile.layers[i].features.size(); j++) { if (tile.layers[i].features[j].type == mvt_point) { points++; } else if (tile.layers[i].features[j].type == mvt_linestring) { lines++; } else if (tile.layers[i].features[j].type == mvt_polygon) { polygons++; } } printf(": { \"points\": %d, \"lines\": %d, \"polygons\": %d, \"extent\": %lld }", points, lines, polygons, tile.layers[i].extent); } printf(" } }\n"); } void handle(std::string message, int z, unsigned x, unsigned y, int describe, std::set<std::string> const &to_decode, bool pipeline, bool stats) { mvt_tile tile; bool was_compressed; try { if (!tile.decode(message, was_compressed)) { fprintf(stderr, "Couldn't parse tile %d/%u/%u\n", z, x, y); exit(EXIT_FAILURE); } } catch (protozero::unknown_pbf_wire_type_exception e) { fprintf(stderr, "PBF decoding error in tile %d/%u/%u\n", z, x, y); exit(EXIT_FAILURE); } if (stats) { do_stats(tile, message.size(), was_compressed, z, x, y); return; } if (!pipeline) { printf("{ \"type\": \"FeatureCollection\""); if (describe) { printf(", \"properties\": { \"zoom\": %d, \"x\": %d, \"y\": %d", z, x, y); if (!was_compressed) { printf(", \"compressed\": false"); } printf(" }"); if (projection != projections) { printf(", \"crs\": { \"type\": \"name\", \"properties\": { \"name\": "); fprintq(stdout, projection->alias); printf(" } }"); } } printf(", \"features\": [\n"); } bool first_layer = true; for (size_t l = 0; l < tile.layers.size(); l++) { mvt_layer &layer = tile.layers[l]; if (layer.extent <= 0) { fprintf(stderr, "Impossible layer extent %lld in mbtiles\n", layer.extent); exit(EXIT_FAILURE); } if (to_decode.size() != 0 && !to_decode.count(layer.name)) { continue; } if (!pipeline) { if (describe) { if (!first_layer) { printf(",\n"); } printf("{ \"type\": \"FeatureCollection\""); printf(", \"properties\": { \"layer\": "); fprintq(stdout, layer.name.c_str()); printf(", \"version\": %d, \"extent\": %lld", layer.version, layer.extent); printf(" }"); printf(", \"features\": [\n"); first_layer = false; } } layer_to_geojson(stdout, layer, z, x, y, !pipeline, pipeline, pipeline, 0, 0, 0, !force); if (!pipeline) { if (describe) { printf("] }\n"); } } } if (!pipeline) { printf("] }\n"); } } void decode(char *fname, int z, unsigned x, unsigned y, std::set<std::string> const &to_decode, bool pipeline, bool stats) { sqlite3 *db; int oz = z; unsigned ox = x, oy = y; int fd = open(fname, O_RDONLY | O_CLOEXEC); if (fd >= 0) { struct stat st; if (fstat(fd, &st) == 0) { if (st.st_size < 50 * 1024 * 1024) { char *map = (char *) mmap(NULL, st.st_size, PROT_READ, MAP_PRIVATE, fd, 0); if (map != NULL && map != MAP_FAILED) { if (strcmp(map, "SQLite format 3") != 0) { if (z >= 0) { std::string s = std::string(map, st.st_size); handle(s, z, x, y, 1, to_decode, pipeline, stats); munmap(map, st.st_size); return; } else { fprintf(stderr, "Must specify zoom/x/y to decode a single pbf file\n"); exit(EXIT_FAILURE); } } } munmap(map, st.st_size); } } else { perror("fstat"); } if (close(fd) != 0) { perror("close"); exit(EXIT_FAILURE); } } else { perror(fname); } if (sqlite3_open(fname, &db) != SQLITE_OK) { fprintf(stderr, "%s: %s\n", fname, sqlite3_errmsg(db)); exit(EXIT_FAILURE); } if (z < 0) { int within = 0; if (!pipeline && !stats) { printf("{ \"type\": \"FeatureCollection\", \"properties\": {\n"); const char *sql2 = "SELECT name, value from metadata order by name;"; sqlite3_stmt *stmt2; if (sqlite3_prepare_v2(db, sql2, -1, &stmt2, NULL) != SQLITE_OK) { fprintf(stderr, "%s: select failed: %s\n", fname, sqlite3_errmsg(db)); exit(EXIT_FAILURE); } while (sqlite3_step(stmt2) == SQLITE_ROW) { if (within) { printf(",\n"); } within = 1; const unsigned char *name = sqlite3_column_text(stmt2, 0); const unsigned char *value = sqlite3_column_text(stmt2, 1); if (name == NULL || value == NULL) { fprintf(stderr, "Corrupt mbtiles file: null metadata\n"); exit(EXIT_FAILURE); } fprintq(stdout, (char *) name); printf(": "); fprintq(stdout, (char *) value); } sqlite3_finalize(stmt2); } if (stats) { printf("[\n"); } const char *sql = "SELECT tile_data, zoom_level, tile_column, tile_row from tiles where zoom_level between ? and ? order by zoom_level, tile_column, tile_row;"; sqlite3_stmt *stmt; if (sqlite3_prepare_v2(db, sql, -1, &stmt, NULL) != SQLITE_OK) { fprintf(stderr, "%s: select failed: %s\n", fname, sqlite3_errmsg(db)); exit(EXIT_FAILURE); } sqlite3_bind_int(stmt, 1, minzoom); sqlite3_bind_int(stmt, 2, maxzoom); if (!pipeline && !stats) { printf("\n}, \"features\": [\n"); } within = 0; while (sqlite3_step(stmt) == SQLITE_ROW) { if (!pipeline && !stats) { if (within) { printf(",\n"); } within = 1; } if (stats) { if (within) { printf(",\n"); } within = 1; } int len = sqlite3_column_bytes(stmt, 0); int tz = sqlite3_column_int(stmt, 1); int tx = sqlite3_column_int(stmt, 2); int ty = sqlite3_column_int(stmt, 3); ty = (1LL << tz) - 1 - ty; const char *s = (const char *) sqlite3_column_blob(stmt, 0); handle(std::string(s, len), tz, tx, ty, 1, to_decode, pipeline, stats); } if (!pipeline && !stats) { printf("] }\n"); } if (stats) { printf("]\n"); } sqlite3_finalize(stmt); } else { int handled = 0; while (z >= 0 && !handled) { const char *sql = "SELECT tile_data from tiles where zoom_level = ? and tile_column = ? and tile_row = ?;"; sqlite3_stmt *stmt; if (sqlite3_prepare_v2(db, sql, -1, &stmt, NULL) != SQLITE_OK) { fprintf(stderr, "%s: select failed: %s\n", fname, sqlite3_errmsg(db)); exit(EXIT_FAILURE); } sqlite3_bind_int(stmt, 1, z); sqlite3_bind_int(stmt, 2, x); sqlite3_bind_int(stmt, 3, (1LL << z) - 1 - y); while (sqlite3_step(stmt) == SQLITE_ROW) { int len = sqlite3_column_bytes(stmt, 0); const char *s = (const char *) sqlite3_column_blob(stmt, 0); if (z != oz) { fprintf(stderr, "%s: Warning: using tile %d/%u/%u instead of %d/%u/%u\n", fname, z, x, y, oz, ox, oy); } handle(std::string(s, len), z, x, y, 0, to_decode, pipeline, stats); handled = 1; } sqlite3_finalize(stmt); z--; x /= 2; y /= 2; } } if (sqlite3_close(db) != SQLITE_OK) { fprintf(stderr, "%s: could not close database: %s\n", fname, sqlite3_errmsg(db)); exit(EXIT_FAILURE); } } void usage(char **argv) { fprintf(stderr, "Usage: %s [-s projection] [-Z minzoom] [-z maxzoom] [-l layer ...] file.mbtiles [zoom x y]\n", argv[0]); exit(EXIT_FAILURE); } int main(int argc, char **argv) { extern int optind; extern char *optarg; int i; std::set<std::string> to_decode; bool pipeline = false; bool stats = false; struct option long_options[] = { {"projection", required_argument, 0, 's'}, {"maximum-zoom", required_argument, 0, 'z'}, {"minimum-zoom", required_argument, 0, 'Z'}, {"layer", required_argument, 0, 'l'}, {"tag-layer-and-zoom", no_argument, 0, 'c'}, {"stats", no_argument, 0, 'S'}, {"force", no_argument, 0, 'f'}, {0, 0, 0, 0}, }; std::string getopt_str; for (size_t lo = 0; long_options[lo].name != NULL; lo++) { if (long_options[lo].val > ' ') { getopt_str.push_back(long_options[lo].val); if (long_options[lo].has_arg == required_argument) { getopt_str.push_back(':'); } } } while ((i = getopt_long(argc, argv, getopt_str.c_str(), long_options, NULL)) != -1) { switch (i) { case 0: break; case 's': set_projection_or_exit(optarg); break; case 'z': maxzoom = atoi(optarg); break; case 'Z': minzoom = atoi(optarg); break; case 'l': to_decode.insert(optarg); break; case 'c': pipeline = true; break; case 'S': stats = true; break; case 'f': force = true; break; default: usage(argv); } } if (argc == optind + 4) { decode(argv[optind], atoi(argv[optind + 1]), atoi(argv[optind + 2]), atoi(argv[optind + 3]), to_decode, pipeline, stats); } else if (argc == optind + 1) { decode(argv[optind], -1, -1, -1, to_decode, pipeline, stats); } else { usage(argv); } return 0; } <|endoftext|>
<commit_before><commit_msg>Remove an unused declaration.<commit_after><|endoftext|>
<commit_before>#include "arguments.h" #include "../utils/version.h" #include <iostream> #include <boost/program_options.hpp> #include <boost/filesystem.hpp> #include <boost/format.hpp> using namespace thewizardplusplus::language_do::arguments; using namespace thewizardplusplus::language_do::utils; using namespace boost; using namespace boost::program_options; using namespace boost::filesystem; const auto POSITIONAL_ARGUMENT_SIGNLE_REPETITION = 1; const auto POSITIONAL_ARGUMENT_UNLIMITED_REPETITIONS = -1; namespace { auto MakeArgumentsDescription() -> options_description; auto ParseArguments( const std::vector<std::string>& arguments, const options_description& arguments_description ) -> variables_map; auto MakePositionalArgumentsDescription() -> positional_options_description; auto MakeParser( const std::vector<std::string>& arguments, const options_description& arguments_description, const positional_options_description& positional_arguments_description ) -> command_line_parser; auto RunParser(command_line_parser& parser) -> variables_map; auto ProcessVersionOption(const variables_map& arguments) -> void; auto ProcessHelpOption( const variables_map& arguments, const options_description& arguments_description ) -> void; auto GetParameters( const std::vector<std::string>& original_arguments, const variables_map& parsed_arguments ) -> Parameters; auto GetInterpreterPathOption( const std::vector<std::string>& arguments ) -> std::string; auto GetFinalStageOption(const variables_map& arguments) -> FinalStage; auto GetOutputFileOption(const variables_map& arguments) -> std::string; auto GetUseOutputOption(const variables_map& arguments) -> bool; auto GetScriptFileOption(const variables_map& arguments) -> std::string; auto GetScriptArgumentOptions( const variables_map& arguments ) -> std::vector<std::string>; } namespace thewizardplusplus { namespace language_do { namespace arguments { auto ProcessArguments(const std::vector<std::string>& arguments) -> Parameters { const auto arguments_description = MakeArgumentsDescription(); const auto parsed_arguments = ParseArguments( arguments, arguments_description ); ProcessVersionOption(parsed_arguments); ProcessHelpOption(parsed_arguments, arguments_description); return GetParameters(arguments, parsed_arguments); } } } } namespace { auto MakeArgumentsDescription() -> options_description { auto description = options_description("Options"); description.add_options() ("version,v", "- show version;") ("help,h", "- show help;") ( "final-stage,f", value<std::string>(), R"(- set final stage (allowed: "code", "ast" and "c");)" ) ( "output-file,o", value<std::string>(), "- output file for compiling result;" ) ("use-output,u", "- output any final stage result to output file;") ("script-file", value<std::string>(), "- script file;") ( "script-argument", value<std::vector<std::string>>()->composing(), "- script argument." ); return description; } auto ParseArguments( const std::vector<std::string>& arguments, const options_description& arguments_description ) -> variables_map { // должно быть создано здесь, т. к. время жизни должно включать время работы // RunParser() const auto positional_arguments_description = MakePositionalArgumentsDescription(); auto parser = MakeParser( arguments, arguments_description, positional_arguments_description ); return RunParser(parser); } auto MakePositionalArgumentsDescription() -> positional_options_description { return positional_options_description() .add("script-file", POSITIONAL_ARGUMENT_SIGNLE_REPETITION) .add("script-argument", POSITIONAL_ARGUMENT_UNLIMITED_REPETITIONS); } auto MakeParser( const std::vector<std::string>& arguments, const options_description& arguments_description, const positional_options_description& positional_arguments_description ) -> command_line_parser { return command_line_parser( std::vector<std::string>( std::begin(arguments) + 1, std::end(arguments) ) ) .options(arguments_description) .positional(positional_arguments_description); } auto RunParser(command_line_parser& parser) -> variables_map { auto arguments = variables_map(); const auto result = parser.run(); store(result, arguments); notify(arguments); return arguments; } auto ProcessVersionOption(const variables_map& arguments) -> void { if (!arguments.count("version")) { return; } std::cout << "Do interpreter, " << VERSION_STRING << "\n" << "(c) thewizardplusplus, 2015\n"; std::exit(EXIT_SUCCESS); } auto ProcessHelpOption( const variables_map& arguments, const options_description& arguments_description ) -> void { if (!arguments.count("help")) { return; } std::cout << "Usage:\n" << " doi [options] <script-file> [<script-argument>...]\n" << "\n" << arguments_description; std::exit(EXIT_SUCCESS); } auto GetParameters( const std::vector<std::string>& original_arguments, const variables_map& parsed_arguments ) -> Parameters { auto parameters = Parameters(); parameters.interpreter_path = GetInterpreterPathOption(original_arguments); parameters.final_stage = GetFinalStageOption(parsed_arguments); parameters.output_file = GetOutputFileOption(parsed_arguments); parameters.use_output = GetUseOutputOption(parsed_arguments); parameters.script_file = GetScriptFileOption(parsed_arguments); parameters.script_arguments = GetScriptArgumentOptions(parsed_arguments); return parameters; } auto GetInterpreterPathOption( const std::vector<std::string>& arguments ) -> std::string { return path(arguments[0]).parent_path().string(); } auto GetFinalStageOption(const variables_map& arguments) -> FinalStage { if (!arguments.count("final-stage")) { return FinalStage::NONE; } auto final_stage = FinalStage::NONE; const auto string_final_stage = arguments["final-stage"].as<std::string>(); if (string_final_stage == "code") { final_stage = FinalStage::CODE; } else if (string_final_stage == "ast") { final_stage = FinalStage::AST; } else if (string_final_stage == "c") { final_stage = FinalStage::C; } else { throw std::runtime_error( (format(R"(unknown final stage "%s")") % string_final_stage).str() ); } return final_stage; } auto GetOutputFileOption(const variables_map& arguments) -> std::string { if (!arguments.count("output-file")) { return ""; } return arguments["output-file"].as<std::string>(); } auto GetUseOutputOption(const variables_map& arguments) -> bool { return arguments.count("use-output") && arguments.count("output-file"); } auto GetScriptFileOption(const variables_map& arguments) -> std::string { if (!arguments.count("script-file")) { throw std::runtime_error("script file not specified"); } return arguments["script-file"].as<std::string>(); } auto GetScriptArgumentOptions( const variables_map& arguments ) -> std::vector<std::string> { if (!arguments.count("script-argument")) { return {}; } return arguments["script-argument"].as<std::vector<std::string>>(); } } <commit_msg>Fixes #34: restore simple code.<commit_after>#include "arguments.h" #include "../utils/version.h" #include <iostream> #include <boost/program_options.hpp> #include <boost/filesystem.hpp> #include <boost/format.hpp> using namespace thewizardplusplus::language_do::arguments; using namespace thewizardplusplus::language_do::utils; using namespace boost; using namespace boost::program_options; using namespace boost::filesystem; const auto POSITIONAL_ARGUMENT_SIGNLE_REPETITION = 1; const auto POSITIONAL_ARGUMENT_UNLIMITED_REPETITIONS = -1; namespace thewizardplusplus { namespace language_do { namespace arguments { auto ProcessArguments(const std::vector<std::string>& arguments) -> Parameters { auto arguments_description = options_description("Options"); arguments_description.add_options() ("version,v", "- show version;") ("help,h", "- show help;") ( "final-stage,f", value<std::string>(), R"(- set final stage (allowed: "code", "ast" and "c");)" ) ( "output-file,o", value<std::string>(), "- output file for compiling result;" ) ("use-output,u", "- output any final stage result to output file;") ("script-file", value<std::string>(), "- script file;") ( "script-argument", value<std::vector<std::string>>()->composing(), "- script argument." ); const auto positional_arguments_description = positional_options_description() .add("script-file", POSITIONAL_ARGUMENT_SIGNLE_REPETITION) .add("script-argument", POSITIONAL_ARGUMENT_UNLIMITED_REPETITIONS); auto parsed_arguments = variables_map(); const auto parsing_result = command_line_parser( std::vector<std::string>( std::begin(arguments) + 1, std::end(arguments) ) ) .options(arguments_description) .positional(positional_arguments_description) .run(); store(parsing_result, parsed_arguments); notify(parsed_arguments); if (parsed_arguments.count("version")) { std::cout << "Do interpreter, " << VERSION_STRING << "\n" << "(c) thewizardplusplus, 2015\n"; std::exit(EXIT_SUCCESS); } if (parsed_arguments.count("help")) { std::cout << "Usage:\n" << " doi [options] <script-file> [<script-argument>...]\n" << "\n" << arguments_description; std::exit(EXIT_SUCCESS); } auto parameters = Parameters(); parameters.interpreter_path = path(arguments[0]).parent_path().string(); if (parsed_arguments.count("final-stage")) { const auto final_stage = parsed_arguments["final-stage"] .as<std::string>(); if (final_stage == "code") { parameters.final_stage = FinalStage::CODE; } else if (final_stage == "ast") { parameters.final_stage = FinalStage::AST; } else if (final_stage == "c") { parameters.final_stage = FinalStage::C; } else { throw std::runtime_error( (format(R"(unknown final stage "%s")") % final_stage).str() ); } } if (parsed_arguments.count("output-file")) { parameters.output_file = parsed_arguments["output-file"] .as<std::string>(); } parameters.use_output = parsed_arguments.count("use-output") && parsed_arguments.count("output-file"); if (parsed_arguments.count("script-file")) { parameters.script_file = parsed_arguments["script-file"] .as<std::string>(); } else { throw std::runtime_error("script file not specified"); } if (parsed_arguments.count("script-argument")) { parameters.script_arguments = parsed_arguments["script-argument"] .as<std::vector<std::string>>(); } return parameters; } } } } <|endoftext|>
<commit_before>#include "ImageLoader.h" #include "Utilities/ResourceManager.h" namespace Graphics { namespace ImageLoader { SDL_Surface* LoadImage ( const std::string& path ) { SDL_RWops* rwops = ResourceManager::OpenFile(path); if (!rwops) return NULL; SDL_Surface* surface = IMG_LoadTyped_RW(rwops, 1, const_cast<char*>("PNG")); return surface; } GLuint CreateTexture ( SDL_Surface* surface, bool autofree, bool rectangle ) { GLuint texID; glGenTextures(1, &texID); GLenum target = rectangle ? GL_TEXTURE_RECTANGLE_ARB : GL_TEXTURE_2D; glBindTexture(target, texID); if (surface->format->BytesPerPixel == 3) { glTexImage2D(target, 0, GL_RGB, surface->w, surface->h, 0, GL_RGB, GL_UNSIGNED_BYTE, surface->pixels); } else { glTexImage2D(target, 0, GL_RGBA, surface->w, surface->h, 0, GL_RGBA, GL_UNSIGNED_BYTE, surface->pixels); } if (autofree) SDL_FreeSurface(surface); return texID; } } } <commit_msg>New SDL fully implemented with correct colors.<commit_after>#include "ImageLoader.h" #include "Utilities/ResourceManager.h" namespace Graphics { namespace ImageLoader { SDL_Surface* LoadImage ( const std::string& path ) { SDL_RWops* rwops = ResourceManager::OpenFile(path); if (!rwops) return NULL; SDL_Surface* surface = IMG_LoadTyped_RW(rwops, 1, const_cast<char*>("PNG")); return surface; } GLuint CreateTexture ( SDL_Surface* surface, bool autofree, bool rectangle ) { GLuint texID; glGenTextures(1, &texID); GLenum target = rectangle ? GL_TEXTURE_RECTANGLE_ARB : GL_TEXTURE_2D; glBindTexture(target, texID); if (surface->format->BytesPerPixel == 3) { GLenum format = (surface->format->Rmask) != 0xFF ? GL_BGR_EXT : GL_RGB; glTexImage2D(target, 0, GL_RGB, surface->w, surface->h, 0, format, GL_UNSIGNED_BYTE, surface->pixels); } else { GLenum format = (surface->format->Rmask) != 0xFF ? GL_BGRA_EXT : GL_RGBA; glTexImage2D(target, 0, GL_RGBA, surface->w, surface->h, 0, format, GL_UNSIGNED_BYTE, surface->pixels); } if (autofree) SDL_FreeSurface(surface); return texID; } } } <|endoftext|>
<commit_before>//////////////////////////////////////////////////////////////////////////////// // taskwarrior - a command line task list manager. // // Copyright 2006 - 2011, Paul Beckingham, Federico Hernandez. // All rights reserved. // // This program is free software; you can redistribute it and/or modify it under // the terms of the GNU General Public License as published by the Free Software // Foundation; either version 2 of the License, or (at your option) any later // version. // // This program is distributed in the hope that it will be useful, but WITHOUT // ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS // FOR A PARTICULAR PURPOSE. See the GNU General Public License for more // details. // // You should have received a copy of the GNU General Public License along with // this program; if not, write to the // // Free Software Foundation, Inc., // 51 Franklin Street, Fifth Floor, // Boston, MA // 02110-1301 // USA // //////////////////////////////////////////////////////////////////////////////// #include <iostream> #include <unistd.h> #include <cmake.h> #include <main.h> #include <test.h> #ifdef HAVE_LIBLUA extern "C" { #include <lua.h> } #endif Context context; //////////////////////////////////////////////////////////////////////////////// int main (int argc, char** argv) { UnitTest t (7); try { DOM dom; // TODO dom.get rc.name t.is (dom.get ("system.version"), VERSION, "DOM system.version -> VERSION"); t.is (dom.get ("system.lua.version"), LUA_RELEASE, "DOM system.lua.version -> LUA_RELEASE"); t.ok (dom.get ("system.os") != "<unknown>", "DOM system.os -> != Unknown"); t.is (dom.get ("context.program"), "", "DOM context.program -> ''"); t.is (dom.get ("context.args"), "", "DOM context.args -> ''"); t.is (dom.get ("context.width"), "0", "DOM context.width -> '0'"); t.is (dom.get ("context.height"), "0", "DOM context.height -> '0'"); // TODO dom.set rc.name } catch (std::string& error) { t.diag (error); return -1; } catch (...) { t.diag ("Unknown error."); return -2; } return 0; } //////////////////////////////////////////////////////////////////////////////// <commit_msg>Unit Tests<commit_after>//////////////////////////////////////////////////////////////////////////////// // taskwarrior - a command line task list manager. // // Copyright 2006 - 2011, Paul Beckingham, Federico Hernandez. // All rights reserved. // // This program is free software; you can redistribute it and/or modify it under // the terms of the GNU General Public License as published by the Free Software // Foundation; either version 2 of the License, or (at your option) any later // version. // // This program is distributed in the hope that it will be useful, but WITHOUT // ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS // FOR A PARTICULAR PURPOSE. See the GNU General Public License for more // details. // // You should have received a copy of the GNU General Public License along with // this program; if not, write to the // // Free Software Foundation, Inc., // 51 Franklin Street, Fifth Floor, // Boston, MA // 02110-1301 // USA // //////////////////////////////////////////////////////////////////////////////// #include <iostream> #include <unistd.h> #include <cmake.h> #include <main.h> #include <test.h> #ifdef HAVE_LIBLUA extern "C" { #include <lua.h> } #endif Context context; //////////////////////////////////////////////////////////////////////////////// int main (int argc, char** argv) { UnitTest t (7); try { // Prime the pump. context.args.capture ("task"); // TODO dom.get rc.name DOM dom; t.is (dom.get ("system.version"), VERSION, "DOM system.version -> VERSION"); t.is (dom.get ("system.lua.version"), LUA_RELEASE, "DOM system.lua.version -> LUA_RELEASE"); t.ok (dom.get ("system.os") != "<unknown>", "DOM system.os -> != Unknown"); t.is (dom.get ("context.program"), "task", "DOM context.program -> 'task'"); t.is (dom.get ("context.args"), "task", "DOM context.args -> 'task'"); t.is (dom.get ("context.width"), "0", "DOM context.width -> '0'"); t.is (dom.get ("context.height"), "0", "DOM context.height -> '0'"); // TODO dom.set rc.name } catch (std::string& error) { t.diag (error); return -1; } catch (...) { t.diag ("Unknown error."); return -2; } return 0; } //////////////////////////////////////////////////////////////////////////////// <|endoftext|>
<commit_before>// Copyright 2022 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 "google/cloud/pubsublite/internal/multipartition_publisher.h" #include <functional> #include <limits> namespace google { namespace cloud { namespace pubsublite_internal { GOOGLE_CLOUD_CPP_INLINE_NAMESPACE_BEGIN using ::google::cloud::pubsublite::AdminServiceConnection; using ::google::cloud::pubsublite::MessageMetadata; using ::google::cloud::pubsublite::Topic; using ::google::cloud::pubsublite::v1::Cursor; using ::google::cloud::pubsublite::v1::PubSubMessage; using ::google::cloud::pubsublite::v1::TopicPartitions; MultipartitionPublisher::MultipartitionPublisher( PartitionPublisherFactory publisher_factory, std::shared_ptr<AdminServiceConnection> admin_connection, AlarmRegistry& alarm_registry, std::unique_ptr<RoutingPolicy> routing_policy, Topic topic) : publisher_factory_{std::move(publisher_factory)}, admin_connection_{std::move(admin_connection)}, routing_policy_{std::move(routing_policy)}, topic_{std::move(topic)}, topic_partitions_request_{[&] { google::cloud::pubsublite::v1::GetTopicPartitionsRequest request; *request.mutable_name() = topic_.FullName(); return request; }()}, cancel_token_{alarm_registry.RegisterAlarm( std::chrono::seconds{60}, [this]() { TriggerPublisherCreation(); })} { } MultipartitionPublisher::~MultipartitionPublisher() { future<void> shutdown = Shutdown(); if (!shutdown.is_ready()) { GCP_LOG(WARNING) << "`Shutdown` must be called and finished before object " "goes out of scope."; assert(false); } shutdown.get(); } future<Status> MultipartitionPublisher::Start() { auto start = service_composite_.Start(); TriggerPublisherCreation(); return start; } future<StatusOr<std::uint32_t>> MultipartitionPublisher::GetNumPartitions() { return admin_connection_->AsyncGetTopicPartitions(topic_partitions_request_) .then([](future<StatusOr<TopicPartitions>> f) -> StatusOr<std::uint32_t> { auto partitions = f.get(); if (!partitions) return std::move(partitions).status(); if (partitions->partition_count() >= std::numeric_limits<std::uint32_t>::max()) { return Status{StatusCode::kInternal, absl::StrCat("Returned partition count is too big: ", partitions->partition_count())}; } return static_cast<std::uint32_t>(partitions->partition_count()); }); } void MultipartitionPublisher::HandleNumPartitions( std::uint32_t num_partitions) { std::uint32_t current_num_partitions; { std::lock_guard<std::mutex> g{mu_}; current_num_partitions = static_cast<std::uint32_t>(partition_publishers_.size()); } assert(num_partitions >= current_num_partitions); // should be no race if (num_partitions == current_num_partitions) return; std::vector<std::shared_ptr<Publisher<Cursor>>> new_partition_publishers; for (std::uint32_t partition = current_num_partitions; partition < num_partitions; ++partition) { new_partition_publishers.push_back(publisher_factory_(partition)); service_composite_.AddServiceObject(new_partition_publishers.back().get()); } { std::lock_guard<std::mutex> g{mu_}; std::move(new_partition_publishers.begin(), new_partition_publishers.end(), std::back_inserter(partition_publishers_)); } TryPublishMessages(); } void MultipartitionPublisher::TriggerPublisherCreation() { { std::lock_guard<std::mutex> g{mu_}; if (outstanding_num_partitions_req_) return; outstanding_num_partitions_req_.emplace(); } GetNumPartitions() .then([this](future<StatusOr<std::uint32_t>> f) { if (!service_composite_.status().ok()) return; auto num_partitions = f.get(); if (num_partitions.ok()) return HandleNumPartitions(*num_partitions); GCP_LOG(WARNING) << "Reading number of partitions for " << topic_.FullName() << "failed: " << num_partitions.status(); bool first_poll; { std::lock_guard<std::mutex> g{mu_}; first_poll = partition_publishers_.empty(); } if (first_poll) { // fail client if first poll fails return service_composite_.Abort(num_partitions.status()); } }) .then([this](future<void>) { absl::optional<promise<void>> p; { std::lock_guard<std::mutex> g{mu_}; assert(outstanding_num_partitions_req_); p.swap(outstanding_num_partitions_req_); } // only set value after done touching member variables p->set_value(); }); } void MultipartitionPublisher::RouteAndPublish(PublishState state) { std::uint32_t partition = state.message.key().empty() ? routing_policy_->Route(state.num_partitions) : routing_policy_->Route(state.message.key(), state.num_partitions); Publisher<Cursor>* publisher; { std::lock_guard<std::mutex> g{mu_}; publisher = partition_publishers_.at(partition).get(); } struct OnPublish { promise<StatusOr<MessageMetadata>> p; std::uint32_t partition; void operator()(future<StatusOr<Cursor>> f) { auto publish_response = f.get(); if (!publish_response) { return p.set_value(std::move(publish_response).status()); } p.set_value(MessageMetadata{partition, *std::move(publish_response)}); } }; publisher->Publish(std::move(state.message)) .then(OnPublish{std::move(state.publish_promise), partition}); } void MultipartitionPublisher::TryPublishMessages() { { std::lock_guard<std::mutex> g{mu_}; if (in_publish_loop_) return; in_publish_loop_ = true; } while (true) { std::deque<PublishState> messages; uint32_t num_partitions; { std::lock_guard<std::mutex> g{mu_}; if (messages_.empty()) { in_publish_loop_ = false; return; } messages.swap(messages_); num_partitions = static_cast<std::uint32_t>(partition_publishers_.size()); } for (PublishState& state : messages) { state.num_partitions = num_partitions; RouteAndPublish(std::move(state)); } } } future<StatusOr<MessageMetadata>> MultipartitionPublisher::Publish( PubSubMessage m) { PublishState state; state.message = std::move(m); future<StatusOr<MessageMetadata>> to_return; { std::lock_guard<std::mutex> g{mu_}; to_return = state.publish_promise.get_future(); messages_.push_back(std::move(state)); // message will be published whenever we successfully read the number of // partitions and publishers are created if (partition_publishers_.empty()) return to_return; } TryPublishMessages(); return to_return; } void MultipartitionPublisher::Flush() { std::vector<Publisher<Cursor>*> publishers; { std::lock_guard<std::mutex> g{mu_}; publishers.reserve(partition_publishers_.size()); for (auto& publisher : partition_publishers_) { publishers.push_back(publisher.get()); } } for (auto* publisher : publishers) { publisher->Flush(); } } future<void> MultipartitionPublisher::Shutdown() { cancel_token_ = nullptr; std::deque<PublishState> messages; { std::lock_guard<std::mutex> g{mu_}; messages.swap(messages_); } for (auto& state : messages) { state.publish_promise.set_value(Status{ StatusCode::kFailedPrecondition, "Multipartition publisher shutdown."}); } auto shutdown = service_composite_.Shutdown(); std::lock_guard<std::mutex> g{mu_}; if (outstanding_num_partitions_req_) { return outstanding_num_partitions_req_->get_future().then( ChainFuture(std::move(shutdown))); } return shutdown; } GOOGLE_CLOUD_CPP_INLINE_NAMESPACE_END } // namespace pubsublite_internal } // namespace cloud } // namespace google <commit_msg>cleanup(pubsublite): explicitly use std (#8791)<commit_after>// Copyright 2022 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 "google/cloud/pubsublite/internal/multipartition_publisher.h" #include <functional> #include <limits> namespace google { namespace cloud { namespace pubsublite_internal { GOOGLE_CLOUD_CPP_INLINE_NAMESPACE_BEGIN using ::google::cloud::pubsublite::AdminServiceConnection; using ::google::cloud::pubsublite::MessageMetadata; using ::google::cloud::pubsublite::Topic; using ::google::cloud::pubsublite::v1::Cursor; using ::google::cloud::pubsublite::v1::PubSubMessage; using ::google::cloud::pubsublite::v1::TopicPartitions; MultipartitionPublisher::MultipartitionPublisher( PartitionPublisherFactory publisher_factory, std::shared_ptr<AdminServiceConnection> admin_connection, AlarmRegistry& alarm_registry, std::unique_ptr<RoutingPolicy> routing_policy, Topic topic) : publisher_factory_{std::move(publisher_factory)}, admin_connection_{std::move(admin_connection)}, routing_policy_{std::move(routing_policy)}, topic_{std::move(topic)}, topic_partitions_request_{[&] { google::cloud::pubsublite::v1::GetTopicPartitionsRequest request; *request.mutable_name() = topic_.FullName(); return request; }()}, cancel_token_{alarm_registry.RegisterAlarm( std::chrono::seconds{60}, [this]() { TriggerPublisherCreation(); })} { } MultipartitionPublisher::~MultipartitionPublisher() { future<void> shutdown = Shutdown(); if (!shutdown.is_ready()) { GCP_LOG(WARNING) << "`Shutdown` must be called and finished before object " "goes out of scope."; assert(false); } shutdown.get(); } future<Status> MultipartitionPublisher::Start() { auto start = service_composite_.Start(); TriggerPublisherCreation(); return start; } future<StatusOr<std::uint32_t>> MultipartitionPublisher::GetNumPartitions() { return admin_connection_->AsyncGetTopicPartitions(topic_partitions_request_) .then([](future<StatusOr<TopicPartitions>> f) -> StatusOr<std::uint32_t> { auto partitions = f.get(); if (!partitions) return std::move(partitions).status(); if (partitions->partition_count() >= std::numeric_limits<std::uint32_t>::max()) { return Status{StatusCode::kInternal, absl::StrCat("Returned partition count is too big: ", partitions->partition_count())}; } return static_cast<std::uint32_t>(partitions->partition_count()); }); } void MultipartitionPublisher::HandleNumPartitions( std::uint32_t num_partitions) { std::uint32_t current_num_partitions; { std::lock_guard<std::mutex> g{mu_}; current_num_partitions = static_cast<std::uint32_t>(partition_publishers_.size()); } assert(num_partitions >= current_num_partitions); // should be no race if (num_partitions == current_num_partitions) return; std::vector<std::shared_ptr<Publisher<Cursor>>> new_partition_publishers; for (std::uint32_t partition = current_num_partitions; partition < num_partitions; ++partition) { new_partition_publishers.push_back(publisher_factory_(partition)); service_composite_.AddServiceObject(new_partition_publishers.back().get()); } { std::lock_guard<std::mutex> g{mu_}; std::move(new_partition_publishers.begin(), new_partition_publishers.end(), std::back_inserter(partition_publishers_)); } TryPublishMessages(); } void MultipartitionPublisher::TriggerPublisherCreation() { { std::lock_guard<std::mutex> g{mu_}; if (outstanding_num_partitions_req_) return; outstanding_num_partitions_req_.emplace(); } GetNumPartitions() .then([this](future<StatusOr<std::uint32_t>> f) { if (!service_composite_.status().ok()) return; auto num_partitions = f.get(); if (num_partitions.ok()) return HandleNumPartitions(*num_partitions); GCP_LOG(WARNING) << "Reading number of partitions for " << topic_.FullName() << "failed: " << num_partitions.status(); bool first_poll; { std::lock_guard<std::mutex> g{mu_}; first_poll = partition_publishers_.empty(); } if (first_poll) { // fail client if first poll fails return service_composite_.Abort(num_partitions.status()); } }) .then([this](future<void>) { absl::optional<promise<void>> p; { std::lock_guard<std::mutex> g{mu_}; assert(outstanding_num_partitions_req_); p.swap(outstanding_num_partitions_req_); } // only set value after done touching member variables p->set_value(); }); } void MultipartitionPublisher::RouteAndPublish(PublishState state) { std::uint32_t partition = state.message.key().empty() ? routing_policy_->Route(state.num_partitions) : routing_policy_->Route(state.message.key(), state.num_partitions); Publisher<Cursor>* publisher; { std::lock_guard<std::mutex> g{mu_}; publisher = partition_publishers_.at(partition).get(); } struct OnPublish { promise<StatusOr<MessageMetadata>> p; std::uint32_t partition; void operator()(future<StatusOr<Cursor>> f) { auto publish_response = f.get(); if (!publish_response) { return p.set_value(std::move(publish_response).status()); } p.set_value(MessageMetadata{partition, *std::move(publish_response)}); } }; publisher->Publish(std::move(state.message)) .then(OnPublish{std::move(state.publish_promise), partition}); } void MultipartitionPublisher::TryPublishMessages() { { std::lock_guard<std::mutex> g{mu_}; if (in_publish_loop_) return; in_publish_loop_ = true; } while (true) { std::deque<PublishState> messages; std::uint32_t num_partitions; { std::lock_guard<std::mutex> g{mu_}; if (messages_.empty()) { in_publish_loop_ = false; return; } messages.swap(messages_); num_partitions = static_cast<std::uint32_t>(partition_publishers_.size()); } for (PublishState& state : messages) { state.num_partitions = num_partitions; RouteAndPublish(std::move(state)); } } } future<StatusOr<MessageMetadata>> MultipartitionPublisher::Publish( PubSubMessage m) { PublishState state; state.message = std::move(m); future<StatusOr<MessageMetadata>> to_return; { std::lock_guard<std::mutex> g{mu_}; to_return = state.publish_promise.get_future(); messages_.push_back(std::move(state)); // message will be published whenever we successfully read the number of // partitions and publishers are created if (partition_publishers_.empty()) return to_return; } TryPublishMessages(); return to_return; } void MultipartitionPublisher::Flush() { std::vector<Publisher<Cursor>*> publishers; { std::lock_guard<std::mutex> g{mu_}; publishers.reserve(partition_publishers_.size()); for (auto& publisher : partition_publishers_) { publishers.push_back(publisher.get()); } } for (auto* publisher : publishers) { publisher->Flush(); } } future<void> MultipartitionPublisher::Shutdown() { cancel_token_ = nullptr; std::deque<PublishState> messages; { std::lock_guard<std::mutex> g{mu_}; messages.swap(messages_); } for (auto& state : messages) { state.publish_promise.set_value(Status{ StatusCode::kFailedPrecondition, "Multipartition publisher shutdown."}); } auto shutdown = service_composite_.Shutdown(); std::lock_guard<std::mutex> g{mu_}; if (outstanding_num_partitions_req_) { return outstanding_num_partitions_req_->get_future().then( ChainFuture(std::move(shutdown))); } return shutdown; } GOOGLE_CLOUD_CPP_INLINE_NAMESPACE_END } // namespace pubsublite_internal } // namespace cloud } // namespace google <|endoftext|>
<commit_before> #include "../Pipeline/Matrix.h" #include <catch.hpp> using namespace generator; TEST_CASE("Matrix types") { IdMatrix matrix(128, 128, 0, 11); matrix.set(33, 33, 0, 5); REQUIRE(matrix.get(33, 33, 0) == 5); for(Size x = 0; x < 128; x++) { for(Size y = 0; y < 128; y++) { matrix.set(x, y, 0, (x * y) & 0b1111); } } for(Size x = 0; x < 128; x++) { for(Size y = 0; y < 128; y++) { REQUIRE(matrix.get(x, y, 0) == ((x * y) & 0b1111)); } } }<commit_msg>Added TiledMatrix tests<commit_after> #include "../Pipeline/Matrix.h" #include <catch.hpp> using namespace generator; TEST_CASE("IdMatrix") { IdMatrix matrix(128, 128, 0, 11); matrix.set(33, 33, 0, 5); REQUIRE(matrix.get(33, 33, 0) == 5); SECTION("Medium matrix") { for(Size x = 0; x < 128; x++) { for(Size y = 0; y < 128; y++) { matrix.set(x, y, 0, (x * y) & 0b11111111111); } } for(Size x = 0; x < 128; x++) { for(Size y = 0; y < 128; y++) { CAPTURE(x); CAPTURE(y); REQUIRE(matrix.get(x, y, 0) == ((x * y) & 0b11111111111)); } } } SECTION("Large matrix") { IdMatrix largeMatrix(256, 256, 0, 32); for(Size x = 0; x < 256; x++) { for(Size y = 0; y < 256; y++) { largeMatrix.set(x, y, 0, (x * y) & 0xffffffff); } } for(Size x = 0; x < 256; x++) { for(Size y = 0; y < 256; y++) { CAPTURE(x); CAPTURE(y); REQUIRE(largeMatrix.get(x, y, 0) == ((x * y) & 0xffffffff)); } } } SECTION("Small matrix") { IdMatrix smallMatrix(64, 64, 0, 2); for(Size x = 0; x < 64; x++) { for(Size y = 0; y < 64; y++) { smallMatrix.set(x, y, 0, (x * y) & 0b11); } } for(Size x = 0; x < 64; x++) { for(Size y = 0; y < 64; y++) { CAPTURE(x); CAPTURE(y); REQUIRE(smallMatrix.get(x, y, 0) == ((x * y) & 0b11)); } } } } TEST_CASE("TiledMatrix single tile") { TiledMatrix matrix(0, 16, 7); for(Int x = 0; x < 128; x++) { for(Int y = 0; y < 128; y++) { matrix.set(x, y, 0, (x * y) & 0b1111111); } } for(Int x = 0; x < 128; x++) { for(Int y = 0; y < 128; y++) { CAPTURE(x); CAPTURE(y); REQUIRE(matrix.get(x, y, 0) == ((x * y) & 0b1111111)); } } } TEST_CASE("TiledMatrix multiple tiles") { TiledMatrix matrix(0, 16, 4); for(Int x = -231; x < 111; x++) { for(Int y = -17; y < 33; y++) { matrix.set(x, y, 0, (x * y) & 0xffff); } } for(Int x = -231; x < 111; x++) { for(Int y = -17; y < 33; y++) { CAPTURE(x); CAPTURE(y); REQUIRE(matrix.get(x, y, 0) == ((x * y) & 0xffff)); } } } TEST_CASE("TiledMatrix OOB") { TiledMatrix matrix(0, 16, 4); for(Int x = -231; x < 111; x++) { for(Int y = -17; y < 33; y++) { matrix.set(x, y, 0, (x * y) & 0xffff); } } REQUIRE(matrix.get(300, 300, 0) == 0); }<|endoftext|>
<commit_before>/*========================================================================= Program: Visualization Toolkit Module: vtkFillHolesFilter.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. =========================================================================*/ #include "vtkFillHolesFilter.h" #include "vtkInformation.h" #include "vtkInformationVector.h" #include "vtkCellArray.h" #include "vtkCellData.h" #include "vtkDoubleArray.h" #include "vtkObjectFactory.h" #include "vtkPointData.h" #include "vtkPolyData.h" #include "vtkTriangleStrip.h" #include "vtkPolygon.h" #include "vtkSphere.h" #include "vtkMath.h" vtkCxxRevisionMacro(vtkFillHolesFilter, "1.1"); vtkStandardNewMacro(vtkFillHolesFilter); //------------------------------------------------------------------------ vtkFillHolesFilter::vtkFillHolesFilter() { this->HoleSize = 1.0; } //------------------------------------------------------------------------ vtkFillHolesFilter::~vtkFillHolesFilter() { } //------------------------------------------------------------------------ int vtkFillHolesFilter::RequestData( vtkInformation *vtkNotUsed(request), vtkInformationVector **inputVector, vtkInformationVector *outputVector) { // get the info objects vtkInformation *inInfo = inputVector[0]->GetInformationObject(0); vtkInformation *outInfo = outputVector->GetInformationObject(0); // get the input and ouptut vtkPolyData *input = vtkPolyData::SafeDownCast( inInfo->Get(vtkDataObject::DATA_OBJECT())); vtkPolyData *output = vtkPolyData::SafeDownCast( outInfo->Get(vtkDataObject::DATA_OBJECT())); vtkPointData *pd=input->GetPointData(), *outPD=output->GetPointData(); vtkDebugMacro(<<"Executing hole fill operation"); // check the input, build data structures as necessary vtkIdType numPts, npts, *pts; vtkPoints *inPts=input->GetPoints(); vtkIdType numPolys = input->GetNumberOfPolys(); vtkIdType numStrips = input->GetNumberOfStrips(); if ( (numPts=input->GetNumberOfPoints()) < 1 || !inPts || (numPolys < 1 && numStrips < 1) ) { vtkDebugMacro(<<"No input data!"); return 1; } vtkPolyData *Mesh = vtkPolyData::New(); Mesh->SetPoints(inPts); vtkCellArray *newPolys, *inPolys=input->GetPolys(), *inStrips=input->GetStrips(); if ( numStrips > 0 ) { newPolys = vtkCellArray::New(); if ( numPolys > 0 ) { newPolys->DeepCopy(inPolys); } else { newPolys->Allocate(newPolys->EstimateSize(numStrips,5)); } inStrips = input->GetStrips(); for ( inStrips->InitTraversal(); inStrips->GetNextCell(npts,pts); ) { vtkTriangleStrip::DecomposeStrip(npts, pts, newPolys); } Mesh->SetPolys(newPolys); newPolys->Delete(); } else { newPolys = inPolys; Mesh->SetPolys(newPolys); } Mesh->BuildLinks(); // Allocate storage for lines/points (arbitrary allocation sizes) // vtkPolyData *Lines = vtkPolyData::New(); vtkCellArray *newLines = vtkCellArray::New(); newLines->Allocate(numPts/10); Lines->SetLines(newLines); Lines->SetPoints(inPts); // grab all free edges and place them into a temporary polydata int abort=0; vtkIdType cellId, p1, p2, numNei, i, newId, numCells=newPolys->GetNumberOfCells(); vtkIdType progressInterval=numCells/20+1; vtkIdList *neighbors = vtkIdList::New(); neighbors->Allocate(VTK_CELL_SIZE); for (cellId=0, newPolys->InitTraversal(); newPolys->GetNextCell(npts,pts) && !abort; cellId++) { if ( ! (cellId % progressInterval) ) //manage progress / early abort { this->UpdateProgress ((double)cellId / numCells); abort = this->GetAbortExecute(); } for (i=0; i < npts; i++) { p1 = pts[i]; p2 = pts[(i+1)%npts]; Mesh->GetCellEdgeNeighbors(cellId,p1,p2, neighbors); numNei = neighbors->GetNumberOfIds(); if ( numNei < 1 ) { newId = newLines->InsertNextCell(2); newLines->InsertCellPoint(p1); newLines->InsertCellPoint(p2); } } } // Track all free edges and see whether polygons can be built from them. // For each polygon of appropriate HoleSize, triangulate the hole and // add to the output list of cells vtkIdType numHolesFilled=0; numCells = newLines->GetNumberOfCells(); vtkCellArray *newCells = NULL; if ( numCells > 3 ) //only do the work if there are free edges { double sphere[4]; vtkIdType startId, neiId, currentCellId, hints[2]; hints[0]=0; hints[1]=0; vtkPolygon *polygon=vtkPolygon::New(); polygon->Points->SetDataTypeToDouble(); vtkIdList *endId = vtkIdList::New(); endId->SetNumberOfIds(1); char *visited = new char [numCells]; memset(visited, 0, numCells); Lines->BuildLinks(); //build the neighbor data structure newCells = vtkCellArray::New(); newCells->DeepCopy(inPolys); for (cellId=0; cellId < numCells && !abort; cellId++) { if ( ! visited[cellId] ) { visited[cellId] = 1; // Setup the polygon Lines->GetCellPoints(cellId, npts, pts); startId = pts[0]; polygon->PointIds->Reset(); polygon->Points->Reset(); polygon->PointIds->InsertId(0,pts[0]); polygon->Points->InsertPoint(0,inPts->GetPoint(pts[0])); // Work around the loop and terminate when the loop ends endId->SetId(0,pts[1]); int valid = 1; currentCellId = cellId; while ( startId != endId->GetId(0) && valid ) { polygon->PointIds->InsertNextId(endId->GetId(0)); polygon->Points->InsertNextPoint(inPts->GetPoint(endId->GetId(0))); Lines->GetCellNeighbors(currentCellId,endId,neighbors); if ( neighbors->GetNumberOfIds() == 0 ) { valid = 0; } else if ( neighbors->GetNumberOfIds() > 1 ) { //have to logically split this vertex valid = 0; } else { neiId = neighbors->GetId(0); visited[neiId] = 1; Lines->GetCellPoints(neiId,npts,pts); endId->SetId( 0, (pts[0] != endId->GetId(0) ? pts[0] : pts[1] ) ); currentCellId = neiId; } }//while loop connected // Evaluate the size of the loop and see if it is small enough if ( valid ) { vtkSphere::ComputeBoundingSphere(static_cast<vtkDoubleArray*>(polygon->Points->GetData())->GetPointer(0), polygon->PointIds->GetNumberOfIds(),sphere,hints); if ( sphere[3] <= this->HoleSize ) { // Now triangulate the loop and pass to the output numHolesFilled++; polygon->NonDegenerateTriangulate(neighbors); for ( i=0; i < neighbors->GetNumberOfIds(); i+=3 ) { newCells->InsertNextCell(3); newCells->InsertCellPoint(polygon->PointIds->GetId(neighbors->GetId(i))); newCells->InsertCellPoint(polygon->PointIds->GetId(neighbors->GetId(i+1))); newCells->InsertCellPoint(polygon->PointIds->GetId(neighbors->GetId(i+2))); } }//if hole small enough }//if a valid loop }//if not yet visited a line }//for all lines polygon->Delete(); endId->Delete(); delete [] visited; }//if loops present in the input // Clean up neighbors->Delete(); Lines->Delete(); // No new points are created, so the points and point data can be passed // through to the output. output->SetPoints(inPts); outPD->PassData(pd); // New cells are created, so currently we do not pass the cell data. // It would be pretty easy to extend the existing cell data and mark // the new cells with special data values. output->SetVerts(input->GetVerts()); output->SetLines(input->GetLines()); if ( newCells ) { output->SetPolys(newCells); newCells->Delete(); } output->SetStrips(input->GetStrips()); Mesh->Delete(); newLines->Delete(); return 1; } //------------------------------------------------------------------------ void vtkFillHolesFilter::PrintSelf(ostream& os, vtkIndent indent) { this->Superclass::PrintSelf(os,indent); os << indent << "Hole Size: " << this->HoleSize << "\n"; } <commit_msg>ENH:Removed warning unused variable<commit_after>/*========================================================================= Program: Visualization Toolkit Module: vtkFillHolesFilter.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. =========================================================================*/ #include "vtkFillHolesFilter.h" #include "vtkInformation.h" #include "vtkInformationVector.h" #include "vtkCellArray.h" #include "vtkCellData.h" #include "vtkDoubleArray.h" #include "vtkObjectFactory.h" #include "vtkPointData.h" #include "vtkPolyData.h" #include "vtkTriangleStrip.h" #include "vtkPolygon.h" #include "vtkSphere.h" #include "vtkMath.h" vtkCxxRevisionMacro(vtkFillHolesFilter, "1.2"); vtkStandardNewMacro(vtkFillHolesFilter); //------------------------------------------------------------------------ vtkFillHolesFilter::vtkFillHolesFilter() { this->HoleSize = 1.0; } //------------------------------------------------------------------------ vtkFillHolesFilter::~vtkFillHolesFilter() { } //------------------------------------------------------------------------ int vtkFillHolesFilter::RequestData( vtkInformation *vtkNotUsed(request), vtkInformationVector **inputVector, vtkInformationVector *outputVector) { // get the info objects vtkInformation *inInfo = inputVector[0]->GetInformationObject(0); vtkInformation *outInfo = outputVector->GetInformationObject(0); // get the input and ouptut vtkPolyData *input = vtkPolyData::SafeDownCast( inInfo->Get(vtkDataObject::DATA_OBJECT())); vtkPolyData *output = vtkPolyData::SafeDownCast( outInfo->Get(vtkDataObject::DATA_OBJECT())); vtkPointData *pd=input->GetPointData(), *outPD=output->GetPointData(); vtkDebugMacro(<<"Executing hole fill operation"); // check the input, build data structures as necessary vtkIdType numPts, npts, *pts; vtkPoints *inPts=input->GetPoints(); vtkIdType numPolys = input->GetNumberOfPolys(); vtkIdType numStrips = input->GetNumberOfStrips(); if ( (numPts=input->GetNumberOfPoints()) < 1 || !inPts || (numPolys < 1 && numStrips < 1) ) { vtkDebugMacro(<<"No input data!"); return 1; } vtkPolyData *Mesh = vtkPolyData::New(); Mesh->SetPoints(inPts); vtkCellArray *newPolys, *inPolys=input->GetPolys(), *inStrips=input->GetStrips(); if ( numStrips > 0 ) { newPolys = vtkCellArray::New(); if ( numPolys > 0 ) { newPolys->DeepCopy(inPolys); } else { newPolys->Allocate(newPolys->EstimateSize(numStrips,5)); } inStrips = input->GetStrips(); for ( inStrips->InitTraversal(); inStrips->GetNextCell(npts,pts); ) { vtkTriangleStrip::DecomposeStrip(npts, pts, newPolys); } Mesh->SetPolys(newPolys); newPolys->Delete(); } else { newPolys = inPolys; Mesh->SetPolys(newPolys); } Mesh->BuildLinks(); // Allocate storage for lines/points (arbitrary allocation sizes) // vtkPolyData *Lines = vtkPolyData::New(); vtkCellArray *newLines = vtkCellArray::New(); newLines->Allocate(numPts/10); Lines->SetLines(newLines); Lines->SetPoints(inPts); // grab all free edges and place them into a temporary polydata int abort=0; vtkIdType cellId, p1, p2, numNei, i, numCells=newPolys->GetNumberOfCells(); vtkIdType progressInterval=numCells/20+1; vtkIdList *neighbors = vtkIdList::New(); neighbors->Allocate(VTK_CELL_SIZE); for (cellId=0, newPolys->InitTraversal(); newPolys->GetNextCell(npts,pts) && !abort; cellId++) { if ( ! (cellId % progressInterval) ) //manage progress / early abort { this->UpdateProgress ((double)cellId / numCells); abort = this->GetAbortExecute(); } for (i=0; i < npts; i++) { p1 = pts[i]; p2 = pts[(i+1)%npts]; Mesh->GetCellEdgeNeighbors(cellId,p1,p2, neighbors); numNei = neighbors->GetNumberOfIds(); if ( numNei < 1 ) { newLines->InsertNextCell(2); newLines->InsertCellPoint(p1); newLines->InsertCellPoint(p2); } } } // Track all free edges and see whether polygons can be built from them. // For each polygon of appropriate HoleSize, triangulate the hole and // add to the output list of cells vtkIdType numHolesFilled=0; numCells = newLines->GetNumberOfCells(); vtkCellArray *newCells = NULL; if ( numCells > 3 ) //only do the work if there are free edges { double sphere[4]; vtkIdType startId, neiId, currentCellId, hints[2]; hints[0]=0; hints[1]=0; vtkPolygon *polygon=vtkPolygon::New(); polygon->Points->SetDataTypeToDouble(); vtkIdList *endId = vtkIdList::New(); endId->SetNumberOfIds(1); char *visited = new char [numCells]; memset(visited, 0, numCells); Lines->BuildLinks(); //build the neighbor data structure newCells = vtkCellArray::New(); newCells->DeepCopy(inPolys); for (cellId=0; cellId < numCells && !abort; cellId++) { if ( ! visited[cellId] ) { visited[cellId] = 1; // Setup the polygon Lines->GetCellPoints(cellId, npts, pts); startId = pts[0]; polygon->PointIds->Reset(); polygon->Points->Reset(); polygon->PointIds->InsertId(0,pts[0]); polygon->Points->InsertPoint(0,inPts->GetPoint(pts[0])); // Work around the loop and terminate when the loop ends endId->SetId(0,pts[1]); int valid = 1; currentCellId = cellId; while ( startId != endId->GetId(0) && valid ) { polygon->PointIds->InsertNextId(endId->GetId(0)); polygon->Points->InsertNextPoint(inPts->GetPoint(endId->GetId(0))); Lines->GetCellNeighbors(currentCellId,endId,neighbors); if ( neighbors->GetNumberOfIds() == 0 ) { valid = 0; } else if ( neighbors->GetNumberOfIds() > 1 ) { //have to logically split this vertex valid = 0; } else { neiId = neighbors->GetId(0); visited[neiId] = 1; Lines->GetCellPoints(neiId,npts,pts); endId->SetId( 0, (pts[0] != endId->GetId(0) ? pts[0] : pts[1] ) ); currentCellId = neiId; } }//while loop connected // Evaluate the size of the loop and see if it is small enough if ( valid ) { vtkSphere::ComputeBoundingSphere(static_cast<vtkDoubleArray*>(polygon->Points->GetData())->GetPointer(0), polygon->PointIds->GetNumberOfIds(),sphere,hints); if ( sphere[3] <= this->HoleSize ) { // Now triangulate the loop and pass to the output numHolesFilled++; polygon->NonDegenerateTriangulate(neighbors); for ( i=0; i < neighbors->GetNumberOfIds(); i+=3 ) { newCells->InsertNextCell(3); newCells->InsertCellPoint(polygon->PointIds->GetId(neighbors->GetId(i))); newCells->InsertCellPoint(polygon->PointIds->GetId(neighbors->GetId(i+1))); newCells->InsertCellPoint(polygon->PointIds->GetId(neighbors->GetId(i+2))); } }//if hole small enough }//if a valid loop }//if not yet visited a line }//for all lines polygon->Delete(); endId->Delete(); delete [] visited; }//if loops present in the input // Clean up neighbors->Delete(); Lines->Delete(); // No new points are created, so the points and point data can be passed // through to the output. output->SetPoints(inPts); outPD->PassData(pd); // New cells are created, so currently we do not pass the cell data. // It would be pretty easy to extend the existing cell data and mark // the new cells with special data values. output->SetVerts(input->GetVerts()); output->SetLines(input->GetLines()); if ( newCells ) { output->SetPolys(newCells); newCells->Delete(); } output->SetStrips(input->GetStrips()); Mesh->Delete(); newLines->Delete(); return 1; } //------------------------------------------------------------------------ void vtkFillHolesFilter::PrintSelf(ostream& os, vtkIndent indent) { this->Superclass::PrintSelf(os,indent); os << indent << "Hole Size: " << this->HoleSize << "\n"; } <|endoftext|>
<commit_before>#include "zmq.h" #include <iostream> #include "AliHLTDataTypes.h" #include "AliHLTComponent.h" #include "AliHLTMessage.h" #include "TClass.h" #include "TCanvas.h" #include "TMap.h" #include "TPRegexp.h" #include "TObjString.h" #include "TDirectory.h" #include "TList.h" #include "AliZMQhelpers.h" #include "TMessage.h" #include "TSystem.h" #include "TApplication.h" #include "TH1.h" #include "TH1F.h" #include <time.h> #include <string> #include <map> #include "TFile.h" #include "TSystem.h" #include "signal.h" class MySignalHandler; //this is meant to become a class, hence the structure with global vars etc. //Also the code is rather flat - it is a bit of a playground to test ideas. //TODO structure this at some point, e.g. introduce a SIMPLE unified way of handling //zmq payloads, maybe a AliZMQmessage class which would by default be multipart and provide //easy access to payloads based on topic or so (a la HLT GetFirstInputObject() etc...) //methods int ProcessOptionString(TString arguments); int UpdatePad(TObject*); int DumpToFile(TObject* object); void* run(void* arg); //configuration vars Bool_t fVerbose = kFALSE; TString fZMQconfigIN = "PULL>tcp://localhost:60211"; int fZMQsocketModeIN=-1; TString fZMQsubscriptionIN = ""; TString fFilter = ""; TString fFileName=""; TFile* fFile=NULL; int fPollInterval = 0; int fPollTimeout = 1000; //1s //internal state void* fZMQcontext = NULL; //ze zmq context void* fZMQin = NULL; //the in socket - entry point for the data to be merged. TApplication* gApp; TCanvas* fCanvas; TObjArray fDrawables; TPRegexp* fSelectionRegexp = NULL; TPRegexp* fUnSelectionRegexp = NULL; TString fDrawOptions; Bool_t fScaleLogX = kFALSE; Bool_t fScaleLogY = kFALSE; Bool_t fScaleLogZ = kFALSE; Bool_t fResetOnRequest = kFALSE; ULong64_t iterations=0; const char* fUSAGE = "ZMQhstViewer: Draw() all ROOT drawables in a message\n" "options: \n" " -in : data in\n" " -sleep : how long to sleep in between requests for data in s (if applicable)\n" " -timeout : how long to wait for the server to reply (s)\n" " -Verbose : be verbose\n" " -select : only show selected histograms (by regexp)\n" " -unselect : as select, only inverted\n" " -drawoptions : what draw option to use\n" " -file : dump input to file and exit\n" " log[xyz] : use log scale on [xyz] dimension\n" ; //_______________________________________________________________________________________ class MySignalHandler : public TSignalHandler { public: MySignalHandler(ESignals sig) : TSignalHandler(sig) {} Bool_t Notify() { Printf("signal received, exiting"); fgTerminationSignaled = true; return TSignalHandler::Notify(); } static bool TerminationSignaled() { return fgTerminationSignaled; } static bool fgTerminationSignaled; }; bool MySignalHandler::fgTerminationSignaled = false; void sig_handler(int signo) { if (signo == SIGINT) printf("received SIGINT\n"); MySignalHandler::fgTerminationSignaled=true; } //_______________________________________________________________________________________ void* run(void* arg) { //main loop while(!MySignalHandler::TerminationSignaled()) { errno=0; //send a request if we are using REQ if (fZMQsocketModeIN==ZMQ_REQ) { TString request; TString requestTopic; if (fSelectionRegexp || fUnSelectionRegexp) { requestTopic = "CONFIG"; if (fSelectionRegexp) request += " select="+fSelectionRegexp->GetPattern(); if (fUnSelectionRegexp) request += " unselect="+fUnSelectionRegexp->GetPattern(); if (fResetOnRequest) request += " ResetOnRequest"; zmq_send(fZMQin, requestTopic.Data(), requestTopic.Length(), ZMQ_SNDMORE); zmq_send(fZMQin, request.Data(), request.Length(), ZMQ_SNDMORE); } if (fVerbose) Printf("sending request %s %s",requestTopic.Data(), request.Data()); zmq_send(fZMQin, "", 0, ZMQ_SNDMORE); zmq_send(fZMQin, "", 0, 0); } //wait for the data zmq_pollitem_t sockets[] = { { fZMQin, 0, ZMQ_POLLIN, 0 }, }; int rc = zmq_poll(sockets, 1, (fZMQsocketModeIN==ZMQ_REQ)?fPollTimeout:-1); if (rc==-1 && errno==ETERM) { Printf("jumping out of main loop"); break; } if (!(sockets[0].revents & ZMQ_POLLIN)) { //server died Printf("connection timed out, server %s died?", fZMQconfigIN.Data()); fZMQsocketModeIN = alizmq_socket_init(fZMQin, fZMQcontext, fZMQconfigIN.Data()); if (fZMQsocketModeIN < 0) return NULL; continue; } else { //get all data (topic+body), possibly many of them aliZMQmsg message; alizmq_msg_recv(&message, fZMQin, 0); for (aliZMQmsg::iterator i=message.begin(); i!=message.end(); ++i) { TObject* object; alizmq_msg_iter_data(i, object); if (object) UpdatePad(object); if (!fFileName.IsNull()) { DumpToFile(object); } } alizmq_msg_close(&message); }//socket 0 gSystem->ProcessEvents(); usleep(fPollInterval); }//main loop return NULL; } //_______________________________________________________________________________________ int main(int argc, char** argv) { //process args int noptions = ProcessOptionString(AliOptionParser::GetFullArgString(argc,argv)); if (noptions<=0) { printf("%s",fUSAGE); return 1; } TH1::AddDirectory(kFALSE); TDirectory::AddDirectory(kFALSE); gApp = new TApplication("viewer", &argc, argv); gApp->SetReturnFromRun(true); //gApp->Run(); fCanvas = new TCanvas(); gSystem->ProcessEvents(); int mainReturnCode=0; //init stuff //globally enable schema evolution for serializing ROOT objects TMessage::EnableSchemaEvolutionForAll(kTRUE); //ZMQ init fZMQcontext = zmq_ctx_new(); fZMQsocketModeIN = alizmq_socket_init(fZMQin, fZMQcontext, fZMQconfigIN.Data(), -1, 2); if (fZMQsocketModeIN < 0) return 1; gSystem->ResetSignal(kSigPipe); gSystem->ResetSignal(kSigQuit); gSystem->ResetSignal(kSigInterrupt); gSystem->ResetSignal(kSigTermination); //gSystem->AddSignalHandler(new MySignalHandler(kSigPipe)); //gSystem->AddSignalHandler(new MySignalHandler(kSigQuit)); //gSystem->AddSignalHandler(new MySignalHandler(kSigInterrupt)); //gSystem->AddSignalHandler(new MySignalHandler(kSigTermination)); if (signal(SIGINT, sig_handler) == SIG_ERR) printf("\ncan't catch SIGINT\n"); run(NULL); Printf("exiting..."); if (fFile) fFile->Close(); delete fFile; fFile=0; //destroy ZMQ sockets int linger=0; zmq_setsockopt(fZMQin, ZMQ_LINGER, &linger, sizeof(linger)); zmq_close(fZMQin); zmq_ctx_term(fZMQcontext); return mainReturnCode; } //______________________________________________________________________________ int DumpToFile(TObject* object) { Option_t* fileMode="RECREATE"; if (!fFile) fFile = new TFile(fFileName,fileMode); if (fVerbose) Printf("writing object %s to %s",object->GetName(), fFileName.Data()); int rc = object->Write(object->GetName(),TObject::kOverwrite); MySignalHandler::fgTerminationSignaled=true; return rc; } //______________________________________________________________________________ int UpdatePad(TObject* object) { if (!object) return -1; const char* name = object->GetName(); TObject* drawable = fDrawables.FindObject(name); int padIndex = fDrawables.IndexOf(drawable); if (fVerbose) Printf("in: %s", name); Bool_t selected = kTRUE; Bool_t unselected = kFALSE; if (fSelectionRegexp) selected = fSelectionRegexp->Match(name); if (fUnSelectionRegexp) unselected = fUnSelectionRegexp->Match(name); if (!selected || unselected) return 0; if (drawable) { //only redraw the one thing if (fVerbose) Printf(" redrawing %s in pad %i", name, padIndex); fCanvas->cd(padIndex+1); gPad->GetListOfPrimitives()->Remove(drawable); gPad->Clear(); fDrawables.RemoveAt(padIndex); delete drawable; fDrawables.AddAt(object, padIndex); object->Draw(fDrawOptions); gPad->Modified(kTRUE); } else { if (fVerbose) Printf(" new object %s", name); //add the new object to the collection, restructure the canvas //and redraw everything fDrawables.AddLast(object); //after we clear the canvas, the pads are gone, clear the pad cache as well fCanvas->Clear(); fCanvas->DivideSquare(fDrawables.GetLast()+1); //redraw all objects at their old places and the new one as last for (int i=0; i<fDrawables.GetLast()+1; i++) { TObject* obj = fDrawables[i]; fCanvas->cd(i+1); if (fScaleLogX) gPad->SetLogx(); if (fScaleLogY) gPad->SetLogy(); if (fScaleLogZ) gPad->SetLogz(); if (fVerbose) Printf(" drawing %s in pad %i", obj->GetName(), i); if (obj) obj->Draw(); } } gSystem->ProcessEvents(); fCanvas->Update(); return 0; } //______________________________________________________________________________ int ProcessOptionString(TString arguments) { //process passed options stringMap* options = AliOptionParser::TokenizeOptionString(arguments); int nOptions = 0; for (stringMap::iterator i=options->begin(); i!=options->end(); ++i) { //Printf(" %s : %s", i->first.data(), i->second.data()); const TString& option = i->first; const TString& value = i->second; if (option.EqualTo("PollInterval") || option.EqualTo("sleep")) { fPollInterval = round(value.Atof()*1e6); } else if (option.EqualTo("PollTimeout") || option.EqualTo("timeout")) { fPollTimeout = round(value.Atof()*1e3); } else if (option.EqualTo("ZMQconfigIN") || option.EqualTo("in") ) { fZMQconfigIN = value; } else if (option.EqualTo("Verbose")) { fVerbose=kTRUE; } else if (option.EqualTo("select")) { delete fSelectionRegexp; fSelectionRegexp=new TPRegexp(value); } else if (option.EqualTo("unselect")) { delete fUnSelectionRegexp; fUnSelectionRegexp=new TPRegexp(value); } else if (option.EqualTo("ResetOnRequest")) { fResetOnRequest = kTRUE; } else if (option.EqualTo("drawoptions")) { fDrawOptions = value; } else if (option.EqualTo("logx")) { fScaleLogX=kTRUE; } else if (option.EqualTo("logy")) { fScaleLogY=kTRUE; } else if (option.EqualTo("logy")) { fScaleLogY=kTRUE; } else if (option.EqualTo("file")) { fFileName = value; } else { nOptions=-1; break; } nOptions++; } delete options; //tidy up return nOptions; } <commit_msg>fix logz<commit_after>#include "zmq.h" #include <iostream> #include "AliHLTDataTypes.h" #include "AliHLTComponent.h" #include "AliHLTMessage.h" #include "TClass.h" #include "TCanvas.h" #include "TMap.h" #include "TPRegexp.h" #include "TObjString.h" #include "TDirectory.h" #include "TList.h" #include "AliZMQhelpers.h" #include "TMessage.h" #include "TSystem.h" #include "TApplication.h" #include "TH1.h" #include "TH1F.h" #include <time.h> #include <string> #include <map> #include "TFile.h" #include "TSystem.h" #include "signal.h" class MySignalHandler; //this is meant to become a class, hence the structure with global vars etc. //Also the code is rather flat - it is a bit of a playground to test ideas. //TODO structure this at some point, e.g. introduce a SIMPLE unified way of handling //zmq payloads, maybe a AliZMQmessage class which would by default be multipart and provide //easy access to payloads based on topic or so (a la HLT GetFirstInputObject() etc...) //methods int ProcessOptionString(TString arguments); int UpdatePad(TObject*); int DumpToFile(TObject* object); void* run(void* arg); //configuration vars Bool_t fVerbose = kFALSE; TString fZMQconfigIN = "PULL>tcp://localhost:60211"; int fZMQsocketModeIN=-1; TString fZMQsubscriptionIN = ""; TString fFilter = ""; TString fFileName=""; TFile* fFile=NULL; int fPollInterval = 0; int fPollTimeout = 1000; //1s //internal state void* fZMQcontext = NULL; //ze zmq context void* fZMQin = NULL; //the in socket - entry point for the data to be merged. TApplication* gApp; TCanvas* fCanvas; TObjArray fDrawables; TPRegexp* fSelectionRegexp = NULL; TPRegexp* fUnSelectionRegexp = NULL; TString fDrawOptions; Bool_t fScaleLogX = kFALSE; Bool_t fScaleLogY = kFALSE; Bool_t fScaleLogZ = kFALSE; Bool_t fResetOnRequest = kFALSE; ULong64_t iterations=0; const char* fUSAGE = "ZMQhstViewer: Draw() all ROOT drawables in a message\n" "options: \n" " -in : data in\n" " -sleep : how long to sleep in between requests for data in s (if applicable)\n" " -timeout : how long to wait for the server to reply (s)\n" " -Verbose : be verbose\n" " -select : only show selected histograms (by regexp)\n" " -unselect : as select, only inverted\n" " -drawoptions : what draw option to use\n" " -file : dump input to file and exit\n" " -log[xyz] : use log scale on [xyz] dimension\n" ; //_______________________________________________________________________________________ class MySignalHandler : public TSignalHandler { public: MySignalHandler(ESignals sig) : TSignalHandler(sig) {} Bool_t Notify() { Printf("signal received, exiting"); fgTerminationSignaled = true; return TSignalHandler::Notify(); } static bool TerminationSignaled() { return fgTerminationSignaled; } static bool fgTerminationSignaled; }; bool MySignalHandler::fgTerminationSignaled = false; void sig_handler(int signo) { if (signo == SIGINT) printf("received SIGINT\n"); MySignalHandler::fgTerminationSignaled=true; } //_______________________________________________________________________________________ void* run(void* arg) { //main loop while(!MySignalHandler::TerminationSignaled()) { errno=0; //send a request if we are using REQ if (fZMQsocketModeIN==ZMQ_REQ) { TString request; TString requestTopic; if (fSelectionRegexp || fUnSelectionRegexp) { requestTopic = "CONFIG"; if (fSelectionRegexp) request += " select="+fSelectionRegexp->GetPattern(); if (fUnSelectionRegexp) request += " unselect="+fUnSelectionRegexp->GetPattern(); if (fResetOnRequest) request += " ResetOnRequest"; zmq_send(fZMQin, requestTopic.Data(), requestTopic.Length(), ZMQ_SNDMORE); zmq_send(fZMQin, request.Data(), request.Length(), ZMQ_SNDMORE); } if (fVerbose) Printf("sending request %s %s",requestTopic.Data(), request.Data()); zmq_send(fZMQin, "", 0, ZMQ_SNDMORE); zmq_send(fZMQin, "", 0, 0); } //wait for the data zmq_pollitem_t sockets[] = { { fZMQin, 0, ZMQ_POLLIN, 0 }, }; int rc = zmq_poll(sockets, 1, (fZMQsocketModeIN==ZMQ_REQ)?fPollTimeout:-1); if (rc==-1 && errno==ETERM) { Printf("jumping out of main loop"); break; } if (!(sockets[0].revents & ZMQ_POLLIN)) { //server died Printf("connection timed out, server %s died?", fZMQconfigIN.Data()); fZMQsocketModeIN = alizmq_socket_init(fZMQin, fZMQcontext, fZMQconfigIN.Data()); if (fZMQsocketModeIN < 0) return NULL; continue; } else { //get all data (topic+body), possibly many of them aliZMQmsg message; alizmq_msg_recv(&message, fZMQin, 0); for (aliZMQmsg::iterator i=message.begin(); i!=message.end(); ++i) { TObject* object; alizmq_msg_iter_data(i, object); if (object) UpdatePad(object); if (!fFileName.IsNull()) { DumpToFile(object); } } alizmq_msg_close(&message); }//socket 0 gSystem->ProcessEvents(); usleep(fPollInterval); }//main loop return NULL; } //_______________________________________________________________________________________ int main(int argc, char** argv) { //process args int noptions = ProcessOptionString(AliOptionParser::GetFullArgString(argc,argv)); if (noptions<=0) { printf("%s",fUSAGE); return 1; } TH1::AddDirectory(kFALSE); TDirectory::AddDirectory(kFALSE); gApp = new TApplication("viewer", &argc, argv); gApp->SetReturnFromRun(true); //gApp->Run(); fCanvas = new TCanvas(); gSystem->ProcessEvents(); int mainReturnCode=0; //init stuff //globally enable schema evolution for serializing ROOT objects TMessage::EnableSchemaEvolutionForAll(kTRUE); //ZMQ init fZMQcontext = zmq_ctx_new(); fZMQsocketModeIN = alizmq_socket_init(fZMQin, fZMQcontext, fZMQconfigIN.Data(), -1, 2); if (fZMQsocketModeIN < 0) return 1; gSystem->ResetSignal(kSigPipe); gSystem->ResetSignal(kSigQuit); gSystem->ResetSignal(kSigInterrupt); gSystem->ResetSignal(kSigTermination); //gSystem->AddSignalHandler(new MySignalHandler(kSigPipe)); //gSystem->AddSignalHandler(new MySignalHandler(kSigQuit)); //gSystem->AddSignalHandler(new MySignalHandler(kSigInterrupt)); //gSystem->AddSignalHandler(new MySignalHandler(kSigTermination)); if (signal(SIGINT, sig_handler) == SIG_ERR) printf("\ncan't catch SIGINT\n"); run(NULL); Printf("exiting..."); if (fFile) fFile->Close(); delete fFile; fFile=0; //destroy ZMQ sockets int linger=0; zmq_setsockopt(fZMQin, ZMQ_LINGER, &linger, sizeof(linger)); zmq_close(fZMQin); zmq_ctx_term(fZMQcontext); return mainReturnCode; } //______________________________________________________________________________ int DumpToFile(TObject* object) { Option_t* fileMode="RECREATE"; if (!fFile) fFile = new TFile(fFileName,fileMode); if (fVerbose) Printf("writing object %s to %s",object->GetName(), fFileName.Data()); int rc = object->Write(object->GetName(),TObject::kOverwrite); MySignalHandler::fgTerminationSignaled=true; return rc; } //______________________________________________________________________________ int UpdatePad(TObject* object) { if (!object) return -1; const char* name = object->GetName(); TObject* drawable = fDrawables.FindObject(name); int padIndex = fDrawables.IndexOf(drawable); if (fVerbose) Printf("in: %s", name); Bool_t selected = kTRUE; Bool_t unselected = kFALSE; if (fSelectionRegexp) selected = fSelectionRegexp->Match(name); if (fUnSelectionRegexp) unselected = fUnSelectionRegexp->Match(name); if (!selected || unselected) return 0; if (drawable) { //only redraw the one thing if (fVerbose) Printf(" redrawing %s in pad %i", name, padIndex); fCanvas->cd(padIndex+1); gPad->GetListOfPrimitives()->Remove(drawable); gPad->Clear(); fDrawables.RemoveAt(padIndex); delete drawable; fDrawables.AddAt(object, padIndex); object->Draw(fDrawOptions); gPad->Modified(kTRUE); } else { if (fVerbose) Printf(" new object %s", name); //add the new object to the collection, restructure the canvas //and redraw everything fDrawables.AddLast(object); //after we clear the canvas, the pads are gone, clear the pad cache as well fCanvas->Clear(); fCanvas->DivideSquare(fDrawables.GetLast()+1); //redraw all objects at their old places and the new one as last for (int i=0; i<fDrawables.GetLast()+1; i++) { TObject* obj = fDrawables[i]; fCanvas->cd(i+1); if (fScaleLogX) gPad->SetLogx(); if (fScaleLogY) gPad->SetLogy(); if (fScaleLogZ) gPad->SetLogz(); if (fVerbose) Printf(" drawing %s in pad %i", obj->GetName(), i); if (obj) obj->Draw(); } } gSystem->ProcessEvents(); fCanvas->Update(); return 0; } //______________________________________________________________________________ int ProcessOptionString(TString arguments) { //process passed options stringMap* options = AliOptionParser::TokenizeOptionString(arguments); int nOptions = 0; for (stringMap::iterator i=options->begin(); i!=options->end(); ++i) { //Printf(" %s : %s", i->first.data(), i->second.data()); const TString& option = i->first; const TString& value = i->second; if (option.EqualTo("PollInterval") || option.EqualTo("sleep")) { fPollInterval = round(value.Atof()*1e6); } else if (option.EqualTo("PollTimeout") || option.EqualTo("timeout")) { fPollTimeout = round(value.Atof()*1e3); } else if (option.EqualTo("ZMQconfigIN") || option.EqualTo("in") ) { fZMQconfigIN = value; } else if (option.EqualTo("Verbose")) { fVerbose=kTRUE; } else if (option.EqualTo("select")) { delete fSelectionRegexp; fSelectionRegexp=new TPRegexp(value); } else if (option.EqualTo("unselect")) { delete fUnSelectionRegexp; fUnSelectionRegexp=new TPRegexp(value); } else if (option.EqualTo("ResetOnRequest")) { fResetOnRequest = kTRUE; } else if (option.EqualTo("drawoptions")) { fDrawOptions = value; } else if (option.EqualTo("logx")) { fScaleLogX=kTRUE; } else if (option.EqualTo("logy")) { fScaleLogY=kTRUE; } else if (option.EqualTo("logz")) { fScaleLogZ=kTRUE; } else if (option.EqualTo("file")) { fFileName = value; } else { nOptions=-1; break; } nOptions++; } delete options; //tidy up return nOptions; } <|endoftext|>
<commit_before>/** * Zillians MMO * Copyright (C) 2007-2010 Zillians.com, Inc. * For more information see http://www.zillians.com * * Zillians MMO is the library and runtime for massive multiplayer online game * development in utility computing model, which runs as a service for every * developer to build their virtual world running on our GPU-assisted machines. * * This is a close source library intended to be used solely within Zillians.com * * 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 * COPYRIGHT HOLDER(S) 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. */ /** * @date Sep 1, 2009 sdk - Initial version created. */ #include "core/Prerequisite.h" #include "compiler/tree/ASTNode.h" #include "compiler/tree/ASTNodeFactory.h" #include "compiler/tree/visitor/general/GarbageCollectionVisitor.h" #include <iostream> #include <string> #include <limits> #define BOOST_TEST_MODULE ThorScriptTreeTest_BasicTreeGenerationTest #define BOOST_TEST_MAIN #include <boost/test/unit_test.hpp> using namespace zillians; using namespace zillians::compiler::tree; using namespace zillians::compiler::tree::visitor; BOOST_AUTO_TEST_SUITE( ThorScriptTreeTest_BasicTreeGenerationTestSuite ) BOOST_AUTO_TEST_CASE( ThorScriptTreeTest_BasicTreeGenerationTestCase1_IsA ) { { ASTNode *node = new Program(new Package(new SimpleIdentifier(L""))); BOOST_CHECK(isa<Program>(node)); BOOST_CHECK(!isa<Literal>(node)); } { ASTNode *node = new BinaryExpr(BinaryExpr::OpCode::ASSIGN, new SimpleIdentifier(L"abc"), new NumericLiteral(123L)); BOOST_CHECK(isa<Expression>(node)); BOOST_CHECK(isa<BinaryExpr>(node)); } { NestedIdentifier* node = new NestedIdentifier(); BOOST_CHECK(isa<Identifier>(node)); } } BOOST_AUTO_TEST_CASE( ThorScriptTreeTest_BasicTreeGenerationTestCase2 ) { { Program* program = new Program(new Package(new SimpleIdentifier(L""))); BOOST_CHECK(program->root->id->toString().empty()); } { Program* program = new Program(); BOOST_CHECK(program->root->id->toString().empty()); // the default package name is empty "" } } BOOST_AUTO_TEST_CASE( ThorScriptTreeTest_BasicTreeGenerationTestCase3 ) { } BOOST_AUTO_TEST_SUITE_END() <commit_msg>new ASTNode: FunctionType and TypeSpecifier<commit_after>/** * Zillians MMO * Copyright (C) 2007-2010 Zillians.com, Inc. * For more information see http://www.zillians.com * * Zillians MMO is the library and runtime for massive multiplayer online game * development in utility computing model, which runs as a service for every * developer to build their virtual world running on our GPU-assisted machines. * * This is a close source library intended to be used solely within Zillians.com * * 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 * COPYRIGHT HOLDER(S) 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. */ /** * @date Sep 1, 2009 sdk - Initial version created. */ #include "core/Prerequisite.h" #include "compiler/tree/ASTNode.h" #include "compiler/tree/ASTNodeFactory.h" #include "compiler/tree/visitor/general/GarbageCollectionVisitor.h" #include <iostream> #include <string> #include <limits> #define BOOST_TEST_MODULE ThorScriptTreeTest_BasicTreeGenerationTest #define BOOST_TEST_MAIN #include <boost/test/unit_test.hpp> using namespace zillians; using namespace zillians::compiler::tree; using namespace zillians::compiler::tree::visitor; BOOST_AUTO_TEST_SUITE( ThorScriptTreeTest_BasicTreeGenerationTestSuite ) BOOST_AUTO_TEST_CASE( ThorScriptTreeTest_BasicTreeGenerationTestCase1_IsA ) { { ASTNode *node = new Program(new Package(new SimpleIdentifier(L""))); BOOST_CHECK(isa<Program>(node)); BOOST_CHECK(!isa<Literal>(node)); } { ASTNode *node = new BinaryExpr(BinaryExpr::OpCode::ASSIGN, new SimpleIdentifier(L"abc"), new NumericLiteral((uint64)123L)); BOOST_CHECK(isa<Expression>(node)); BOOST_CHECK(isa<BinaryExpr>(node)); } { NestedIdentifier* node = new NestedIdentifier(); BOOST_CHECK(isa<Identifier>(node)); } } BOOST_AUTO_TEST_CASE( ThorScriptTreeTest_BasicTreeGenerationTestCase2 ) { { Program* program = new Program(new Package(new SimpleIdentifier(L""))); BOOST_CHECK(program->root->id->toString().empty()); } { Program* program = new Program(); BOOST_CHECK(program->root->id->toString().empty()); // the default package name is empty "" } } BOOST_AUTO_TEST_CASE( ThorScriptTreeTest_BasicTreeGenerationTestCase3 ) { } BOOST_AUTO_TEST_SUITE_END() <|endoftext|>
<commit_before>/*----------------------------------------------------------------------------- This source file is part of Hopsan NG Copyright (c) 2011 Mikael Axin, Robert Braun, Alessandro Dell'Amico, Björn Eriksson, Peter Nordin, Karl Pettersson, Petter Krus, Ingo Staack This file is provided "as is", with no guarantee or warranty for the functionality or reliability of the contents. All contents in this file is the original work of the copyright holders at the Division of Fluid and Mechatronic Systems (Flumes) at Linköping University. Modifying, using or redistributing any part of this file is prohibited without explicit permission from the copyright holders. -----------------------------------------------------------------------------*/ //! //! @file HVCWidget.cpp //! @author Peter Nordin <peter.nordin@liu.se> //! @date 2012 //! //! @brief Contains class for Hopsan validation widget //! //$Id$ //Qt includes #include <QCheckBox> #include <QLabel> #include <QFileDialog> #include <QToolButton> #include <QHBoxLayout> #include <QGridLayout> #include <QPushButton> //Hopsan includes #include "common.h" #include "global.h" #include "GUIObjects/GUISystem.h" #include "HVCWidget.h" #include "LogDataHandler.h" #include "ModelHandler.h" #include "PlotHandler.h" #include "Utilities/XMLUtilities.h" #include "Widgets/ModelWidget.h" #include "MessageHandler.h" HVCWidget::HVCWidget(QWidget *parent) : QDialog(parent) { mpHvcOpenPathEdit = new QLineEdit(); QPushButton *pBrowseButton = new QPushButton(); pBrowseButton->setIcon(QIcon(QString(ICONPATH)+"Hopsan-Open.png")); QHBoxLayout *pOpenFileHLayout = new QHBoxLayout(); pOpenFileHLayout->addWidget(new QLabel("HVC: ")); pOpenFileHLayout->addWidget(mpHvcOpenPathEdit); pOpenFileHLayout->addWidget(pBrowseButton); QCheckBox *pFoundModelCheckBox = new QCheckBox(); QCheckBox *pFoundDataCheckBox = new QCheckBox(); QHBoxLayout *pOpenStatusHLayout = new QHBoxLayout(); pOpenStatusHLayout->addWidget(new QLabel("Found model: ")); pOpenStatusHLayout->addWidget(pFoundModelCheckBox); pOpenStatusHLayout->addWidget(new QLabel("Found data: ")); pOpenStatusHLayout->addWidget(pFoundDataCheckBox); mpAllVariablesTree = new FullNameVariableTreeWidget(); mpSelectedVariablesTree = new FullNameVariableTreeWidget(); QHBoxLayout *pVariablesHLayout = new QHBoxLayout(); pVariablesHLayout->addWidget(mpAllVariablesTree); pVariablesHLayout->addSpacing(10); pVariablesHLayout->addWidget(mpSelectedVariablesTree); QHBoxLayout *pButtonLayout = new QHBoxLayout(); QPushButton *pSaveButton = new QPushButton("Save hvc"); pSaveButton->setDisabled(true); QPushButton *pCloseButton = new QPushButton("Close"); QPushButton *pCompareButton = new QPushButton("Compare"); pButtonLayout->addWidget(pCompareButton); pButtonLayout->addWidget(pSaveButton); pButtonLayout->addWidget(pCloseButton); QVBoxLayout *pMainLayout = new QVBoxLayout(); pMainLayout->addWidget(new QLabel("Not yet finished, but you can use the compare function")); pMainLayout->addWidget(new QLabel("You can generate new HVC files from the plotwindow")); pMainLayout->addLayout(pOpenFileHLayout); pMainLayout->addLayout(pOpenStatusHLayout); pMainLayout->addLayout(pVariablesHLayout); pMainLayout->addLayout(pButtonLayout); this->setLayout(pMainLayout); connect(pCloseButton, SIGNAL(clicked()), this, SLOT(close())); connect(pBrowseButton, SIGNAL(clicked()), this, SLOT(openHvcFile())); connect(pCompareButton, SIGNAL(clicked()), this, SLOT(runHvcTest())); this->resize(800, 600); this->setWindowTitle("Hopsan Model Validation"); } void HVCWidget::openHvcFile() { QFile hvcFile; hvcFile.setFileName(QFileDialog::getOpenFileName(this, "Select a HVC file")); if (hvcFile.exists()) { // Clear clearContents(); QFileInfo hvcFileInfo = QFileInfo(hvcFile); QDomDocument xmlDocument; QDomElement rootElement = loadXMLDomDocument(hvcFile, xmlDocument, "hopsanvalidationconfiguration"); if (rootElement.isNull()) { //! @todo some error message return; } QFile hmfFile, dataFile; if (rootElement.attribute("hvcversion") == "0.1") { // Load old format QDomElement xmlValidation = rootElement.firstChildElement("validation"); QString modelFilePath = xmlValidation.firstChildElement("modelfile").text(); if (modelFilePath.isEmpty()) { // Use same name as hvc file instead modelFilePath = hvcFileInfo.absolutePath()+"/"+hvcFileInfo.baseName()+".hmf"; } else { // Make sure absoulte, the loaded modelpath should be relative to the hvc file modelFilePath = hvcFileInfo.absolutePath()+"/"+modelFilePath; } hmfFile.setFileName(modelFilePath); if (hmfFile.exists()) { mModelFilePath = modelFilePath; QDomElement xmlComponent = xmlValidation.firstChildElement("component"); while (!xmlComponent.isNull()) { QDomElement xmlPort = xmlComponent.firstChildElement("port"); while (!xmlPort.isNull()) { QString dataFilePath = xmlComponent.firstChildElement("csvfile").text(); if (dataFilePath.isEmpty()) { // Use same name as hvc file instead dataFilePath = hvcFileInfo.absolutePath()+"/"+hvcFileInfo.baseName()+".csv"; } dataFile.setFileName(dataFilePath); QDomElement xmlVariable = xmlPort.firstChildElement("variable"); while (!xmlVariable.isNull()) { // check if we should override data file if (!xmlComponent.firstChildElement("csvfile").isNull()) { QString dataFilePath = xmlComponent.firstChildElement("csvfile").text(); if (dataFilePath.isEmpty()) { // Use same name as hvc file instead dataFilePath = hvcFileInfo.absolutePath()+"/"+hvcFileInfo.baseName()+".csv"; } dataFile.setFileName(dataFilePath); } HvcConfig conf; conf.mDataColumn = parseDomIntegerNode(xmlVariable.firstChildElement("column"), 0); conf.mTolerance = parseDomValueNode(xmlVariable.firstChildElement("tolerance"), conf.mTolerance); conf.mFullVarName = xmlComponent.attribute("name")+"#"+xmlPort.attribute("name")+"#"+xmlVariable.attribute("name"); conf.mDataFile = dataFile.fileName(); mDataConfigs.append(conf); // Populate the tree mpAllVariablesTree->addFullNameVariable(conf.mFullVarName); mpSelectedVariablesTree->addFullNameVariable(conf.mFullVarName); // Next variable to check xmlVariable = xmlVariable.nextSiblingElement("variable"); } xmlPort = xmlPort.nextSiblingElement("port"); } xmlComponent = xmlComponent.nextSiblingElement("component"); } } else { //! @todo some error } } else if (rootElement.attribute("hvcversion") == "0.2") { // Get model to load QDomElement xmlValidation = rootElement.firstChildElement("validation"); QString modelFilePath = xmlValidation.firstChildElement("modelfile").text(); if (modelFilePath.isEmpty()) { // Use same name as hvc file instead modelFilePath = hvcFileInfo.absolutePath()+"/"+hvcFileInfo.baseName()+".hmf"; } else { // Make sure absoulte, the loaded modelpath should be relative to the hvc file modelFilePath = hvcFileInfo.absolutePath()+"/"+modelFilePath; } hmfFile.setFileName(modelFilePath); if (hmfFile.exists()) { mModelFilePath = modelFilePath; QString dataFilePath = xmlValidation.firstChildElement("hvdfile").text(); if (dataFilePath.isEmpty()) { // Use same name as hvc file instead dataFilePath = hvcFileInfo.absolutePath()+"/"+hvcFileInfo.baseName()+".hvd"; } else { // Make sure absoulte, the loaded datafilepath should be relative to the hvc file dataFilePath = hvcFileInfo.absolutePath()+"/"+dataFilePath; } dataFile.setFileName(dataFilePath); QDomElement xmlVariable = xmlValidation.firstChildElement("variable"); while (!xmlVariable.isNull()) { HvcConfig conf; conf.mDataColumn = parseDomIntegerNode(xmlVariable.firstChildElement("column"), 0); conf.mTimeColumn = parseDomIntegerNode(xmlVariable.firstChildElement("timecolumn"), 0); conf.mTolerance = parseDomValueNode(xmlVariable.firstChildElement("tolerance"), conf.mTolerance); conf.mFullVarName = xmlVariable.attribute("name"); conf.mDataFile = dataFile.fileName(); mDataConfigs.append(conf); // Populate the tree mpAllVariablesTree->addFullNameVariable(conf.mFullVarName); mpSelectedVariablesTree->addFullNameVariable(conf.mFullVarName); // Next variable to check xmlVariable = xmlVariable.nextSiblingElement("variable"); } } else { //! @todo some error } } else { // Unsupported format } // Show file in line edit mpHvcOpenPathEdit->setText(hvcFile.fileName()); // Find model and any data files, update status // Populate tree } } void HVCWidget::clearContents() { mpHvcOpenPathEdit->clear(); mpAllVariablesTree->clear(); mpSelectedVariablesTree->clear(); mModelFilePath.clear(); mDataConfigs.clear(); } void HVCWidget::runHvcTest() { // First load the model gpModelHandler->loadModel(mModelFilePath, true); // Switch to that tab // Simulate the system if (gpModelHandler->getCurrentModel()) { gpModelHandler->getCurrentModel()->simulate_blocking(); } // Run each test gpPlotHandler->closeAllOpenWindows(); //Close all plot windows to avoid confusion if we run several tests after each other for (int t=0; t<mDataConfigs.size(); ++t) { LogDataHandler *pImportLogDataHandler = gpModelHandler->getCurrentTopLevelSystem()->getLogDataHandler(); LogDataHandler *pVariableLogDataHandler = pImportLogDataHandler; QString variableName = mDataConfigs[t].mFullVarName; // Handle subsystem variables if (variableName.contains('$')) { QStringList fields = variableName.split('$'); fields.erase(fields.begin()); // Remove the first "top-level system" name ContainerObject *pContainer=gpModelHandler->getCurrentTopLevelSystem(); while (!fields.front().contains('#')) { ModelObject *pObj = pContainer->getModelObject(fields.front()); if (pObj && (pObj->type() == SystemContainerType)) { pContainer = qobject_cast<ContainerObject*>(pObj); } else { gpMessageHandler->addErrorMessage(QString("Could not find system: %1").arg(fields.front())); return; } fields.erase(fields.begin()); } pVariableLogDataHandler = pContainer->getLogDataHandler(); variableName = fields.front(); } QVector<int> columns, timecolumns; QStringList names; columns.append(mDataConfigs[t].mDataColumn); timecolumns.append(mDataConfigs[t].mTimeColumn); names.append(mDataConfigs[t].mFullVarName+"_valid"); pImportLogDataHandler->importTimeVariablesFromCSVColumns(mDataConfigs[t].mDataFile, columns, names, timecolumns); QString windowName = QString("Validation Plot %1").arg(t); gpPlotHandler->createNewOrReplacePlotwindow(windowName); gpPlotHandler->plotDataToWindow(windowName, pVariableLogDataHandler->getVectorVariable(variableName,-1), 0); gpPlotHandler->plotDataToWindow(windowName, pImportLogDataHandler->getVectorVariable(mDataConfigs[t].mFullVarName+"_valid",-1), 0); } } void FullNameVariableTreeWidget::addFullNameVariable(const QString &rFullName, const QString &rRemaningName, QTreeWidgetItem *pParentItem) { if (!rFullName.isEmpty()) { bool isLeaf=false; QStringList systems = rRemaningName.split("$"); QString name; // If we have a system part if (systems.size() > 1) { name = systems.first(); } // Else we have a comp::port::var else { QStringList compportvar = rRemaningName.split("#"); if (compportvar.size()==1) { isLeaf = true; } name = compportvar.first(); } QTreeWidgetItem* pLevelItem=0; // Add a new level in the tree if (pParentItem) { QTreeWidgetItem* pFound=0; for (int c=0; c<pParentItem->childCount(); ++c) { if (pParentItem->child(c)->text(0) == name) { // We assume there will never be duplicates due to uniqe name requirements pFound = pParentItem->child(c); break; } } if (pFound) { pLevelItem = pFound; } else { // Add new item pLevelItem = new QTreeWidgetItem(QStringList(name)); pParentItem->addChild(pLevelItem); } } else { QList<QTreeWidgetItem*> found = this->findItems(name, 0); if (found.isEmpty()) { // Add new top level item pLevelItem = new QTreeWidgetItem(QStringList(name)); addTopLevelItem(pLevelItem); } else { // We assume there will never be duplicates due to uniqe name requirements pLevelItem = found.first(); } } if (isLeaf) { pLevelItem->setData(0,Qt::UserRole,rFullName); } else { // Recurse QString shorterRemaningName = rRemaningName; shorterRemaningName.remove(0, name.size()+1); addFullNameVariable(rFullName, shorterRemaningName, pLevelItem); } } } FullNameVariableTreeWidget::FullNameVariableTreeWidget(QWidget *pParent) : QTreeWidget(pParent) { //Nothing } void FullNameVariableTreeWidget::addFullNameVariable(const QString &rFullName) { addFullNameVariable(rFullName, rFullName, 0); } //void FullNameVariableTreeWidget::mousePressEvent(QMouseEvent *event) //{ // QTreeWidget::mousePressEvent(event); // //! @todo dragstartposition // QTreeWidgetItem *pItem = this->itemAt(event->pos()); // if (pItem && (pItem->childCount() == 0)) // { // QDrag *pDrag = new QDrag(this); // QMimeData *pMime = new QMimeData; // pMime->setText(pItem->data(0, Qt::UserRole).toString()); // pDrag->setMimeData(pMime); // Qt::DropAction dropAction = pDrag->exec(Qt::CopyAction | Qt::MoveAction); // } //} //void FullNameVariableTreeWidget::dropEvent(QDropEvent *event) //{ // if (!event->mimeData()->text().isEmpty()) // { // addFullNameVariable(event->mimeData()->text()); // event->acceptProposedAction(); // } //} //void FullNameVariableTreeWidget::dragEnterEvent(QDragEnterEvent *event) //{ // if (!event->mimeData()->text().isEmpty()) // { // event->acceptProposedAction(); // } //} <commit_msg>Fixed uninitialized variable<commit_after>/*----------------------------------------------------------------------------- This source file is part of Hopsan NG Copyright (c) 2011 Mikael Axin, Robert Braun, Alessandro Dell'Amico, Björn Eriksson, Peter Nordin, Karl Pettersson, Petter Krus, Ingo Staack This file is provided "as is", with no guarantee or warranty for the functionality or reliability of the contents. All contents in this file is the original work of the copyright holders at the Division of Fluid and Mechatronic Systems (Flumes) at Linköping University. Modifying, using or redistributing any part of this file is prohibited without explicit permission from the copyright holders. -----------------------------------------------------------------------------*/ //! //! @file HVCWidget.cpp //! @author Peter Nordin <peter.nordin@liu.se> //! @date 2012 //! //! @brief Contains class for Hopsan validation widget //! //$Id$ //Qt includes #include <QCheckBox> #include <QLabel> #include <QFileDialog> #include <QToolButton> #include <QHBoxLayout> #include <QGridLayout> #include <QPushButton> //Hopsan includes #include "common.h" #include "global.h" #include "GUIObjects/GUISystem.h" #include "HVCWidget.h" #include "LogDataHandler.h" #include "ModelHandler.h" #include "PlotHandler.h" #include "Utilities/XMLUtilities.h" #include "Widgets/ModelWidget.h" #include "MessageHandler.h" HVCWidget::HVCWidget(QWidget *parent) : QDialog(parent) { mpHvcOpenPathEdit = new QLineEdit(); QPushButton *pBrowseButton = new QPushButton(); pBrowseButton->setIcon(QIcon(QString(ICONPATH)+"Hopsan-Open.png")); QHBoxLayout *pOpenFileHLayout = new QHBoxLayout(); pOpenFileHLayout->addWidget(new QLabel("HVC: ")); pOpenFileHLayout->addWidget(mpHvcOpenPathEdit); pOpenFileHLayout->addWidget(pBrowseButton); QCheckBox *pFoundModelCheckBox = new QCheckBox(); QCheckBox *pFoundDataCheckBox = new QCheckBox(); QHBoxLayout *pOpenStatusHLayout = new QHBoxLayout(); pOpenStatusHLayout->addWidget(new QLabel("Found model: ")); pOpenStatusHLayout->addWidget(pFoundModelCheckBox); pOpenStatusHLayout->addWidget(new QLabel("Found data: ")); pOpenStatusHLayout->addWidget(pFoundDataCheckBox); mpAllVariablesTree = new FullNameVariableTreeWidget(); mpSelectedVariablesTree = new FullNameVariableTreeWidget(); QHBoxLayout *pVariablesHLayout = new QHBoxLayout(); pVariablesHLayout->addWidget(mpAllVariablesTree); pVariablesHLayout->addSpacing(10); pVariablesHLayout->addWidget(mpSelectedVariablesTree); QHBoxLayout *pButtonLayout = new QHBoxLayout(); QPushButton *pSaveButton = new QPushButton("Save hvc"); pSaveButton->setDisabled(true); QPushButton *pCloseButton = new QPushButton("Close"); QPushButton *pCompareButton = new QPushButton("Compare"); pButtonLayout->addWidget(pCompareButton); pButtonLayout->addWidget(pSaveButton); pButtonLayout->addWidget(pCloseButton); QVBoxLayout *pMainLayout = new QVBoxLayout(); pMainLayout->addWidget(new QLabel("Not yet finished, but you can use the compare function")); pMainLayout->addWidget(new QLabel("You can generate new HVC files from the plotwindow")); pMainLayout->addLayout(pOpenFileHLayout); pMainLayout->addLayout(pOpenStatusHLayout); pMainLayout->addLayout(pVariablesHLayout); pMainLayout->addLayout(pButtonLayout); this->setLayout(pMainLayout); connect(pCloseButton, SIGNAL(clicked()), this, SLOT(close())); connect(pBrowseButton, SIGNAL(clicked()), this, SLOT(openHvcFile())); connect(pCompareButton, SIGNAL(clicked()), this, SLOT(runHvcTest())); this->resize(800, 600); this->setWindowTitle("Hopsan Model Validation"); } void HVCWidget::openHvcFile() { QFile hvcFile; hvcFile.setFileName(QFileDialog::getOpenFileName(this, "Select a HVC file")); if (hvcFile.exists()) { // Clear clearContents(); QFileInfo hvcFileInfo = QFileInfo(hvcFile); QDomDocument xmlDocument; QDomElement rootElement = loadXMLDomDocument(hvcFile, xmlDocument, "hopsanvalidationconfiguration"); if (rootElement.isNull()) { //! @todo some error message return; } QFile hmfFile, dataFile; if (rootElement.attribute("hvcversion") == "0.1") { // Load old format QDomElement xmlValidation = rootElement.firstChildElement("validation"); QString modelFilePath = xmlValidation.firstChildElement("modelfile").text(); if (modelFilePath.isEmpty()) { // Use same name as hvc file instead modelFilePath = hvcFileInfo.absolutePath()+"/"+hvcFileInfo.baseName()+".hmf"; } else { // Make sure absoulte, the loaded modelpath should be relative to the hvc file modelFilePath = hvcFileInfo.absolutePath()+"/"+modelFilePath; } hmfFile.setFileName(modelFilePath); if (hmfFile.exists()) { mModelFilePath = modelFilePath; QDomElement xmlComponent = xmlValidation.firstChildElement("component"); while (!xmlComponent.isNull()) { QDomElement xmlPort = xmlComponent.firstChildElement("port"); while (!xmlPort.isNull()) { QString dataFilePath = xmlComponent.firstChildElement("csvfile").text(); if (dataFilePath.isEmpty()) { // Use same name as hvc file instead dataFilePath = hvcFileInfo.absolutePath()+"/"+hvcFileInfo.baseName()+".csv"; } dataFile.setFileName(dataFilePath); QDomElement xmlVariable = xmlPort.firstChildElement("variable"); while (!xmlVariable.isNull()) { // check if we should override data file if (!xmlComponent.firstChildElement("csvfile").isNull()) { QString dataFilePath = xmlComponent.firstChildElement("csvfile").text(); if (dataFilePath.isEmpty()) { // Use same name as hvc file instead dataFilePath = hvcFileInfo.absolutePath()+"/"+hvcFileInfo.baseName()+".csv"; } dataFile.setFileName(dataFilePath); } HvcConfig conf; conf.mDataColumn = parseDomIntegerNode(xmlVariable.firstChildElement("column"), 0); conf.mTimeColumn = 0; conf.mTolerance = parseDomValueNode(xmlVariable.firstChildElement("tolerance"), conf.mTolerance); conf.mFullVarName = xmlComponent.attribute("name")+"#"+xmlPort.attribute("name")+"#"+xmlVariable.attribute("name"); conf.mDataFile = dataFile.fileName(); mDataConfigs.append(conf); // Populate the tree mpAllVariablesTree->addFullNameVariable(conf.mFullVarName); mpSelectedVariablesTree->addFullNameVariable(conf.mFullVarName); // Next variable to check xmlVariable = xmlVariable.nextSiblingElement("variable"); } xmlPort = xmlPort.nextSiblingElement("port"); } xmlComponent = xmlComponent.nextSiblingElement("component"); } } else { //! @todo some error } } else if (rootElement.attribute("hvcversion") == "0.2") { // Get model to load QDomElement xmlValidation = rootElement.firstChildElement("validation"); QString modelFilePath = xmlValidation.firstChildElement("modelfile").text(); if (modelFilePath.isEmpty()) { // Use same name as hvc file instead modelFilePath = hvcFileInfo.absolutePath()+"/"+hvcFileInfo.baseName()+".hmf"; } else { // Make sure absoulte, the loaded modelpath should be relative to the hvc file modelFilePath = hvcFileInfo.absolutePath()+"/"+modelFilePath; } hmfFile.setFileName(modelFilePath); if (hmfFile.exists()) { mModelFilePath = modelFilePath; QString dataFilePath = xmlValidation.firstChildElement("hvdfile").text(); if (dataFilePath.isEmpty()) { // Use same name as hvc file instead dataFilePath = hvcFileInfo.absolutePath()+"/"+hvcFileInfo.baseName()+".hvd"; } else { // Make sure absoulte, the loaded datafilepath should be relative to the hvc file dataFilePath = hvcFileInfo.absolutePath()+"/"+dataFilePath; } dataFile.setFileName(dataFilePath); QDomElement xmlVariable = xmlValidation.firstChildElement("variable"); while (!xmlVariable.isNull()) { HvcConfig conf; conf.mDataColumn = parseDomIntegerNode(xmlVariable.firstChildElement("column"), 0); conf.mTimeColumn = parseDomIntegerNode(xmlVariable.firstChildElement("timecolumn"), 0); conf.mTolerance = parseDomValueNode(xmlVariable.firstChildElement("tolerance"), conf.mTolerance); conf.mFullVarName = xmlVariable.attribute("name"); conf.mDataFile = dataFile.fileName(); mDataConfigs.append(conf); // Populate the tree mpAllVariablesTree->addFullNameVariable(conf.mFullVarName); mpSelectedVariablesTree->addFullNameVariable(conf.mFullVarName); // Next variable to check xmlVariable = xmlVariable.nextSiblingElement("variable"); } } else { //! @todo some error } } else { // Unsupported format } // Show file in line edit mpHvcOpenPathEdit->setText(hvcFile.fileName()); // Find model and any data files, update status // Populate tree } } void HVCWidget::clearContents() { mpHvcOpenPathEdit->clear(); mpAllVariablesTree->clear(); mpSelectedVariablesTree->clear(); mModelFilePath.clear(); mDataConfigs.clear(); } void HVCWidget::runHvcTest() { // First load the model gpModelHandler->loadModel(mModelFilePath, true); // Switch to that tab // Simulate the system if (gpModelHandler->getCurrentModel()) { gpModelHandler->getCurrentModel()->simulate_blocking(); } // Run each test gpPlotHandler->closeAllOpenWindows(); //Close all plot windows to avoid confusion if we run several tests after each other for (int t=0; t<mDataConfigs.size(); ++t) { LogDataHandler *pImportLogDataHandler = gpModelHandler->getCurrentTopLevelSystem()->getLogDataHandler(); LogDataHandler *pVariableLogDataHandler = pImportLogDataHandler; QString variableName = mDataConfigs[t].mFullVarName; // Handle subsystem variables if (variableName.contains('$')) { QStringList fields = variableName.split('$'); fields.erase(fields.begin()); // Remove the first "top-level system" name ContainerObject *pContainer=gpModelHandler->getCurrentTopLevelSystem(); while (!fields.front().contains('#')) { ModelObject *pObj = pContainer->getModelObject(fields.front()); if (pObj && (pObj->type() == SystemContainerType)) { pContainer = qobject_cast<ContainerObject*>(pObj); } else { gpMessageHandler->addErrorMessage(QString("Could not find system: %1").arg(fields.front())); return; } fields.erase(fields.begin()); } pVariableLogDataHandler = pContainer->getLogDataHandler(); variableName = fields.front(); } QVector<int> columns, timecolumns; QStringList names; columns.append(mDataConfigs[t].mDataColumn); timecolumns.append(mDataConfigs[t].mTimeColumn); names.append(mDataConfigs[t].mFullVarName+"_valid"); pImportLogDataHandler->importTimeVariablesFromCSVColumns(mDataConfigs[t].mDataFile, columns, names, timecolumns); QString windowName = QString("Validation Plot %1").arg(t); gpPlotHandler->createNewOrReplacePlotwindow(windowName); gpPlotHandler->plotDataToWindow(windowName, pVariableLogDataHandler->getVectorVariable(variableName,-1), 0); gpPlotHandler->plotDataToWindow(windowName, pImportLogDataHandler->getVectorVariable(mDataConfigs[t].mFullVarName+"_valid",-1), 0); } } void FullNameVariableTreeWidget::addFullNameVariable(const QString &rFullName, const QString &rRemaningName, QTreeWidgetItem *pParentItem) { if (!rFullName.isEmpty()) { bool isLeaf=false; QStringList systems = rRemaningName.split("$"); QString name; // If we have a system part if (systems.size() > 1) { name = systems.first(); } // Else we have a comp::port::var else { QStringList compportvar = rRemaningName.split("#"); if (compportvar.size()==1) { isLeaf = true; } name = compportvar.first(); } QTreeWidgetItem* pLevelItem=0; // Add a new level in the tree if (pParentItem) { QTreeWidgetItem* pFound=0; for (int c=0; c<pParentItem->childCount(); ++c) { if (pParentItem->child(c)->text(0) == name) { // We assume there will never be duplicates due to uniqe name requirements pFound = pParentItem->child(c); break; } } if (pFound) { pLevelItem = pFound; } else { // Add new item pLevelItem = new QTreeWidgetItem(QStringList(name)); pParentItem->addChild(pLevelItem); } } else { QList<QTreeWidgetItem*> found = this->findItems(name, 0); if (found.isEmpty()) { // Add new top level item pLevelItem = new QTreeWidgetItem(QStringList(name)); addTopLevelItem(pLevelItem); } else { // We assume there will never be duplicates due to uniqe name requirements pLevelItem = found.first(); } } if (isLeaf) { pLevelItem->setData(0,Qt::UserRole,rFullName); } else { // Recurse QString shorterRemaningName = rRemaningName; shorterRemaningName.remove(0, name.size()+1); addFullNameVariable(rFullName, shorterRemaningName, pLevelItem); } } } FullNameVariableTreeWidget::FullNameVariableTreeWidget(QWidget *pParent) : QTreeWidget(pParent) { //Nothing } void FullNameVariableTreeWidget::addFullNameVariable(const QString &rFullName) { addFullNameVariable(rFullName, rFullName, 0); } //void FullNameVariableTreeWidget::mousePressEvent(QMouseEvent *event) //{ // QTreeWidget::mousePressEvent(event); // //! @todo dragstartposition // QTreeWidgetItem *pItem = this->itemAt(event->pos()); // if (pItem && (pItem->childCount() == 0)) // { // QDrag *pDrag = new QDrag(this); // QMimeData *pMime = new QMimeData; // pMime->setText(pItem->data(0, Qt::UserRole).toString()); // pDrag->setMimeData(pMime); // Qt::DropAction dropAction = pDrag->exec(Qt::CopyAction | Qt::MoveAction); // } //} //void FullNameVariableTreeWidget::dropEvent(QDropEvent *event) //{ // if (!event->mimeData()->text().isEmpty()) // { // addFullNameVariable(event->mimeData()->text()); // event->acceptProposedAction(); // } //} //void FullNameVariableTreeWidget::dragEnterEvent(QDragEnterEvent *event) //{ // if (!event->mimeData()->text().isEmpty()) // { // event->acceptProposedAction(); // } //} <|endoftext|>
<commit_before>/*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #ifndef MITKDIFFUSIONIMAGETODIFFUSIONIMAGEFILTER_CPP #define MITKDIFFUSIONIMAGETODIFFUSIONIMAGEFILTER_CPP #include "mitkDWIHeadMotionCorrectionFilter.h" #include "itkSplitDWImageFilter.h" #include "itkB0ImageExtractionToSeparateImageFilter.h" #include "mitkImageTimeSelector.h" #include "mitkPyramidImageRegistrationMethod.h" #include "mitkImageToDiffusionImageSource.h" #include "mitkDiffusionImageCorrectionFilter.h" #include <vector> #include "mitkIOUtil.h" #include <itkImage.h> template< typename DiffusionPixelType> mitk::DWIHeadMotionCorrectionFilter<DiffusionPixelType> ::DWIHeadMotionCorrectionFilter(): m_CurrentStep(0), m_Steps(100), m_IsInValidState(true), m_AbortRegistration(false) { } template< typename DiffusionPixelType> void mitk::DWIHeadMotionCorrectionFilter<DiffusionPixelType> ::GenerateData() { typedef itk::SplitDWImageFilter< DiffusionPixelType, DiffusionPixelType> SplitFilterType; DiffusionImageType* input = const_cast<DiffusionImageType*>(this->GetInput(0)); unsigned int numberOfSteps = input->GetVectorImage()->GetNumberOfComponentsPerPixel () ; m_Steps = numberOfSteps; // // (1) Extract the b-zero images to a 3d+t image, register them by NCorr metric and // rigid registration : they will then be used are reference image for registering // the gradient images // typedef itk::B0ImageExtractionToSeparateImageFilter< DiffusionPixelType, DiffusionPixelType> B0ExtractorType; typename B0ExtractorType::Pointer b0_extractor = B0ExtractorType::New(); b0_extractor->SetInput( input->GetVectorImage() ); b0_extractor->SetDirections( input->GetDirections() ); b0_extractor->Update(); mitk::Image::Pointer b0Image = mitk::Image::New(); b0Image->InitializeByItk( b0_extractor->GetOutput() ); b0Image->SetImportChannel( b0_extractor->GetOutput()->GetBufferPointer(), mitk::Image::CopyMemory ); // (2.1) Use the extractor to access the extracted b0 volumes mitk::ImageTimeSelector::Pointer t_selector = mitk::ImageTimeSelector::New(); t_selector->SetInput( b0Image ); t_selector->SetTimeNr(0); t_selector->Update(); // first unweighted image as reference space for the registration mitk::Image::Pointer b0referenceImage = t_selector->GetOutput(); mitk::PyramidImageRegistrationMethod::Pointer registrationMethod = mitk::PyramidImageRegistrationMethod::New(); registrationMethod->SetFixedImage( b0referenceImage ); registrationMethod->SetTransformToRigid(); // the unweighted images are of same modality registrationMethod->SetCrossModalityOff(); // use the advanced (windowed sinc) interpolation registrationMethod->SetUseAdvancedInterpolation(true); // Initialize the temporary output image mitk::Image::Pointer registeredB0Image = b0Image->Clone(); const unsigned int numberOfb0Images = b0Image->GetTimeSteps(); if( numberOfb0Images > 1) { mitk::ImageTimeSelector::Pointer t_selector2 = mitk::ImageTimeSelector::New(); t_selector2->SetInput( b0Image ); for( unsigned int i=1; i<numberOfb0Images; i++) { m_CurrentStep = i + 1; if( m_AbortRegistration == true) { m_IsInValidState = false; mitkThrow() << "Stopped by user."; }; t_selector2->SetTimeNr(i); t_selector2->Update(); registrationMethod->SetMovingImage( t_selector2->GetOutput() ); try { MITK_INFO << " === (" << i <<"/"<< numberOfb0Images-1 << ") :: Starting registration"; registrationMethod->Update(); } catch( const itk::ExceptionObject& e) { m_IsInValidState = false; mitkThrow() << "Failed to register the b0 images, the PyramidRegistration threw an exception: \n" << e.what(); } // import volume to the inter-results registeredB0Image->SetImportVolume( registrationMethod->GetResampledMovingImage()->GetData(), i, 0, mitk::Image::ReferenceMemory ); } // use the accumulateImageFilter as provided by the ItkAccumulateFilter method in the header file AccessFixedDimensionByItk_1(registeredB0Image, ItkAccumulateFilter, (4), b0referenceImage ); } // // (2) Split the diffusion image into a 3d+t regular image, extract only the weighted images // typename SplitFilterType::Pointer split_filter = SplitFilterType::New(); split_filter->SetInput (input->GetVectorImage() ); split_filter->SetExtractAllAboveThreshold(20, input->GetB_ValueMap() ); try { split_filter->Update(); } catch( const itk::ExceptionObject &e) { m_IsInValidState = false; mitkThrow() << " Caught exception from SplitImageFilter : " << e.what(); } mitk::Image::Pointer splittedImage = mitk::Image::New(); splittedImage->InitializeByItk( split_filter->GetOutput() ); splittedImage->SetImportChannel( split_filter->GetOutput()->GetBufferPointer(), mitk::Image::CopyMemory ); // // (3) Use again the time-selector to access the components separately in order // to perform the registration of Image -> unweighted reference // mitk::PyramidImageRegistrationMethod::Pointer weightedRegistrationMethod = mitk::PyramidImageRegistrationMethod::New(); weightedRegistrationMethod->SetTransformToAffine(); weightedRegistrationMethod->SetCrossModalityOn(); // // - (3.1) Set the reference image // - a single b0 image // - average over the registered b0 images if multiple present // weightedRegistrationMethod->SetFixedImage( b0referenceImage ); // use the advanced (windowed sinc) interpolation weightedRegistrationMethod->SetUseAdvancedInterpolation(true); // // - (3.2) Register all timesteps in the splitted image onto the first reference // unsigned int maxImageIdx = splittedImage->GetTimeSteps(); mitk::TimeGeometry* tsg = splittedImage->GetTimeGeometry(); mitk::ProportionalTimeGeometry* ptg = dynamic_cast<ProportionalTimeGeometry*>(tsg); ptg->Expand(maxImageIdx+1); mitk::Image::Pointer registeredWeighted = mitk::Image::New(); registeredWeighted->Initialize( splittedImage->GetPixelType(0), *tsg ); // insert the first unweighted reference as the first volume registeredWeighted->SetImportVolume( b0referenceImage->GetData(), 0,0, mitk::Image::CopyMemory ); // mitk::Image::Pointer registeredWeighted = splittedImage->Clone(); // this time start at 0, we have only gradient images in the 3d+t file // the reference image comes form an other image mitk::ImageTimeSelector::Pointer t_selector_w = mitk::ImageTimeSelector::New(); t_selector_w->SetInput( splittedImage ); // store the rotation parts of the transformations in a vector typedef mitk::PyramidImageRegistrationMethod::TransformMatrixType MatrixType; std::vector< MatrixType > estimated_transforms; for( unsigned int i=0; i<maxImageIdx; i++) { m_CurrentStep = numberOfb0Images + i + 1; if( m_AbortRegistration == true) { m_IsInValidState = false; mitkThrow() << "Stopped by user."; }; t_selector_w->SetTimeNr(i); t_selector_w->Update(); weightedRegistrationMethod->SetMovingImage( t_selector_w->GetOutput() ); try { MITK_INFO << " === (" << i+1 <<"/"<< maxImageIdx << ") :: Starting registration"; weightedRegistrationMethod->Update(); } catch( const itk::ExceptionObject& e) { m_IsInValidState = false; mitkThrow() << "Failed to register the b0 images, the PyramidRegistration threw an exception: \n" << e.what(); } // allow expansion registeredWeighted->SetImportVolume( weightedRegistrationMethod->GetResampledMovingImage()->GetData(), i+1, 0, mitk::Image::CopyMemory); estimated_transforms.push_back( weightedRegistrationMethod->GetLastRotationMatrix() ); } // // (4) Cast the resulting image back to an diffusion weighted image // typename DiffusionImageType::GradientDirectionContainerType *gradients = input->GetDirections(); typename DiffusionImageType::GradientDirectionContainerType::Pointer gradients_new = DiffusionImageType::GradientDirectionContainerType::New(); typename DiffusionImageType::GradientDirectionType bzero_vector; bzero_vector.fill(0); // compose the direction vector // - no direction for the first image // - correct ordering of the directions based on the index list gradients_new->push_back( bzero_vector ); typename SplitFilterType::IndexListType index_list = split_filter->GetIndexList(); typename SplitFilterType::IndexListType::const_iterator lIter = index_list.begin(); while( lIter != index_list.end() ) { gradients_new->push_back( gradients->at( *lIter ) ); ++lIter; } typename mitk::ImageToDiffusionImageSource< DiffusionPixelType >::Pointer caster = mitk::ImageToDiffusionImageSource< DiffusionPixelType >::New(); caster->SetImage( registeredWeighted ); caster->SetBValue( input->GetB_Value() ); caster->SetGradientDirections( gradients_new.GetPointer() ); try { caster->Update(); } catch( const itk::ExceptionObject& e) { m_IsInValidState = false; MITK_ERROR << "Casting back to diffusion image failed: "; mitkThrow() << "Subprocess failed with exception: " << e.what(); } // // (5) Adapt the gradient directions according to the estimated transforms // typedef mitk::DiffusionImageCorrectionFilter< DiffusionPixelType > CorrectionFilterType; typename CorrectionFilterType::Pointer corrector = CorrectionFilterType::New(); OutputImagePointerType output = caster->GetOutput(); corrector->SetImage( output ); corrector->CorrectDirections( estimated_transforms ); // // (6) Pass the corrected image to the filters output port // m_CurrentStep += 1; this->GetOutput()->SetVectorImage(output->GetVectorImage()); this->GetOutput()->SetB_Value(output->GetB_Value()); this->GetOutput()->SetDirections(output->GetDirections()); this->GetOutput()->SetMeasurementFrame(output->GetMeasurementFrame()); this->GetOutput()->InitializeFromVectorImage(); this->GetOutput()->Modified(); } #endif // MITKDIFFUSIONIMAGETODIFFUSIONIMAGEFILTER_CPP<commit_msg>Added missing init of the expanded geometry<commit_after>/*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #ifndef MITKDIFFUSIONIMAGETODIFFUSIONIMAGEFILTER_CPP #define MITKDIFFUSIONIMAGETODIFFUSIONIMAGEFILTER_CPP #include "mitkDWIHeadMotionCorrectionFilter.h" #include "itkSplitDWImageFilter.h" #include "itkB0ImageExtractionToSeparateImageFilter.h" #include "mitkImageTimeSelector.h" #include "mitkPyramidImageRegistrationMethod.h" #include "mitkImageToDiffusionImageSource.h" #include "mitkDiffusionImageCorrectionFilter.h" #include <vector> #include "mitkIOUtil.h" #include <itkImage.h> template< typename DiffusionPixelType> mitk::DWIHeadMotionCorrectionFilter<DiffusionPixelType> ::DWIHeadMotionCorrectionFilter(): m_CurrentStep(0), m_Steps(100), m_IsInValidState(true), m_AbortRegistration(false) { } template< typename DiffusionPixelType> void mitk::DWIHeadMotionCorrectionFilter<DiffusionPixelType> ::GenerateData() { typedef itk::SplitDWImageFilter< DiffusionPixelType, DiffusionPixelType> SplitFilterType; DiffusionImageType* input = const_cast<DiffusionImageType*>(this->GetInput(0)); unsigned int numberOfSteps = input->GetVectorImage()->GetNumberOfComponentsPerPixel () ; m_Steps = numberOfSteps; // // (1) Extract the b-zero images to a 3d+t image, register them by NCorr metric and // rigid registration : they will then be used are reference image for registering // the gradient images // typedef itk::B0ImageExtractionToSeparateImageFilter< DiffusionPixelType, DiffusionPixelType> B0ExtractorType; typename B0ExtractorType::Pointer b0_extractor = B0ExtractorType::New(); b0_extractor->SetInput( input->GetVectorImage() ); b0_extractor->SetDirections( input->GetDirections() ); b0_extractor->Update(); mitk::Image::Pointer b0Image = mitk::Image::New(); b0Image->InitializeByItk( b0_extractor->GetOutput() ); b0Image->SetImportChannel( b0_extractor->GetOutput()->GetBufferPointer(), mitk::Image::CopyMemory ); // (2.1) Use the extractor to access the extracted b0 volumes mitk::ImageTimeSelector::Pointer t_selector = mitk::ImageTimeSelector::New(); t_selector->SetInput( b0Image ); t_selector->SetTimeNr(0); t_selector->Update(); // first unweighted image as reference space for the registration mitk::Image::Pointer b0referenceImage = t_selector->GetOutput(); mitk::PyramidImageRegistrationMethod::Pointer registrationMethod = mitk::PyramidImageRegistrationMethod::New(); registrationMethod->SetFixedImage( b0referenceImage ); registrationMethod->SetTransformToRigid(); // the unweighted images are of same modality registrationMethod->SetCrossModalityOff(); // use the advanced (windowed sinc) interpolation registrationMethod->SetUseAdvancedInterpolation(true); // Initialize the temporary output image mitk::Image::Pointer registeredB0Image = b0Image->Clone(); const unsigned int numberOfb0Images = b0Image->GetTimeSteps(); if( numberOfb0Images > 1) { mitk::ImageTimeSelector::Pointer t_selector2 = mitk::ImageTimeSelector::New(); t_selector2->SetInput( b0Image ); for( unsigned int i=1; i<numberOfb0Images; i++) { m_CurrentStep = i + 1; if( m_AbortRegistration == true) { m_IsInValidState = false; mitkThrow() << "Stopped by user."; }; t_selector2->SetTimeNr(i); t_selector2->Update(); registrationMethod->SetMovingImage( t_selector2->GetOutput() ); try { MITK_INFO << " === (" << i <<"/"<< numberOfb0Images-1 << ") :: Starting registration"; registrationMethod->Update(); } catch( const itk::ExceptionObject& e) { m_IsInValidState = false; mitkThrow() << "Failed to register the b0 images, the PyramidRegistration threw an exception: \n" << e.what(); } // import volume to the inter-results registeredB0Image->SetImportVolume( registrationMethod->GetResampledMovingImage()->GetData(), i, 0, mitk::Image::ReferenceMemory ); } // use the accumulateImageFilter as provided by the ItkAccumulateFilter method in the header file AccessFixedDimensionByItk_1(registeredB0Image, ItkAccumulateFilter, (4), b0referenceImage ); } // // (2) Split the diffusion image into a 3d+t regular image, extract only the weighted images // typename SplitFilterType::Pointer split_filter = SplitFilterType::New(); split_filter->SetInput (input->GetVectorImage() ); split_filter->SetExtractAllAboveThreshold(20, input->GetB_ValueMap() ); try { split_filter->Update(); } catch( const itk::ExceptionObject &e) { m_IsInValidState = false; mitkThrow() << " Caught exception from SplitImageFilter : " << e.what(); } mitk::Image::Pointer splittedImage = mitk::Image::New(); splittedImage->InitializeByItk( split_filter->GetOutput() ); splittedImage->SetImportChannel( split_filter->GetOutput()->GetBufferPointer(), mitk::Image::CopyMemory ); // // (3) Use again the time-selector to access the components separately in order // to perform the registration of Image -> unweighted reference // mitk::PyramidImageRegistrationMethod::Pointer weightedRegistrationMethod = mitk::PyramidImageRegistrationMethod::New(); weightedRegistrationMethod->SetTransformToAffine(); weightedRegistrationMethod->SetCrossModalityOn(); // // - (3.1) Set the reference image // - a single b0 image // - average over the registered b0 images if multiple present // weightedRegistrationMethod->SetFixedImage( b0referenceImage ); // use the advanced (windowed sinc) interpolation weightedRegistrationMethod->SetUseAdvancedInterpolation(true); // // - (3.2) Register all timesteps in the splitted image onto the first reference // unsigned int maxImageIdx = splittedImage->GetTimeSteps(); mitk::TimeGeometry* tsg = splittedImage->GetTimeGeometry(); mitk::ProportionalTimeGeometry* ptg = dynamic_cast<ProportionalTimeGeometry*>(tsg); ptg->Expand(maxImageIdx+1); ptg->SetTimeStepGeometry( ptg->GetGeometryForTimeStep(0), 6 ); mitk::Image::Pointer registeredWeighted = mitk::Image::New(); registeredWeighted->Initialize( splittedImage->GetPixelType(0), *tsg ); // insert the first unweighted reference as the first volume registeredWeighted->SetImportVolume( b0referenceImage->GetData(), 0,0, mitk::Image::CopyMemory ); // mitk::Image::Pointer registeredWeighted = splittedImage->Clone(); // this time start at 0, we have only gradient images in the 3d+t file // the reference image comes form an other image mitk::ImageTimeSelector::Pointer t_selector_w = mitk::ImageTimeSelector::New(); t_selector_w->SetInput( splittedImage ); // store the rotation parts of the transformations in a vector typedef mitk::PyramidImageRegistrationMethod::TransformMatrixType MatrixType; std::vector< MatrixType > estimated_transforms; for( unsigned int i=0; i<maxImageIdx; i++) { m_CurrentStep = numberOfb0Images + i + 1; if( m_AbortRegistration == true) { m_IsInValidState = false; mitkThrow() << "Stopped by user."; }; t_selector_w->SetTimeNr(i); t_selector_w->Update(); weightedRegistrationMethod->SetMovingImage( t_selector_w->GetOutput() ); try { MITK_INFO << " === (" << i+1 <<"/"<< maxImageIdx << ") :: Starting registration"; weightedRegistrationMethod->Update(); } catch( const itk::ExceptionObject& e) { m_IsInValidState = false; mitkThrow() << "Failed to register the b0 images, the PyramidRegistration threw an exception: \n" << e.what(); } // allow expansion registeredWeighted->SetImportVolume( weightedRegistrationMethod->GetResampledMovingImage()->GetData(), i+1, 0, mitk::Image::CopyMemory); estimated_transforms.push_back( weightedRegistrationMethod->GetLastRotationMatrix() ); } // // (4) Cast the resulting image back to an diffusion weighted image // typename DiffusionImageType::GradientDirectionContainerType *gradients = input->GetDirections(); typename DiffusionImageType::GradientDirectionContainerType::Pointer gradients_new = DiffusionImageType::GradientDirectionContainerType::New(); typename DiffusionImageType::GradientDirectionType bzero_vector; bzero_vector.fill(0); // compose the direction vector // - no direction for the first image // - correct ordering of the directions based on the index list gradients_new->push_back( bzero_vector ); typename SplitFilterType::IndexListType index_list = split_filter->GetIndexList(); typename SplitFilterType::IndexListType::const_iterator lIter = index_list.begin(); while( lIter != index_list.end() ) { gradients_new->push_back( gradients->at( *lIter ) ); ++lIter; } typename mitk::ImageToDiffusionImageSource< DiffusionPixelType >::Pointer caster = mitk::ImageToDiffusionImageSource< DiffusionPixelType >::New(); caster->SetImage( registeredWeighted ); caster->SetBValue( input->GetB_Value() ); caster->SetGradientDirections( gradients_new.GetPointer() ); try { caster->Update(); } catch( const itk::ExceptionObject& e) { m_IsInValidState = false; MITK_ERROR << "Casting back to diffusion image failed: "; mitkThrow() << "Subprocess failed with exception: " << e.what(); } // // (5) Adapt the gradient directions according to the estimated transforms // typedef mitk::DiffusionImageCorrectionFilter< DiffusionPixelType > CorrectionFilterType; typename CorrectionFilterType::Pointer corrector = CorrectionFilterType::New(); OutputImagePointerType output = caster->GetOutput(); corrector->SetImage( output ); corrector->CorrectDirections( estimated_transforms ); // // (6) Pass the corrected image to the filters output port // m_CurrentStep += 1; this->GetOutput()->SetVectorImage(output->GetVectorImage()); this->GetOutput()->SetB_Value(output->GetB_Value()); this->GetOutput()->SetDirections(output->GetDirections()); this->GetOutput()->SetMeasurementFrame(output->GetMeasurementFrame()); this->GetOutput()->InitializeFromVectorImage(); this->GetOutput()->Modified(); } #endif // MITKDIFFUSIONIMAGETODIFFUSIONIMAGEFILTER_CPP <|endoftext|>
<commit_before><commit_msg>Create 1255 - Substring Frequency.cpp<commit_after><|endoftext|>
<commit_before>/*========================================================================= Program: Visualization Toolkit Module: vtkImageCacheFilter.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. =========================================================================*/ #include "vtkImageCacheFilter.h" #include "vtkImageData.h" #include "vtkObjectFactory.h" #include "vtkPointData.h" vtkCxxRevisionMacro(vtkImageCacheFilter, "1.20"); vtkStandardNewMacro(vtkImageCacheFilter); //---------------------------------------------------------------------------- vtkImageCacheFilter::vtkImageCacheFilter() { this->CacheSize = 0; this->Data = NULL; this->Times = NULL; this->SetCacheSize(10); } //---------------------------------------------------------------------------- vtkImageCacheFilter::~vtkImageCacheFilter() { this->SetCacheSize(0); } //---------------------------------------------------------------------------- void vtkImageCacheFilter::PrintSelf(ostream& os, vtkIndent indent) { this->Superclass::PrintSelf(os,indent); int idx, *ext; vtkIndent i2 = indent.GetNextIndent(); os << indent << "CacheSize: " << this->CacheSize << endl; os << indent << "Caches: \n"; for (idx = 0; idx < this->CacheSize; ++idx) { if (this->Data[idx]) { ext = this->Data[idx]->GetExtent(); os << i2 << idx << ": (" << this->Times[idx] << ") " << ext[0] << ", " << ext[1] << ", " << ext[2] << ", " << ext[3] << ", " << ext[4] << ", " << ext[5] << endl; } } } void vtkImageCacheFilter::SetCacheSize(int size) { int idx; if (size == this->CacheSize) { return; } this->Modified(); // free the old data for (idx = 0; idx < this->CacheSize; ++idx) { if (this->Data[idx]) { this->Data[idx]->Delete(); this->Data[idx] = NULL; } } if (this->Data) { delete [] this->Data; this->Data = NULL; } if (this->Times) { delete [] this->Times; this->Times = NULL; } this->CacheSize = size; if (size == 0) { return; } this->Data = new vtkImageData* [size]; this->Times = new unsigned long [size]; for (idx = 0; idx < size; ++idx) { this->Data[idx] = NULL; this->Times[idx] = 0; } } //---------------------------------------------------------------------------- // This method simply copies by reference the input data to the output. void vtkImageCacheFilter::UpdateData(vtkDataObject *outObject) { unsigned long pmt; int *uExt, *ext; vtkImageData *outData = (vtkImageData *)(outObject); vtkImageData *inData = this->GetInput(); int i; int flag = 0; if (!inData) { vtkErrorMacro(<< "Input not set."); return; } uExt = outData->GetUpdateExtent(); // First look through the cached data to see if it is still valid. pmt = inData->GetPipelineMTime(); for (i = 0; i < this->CacheSize; ++i) { if (this->Data[i] && this->Times[i] < pmt) { this->Data[i]->Delete(); this->Times[i] = 0; } } // Look for data that contains UpdateExtent. for (i = 0; i < this->CacheSize; ++i) { if (this->Data[i]) { ext = this->Data[i]->GetExtent(); if (uExt[0] >= ext[0] && uExt[1] <= ext[1] && uExt[2] >= ext[2] && uExt[3] <= ext[3] && uExt[4] >= ext[4] && uExt[5] <= ext[5]) { vtkDebugMacro("Found Cached Data to meet request" ); // Pass this data to output. outData->SetExtent(ext); outData->GetPointData()->PassData(this->Data[i]->GetPointData()); outData->DataHasBeenGenerated(); flag = 1; } } } if (flag == 0) { unsigned long bestTime = VTK_LARGE_INTEGER; int bestIdx = 0; // we need to update. inData->SetUpdateExtent(uExt); inData->PropagateUpdateExtent(); inData->UpdateData(); if (inData->GetDataReleased()) { // special case return; } vtkDebugMacro("Generating Data to meet request" ); outData->SetExtent(inData->GetExtent()); outData->GetPointData()->PassData(inData->GetPointData()); outData->DataHasBeenGenerated(); // Save the image in cache. // Find a spot to put the data. for (i = 0; i < this->CacheSize; ++i) { if (this->Data[i] == NULL) { bestIdx = i; bestTime = 0; break; } if (this->Times[i] < bestTime) { bestIdx = i; bestTime = this->Times[i]; } } if (this->Data[bestIdx] == NULL) { this->Data[bestIdx] = vtkImageData::New(); } this->Data[bestIdx]->ReleaseData(); this->Data[bestIdx]->SetScalarType(inData->GetScalarType()); this->Data[bestIdx]->SetExtent(inData->GetExtent()); this->Data[bestIdx]->SetNumberOfScalarComponents(inData->GetNumberOfScalarComponents()); this->Data[bestIdx]->GetPointData()->SetScalars(inData->GetPointData()->GetScalars()); this->Times[bestIdx] = inData->GetUpdateTime(); // release input data if (this->GetInput()->ShouldIReleaseData()) { this->GetInput()->ReleaseData(); } } } <commit_msg>BUG: Fix Bug #787 - Exception on vtkImageCacheFilter after modifying the pipeline.<commit_after>/*========================================================================= Program: Visualization Toolkit Module: vtkImageCacheFilter.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. =========================================================================*/ #include "vtkImageCacheFilter.h" #include "vtkImageData.h" #include "vtkObjectFactory.h" #include "vtkPointData.h" vtkCxxRevisionMacro(vtkImageCacheFilter, "1.21"); vtkStandardNewMacro(vtkImageCacheFilter); //---------------------------------------------------------------------------- vtkImageCacheFilter::vtkImageCacheFilter() { this->CacheSize = 0; this->Data = NULL; this->Times = NULL; this->SetCacheSize(10); } //---------------------------------------------------------------------------- vtkImageCacheFilter::~vtkImageCacheFilter() { this->SetCacheSize(0); } //---------------------------------------------------------------------------- void vtkImageCacheFilter::PrintSelf(ostream& os, vtkIndent indent) { this->Superclass::PrintSelf(os,indent); int idx, *ext; vtkIndent i2 = indent.GetNextIndent(); os << indent << "CacheSize: " << this->CacheSize << endl; os << indent << "Caches: \n"; for (idx = 0; idx < this->CacheSize; ++idx) { if (this->Data[idx]) { ext = this->Data[idx]->GetExtent(); os << i2 << idx << ": (" << this->Times[idx] << ") " << ext[0] << ", " << ext[1] << ", " << ext[2] << ", " << ext[3] << ", " << ext[4] << ", " << ext[5] << endl; } } } //---------------------------------------------------------------------------- void vtkImageCacheFilter::SetCacheSize(int size) { int idx; if (size == this->CacheSize) { return; } this->Modified(); // free the old data for (idx = 0; idx < this->CacheSize; ++idx) { if (this->Data[idx]) { this->Data[idx]->Delete(); this->Data[idx] = NULL; } } if (this->Data) { delete [] this->Data; this->Data = NULL; } if (this->Times) { delete [] this->Times; this->Times = NULL; } this->CacheSize = size; if (size == 0) { return; } this->Data = new vtkImageData* [size]; this->Times = new unsigned long [size]; for (idx = 0; idx < size; ++idx) { this->Data[idx] = NULL; this->Times[idx] = 0; } } //---------------------------------------------------------------------------- // This method simply copies by reference the input data to the output. void vtkImageCacheFilter::UpdateData(vtkDataObject *outObject) { unsigned long pmt; int *uExt, *ext; vtkImageData *outData = (vtkImageData *)(outObject); vtkImageData *inData = this->GetInput(); int i; int flag = 0; if (!inData) { vtkErrorMacro(<< "Input not set."); return; } uExt = outData->GetUpdateExtent(); // First look through the cached data to see if it is still valid. pmt = inData->GetPipelineMTime(); for (i = 0; i < this->CacheSize; ++i) { if (this->Data[i] && this->Times[i] < pmt) { this->Data[i]->Delete(); this->Data[i] = NULL; this->Times[i] = 0; } } // Look for data that contains UpdateExtent. for (i = 0; i < this->CacheSize; ++i) { if (this->Data[i]) { ext = this->Data[i]->GetExtent(); if (uExt[0] >= ext[0] && uExt[1] <= ext[1] && uExt[2] >= ext[2] && uExt[3] <= ext[3] && uExt[4] >= ext[4] && uExt[5] <= ext[5]) { vtkDebugMacro("Found Cached Data to meet request" ); // Pass this data to output. outData->SetExtent(ext); outData->GetPointData()->PassData(this->Data[i]->GetPointData()); outData->DataHasBeenGenerated(); flag = 1; } } } if (flag == 0) { unsigned long bestTime = VTK_LARGE_INTEGER; int bestIdx = 0; // we need to update. inData->SetUpdateExtent(uExt); inData->PropagateUpdateExtent(); inData->UpdateData(); if (inData->GetDataReleased()) { // special case return; } vtkDebugMacro("Generating Data to meet request" ); outData->SetExtent(inData->GetExtent()); outData->GetPointData()->PassData(inData->GetPointData()); outData->DataHasBeenGenerated(); // Save the image in cache. // Find a spot to put the data. for (i = 0; i < this->CacheSize; ++i) { if (this->Data[i] == NULL) { bestIdx = i; bestTime = 0; break; } if (this->Times[i] < bestTime) { bestIdx = i; bestTime = this->Times[i]; } } if (this->Data[bestIdx] == NULL) { this->Data[bestIdx] = vtkImageData::New(); } this->Data[bestIdx]->ReleaseData(); this->Data[bestIdx]->SetScalarType(inData->GetScalarType()); this->Data[bestIdx]->SetExtent(inData->GetExtent()); this->Data[bestIdx]->SetNumberOfScalarComponents(inData->GetNumberOfScalarComponents()); this->Data[bestIdx]->GetPointData()->SetScalars(inData->GetPointData()->GetScalars()); this->Times[bestIdx] = inData->GetUpdateTime(); // release input data if (this->GetInput()->ShouldIReleaseData()) { this->GetInput()->ReleaseData(); } } } <|endoftext|>
<commit_before>#define GROUP_TEST(regex, anchor, input, n) \ test_case(_FORMAT(regex, anchor, input)) { \ re2::StringPiece g2[n]; \ re2::StringPiece gj[n]; \ if ( _RE2_RUN(_RE2(regex), input, anchor, g2, n) \ != _R2J_RUN(_R2J(regex), input, anchor, gj, n)) return Result::Fail("invalid answer"); \ for (size_t i = 0; i < n; i++) { \ if (g2[i] != gj[i]) { \ return Result::Fail( \ "group %zu incorrect\n" \ " expected [%d] '%s'\n" \ " matched [%d] '%s'", i, g2[i].size(), g2[i].data(), gj[i].size(), gj[i].data()); \ } \ } \ } GROUP_TEST("Hello, (.*)!", ANCHOR_START, "Hello, World!", 2); GROUP_TEST("([^ ]*?), (.*)", UNANCHORED, "Hi there, world!", 3); GROUP_TEST("([+-]?(?:(0b)[01]+|(0o)[0-7]+|(0x)[0-9a-f]+))", ANCHOR_BOTH, "0b00010", 6); GROUP_TEST("([+-]?(?:(0b)[01]+|(0o)[0-7]+|(0x)[0-9a-f]+|[0-9]+((?:\\.[0-9]+)?(?:e[+-]?[0-9]+)?)(j)?))", ANCHOR_BOTH, "0b00010", 6); GROUP_TEST("([+-]?(?:(0b)[01]+|(0o)[0-7]+|(0x)[0-9a-f]+|[0-9]+((?:\\.[0-9]+)?(?:e[+-]?[0-9]+)?)(j)?))", ANCHOR_BOTH, "30.5e+1j", 6); <commit_msg>Fix subgroup output in failing tests.<commit_after>#define GROUP_TEST(regex, anchor, input, n) \ test_case(_FORMAT(regex, anchor, input)) { \ re2::StringPiece g2[n]; \ re2::StringPiece gj[n]; \ if ( _RE2_RUN(_RE2(regex), input, anchor, g2, n) \ != _R2J_RUN(_R2J(regex), input, anchor, gj, n)) return Result::Fail("invalid answer"); \ for (size_t i = 0; i < n; i++) { \ if (g2[i] != gj[i]) { \ return Result::Fail( \ "group %zu incorrect\n" \ " expected [%d] '%.*s'\n" \ " matched [%d] '%.*s'", i, g2[i].size(), g2[i].size(), g2[i].data(), \ gj[i].size(), gj[i].size(), gj[i].data()); \ } \ } \ } GROUP_TEST("Hello, (.*)!", ANCHOR_START, "Hello, World!", 2); GROUP_TEST("([^ ]*?), (.*)", UNANCHORED, "Hi there, world!", 3); GROUP_TEST("([+-]?(?:(0b)[01]+|(0o)[0-7]+|(0x)[0-9a-f]+))", ANCHOR_BOTH, "0b00010", 6); GROUP_TEST("([+-]?(?:(0b)[01]+|(0o)[0-7]+|(0x)[0-9a-f]+|[0-9]+((?:\\.[0-9]+)?(?:e[+-]?[0-9]+)?)(j)?))", ANCHOR_BOTH, "0b00010", 6); GROUP_TEST("([+-]?(?:(0b)[01]+|(0o)[0-7]+|(0x)[0-9a-f]+|[0-9]+((?:\\.[0-9]+)?(?:e[+-]?[0-9]+)?)(j)?))", ANCHOR_BOTH, "30.5e+1j", 6); <|endoftext|>
<commit_before> #include <plan_and_run/demo_application.h> /* LOAD PARAMETERS Goal: - Load missing application parameters into the from the ros parameter server. - Use a private NodeHandle in order to load parameters defined in the node's namespace. Hints: - Look at how the 'config_' structure is used to save the parameters. - A private NodeHandle can be created by passing the "~" string to its constructor. */ namespace plan_and_run { void DemoApplication::loadParameters() { //ROS_ERROR_STREAM("Task '"<<__FUNCTION__ <<"' is incomplete. Exiting"); exit(-1); /* Fill Code: * Goal: * - Create a private handle by passing the "~" string to its constructor * Hint: * - Replace the string in ph below with "~" to make it a private node. */ ros::NodeHandle ph("~"); // creating handle with public scope ros::NodeHandle nh; /* Fill Code: * Goal: * - Read missing parameters 'tip_link' and 'world_frame' from ros parameter server */ if(ph.getParam("group_name",config_.group_name) && ph.getParam("tip_link",config_.tip_link) && ph.getParam("base_link",config_.base_link) && ph.getParam("world_frame",config_.world_frame) && ph.getParam("trajectory/time_delay",config_.time_delay) && ph.getParam("trajectory/foci_distance",config_.foci_distance) && ph.getParam("trajectory/radius",config_.radius) && ph.getParam("trajectory/num_points",config_.num_points) && ph.getParam("trajectory/num_lemniscates",config_.num_lemniscates) && ph.getParam("trajectory/center",config_.center) && ph.getParam("trajectory/seed_pose",config_.seed_pose) && ph.getParam("visualization/min_point_distance",config_.min_point_distance) && nh.getParam("controller_joint_names",config_.joint_names) ) { ROS_INFO_STREAM("Loaded application parameters"); } else { ROS_ERROR_STREAM("Failed to load application parameters"); exit(-1); } ROS_INFO_STREAM("Task '"<<__FUNCTION__<<"' completed"); } } <commit_msg>Fixing Typo in load_parameter Solution Comments<commit_after> #include <plan_and_run/demo_application.h> /* LOAD PARAMETERS Goal: - Load missing application parameters from the ros parameter server. - Use a private NodeHandle in order to load parameters defined in the node's namespace. Hints: - Look at how the 'config_' structure is used to save the parameters. - A private NodeHandle can be created by passing the "~" string to its constructor. */ namespace plan_and_run { void DemoApplication::loadParameters() { //ROS_ERROR_STREAM("Task '"<<__FUNCTION__ <<"' is incomplete. Exiting"); exit(-1); /* Fill Code: * Goal: * - Create a private handle by passing the "~" string to its constructor * Hint: * - Replace the string in ph below with "~" to make it a private node. */ ros::NodeHandle ph("~"); // creating handle with public scope ros::NodeHandle nh; /* Fill Code: * Goal: * - Read missing parameters 'tip_link' and 'world_frame' from ros parameter server */ if(ph.getParam("group_name",config_.group_name) && ph.getParam("tip_link",config_.tip_link) && ph.getParam("base_link",config_.base_link) && ph.getParam("world_frame",config_.world_frame) && ph.getParam("trajectory/time_delay",config_.time_delay) && ph.getParam("trajectory/foci_distance",config_.foci_distance) && ph.getParam("trajectory/radius",config_.radius) && ph.getParam("trajectory/num_points",config_.num_points) && ph.getParam("trajectory/num_lemniscates",config_.num_lemniscates) && ph.getParam("trajectory/center",config_.center) && ph.getParam("trajectory/seed_pose",config_.seed_pose) && ph.getParam("visualization/min_point_distance",config_.min_point_distance) && nh.getParam("controller_joint_names",config_.joint_names) ) { ROS_INFO_STREAM("Loaded application parameters"); } else { ROS_ERROR_STREAM("Failed to load application parameters"); exit(-1); } ROS_INFO_STREAM("Task '"<<__FUNCTION__<<"' completed"); } } <|endoftext|>
<commit_before>//===- CallingConvEmitter.cpp - Generate calling conventions --------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This tablegen backend is responsible for emitting descriptions of the calling // conventions supported by this target. // //===----------------------------------------------------------------------===// #include "CallingConvEmitter.h" #include "Record.h" #include "CodeGenTarget.h" using namespace llvm; void CallingConvEmitter::run(std::ostream &O) { EmitSourceFileHeader("Calling Convention Implementation Fragment", O); std::vector<Record*> CCs = Records.getAllDerivedDefinitions("CallingConv"); // Emit prototypes for all of the CC's so that they can forward ref each // other. for (unsigned i = 0, e = CCs.size(); i != e; ++i) { O << "static bool " << CCs[i]->getName() << "(unsigned ValNo, MVT ValVT,\n" << std::string(CCs[i]->getName().size()+13, ' ') << "MVT LocVT, CCValAssign::LocInfo LocInfo,\n" << std::string(CCs[i]->getName().size()+13, ' ') << "ISD::ArgFlagsTy ArgFlags, CCState &State);\n"; } // Emit each calling convention description in full. for (unsigned i = 0, e = CCs.size(); i != e; ++i) EmitCallingConv(CCs[i], O); } void CallingConvEmitter::EmitCallingConv(Record *CC, std::ostream &O) { ListInit *CCActions = CC->getValueAsListInit("Actions"); Counter = 0; O << "\n\nstatic bool " << CC->getName() << "(unsigned ValNo, MVT ValVT,\n" << std::string(CC->getName().size()+13, ' ') << "MVT LocVT, CCValAssign::LocInfo LocInfo,\n" << std::string(CC->getName().size()+13, ' ') << "ISD::ArgFlagsTy ArgFlags, CCState &State) {\n"; // Emit all of the actions, in order. for (unsigned i = 0, e = CCActions->getSize(); i != e; ++i) { O << "\n"; EmitAction(CCActions->getElementAsRecord(i), 2, O); } O << "\n return true; // CC didn't match.\n"; O << "}\n"; } void CallingConvEmitter::EmitAction(Record *Action, unsigned Indent, std::ostream &O) { std::string IndentStr = std::string(Indent, ' '); if (Action->isSubClassOf("CCPredicateAction")) { O << IndentStr << "if ("; if (Action->isSubClassOf("CCIfType")) { ListInit *VTs = Action->getValueAsListInit("VTs"); for (unsigned i = 0, e = VTs->getSize(); i != e; ++i) { Record *VT = VTs->getElementAsRecord(i); if (i != 0) O << " ||\n " << IndentStr; O << "LocVT == " << getEnumName(getValueType(VT)); } } else if (Action->isSubClassOf("CCIf")) { O << Action->getValueAsString("Predicate"); } else { Action->dump(); throw "Unknown CCPredicateAction!"; } O << ") {\n"; EmitAction(Action->getValueAsDef("SubAction"), Indent+2, O); O << IndentStr << "}\n"; } else { if (Action->isSubClassOf("CCDelegateTo")) { Record *CC = Action->getValueAsDef("CC"); O << IndentStr << "if (!" << CC->getName() << "(ValNo, ValVT, LocVT, LocInfo, ArgFlags, State))\n" << IndentStr << " return false;\n"; } else if (Action->isSubClassOf("CCAssignToReg")) { ListInit *RegList = Action->getValueAsListInit("RegList"); if (RegList->getSize() == 1) { O << IndentStr << "if (unsigned Reg = State.AllocateReg("; O << getQualifiedName(RegList->getElementAsRecord(0)) << ")) {\n"; } else { O << IndentStr << "static const unsigned RegList" << ++Counter << "[] = {\n"; O << IndentStr << " "; for (unsigned i = 0, e = RegList->getSize(); i != e; ++i) { if (i != 0) O << ", "; O << getQualifiedName(RegList->getElementAsRecord(i)); } O << "\n" << IndentStr << "};\n"; O << IndentStr << "if (unsigned Reg = State.AllocateReg(RegList" << Counter << ", " << RegList->getSize() << ")) {\n"; } O << IndentStr << " State.addLoc(CCValAssign::getReg(ValNo, ValVT, " << "Reg, LocVT, LocInfo));\n"; O << IndentStr << " return false;\n"; O << IndentStr << "}\n"; } else if (Action->isSubClassOf("CCAssignToRegWithShadow")) { ListInit *RegList = Action->getValueAsListInit("RegList"); ListInit *ShadowRegList = Action->getValueAsListInit("ShadowRegList"); if (ShadowRegList->getSize() >0 && ShadowRegList->getSize() != RegList->getSize()) throw "Invalid length of list of shadowed registers"; if (RegList->getSize() == 1) { O << IndentStr << "if (unsigned Reg = State.AllocateReg("; O << getQualifiedName(RegList->getElementAsRecord(0)); O << ", " << getQualifiedName(ShadowRegList->getElementAsRecord(0)); O << ")) {\n"; } else { unsigned RegListNumber = ++Counter; unsigned ShadowRegListNumber = ++Counter; O << IndentStr << "static const unsigned RegList" << RegListNumber << "[] = {\n"; O << IndentStr << " "; for (unsigned i = 0, e = RegList->getSize(); i != e; ++i) { if (i != 0) O << ", "; O << getQualifiedName(RegList->getElementAsRecord(i)); } O << "\n" << IndentStr << "};\n"; O << IndentStr << "static const unsigned RegList" << ShadowRegListNumber << "[] = {\n"; O << IndentStr << " "; for (unsigned i = 0, e = ShadowRegList->getSize(); i != e; ++i) { if (i != 0) O << ", "; O << getQualifiedName(ShadowRegList->getElementAsRecord(i)); } O << "\n" << IndentStr << "};\n"; O << IndentStr << "if (unsigned Reg = State.AllocateReg(RegList" << RegListNumber << ", " << "RegList" << ShadowRegListNumber << ", " << RegList->getSize() << ")) {\n"; } O << IndentStr << " State.addLoc(CCValAssign::getReg(ValNo, ValVT, " << "Reg, LocVT, LocInfo));\n"; O << IndentStr << " return false;\n"; O << IndentStr << "}\n"; } else if (Action->isSubClassOf("CCAssignToStack")) { int Size = Action->getValueAsInt("Size"); int Align = Action->getValueAsInt("Align"); O << IndentStr << "unsigned Offset" << ++Counter << " = State.AllocateStack("; if (Size) O << Size << ", "; else O << "\n" << IndentStr << " State.getTarget().getTargetData()" "->getTypePaddedSize(LocVT.getTypeForMVT()), "; if (Align) O << Align; else O << "\n" << IndentStr << " State.getTarget().getTargetData()" "->getABITypeAlignment(LocVT.getTypeForMVT())"; O << ");\n" << IndentStr << "State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset" << Counter << ", LocVT, LocInfo));\n"; O << IndentStr << "return false;\n"; } else if (Action->isSubClassOf("CCPromoteToType")) { Record *DestTy = Action->getValueAsDef("DestTy"); O << IndentStr << "LocVT = " << getEnumName(getValueType(DestTy)) <<";\n"; O << IndentStr << "if (ArgFlags.isSExt())\n" << IndentStr << IndentStr << "LocInfo = CCValAssign::SExt;\n" << IndentStr << "else if (ArgFlags.isZExt())\n" << IndentStr << IndentStr << "LocInfo = CCValAssign::ZExt;\n" << IndentStr << "else\n" << IndentStr << IndentStr << "LocInfo = CCValAssign::AExt;\n"; } else if (Action->isSubClassOf("CCPassByVal")) { int Size = Action->getValueAsInt("Size"); int Align = Action->getValueAsInt("Align"); O << IndentStr << "State.HandleByVal(ValNo, ValVT, LocVT, LocInfo, " << Size << ", " << Align << ", ArgFlags);\n"; O << IndentStr << "return false;\n"; } else { Action->dump(); throw "Unknown CCAction!"; } } } <commit_msg>Use CallConvLower.h and TableGen descriptions of the calling conventions for ARM. Patch by Sandeep Patel.<commit_after>//===- CallingConvEmitter.cpp - Generate calling conventions --------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This tablegen backend is responsible for emitting descriptions of the calling // conventions supported by this target. // //===----------------------------------------------------------------------===// #include "CallingConvEmitter.h" #include "Record.h" #include "CodeGenTarget.h" using namespace llvm; void CallingConvEmitter::run(std::ostream &O) { EmitSourceFileHeader("Calling Convention Implementation Fragment", O); std::vector<Record*> CCs = Records.getAllDerivedDefinitions("CallingConv"); // Emit prototypes for all of the CC's so that they can forward ref each // other. for (unsigned i = 0, e = CCs.size(); i != e; ++i) { O << "static bool " << CCs[i]->getName() << "(unsigned ValNo, MVT ValVT,\n" << std::string(CCs[i]->getName().size()+13, ' ') << "MVT LocVT, CCValAssign::LocInfo LocInfo,\n" << std::string(CCs[i]->getName().size()+13, ' ') << "ISD::ArgFlagsTy ArgFlags, CCState &State);\n"; } // Emit each calling convention description in full. for (unsigned i = 0, e = CCs.size(); i != e; ++i) EmitCallingConv(CCs[i], O); } void CallingConvEmitter::EmitCallingConv(Record *CC, std::ostream &O) { ListInit *CCActions = CC->getValueAsListInit("Actions"); Counter = 0; O << "\n\nstatic bool " << CC->getName() << "(unsigned ValNo, MVT ValVT,\n" << std::string(CC->getName().size()+13, ' ') << "MVT LocVT, CCValAssign::LocInfo LocInfo,\n" << std::string(CC->getName().size()+13, ' ') << "ISD::ArgFlagsTy ArgFlags, CCState &State) {\n"; // Emit all of the actions, in order. for (unsigned i = 0, e = CCActions->getSize(); i != e; ++i) { O << "\n"; EmitAction(CCActions->getElementAsRecord(i), 2, O); } O << "\n return true; // CC didn't match.\n"; O << "}\n"; } void CallingConvEmitter::EmitAction(Record *Action, unsigned Indent, std::ostream &O) { std::string IndentStr = std::string(Indent, ' '); if (Action->isSubClassOf("CCPredicateAction")) { O << IndentStr << "if ("; if (Action->isSubClassOf("CCIfType")) { ListInit *VTs = Action->getValueAsListInit("VTs"); for (unsigned i = 0, e = VTs->getSize(); i != e; ++i) { Record *VT = VTs->getElementAsRecord(i); if (i != 0) O << " ||\n " << IndentStr; O << "LocVT == " << getEnumName(getValueType(VT)); } } else if (Action->isSubClassOf("CCIf")) { O << Action->getValueAsString("Predicate"); } else { Action->dump(); throw "Unknown CCPredicateAction!"; } O << ") {\n"; EmitAction(Action->getValueAsDef("SubAction"), Indent+2, O); O << IndentStr << "}\n"; } else { if (Action->isSubClassOf("CCDelegateTo")) { Record *CC = Action->getValueAsDef("CC"); O << IndentStr << "if (!" << CC->getName() << "(ValNo, ValVT, LocVT, LocInfo, ArgFlags, State))\n" << IndentStr << " return false;\n"; } else if (Action->isSubClassOf("CCAssignToReg")) { ListInit *RegList = Action->getValueAsListInit("RegList"); if (RegList->getSize() == 1) { O << IndentStr << "if (unsigned Reg = State.AllocateReg("; O << getQualifiedName(RegList->getElementAsRecord(0)) << ")) {\n"; } else { O << IndentStr << "static const unsigned RegList" << ++Counter << "[] = {\n"; O << IndentStr << " "; for (unsigned i = 0, e = RegList->getSize(); i != e; ++i) { if (i != 0) O << ", "; O << getQualifiedName(RegList->getElementAsRecord(i)); } O << "\n" << IndentStr << "};\n"; O << IndentStr << "if (unsigned Reg = State.AllocateReg(RegList" << Counter << ", " << RegList->getSize() << ")) {\n"; } O << IndentStr << " State.addLoc(CCValAssign::getReg(ValNo, ValVT, " << "Reg, LocVT, LocInfo));\n"; O << IndentStr << " return false;\n"; O << IndentStr << "}\n"; } else if (Action->isSubClassOf("CCAssignToRegWithShadow")) { ListInit *RegList = Action->getValueAsListInit("RegList"); ListInit *ShadowRegList = Action->getValueAsListInit("ShadowRegList"); if (ShadowRegList->getSize() >0 && ShadowRegList->getSize() != RegList->getSize()) throw "Invalid length of list of shadowed registers"; if (RegList->getSize() == 1) { O << IndentStr << "if (unsigned Reg = State.AllocateReg("; O << getQualifiedName(RegList->getElementAsRecord(0)); O << ", " << getQualifiedName(ShadowRegList->getElementAsRecord(0)); O << ")) {\n"; } else { unsigned RegListNumber = ++Counter; unsigned ShadowRegListNumber = ++Counter; O << IndentStr << "static const unsigned RegList" << RegListNumber << "[] = {\n"; O << IndentStr << " "; for (unsigned i = 0, e = RegList->getSize(); i != e; ++i) { if (i != 0) O << ", "; O << getQualifiedName(RegList->getElementAsRecord(i)); } O << "\n" << IndentStr << "};\n"; O << IndentStr << "static const unsigned RegList" << ShadowRegListNumber << "[] = {\n"; O << IndentStr << " "; for (unsigned i = 0, e = ShadowRegList->getSize(); i != e; ++i) { if (i != 0) O << ", "; O << getQualifiedName(ShadowRegList->getElementAsRecord(i)); } O << "\n" << IndentStr << "};\n"; O << IndentStr << "if (unsigned Reg = State.AllocateReg(RegList" << RegListNumber << ", " << "RegList" << ShadowRegListNumber << ", " << RegList->getSize() << ")) {\n"; } O << IndentStr << " State.addLoc(CCValAssign::getReg(ValNo, ValVT, " << "Reg, LocVT, LocInfo));\n"; O << IndentStr << " return false;\n"; O << IndentStr << "}\n"; } else if (Action->isSubClassOf("CCAssignToStack")) { int Size = Action->getValueAsInt("Size"); int Align = Action->getValueAsInt("Align"); O << IndentStr << "unsigned Offset" << ++Counter << " = State.AllocateStack("; if (Size) O << Size << ", "; else O << "\n" << IndentStr << " State.getTarget().getTargetData()" "->getTypePaddedSize(LocVT.getTypeForMVT()), "; if (Align) O << Align; else O << "\n" << IndentStr << " State.getTarget().getTargetData()" "->getABITypeAlignment(LocVT.getTypeForMVT())"; O << ");\n" << IndentStr << "State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset" << Counter << ", LocVT, LocInfo));\n"; O << IndentStr << "return false;\n"; } else if (Action->isSubClassOf("CCPromoteToType")) { Record *DestTy = Action->getValueAsDef("DestTy"); O << IndentStr << "LocVT = " << getEnumName(getValueType(DestTy)) <<";\n"; O << IndentStr << "if (ArgFlags.isSExt())\n" << IndentStr << IndentStr << "LocInfo = CCValAssign::SExt;\n" << IndentStr << "else if (ArgFlags.isZExt())\n" << IndentStr << IndentStr << "LocInfo = CCValAssign::ZExt;\n" << IndentStr << "else\n" << IndentStr << IndentStr << "LocInfo = CCValAssign::AExt;\n"; } else if (Action->isSubClassOf("CCBitConvertToType")) { Record *DestTy = Action->getValueAsDef("DestTy"); O << IndentStr << "LocVT = " << getEnumName(getValueType(DestTy)) <<";\n"; O << IndentStr << "LocInfo = CCValAssign::BCvt;\n"; } else if (Action->isSubClassOf("CCPassByVal")) { int Size = Action->getValueAsInt("Size"); int Align = Action->getValueAsInt("Align"); O << IndentStr << "State.HandleByVal(ValNo, ValVT, LocVT, LocInfo, " << Size << ", " << Align << ", ArgFlags);\n"; O << IndentStr << "return false;\n"; } else if (Action->isSubClassOf("CCCustom")) { O << IndentStr << "if (" << Action->getValueAsString("FuncName") << "(ValNo, ValVT, " << "LocVT, LocInfo, ArgFlags, State))\n"; O << IndentStr << IndentStr << "return false;\n"; } else { Action->dump(); throw "Unknown CCAction!"; } } } <|endoftext|>
<commit_before>/* * PerformanceCounter.cpp 10.08.2006 (mueller) * * Copyright (C) 2006 by Universitaet Stuttgart (VIS). Alle Rechte vorbehalten. * Copyright (C) 2005 by Christoph Mueller (christoph.mueller@vis.uni-stuttgart.de). Alle Rechte vorbehalten. */ #ifdef _WIN32 #include <windows.h> #else /* _WIN32 */ #include <sys/time.h> #endif /* _WIN32 */ #include "vislib/assert.h" #include "vislib/memutils.h" #include "vislib/PerformanceCounter.h" #include "vislib/SystemException.h" #include "vislib/Trace.h" /* * vislib::sys::PerformanceCounter::Query */ UINT64 vislib::sys::PerformanceCounter::Query(void) { #ifdef _WIN32 LARGE_INTEGER timerFreq, timerCount; if (!::QueryPerformanceFrequency(&timerFreq)) { TRACE(_T("QueryPerformanceFrequency failed in ") _T("vislib::sys::PerformanceCounter::Query\n")); throw SystemException(::GetLastError(), __FILE__, __LINE__); } if (!::QueryPerformanceCounter(&timerCount)) { TRACE(_T("QueryPerformanceCounter failed in ") _T("vislib::sys::PerformanceCounter::Query\n")); throw SystemException(::GetLastError(), __FILE__, __LINE__); } return (timerCount.QuadPart * 1000) / timerFreq.QuadPart; #else /* _WIN32 */ struct timeval t; ::gettimeofday(&t, NULL); return static_cast<UINT64>((t.tv_sec * 1e6 + t.tv_usec) / 1000.0); #endif /* _WIN32 */ } /* * vislib::sys::PerformanceCounter::operator = */ vislib::sys::PerformanceCounter& vislib::sys::PerformanceCounter::operator =( const PerformanceCounter& rhs) { if (this != &rhs) { this->mark = rhs.mark; } return *this; } <commit_msg>Linux error handling.<commit_after>/* * PerformanceCounter.cpp 10.08.2006 (mueller) * * Copyright (C) 2006 by Universitaet Stuttgart (VIS). Alle Rechte vorbehalten. * Copyright (C) 2005 by Christoph Mueller (christoph.mueller@vis.uni-stuttgart.de). Alle Rechte vorbehalten. */ #ifdef _WIN32 #include <windows.h> #else /* _WIN32 */ #include <sys/time.h> #endif /* _WIN32 */ #include "vislib/assert.h" #include "vislib/error.h" #include "vislib/memutils.h" #include "vislib/PerformanceCounter.h" #include "vislib/SystemException.h" #include "vislib/Trace.h" /* * vislib::sys::PerformanceCounter::Query */ UINT64 vislib::sys::PerformanceCounter::Query(void) { #ifdef _WIN32 LARGE_INTEGER timerFreq, timerCount; if (!::QueryPerformanceFrequency(&timerFreq)) { TRACE(_T("QueryPerformanceFrequency failed in ") _T("vislib::sys::PerformanceCounter::Query\n")); throw SystemException(::GetLastError(), __FILE__, __LINE__); } if (!::QueryPerformanceCounter(&timerCount)) { TRACE(_T("QueryPerformanceCounter failed in ") _T("vislib::sys::PerformanceCounter::Query\n")); throw SystemException(::GetLastError(), __FILE__, __LINE__); } return (timerCount.QuadPart * 1000) / timerFreq.QuadPart; #else /* _WIN32 */ struct timeval t; if (::gettimeofday(&t, NULL) == -1) { throw SystemException(::GetLastError(), __FILE__, __LINE__); } return static_cast<UINT64>((t.tv_sec * 1e6 + t.tv_usec) / 1000.0); #endif /* _WIN32 */ } /* * vislib::sys::PerformanceCounter::operator = */ vislib::sys::PerformanceCounter& vislib::sys::PerformanceCounter::operator =( const PerformanceCounter& rhs) { if (this != &rhs) { this->mark = rhs.mark; } return *this; } <|endoftext|>
<commit_before>// Copyright (c) 2020 The Orbit 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 "OrbitClientModel/CaptureSerializer.h" #include <google/protobuf/io/coded_stream.h> #include <google/protobuf/io/zero_copy_stream_impl.h> #include <google/protobuf/message.h> #include <fstream> #include <memory> #include "Callstack.h" #include "EventTracer.h" #include "FunctionUtils.h" #include "OrbitBase/MakeUniqueForOverwrite.h" #include "OrbitProcess.h" #include "absl/strings/str_format.h" #include "capture_data.pb.h" using orbit_client_protos::CallstackEvent; using orbit_client_protos::CallstackInfo; using orbit_client_protos::CaptureInfo; using orbit_client_protos::FunctionInfo; using orbit_client_protos::FunctionStats; using orbit_client_protos::TimerInfo; void CaptureDeserializer::WriteMessage(const google::protobuf::Message* message, google::protobuf::io::CodedOutputStream* output) { uint32_t message_size = message->ByteSizeLong(); output->WriteLittleEndian32(message_size); message->SerializeToCodedStream(output); } CaptureInfo CaptureDeserializer::GenerateCaptureInfo( const CaptureData& capture_data, const absl::flat_hash_map<uint64_t, std::string>& key_to_string_map) { CaptureInfo capture_info; for (const auto& pair : capture_data.selected_functions()) { capture_info.add_selected_functions()->CopyFrom(pair.second); } capture_info.set_process_id(capture_data.process_id()); capture_info.set_process_name(capture_data.process_name()); capture_info.mutable_thread_names()->insert(capture_data.thread_names().begin(), capture_data.thread_names().end()); capture_info.mutable_address_infos()->Reserve(capture_data.address_infos().size()); for (const auto& address_info : capture_data.address_infos()) { orbit_client_protos::LinuxAddressInfo* added_address_info = capture_info.add_address_infos(); added_address_info->CopyFrom(address_info.second); // Fix names in address infos (some might only be in process): added_address_info->set_function_name( capture_data.GetFunctionNameByAddress(added_address_info->absolute_address())); } const absl::flat_hash_map<uint64_t, FunctionStats>& functions_stats = capture_data.functions_stats(); capture_info.mutable_function_stats()->insert(functions_stats.begin(), functions_stats.end()); // TODO: this is not really synchronized, since GetCallstacks processing below // is not under the same mutex lock we could end up having list of callstacks // inconsistent with unique_callstacks. Revisit sampling profiler data // thread-safety. capture_data.GetCallstackData()->ForEachUniqueCallstack( [&capture_info](const CallStack& call_stack) { CallstackInfo* callstack = capture_info.add_callstacks(); *callstack->mutable_data() = {call_stack.GetFrames().begin(), call_stack.GetFrames().end()}; }); const auto& callstacks = capture_data.GetCallstackData()->callstack_events(); capture_info.mutable_callstack_events()->Reserve(callstacks.size()); for (const auto& callstack : callstacks) { capture_info.add_callstack_events()->CopyFrom(callstack); } capture_info.mutable_key_to_string()->insert(key_to_string_map.begin(), key_to_string_map.end()); return capture_info; } <commit_msg>Ammend comment to match renamed method<commit_after>// Copyright (c) 2020 The Orbit 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 "OrbitClientModel/CaptureSerializer.h" #include <google/protobuf/io/coded_stream.h> #include <google/protobuf/io/zero_copy_stream_impl.h> #include <google/protobuf/message.h> #include <fstream> #include <memory> #include "Callstack.h" #include "EventTracer.h" #include "FunctionUtils.h" #include "OrbitBase/MakeUniqueForOverwrite.h" #include "OrbitProcess.h" #include "absl/strings/str_format.h" #include "capture_data.pb.h" using orbit_client_protos::CallstackEvent; using orbit_client_protos::CallstackInfo; using orbit_client_protos::CaptureInfo; using orbit_client_protos::FunctionInfo; using orbit_client_protos::FunctionStats; using orbit_client_protos::TimerInfo; void CaptureDeserializer::WriteMessage(const google::protobuf::Message* message, google::protobuf::io::CodedOutputStream* output) { uint32_t message_size = message->ByteSizeLong(); output->WriteLittleEndian32(message_size); message->SerializeToCodedStream(output); } CaptureInfo CaptureDeserializer::GenerateCaptureInfo( const CaptureData& capture_data, const absl::flat_hash_map<uint64_t, std::string>& key_to_string_map) { CaptureInfo capture_info; for (const auto& pair : capture_data.selected_functions()) { capture_info.add_selected_functions()->CopyFrom(pair.second); } capture_info.set_process_id(capture_data.process_id()); capture_info.set_process_name(capture_data.process_name()); capture_info.mutable_thread_names()->insert(capture_data.thread_names().begin(), capture_data.thread_names().end()); capture_info.mutable_address_infos()->Reserve(capture_data.address_infos().size()); for (const auto& address_info : capture_data.address_infos()) { orbit_client_protos::LinuxAddressInfo* added_address_info = capture_info.add_address_infos(); added_address_info->CopyFrom(address_info.second); // Fix names in address infos (some might only be in process): added_address_info->set_function_name( capture_data.GetFunctionNameByAddress(added_address_info->absolute_address())); } const absl::flat_hash_map<uint64_t, FunctionStats>& functions_stats = capture_data.functions_stats(); capture_info.mutable_function_stats()->insert(functions_stats.begin(), functions_stats.end()); // TODO: this is not really synchronized, since GetCallstackData processing below is not under the // same mutex lock we could end up having list of callstacks inconsistent with unique_callstacks. // Revisit sampling profiler data thread-safety. capture_data.GetCallstackData()->ForEachUniqueCallstack( [&capture_info](const CallStack& call_stack) { CallstackInfo* callstack = capture_info.add_callstacks(); *callstack->mutable_data() = {call_stack.GetFrames().begin(), call_stack.GetFrames().end()}; }); const auto& callstacks = capture_data.GetCallstackData()->callstack_events(); capture_info.mutable_callstack_events()->Reserve(callstacks.size()); for (const auto& callstack : callstacks) { capture_info.add_callstack_events()->CopyFrom(callstack); } capture_info.mutable_key_to_string()->insert(key_to_string_map.begin(), key_to_string_map.end()); return capture_info; } <|endoftext|>
<commit_before>// ////////////////////////////////////////////////////////////////////// // Import section // ////////////////////////////////////////////////////////////////////// // STL #include <cassert> #include <sstream> // StdAir #include <stdair/STDAIR_Service.hpp> // AirSched #include <airsched/basic/BasConst_AIRSCHED_Service.hpp> #include <airsched/service/AIRSCHED_ServiceContext.hpp> namespace AIRSCHED { // ////////////////////////////////////////////////////////////////////// AIRSCHED_ServiceContext::AIRSCHED_ServiceContext() : _ownStdairService (false) { } // ////////////////////////////////////////////////////////////////////// AIRSCHED_ServiceContext:: AIRSCHED_ServiceContext (const AIRSCHED_ServiceContext&) { assert (false); } // ////////////////////////////////////////////////////////////////////// AIRSCHED_ServiceContext::~AIRSCHED_ServiceContext() { } // //////////////////////////////////////////////////////////////////// stdair::STDAIR_Service& AIRSCHED_ServiceContext::getSTDAIR_Service() const { assert (_stdairService != NULL); return *_stdairService; } // ////////////////////////////////////////////////////////////////////// const std::string AIRSCHED_ServiceContext::shortDisplay() const { std::ostringstream oStr; oStr << "AIRSCHED_ServiceContext -- Owns StdAir service: " << _ownStdairService; return oStr.str(); } // ////////////////////////////////////////////////////////////////////// const std::string AIRSCHED_ServiceContext::display() const { std::ostringstream oStr; oStr << shortDisplay(); return oStr.str(); } // ////////////////////////////////////////////////////////////////////// const std::string AIRSCHED_ServiceContext::describe() const { return shortDisplay(); } // //////////////////////////////////////////////////////////////////// void AIRSCHED_ServiceContext::reset() { if (_ownStdairService == true) { _stdairService.reset(); } } } <commit_msg>[Dev] Reset the stdair service shared pointer in order to decrease the count by one every time (and not only when owning the stdair service).<commit_after>// ////////////////////////////////////////////////////////////////////// // Import section // ////////////////////////////////////////////////////////////////////// // STL #include <cassert> #include <sstream> // StdAir #include <stdair/STDAIR_Service.hpp> // AirSched #include <airsched/basic/BasConst_AIRSCHED_Service.hpp> #include <airsched/service/AIRSCHED_ServiceContext.hpp> namespace AIRSCHED { // ////////////////////////////////////////////////////////////////////// AIRSCHED_ServiceContext::AIRSCHED_ServiceContext() : _ownStdairService (false) { } // ////////////////////////////////////////////////////////////////////// AIRSCHED_ServiceContext:: AIRSCHED_ServiceContext (const AIRSCHED_ServiceContext&) { assert (false); } // ////////////////////////////////////////////////////////////////////// AIRSCHED_ServiceContext::~AIRSCHED_ServiceContext() { } // //////////////////////////////////////////////////////////////////// stdair::STDAIR_Service& AIRSCHED_ServiceContext::getSTDAIR_Service() const { assert (_stdairService != NULL); return *_stdairService; } // ////////////////////////////////////////////////////////////////////// const std::string AIRSCHED_ServiceContext::shortDisplay() const { std::ostringstream oStr; oStr << "AIRSCHED_ServiceContext -- Owns StdAir service: " << _ownStdairService; return oStr.str(); } // ////////////////////////////////////////////////////////////////////// const std::string AIRSCHED_ServiceContext::display() const { std::ostringstream oStr; oStr << shortDisplay(); return oStr.str(); } // ////////////////////////////////////////////////////////////////////// const std::string AIRSCHED_ServiceContext::describe() const { return shortDisplay(); } // //////////////////////////////////////////////////////////////////// void AIRSCHED_ServiceContext::reset() { // The shared_ptr<>::reset() method drops the refcount by one. // If the count result is dropping to zero, the resource pointed to // by the shared_ptr<> will be freed. // Reset the stdair shared pointer _stdairService.reset(); } } <|endoftext|>
<commit_before>// // splitter_dbs.cc // P2PSP // // This code is distributed under the GNU General Public License (see // THE_GENERAL_GNU_PUBLIC_LICENSE.txt for extending this information). // Copyright (C) 2016, the P2PSP team. // http://www.p2psp.org // // DBS: Data Broadcasting Set of rules // #include "splitter_dbs.h" #include "../util/trace.h" namespace p2psp { using namespace std; using namespace boost; const int SplitterDBS::kMaxChunkLoss = 32; // Chunk losses threshold to reject a peer from the team const int SplitterDBS::kMonitorNumber = 1; SplitterDBS::SplitterDBS() : SplitterIMS(), losses_(0, &SplitterDBS::GetHash) { // TODO: Check if there is a better way to replace kMcastAddr with 0.0.0.0 mcast_addr_ = "0.0.0.0"; max_number_of_chunk_loss_ = kMaxChunkLoss; max_number_of_monitors_ = kMonitorNumber; peer_number_ = 0; destination_of_chunk_.reserve(buffer_size_); magic_flags_ = Common::kDBS; TRACE("max_number_of_chunk_loss = " << max_number_of_chunk_loss_); TRACE("mcast_addr = " << mcast_addr_); TRACE("Initialized DBS"); } SplitterDBS::~SplitterDBS() {} char SplitterDBS::GetMagicFlags() { return magic_flags_; } void SplitterDBS::SendMagicFlags( const std::shared_ptr<boost::asio::ip::tcp::socket> &peer_serve_socket) { char message[1]; message[0] = magic_flags_; peer_serve_socket->send(asio::buffer(message)); LOG("Magic flags = " << bitset<8>(message[0])); } void SplitterDBS::SendTheListSize( const std::shared_ptr<boost::asio::ip::tcp::socket> &peer_serve_socket) { char message[2]; TRACE("Sending the number of monitors " << max_number_of_monitors_); (*(uint16_t *)&message) = htons(max_number_of_monitors_); peer_serve_socket->send(asio::buffer(message)); TRACE("Sending a list of peers of size " << to_string(peer_list_.size())); (*(uint16_t *)&message) = htons(peer_list_.size()); peer_serve_socket->send(asio::buffer(message)); } void SplitterDBS::SendTheListOfPeers( const std::shared_ptr<boost::asio::ip::tcp::socket> &peer_serve_socket) { SendTheListSize(peer_serve_socket); int counter = 0; char message[6]; in_addr addr; for (std::vector<asio::ip::udp::endpoint>::iterator it = peer_list_.begin(); it != peer_list_.end(); ++it) { inet_aton(it->address().to_string().c_str(), &addr); (*(in_addr *)&message) = addr; (*(uint16_t *)(message + 4)) = htons(it->port()); peer_serve_socket->send(asio::buffer(message)); TRACE(to_string(counter) << ", " << *it); counter++; } } void SplitterDBS::SendThePeerEndpoint( const std::shared_ptr<boost::asio::ip::tcp::socket> &peer_serve_socket) { asio::ip::tcp::endpoint peer_endpoint = peer_serve_socket->remote_endpoint(); char message[6]; in_addr addr; inet_aton(peer_endpoint.address().to_string().c_str(), &addr); (*(in_addr *)&message) = addr; (*(uint16_t *)(message + 4)) = htons(peer_endpoint.port()); peer_serve_socket->send(asio::buffer(message)); } void SplitterDBS::SendConfiguration( const std::shared_ptr<boost::asio::ip::tcp::socket> &sock) { SplitterIMS::SendConfiguration(sock); SendThePeerEndpoint(sock); SendMagicFlags(sock); } void SplitterDBS::InsertPeer(const boost::asio::ip::udp::endpoint &peer) { if (find(peer_list_.begin(), peer_list_.end(), peer) != peer_list_.end()) { peer_list_.erase(find(peer_list_.begin(), peer_list_.end(), peer)); } peer_list_.push_back(peer); losses_[peer] = 0; TRACE("Inserted peer " << peer); } void SplitterDBS::HandleAPeerArrival( std::shared_ptr<boost::asio::ip::tcp::socket> serve_socket) { /* In the DBS, the splitter sends to the incomming peer the list of peers. Notice that the transmission of the list of peers (something that could need some time if the team is big or if the peer is slow) is done in a separate thread. This helps to avoid DoS (Denial of Service) attacks. */ asio::ip::tcp::endpoint incoming_peer = serve_socket->remote_endpoint(); TRACE("Accepted connection from peer " << incoming_peer); SendConfiguration(serve_socket); SendTheListOfPeers(serve_socket); serve_socket->close(); InsertPeer(boost::asio::ip::udp::endpoint(incoming_peer.address(), incoming_peer.port())); // TODO: In original code, incoming_peer is returned, but is not used } size_t SplitterDBS::ReceiveMessage(std::vector<char> &message, boost::asio::ip::udp::endpoint &endpoint) { system::error_code ec; size_t bytes_transferred = team_socket_.receive_from(asio::buffer(message), endpoint, 0, ec); if (ec) { ERROR("Unexepected error: " << ec.message()); } return bytes_transferred; } void SplitterDBS::IncrementUnsupportivityOfPeer( const boost::asio::ip::udp::endpoint &peer) { bool peerExists = true; try { losses_[peer] += 1; } catch (std::exception e) { TRACE("The unsupportive peer " << peer << " does not exist!"); peerExists = false; } if (peerExists) { TRACE("" << peer << " has lost " << to_string(losses_[peer]) << " chunks"); if (losses_[peer] > max_number_of_chunk_loss_) { TRACE("" << peer << " removed"); RemovePeer(peer); } } } void SplitterDBS::ProcessLostChunk( int lost_chunk_number, const boost::asio::ip::udp::endpoint &sender) { asio::ip::udp::endpoint destination = GetLosser(lost_chunk_number); TRACE("" << sender << " complains about lost chunk " << to_string(lost_chunk_number) << " sent to " << destination); if (find(peer_list_.begin() + max_number_of_monitors_, peer_list_.end(), destination) != peer_list_.end()) { TRACE("Lost chunk index = " << lost_chunk_number); } IncrementUnsupportivityOfPeer(destination); } uint16_t SplitterDBS::GetLostChunkNumber(const std::vector<char> &message) { // TODO: Check if this is totally correct return ntohs(*(uint16_t *)message.data()); } asio::ip::udp::endpoint SplitterDBS::GetLosser(int lost_chunk_number) { return destination_of_chunk_[lost_chunk_number % buffer_size_]; } void SplitterDBS::RemovePeer(const asio::ip::udp::endpoint &peer) { // If peer_list_ contains the peer, remove it if (find(peer_list_.begin(), peer_list_.end(), peer) != peer_list_.end()) { peer_list_.erase(remove(peer_list_.begin(), peer_list_.end(), peer), peer_list_.end()); // In order to avoid negative peer_number_ value while peer_list_ still // contains any peer (in Python this is not necessary because negative // indexes can be used) if (peer_list_.size() > 0) { peer_number_ = (peer_number_ - 1) % peer_list_.size(); } else { peer_number_--; } } losses_.erase(peer); } void SplitterDBS::ProcessGoodbye(const boost::asio::ip::udp::endpoint &peer) { TRACE("Received 'goodbye' from " << peer); // TODO: stdout flush? RemovePeer(peer); } void SplitterDBS::ModerateTheTeam() { std::vector<char> message(2); asio::ip::udp::endpoint sender; while (alive_) { size_t bytes_transferred = ReceiveMessage(message, sender); if (bytes_transferred == 2) { /* The peer complains about a lost chunk. In this situation, the splitter counts the number of complains. If this number exceeds a threshold, the unsupportive peer is expelled from the team. */ uint16_t lost_chunk_number = GetLostChunkNumber(message); ProcessLostChunk(lost_chunk_number, sender); } else { /* The peer wants to leave the team. A !2-length payload means that the peer wants to go away. */ ProcessGoodbye(sender); } } } void SplitterDBS::SetupTeamSocket() { system::error_code ec; asio::ip::udp::endpoint endpoint(asio::ip::udp::v4(), team_port_); team_socket_.open(asio::ip::udp::v4()); asio::socket_base::reuse_address reuseAddress(true); team_socket_.set_option(reuseAddress, ec); team_socket_.bind(endpoint); if (ec) { ERROR(ec.message()); } } void SplitterDBS::ResetCounters() { unordered::unordered_map<asio::ip::udp::endpoint, int>::iterator it; for (it = losses_.begin(); it != losses_.end(); ++it) { losses_[it->first] = it->second / 2; } } void SplitterDBS::ResetCountersThread() { while (alive_) { ResetCounters(); this_thread::sleep(posix_time::seconds(Common::kCountersTiming)); } } void SplitterDBS::ComputeNextPeerNumber(asio::ip::udp::endpoint &peer) { peer_number_ = (peer_number_ + 1) % peer_list_.size(); } void SplitterDBS::Run() { ReceiveTheHeader(); /* A DBS splitter runs 4 threads. The main one and the "handle_arrivals" thread are equivalent to the daemons used by the IMS splitter. "moderate_the_team" and "reset_counters_thread" are new. */ TRACE("waiting for the monitor peers ..."); std::shared_ptr<asio::ip::tcp::socket> connection = make_shared<asio::ip::tcp::socket>(boost::ref(io_service_)); acceptor_.accept(*connection); HandleAPeerArrival(connection); // Threads thread t1(bind(&SplitterIMS::HandleArrivals, this)); thread t2(bind(&SplitterDBS::ModerateTheTeam, this)); thread t3(bind(&SplitterDBS::ResetCountersThread, this)); vector<char> message(sizeof(uint16_t) + chunk_size_); asio::ip::udp::endpoint peer; while (alive_) { asio::streambuf chunk; size_t bytes_transferred = ReceiveChunk(chunk); try { peer = peer_list_.at(peer_number_); (*(uint16_t *)message.data()) = htons(chunk_number_); copy(asio::buffer_cast<const char *>(chunk.data()), asio::buffer_cast<const char *>(chunk.data()) + chunk.size(), message.data() + sizeof(uint16_t)); SendChunk(message, peer); destination_of_chunk_[chunk_number_ % buffer_size_] = peer; chunk_number_ = (chunk_number_ + 1) % Common::kMaxChunkNumber; ComputeNextPeerNumber(peer); } catch (const std::out_of_range &oor) { TRACE("The monitor peer has died!"); exit(-1); } chunk.consume(bytes_transferred); } } std::vector<boost::asio::ip::udp::endpoint> SplitterDBS::GetPeerList() { return peer_list_; } int SplitterDBS::GetLoss(const boost::asio::ip::udp::endpoint &peer) { return losses_[peer]; } void SplitterDBS::SetMaxNumberOfChunkLoss(int max_number_of_chunk_loss) { max_number_of_chunk_loss_ = max_number_of_chunk_loss; } int SplitterDBS::GetMaxNumberOfChunkLoss() { return max_number_of_chunk_loss_; } void SplitterDBS::SetMaxNumberOfMonitors(int max_number_of_monitors) { max_number_of_monitors_ = max_number_of_monitors; } int SplitterDBS::GetMaxNumberOfMonitors() { return max_number_of_monitors_; } void SplitterDBS::Start() { TRACE("Start"); thread_.reset(new boost::thread(boost::bind(&SplitterDBS::Run, this))); } int SplitterDBS::GetDefaultMaxNumberOfChunkLoss() { return kMaxChunkLoss; } int SplitterDBS::GetDefaultMaxNumberOfMonitors() { return kMonitorNumber; } } <commit_msg>Write chunk data to file<commit_after>// // splitter_dbs.cc // P2PSP // // This code is distributed under the GNU General Public License (see // THE_GENERAL_GNU_PUBLIC_LICENSE.txt for extending this information). // Copyright (C) 2016, the P2PSP team. // http://www.p2psp.org // // DBS: Data Broadcasting Set of rules // #include "splitter_dbs.h" #include "../util/trace.h" #include <fstream> #include <cstdlib> #include <iterator> #include <boost/lexical_cast.hpp> using boost::lexical_cast; #include <boost/uuid/uuid.hpp> using boost::uuids::uuid; #include <boost/uuid/uuid_generators.hpp> using boost::uuids::random_generator; #include <boost/uuid/uuid_io.hpp> namespace p2psp { using namespace std; using namespace boost; const int SplitterDBS::kMaxChunkLoss = 32; // Chunk losses threshold to reject a peer from the team const int SplitterDBS::kMonitorNumber = 1; SplitterDBS::SplitterDBS() : SplitterIMS(), losses_(0, &SplitterDBS::GetHash) { // TODO: Check if there is a better way to replace kMcastAddr with 0.0.0.0 mcast_addr_ = "0.0.0.0"; max_number_of_chunk_loss_ = kMaxChunkLoss; max_number_of_monitors_ = kMonitorNumber; peer_number_ = 0; destination_of_chunk_.reserve(buffer_size_); magic_flags_ = Common::kDBS; TRACE("max_number_of_chunk_loss = " << max_number_of_chunk_loss_); TRACE("mcast_addr = " << mcast_addr_); TRACE("Initialized DBS"); } SplitterDBS::~SplitterDBS() {} char SplitterDBS::GetMagicFlags() { return magic_flags_; } void SplitterDBS::SendMagicFlags( const std::shared_ptr<boost::asio::ip::tcp::socket> &peer_serve_socket) { char message[1]; message[0] = magic_flags_; peer_serve_socket->send(asio::buffer(message)); LOG("Magic flags = " << bitset<8>(message[0])); } void SplitterDBS::SendTheListSize( const std::shared_ptr<boost::asio::ip::tcp::socket> &peer_serve_socket) { char message[2]; TRACE("Sending the number of monitors " << max_number_of_monitors_); (*(uint16_t *)&message) = htons(max_number_of_monitors_); peer_serve_socket->send(asio::buffer(message)); TRACE("Sending a list of peers of size " << to_string(peer_list_.size())); (*(uint16_t *)&message) = htons(peer_list_.size()); peer_serve_socket->send(asio::buffer(message)); } void SplitterDBS::SendTheListOfPeers( const std::shared_ptr<boost::asio::ip::tcp::socket> &peer_serve_socket) { SendTheListSize(peer_serve_socket); int counter = 0; char message[6]; in_addr addr; for (std::vector<asio::ip::udp::endpoint>::iterator it = peer_list_.begin(); it != peer_list_.end(); ++it) { inet_aton(it->address().to_string().c_str(), &addr); (*(in_addr *)&message) = addr; (*(uint16_t *)(message + 4)) = htons(it->port()); peer_serve_socket->send(asio::buffer(message)); TRACE(to_string(counter) << ", " << *it); counter++; } } void SplitterDBS::SendThePeerEndpoint( const std::shared_ptr<boost::asio::ip::tcp::socket> &peer_serve_socket) { asio::ip::tcp::endpoint peer_endpoint = peer_serve_socket->remote_endpoint(); char message[6]; in_addr addr; inet_aton(peer_endpoint.address().to_string().c_str(), &addr); (*(in_addr *)&message) = addr; (*(uint16_t *)(message + 4)) = htons(peer_endpoint.port()); peer_serve_socket->send(asio::buffer(message)); } void SplitterDBS::SendConfiguration( const std::shared_ptr<boost::asio::ip::tcp::socket> &sock) { SplitterIMS::SendConfiguration(sock); SendThePeerEndpoint(sock); SendMagicFlags(sock); } void SplitterDBS::InsertPeer(const boost::asio::ip::udp::endpoint &peer) { if (find(peer_list_.begin(), peer_list_.end(), peer) != peer_list_.end()) { peer_list_.erase(find(peer_list_.begin(), peer_list_.end(), peer)); } peer_list_.push_back(peer); losses_[peer] = 0; TRACE("Inserted peer " << peer); } void SplitterDBS::HandleAPeerArrival( std::shared_ptr<boost::asio::ip::tcp::socket> serve_socket) { /* In the DBS, the splitter sends to the incomming peer the list of peers. Notice that the transmission of the list of peers (something that could need some time if the team is big or if the peer is slow) is done in a separate thread. This helps to avoid DoS (Denial of Service) attacks. */ asio::ip::tcp::endpoint incoming_peer = serve_socket->remote_endpoint(); TRACE("Accepted connection from peer " << incoming_peer); SendConfiguration(serve_socket); SendTheListOfPeers(serve_socket); serve_socket->close(); InsertPeer(boost::asio::ip::udp::endpoint(incoming_peer.address(), incoming_peer.port())); // TODO: In original code, incoming_peer is returned, but is not used } size_t SplitterDBS::ReceiveMessage(std::vector<char> &message, boost::asio::ip::udp::endpoint &endpoint) { system::error_code ec; size_t bytes_transferred = team_socket_.receive_from(asio::buffer(message), endpoint, 0, ec); if (ec) { ERROR("Unexepected error: " << ec.message()); } return bytes_transferred; } void SplitterDBS::IncrementUnsupportivityOfPeer( const boost::asio::ip::udp::endpoint &peer) { bool peerExists = true; try { losses_[peer] += 1; } catch (std::exception e) { TRACE("The unsupportive peer " << peer << " does not exist!"); peerExists = false; } if (peerExists) { TRACE("" << peer << " has lost " << to_string(losses_[peer]) << " chunks"); if (losses_[peer] > max_number_of_chunk_loss_) { TRACE("" << peer << " removed"); RemovePeer(peer); } } } void SplitterDBS::ProcessLostChunk( int lost_chunk_number, const boost::asio::ip::udp::endpoint &sender) { asio::ip::udp::endpoint destination = GetLosser(lost_chunk_number); TRACE("" << sender << " complains about lost chunk " << to_string(lost_chunk_number) << " sent to " << destination); if (find(peer_list_.begin() + max_number_of_monitors_, peer_list_.end(), destination) != peer_list_.end()) { TRACE("Lost chunk index = " << lost_chunk_number); } IncrementUnsupportivityOfPeer(destination); } uint16_t SplitterDBS::GetLostChunkNumber(const std::vector<char> &message) { // TODO: Check if this is totally correct return ntohs(*(uint16_t *)message.data()); } asio::ip::udp::endpoint SplitterDBS::GetLosser(int lost_chunk_number) { return destination_of_chunk_[lost_chunk_number % buffer_size_]; } void SplitterDBS::RemovePeer(const asio::ip::udp::endpoint &peer) { // If peer_list_ contains the peer, remove it if (find(peer_list_.begin(), peer_list_.end(), peer) != peer_list_.end()) { peer_list_.erase(remove(peer_list_.begin(), peer_list_.end(), peer), peer_list_.end()); // In order to avoid negative peer_number_ value while peer_list_ still // contains any peer (in Python this is not necessary because negative // indexes can be used) if (peer_list_.size() > 0) { peer_number_ = (peer_number_ - 1) % peer_list_.size(); } else { peer_number_--; } } losses_.erase(peer); } void SplitterDBS::ProcessGoodbye(const boost::asio::ip::udp::endpoint &peer) { TRACE("Received 'goodbye' from " << peer); // TODO: stdout flush? RemovePeer(peer); } void SplitterDBS::ModerateTheTeam() { std::vector<char> message(2); asio::ip::udp::endpoint sender; while (alive_) { size_t bytes_transferred = ReceiveMessage(message, sender); if (bytes_transferred == 2) { /* The peer complains about a lost chunk. In this situation, the splitter counts the number of complains. If this number exceeds a threshold, the unsupportive peer is expelled from the team. */ uint16_t lost_chunk_number = GetLostChunkNumber(message); ProcessLostChunk(lost_chunk_number, sender); } else { /* The peer wants to leave the team. A !2-length payload means that the peer wants to go away. */ ProcessGoodbye(sender); } } } void SplitterDBS::SetupTeamSocket() { system::error_code ec; asio::ip::udp::endpoint endpoint(asio::ip::udp::v4(), team_port_); team_socket_.open(asio::ip::udp::v4()); asio::socket_base::reuse_address reuseAddress(true); team_socket_.set_option(reuseAddress, ec); team_socket_.bind(endpoint); if (ec) { ERROR(ec.message()); } } void SplitterDBS::ResetCounters() { unordered::unordered_map<asio::ip::udp::endpoint, int>::iterator it; for (it = losses_.begin(); it != losses_.end(); ++it) { losses_[it->first] = it->second / 2; } } void SplitterDBS::ResetCountersThread() { while (alive_) { ResetCounters(); this_thread::sleep(posix_time::seconds(Common::kCountersTiming)); } } void SplitterDBS::ComputeNextPeerNumber(asio::ip::udp::endpoint &peer) { peer_number_ = (peer_number_ + 1) % peer_list_.size(); } void SplitterDBS::Run() { ReceiveTheHeader(); /* A DBS splitter runs 4 threads. The main one and the "handle_arrivals" thread are equivalent to the daemons used by the IMS splitter. "moderate_the_team" and "reset_counters_thread" are new. */ TRACE("waiting for the monitor peers ..."); std::shared_ptr<asio::ip::tcp::socket> connection = make_shared<asio::ip::tcp::socket>(boost::ref(io_service_)); acceptor_.accept(*connection); HandleAPeerArrival(connection); //File to examine chunk data //string fname = "chunk_output"+to_string(rand()%10+1)+".txt"; string fname = lexical_cast<string>((random_generator())()); fstream file(fname,ios::out); ostream_iterator<char> output_iterator(file); ostream_iterator<char> output_iterator2(file, "\nChunk Number\n"); ostringstream oss,f4b; // Threads thread t1(bind(&SplitterIMS::HandleArrivals, this)); thread t2(bind(&SplitterDBS::ModerateTheTeam, this)); thread t3(bind(&SplitterDBS::ResetCountersThread, this)); vector<char> message(sizeof(uint16_t) + chunk_size_); asio::ip::udp::endpoint peer; while (alive_) { asio::streambuf chunk; size_t bytes_transferred = ReceiveChunk(chunk); try { peer = peer_list_.at(peer_number_); (*(uint16_t *)message.data()) = htons(chunk_number_); copy(asio::buffer_cast<const char *>(chunk.data()), asio::buffer_cast<const char *>(chunk.data()) + chunk.size(), message.data() + sizeof(uint16_t)); size_t len = to_string(chunk_number_).length(); //file<<to_string(chunk_number_).c_str()<<endl; //copy(asio::buffer_cast<const char *>(chunk.data()), //asio::buffer_cast<const char *>(chunk.data()) + 4,ostream_iterator<char>(f4b)); //file << "First 4 bytes of chunk\n"<<f4b.str()<<"\n\n"; //cout<<chunk_number_<<"\n\n"; //*message.data() = ntohs(*message.data()); copy(asio::buffer_cast<const char *>(chunk.data()), asio::buffer_cast<const char *>(chunk.data()) + chunk.size(),ostream_iterator<char>(oss)); file << oss.str(); oss.str("");//f4b.str(""); SendChunk(message, peer); destination_of_chunk_[chunk_number_ % buffer_size_] = peer; chunk_number_ = (chunk_number_ + 1) % Common::kMaxChunkNumber; ComputeNextPeerNumber(peer); } catch (const std::out_of_range &oor) { TRACE("The monitor peer has died!"); file.close(); exit(-1); } chunk.consume(bytes_transferred); } } std::vector<boost::asio::ip::udp::endpoint> SplitterDBS::GetPeerList() { return peer_list_; } int SplitterDBS::GetLoss(const boost::asio::ip::udp::endpoint &peer) { return losses_[peer]; } void SplitterDBS::SetMaxNumberOfChunkLoss(int max_number_of_chunk_loss) { max_number_of_chunk_loss_ = max_number_of_chunk_loss; } int SplitterDBS::GetMaxNumberOfChunkLoss() { return max_number_of_chunk_loss_; } void SplitterDBS::SetMaxNumberOfMonitors(int max_number_of_monitors) { max_number_of_monitors_ = max_number_of_monitors; } int SplitterDBS::GetMaxNumberOfMonitors() { return max_number_of_monitors_; } void SplitterDBS::Start() { TRACE("Start"); thread_.reset(new boost::thread(boost::bind(&SplitterDBS::Run, this))); } int SplitterDBS::GetDefaultMaxNumberOfChunkLoss() { return kMaxChunkLoss; } int SplitterDBS::GetDefaultMaxNumberOfMonitors() { return kMonitorNumber; } } <|endoftext|>
<commit_before>//------------------------------------------------------------------------------ // M6567Window.cc //------------------------------------------------------------------------------ #include "M6567Window.h" #include "IMUI/IMUI.h" #include "Util.h" #include "yakc/util/breadboard.h" using namespace Oryol; namespace YAKC { //------------------------------------------------------------------------------ void M6567Window::Setup(yakc& emu) { this->setName("M6567 (VIC-II) State"); for (int i = 0; i < 16; i++) { this->paletteColors[i] = Util::RGBA8toImVec4(m6567_color(i)); } } //------------------------------------------------------------------------------ void M6567Window::drawColor(const char* text, uint8_t palIndex) { ImGui::Text("%s%02X", text, palIndex); ImGui::SameLine(); ImGui::ColorButton(text, this->paletteColors[palIndex&0xF], ImGuiColorEditFlags_NoAlpha, ImVec2(12, 12)); } //------------------------------------------------------------------------------ static void drawSpriteShifter(const char* label, uint32_t shf) { char str[33] = { }; for (int i = 0; i < 32; i++) { str[i] = (((shf<<i) & (1<<31)) != 0) ? 'X':'.'; } str[32] = 0; ImGui::Text("%s: %s\n", label, str); } //------------------------------------------------------------------------------ #define UINT8_BITS(m) m&(1<<7)?'1':'0',m&(1<<6)?'1':'0',m&(1<<5)?'1':'0',m&(1<<4)?'1':'0',m&(1<<3)?'1':'0',m&(1<<2)?'1':'0',m&(1<<1)?'1':'0',m&(1<<0)?'1':'0' bool M6567Window::Draw(yakc& emu) { ImGui::SetNextWindowSize(ImVec2(380, 460), ImGuiSetCond_Once); if (ImGui::Begin(this->title.AsCStr(), &this->Visible)) { m6567_t& vic = board.m6567; const char* type = "unknown"; switch (vic.type) { case M6567_TYPE_6567R8: type = "6567R8 (NTSC)"; break; case M6567_TYPE_6569: type = "6569 (PAL)"; break; } ImGui::Text("Type: %s", type); ImGui::Checkbox("Debug Visualization", &board.m6567.debug_vis); if (ImGui::CollapsingHeader("Registers", "#vicreg", true, true)) { const auto& r = vic.reg; ImGui::Text("M0XY: %02X %02X M1XY: %02X %02X M2XY: %02X %02X M3XY: %02X %02X", r.mxy[0][0], r.mxy[0][1], r.mxy[1][0], r.mxy[1][1], r.mxy[2][0], r.mxy[2][1], r.mxy[3][0], r.mxy[3][1]); ImGui::Text("M4XY: %02X %02X M5XY: %02X %02X M6XY: %02X %02X M7XY: %02X %02X", r.mxy[4][0], r.mxy[4][1], r.mxy[5][0], r.mxy[6][1], r.mxy[6][0], r.mxy[6][1], r.mxy[7][0], r.mxy[7][1]); ImGui::Text("CTRL1 RST8:%c ECM:%c BMM:%c DEN:%c RSEL:%c YSCROLL:%d\n", r.ctrl_1 & (1<<7) ? '1':'0', r.ctrl_1 & (1<<6) ? '1':'0', r.ctrl_1 & (1<<5) ? '1':'0', r.ctrl_1 & (1<<4) ? '1':'0', r.ctrl_1 & (1<<3) ? '1':'0', r.ctrl_1 & 7); ImGui::Text("MSBX: %c%c%c%c%c%c%c%c RASTER: %02X LPX: %02X LPY: %02X", UINT8_BITS(r.mx8), r.raster, r.lightpen_xy[0], r.lightpen_xy[1]); ImGui::Text("ME: %c%c%c%c%c%c%c%c", UINT8_BITS(r.me)); ImGui::Text("CTRL2 RES:%c MCM:%c CSEL:%c XSCROLL:%d", r.ctrl_2 & (1<<5) ? '1':'0', r.ctrl_2 & (1<<4) ? '1':'0', r.ctrl_2 & (1<<3) ? '1':'0', r.ctrl_2 & 7); ImGui::Text("MYE: %c%c%c%c%c%c%c%c", UINT8_BITS(r.mye)); ImGui::Text("MEMPTRS VM:%02X CB:%02X", (r.mem_ptrs>>4)&0x0F, (r.mem_ptrs>>1)&0x07); ImGui::Text("INT IRQ:%c ILP:%c IMMC:%c IMBC:%c IRST:%c", r.int_latch & (1<<7) ? '1':'0', r.int_latch & (1<<3) ? '1':'0', r.int_latch & (1<<2) ? '1':'0', r.int_latch & (1<<1) ? '1':'0', r.int_latch & (1<<0) ? '1':'0'); ImGui::Text("INT MASK ELP:%c EMMC:%c EMBC:%c ERST:%c", r.int_mask & (1<<3) ? '1':'0', r.int_mask & (1<<2) ? '1':'0', r.int_mask & (1<<1) ? '1':'0', r.int_mask & (1<<0) ? '1':'0'); ImGui::Text("MDP: %c%c%c%c%c%c%c%c MMC: %c%c%c%c%c%c%c%c", UINT8_BITS(r.mob_data_priority), UINT8_BITS(r.mmc)); ImGui::Text("MXE: %c%c%c%c%c%c%c%c", UINT8_BITS(r.mxe)); ImGui::Text("MCM: %c%c%c%c%c%c%c%c MDM: %c%c%c%c%c%c%c%c", UINT8_BITS(r.mob_mob_coll), UINT8_BITS(r.mob_data_coll)); this->drawColor("EC: ", r.ec); this->drawColor("B0C: ", r.bc[0]); ImGui::SameLine(); this->drawColor("B1C: ", r.bc[1]); ImGui::SameLine(); this->drawColor("B2C: ", r.bc[2]); ImGui::SameLine(); this->drawColor("B3C: ", r.bc[3]); this->drawColor("MM0: ", r.mm[0]); ImGui::SameLine(); this->drawColor("MM1: ", r.mm[1]); this->drawColor("M0C: ", r.mc[0]); ImGui::SameLine(); this->drawColor("M1C: ", r.mc[1]); ImGui::SameLine(); this->drawColor("M2C: ", r.mc[2]); ImGui::SameLine(); this->drawColor("M3C: ", r.mc[3]); this->drawColor("M4C: ", r.mc[4]); ImGui::SameLine(); this->drawColor("M5C: ", r.mc[5]); ImGui::SameLine(); this->drawColor("M6C: ", r.mc[6]); ImGui::SameLine(); this->drawColor("M7C: ", r.mc[7]); } if (ImGui::CollapsingHeader("Sprite Units", "#sprite", true, false)) { for (int i = 0; i < 8; i++) { ImGui::PushID(i); static const char* labels[8] = { "Sprite Unit 0", "Sprite Unit 1", "Sprite Unit 2", "Sprite Unit 3", "Sprite Unit 4", "Sprite Unit 5", "Sprite Unit 6", "Sprite Unit 7", }; if (ImGui::CollapsingHeader(labels[i], "#sprite", true, false)) { const auto& su = vic.sunit[i]; ImGui::Text("h_first/last/offset: %2d <=> %2d, %d", su.h_first, su.h_last, su.h_offset); ImGui::Text("p_data: %02X", su.p_data); ImGui::SameLine(); ImGui::Text("mc: %02X", su.mc); ImGui::SameLine(); ImGui::Text("mc_base: %02X", su.mc_base); ImGui::Text("dma_enabled: %s", su.dma_enabled ? "ON ":"OFF"); ImGui::SameLine(); ImGui::Text("disp_enabled: %s", su.disp_enabled ? "ON ":"OFF"); ImGui::SameLine(); ImGui::Text("expand: %s", su.expand ? "ON":"OFF"); drawSpriteShifter("shifter", su.shift); } ImGui::PopID(); } } if (ImGui::CollapsingHeader("Internal State", "#vicstate", true, true)) { ImGui::Text("g_mode: %d v_irq_line: %3d\n", vic.gunit.mode, vic.rs.v_irqline); ImGui::Text("h_count: %2d v_count: %3d", vic.rs.h_count, vic.rs.v_count); ImGui::Text("vc: %04X: vcbase: %04X rc: %d vmli: %2d", vic.rs.vc, vic.rs.vc_base, vic.rs.rc, vic.vm.vmli); ImGui::Text("c_addr_or: %04X i_addr: %04X", vic.mem.c_addr_or, vic.mem.i_addr); ImGui::Text("g_addr_or: %04X g_addr_and: %04X",vic.mem.g_addr_or, vic.mem.g_addr_and); ImGui::Text("brd_left: %2d brd_top: %3d", vic.brd.left, vic.brd.top); ImGui::Text("brd_right: %2d brd_btm: %3d", vic.brd.right, vic.brd.bottom); ImGui::Text("m_border: %s v_border: %s", vic.brd.main?"ON ":"OFF", vic.brd.vert?"ON ":"OFF"); ImGui::Text("badline: %s display: %s", vic.rs.badline?"ON ":"OFF", vic.rs.display_state?"ON ":"OFF"); ImGui::Text("crt_x: %2d crt_y: %3d", vic.crt.x, vic.crt.y); ImGui::Text("line buffer:"); const uint16_t* l = vic.vm.line; ImGui::Text(" %03X %03X %03X %03X %03X %03X %03X %03X %03X %03X\n" " %03X %03X %03X %03X %03X %03X %03X %03X %03X %03X\n" " %03X %03X %03X %03X %03X %03X %03X %03X %03X %03X\n" " %03X %03X %03X %03X %03X %03X %03X %03X %03X %03X", l[ 0], l[ 1], l[ 2], l[ 3], l[ 4], l[ 5], l[ 6], l[ 7], l[ 8], l[ 9], l[10], l[11], l[12], l[13], l[14], l[15], l[16], l[17], l[18], l[19], l[20], l[21], l[22], l[23], l[24], l[25], l[26], l[27], l[28], l[29], l[30], l[31], l[32], l[33], l[34], l[35], l[36], l[37], l[38], l[39]); } if (board.dbg.break_stopped()) { ImGui::Separator(); if (ImGui::Button(">| Bad")) { this->badline = vic.rs.badline; emu.step_until([this](uint32_t ticks)->bool { bool cur_badline = board.m6567.rs.badline; bool triggered = (cur_badline != this->badline) && cur_badline; this->badline = cur_badline; return (ticks > (64*312)) || triggered; }); } if (ImGui::IsItemHovered()) { ImGui::SetTooltip("Run to next badline"); } } } ImGui::End(); return this->Visible; } } // namespace YAKC <commit_msg>fixes for m6567 changes<commit_after>//------------------------------------------------------------------------------ // M6567Window.cc //------------------------------------------------------------------------------ #include "M6567Window.h" #include "IMUI/IMUI.h" #include "Util.h" #include "yakc/util/breadboard.h" using namespace Oryol; namespace YAKC { //------------------------------------------------------------------------------ void M6567Window::Setup(yakc& emu) { this->setName("M6567 (VIC-II) State"); for (int i = 0; i < 16; i++) { this->paletteColors[i] = Util::RGBA8toImVec4(m6567_color(i)); } } //------------------------------------------------------------------------------ void M6567Window::drawColor(const char* text, uint8_t palIndex) { ImGui::Text("%s%02X", text, palIndex); ImGui::SameLine(); ImGui::ColorButton(text, this->paletteColors[palIndex&0xF], ImGuiColorEditFlags_NoAlpha, ImVec2(12, 12)); } //------------------------------------------------------------------------------ static void drawSpriteShifter(const char* label, uint32_t shf) { char str[33] = { }; for (int i = 0; i < 32; i++) { str[i] = (((shf<<i) & (1<<31)) != 0) ? 'X':'.'; } str[32] = 0; ImGui::Text("%s: %s\n", label, str); } //------------------------------------------------------------------------------ #define UINT8_BITS(m) m&(1<<7)?'1':'0',m&(1<<6)?'1':'0',m&(1<<5)?'1':'0',m&(1<<4)?'1':'0',m&(1<<3)?'1':'0',m&(1<<2)?'1':'0',m&(1<<1)?'1':'0',m&(1<<0)?'1':'0' bool M6567Window::Draw(yakc& emu) { ImGui::SetNextWindowSize(ImVec2(380, 460), ImGuiSetCond_Once); if (ImGui::Begin(this->title.AsCStr(), &this->Visible)) { m6567_t& vic = board.m6567; const char* type = "unknown"; switch (vic.type) { case M6567_TYPE_6567R8: type = "6567R8 (NTSC)"; break; case M6567_TYPE_6569: type = "6569 (PAL)"; break; } ImGui::Text("Type: %s", type); ImGui::Checkbox("Debug Visualization", &board.m6567.debug_vis); if (ImGui::CollapsingHeader("Registers", "#vicreg", true, true)) { const auto& r = vic.reg; ImGui::Text("M0XY: %02X %02X M1XY: %02X %02X M2XY: %02X %02X M3XY: %02X %02X", r.mxy[0][0], r.mxy[0][1], r.mxy[1][0], r.mxy[1][1], r.mxy[2][0], r.mxy[2][1], r.mxy[3][0], r.mxy[3][1]); ImGui::Text("M4XY: %02X %02X M5XY: %02X %02X M6XY: %02X %02X M7XY: %02X %02X", r.mxy[4][0], r.mxy[4][1], r.mxy[5][0], r.mxy[6][1], r.mxy[6][0], r.mxy[6][1], r.mxy[7][0], r.mxy[7][1]); ImGui::Text("CTRL1 RST8:%c ECM:%c BMM:%c DEN:%c RSEL:%c YSCROLL:%d\n", r.ctrl_1 & (1<<7) ? '1':'0', r.ctrl_1 & (1<<6) ? '1':'0', r.ctrl_1 & (1<<5) ? '1':'0', r.ctrl_1 & (1<<4) ? '1':'0', r.ctrl_1 & (1<<3) ? '1':'0', r.ctrl_1 & 7); ImGui::Text("MSBX: %c%c%c%c%c%c%c%c RASTER: %02X LPX: %02X LPY: %02X", UINT8_BITS(r.mx8), r.raster, r.lightpen_xy[0], r.lightpen_xy[1]); ImGui::Text("ME: %c%c%c%c%c%c%c%c", UINT8_BITS(r.me)); ImGui::Text("CTRL2 RES:%c MCM:%c CSEL:%c XSCROLL:%d", r.ctrl_2 & (1<<5) ? '1':'0', r.ctrl_2 & (1<<4) ? '1':'0', r.ctrl_2 & (1<<3) ? '1':'0', r.ctrl_2 & 7); ImGui::Text("MYE: %c%c%c%c%c%c%c%c", UINT8_BITS(r.mye)); ImGui::Text("MEMPTRS VM:%02X CB:%02X", (r.mem_ptrs>>4)&0x0F, (r.mem_ptrs>>1)&0x07); ImGui::Text("INT IRQ:%c ILP:%c IMMC:%c IMBC:%c IRST:%c", r.int_latch & (1<<7) ? '1':'0', r.int_latch & (1<<3) ? '1':'0', r.int_latch & (1<<2) ? '1':'0', r.int_latch & (1<<1) ? '1':'0', r.int_latch & (1<<0) ? '1':'0'); ImGui::Text("INT MASK ELP:%c EMMC:%c EMBC:%c ERST:%c", r.int_mask & (1<<3) ? '1':'0', r.int_mask & (1<<2) ? '1':'0', r.int_mask & (1<<1) ? '1':'0', r.int_mask & (1<<0) ? '1':'0'); ImGui::Text("MDP: %c%c%c%c%c%c%c%c MMC: %c%c%c%c%c%c%c%c", UINT8_BITS(r.mdp), UINT8_BITS(r.mmc)); ImGui::Text("MXE: %c%c%c%c%c%c%c%c", UINT8_BITS(r.mxe)); ImGui::Text("MCM: %c%c%c%c%c%c%c%c MDM: %c%c%c%c%c%c%c%c", UINT8_BITS(r.mob_mob_coll), UINT8_BITS(r.mob_data_coll)); this->drawColor("EC: ", r.ec); this->drawColor("B0C: ", r.bc[0]); ImGui::SameLine(); this->drawColor("B1C: ", r.bc[1]); ImGui::SameLine(); this->drawColor("B2C: ", r.bc[2]); ImGui::SameLine(); this->drawColor("B3C: ", r.bc[3]); this->drawColor("MM0: ", r.mm[0]); ImGui::SameLine(); this->drawColor("MM1: ", r.mm[1]); this->drawColor("M0C: ", r.mc[0]); ImGui::SameLine(); this->drawColor("M1C: ", r.mc[1]); ImGui::SameLine(); this->drawColor("M2C: ", r.mc[2]); ImGui::SameLine(); this->drawColor("M3C: ", r.mc[3]); this->drawColor("M4C: ", r.mc[4]); ImGui::SameLine(); this->drawColor("M5C: ", r.mc[5]); ImGui::SameLine(); this->drawColor("M6C: ", r.mc[6]); ImGui::SameLine(); this->drawColor("M7C: ", r.mc[7]); } if (ImGui::CollapsingHeader("Sprite Units", "#sprite", true, false)) { for (int i = 0; i < 8; i++) { ImGui::PushID(i); static const char* labels[8] = { "Sprite Unit 0", "Sprite Unit 1", "Sprite Unit 2", "Sprite Unit 3", "Sprite Unit 4", "Sprite Unit 5", "Sprite Unit 6", "Sprite Unit 7", }; if (ImGui::CollapsingHeader(labels[i], "#sprite", true, false)) { const auto& su = vic.sunit[i]; ImGui::Text("h_first/last/offset: %2d <=> %2d, %d", su.h_first, su.h_last, su.h_offset); ImGui::Text("p_data: %02X", su.p_data); ImGui::SameLine(); ImGui::Text("mc: %02X", su.mc); ImGui::SameLine(); ImGui::Text("mc_base: %02X", su.mc_base); ImGui::Text("dma_enabled: %s", su.dma_enabled ? "ON ":"OFF"); ImGui::SameLine(); ImGui::Text("disp_enabled: %s", su.disp_enabled ? "ON ":"OFF"); ImGui::SameLine(); ImGui::Text("expand: %s", su.expand ? "ON":"OFF"); drawSpriteShifter("shifter", su.shift); } ImGui::PopID(); } } if (ImGui::CollapsingHeader("Internal State", "#vicstate", true, true)) { ImGui::Text("g_mode: %d v_irq_line: %3d\n", vic.gunit.mode, vic.rs.v_irqline); ImGui::Text("h_count: %2d v_count: %3d", vic.rs.h_count, vic.rs.v_count); ImGui::Text("vc: %04X: vcbase: %04X rc: %d vmli: %2d", vic.rs.vc, vic.rs.vc_base, vic.rs.rc, vic.vm.vmli); ImGui::Text("c_addr_or: %04X i_addr: %04X", vic.mem.c_addr_or, vic.mem.i_addr); ImGui::Text("g_addr_or: %04X g_addr_and: %04X",vic.mem.g_addr_or, vic.mem.g_addr_and); ImGui::Text("brd_left: %2d brd_top: %3d", vic.brd.left, vic.brd.top); ImGui::Text("brd_right: %2d brd_btm: %3d", vic.brd.right, vic.brd.bottom); ImGui::Text("m_border: %s v_border: %s", vic.brd.main?"ON ":"OFF", vic.brd.vert?"ON ":"OFF"); ImGui::Text("badline: %s display: %s", vic.rs.badline?"ON ":"OFF", vic.rs.display_state?"ON ":"OFF"); ImGui::Text("crt_x: %2d crt_y: %3d", vic.crt.x, vic.crt.y); ImGui::Text("line buffer:"); const uint16_t* l = vic.vm.line; ImGui::Text(" %03X %03X %03X %03X %03X %03X %03X %03X %03X %03X\n" " %03X %03X %03X %03X %03X %03X %03X %03X %03X %03X\n" " %03X %03X %03X %03X %03X %03X %03X %03X %03X %03X\n" " %03X %03X %03X %03X %03X %03X %03X %03X %03X %03X", l[ 0], l[ 1], l[ 2], l[ 3], l[ 4], l[ 5], l[ 6], l[ 7], l[ 8], l[ 9], l[10], l[11], l[12], l[13], l[14], l[15], l[16], l[17], l[18], l[19], l[20], l[21], l[22], l[23], l[24], l[25], l[26], l[27], l[28], l[29], l[30], l[31], l[32], l[33], l[34], l[35], l[36], l[37], l[38], l[39]); } if (board.dbg.break_stopped()) { ImGui::Separator(); if (ImGui::Button(">| Bad")) { this->badline = vic.rs.badline; emu.step_until([this](uint32_t ticks)->bool { bool cur_badline = board.m6567.rs.badline; bool triggered = (cur_badline != this->badline) && cur_badline; this->badline = cur_badline; return (ticks > (64*312)) || triggered; }); } if (ImGui::IsItemHovered()) { ImGui::SetTooltip("Run to next badline"); } } } ImGui::End(); return this->Visible; } } // namespace YAKC <|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. // // Note that although this is not a "browser" test, it runs as part of // browser_tests. This is because WebKit does not work properly if it is // shutdown and re-initialized. Since browser_tests runs each test in a // new process, this avoids the problem. #include "chrome/renderer/safe_browsing/phishing_dom_feature_extractor.h" #include "base/callback.h" #include "base/message_loop.h" #include "base/time.h" #include "chrome/renderer/safe_browsing/features.h" #include "chrome/renderer/safe_browsing/mock_feature_extractor_clock.h" #include "chrome/renderer/safe_browsing/render_view_fake_resources_test.h" #include "testing/gmock/include/gmock/gmock.h" using ::testing::ContainerEq; using ::testing::Return; namespace safe_browsing { class PhishingDOMFeatureExtractorTest : public RenderViewFakeResourcesTest { protected: virtual void SetUp() { // Set up WebKit and the RenderView. RenderViewFakeResourcesTest::SetUp(); extractor_.reset(new PhishingDOMFeatureExtractor(view_, &clock_)); } virtual void TearDown() { RenderViewFakeResourcesTest::TearDown(); } // Runs the DOMFeatureExtractor on the RenderView, waiting for the // completion callback. Returns the success boolean from the callback. bool ExtractFeatures(FeatureMap* features) { success_ = false; extractor_->ExtractFeatures( features, NewCallback(this, &PhishingDOMFeatureExtractorTest::ExtractionDone)); message_loop_.Run(); return success_; } // Completion callback for feature extraction. void ExtractionDone(bool success) { success_ = success; message_loop_.Quit(); } MockFeatureExtractorClock clock_; scoped_ptr<PhishingDOMFeatureExtractor> extractor_; bool success_; // holds the success value from ExtractFeatures }; TEST_F(PhishingDOMFeatureExtractorTest, FormFeatures) { // This test doesn't exercise the extraction timing. EXPECT_CALL(clock_, Now()).WillRepeatedly(Return(base::TimeTicks::Now())); responses_["http://host.com/"] = "<html><head><body>" "<form action=\"query\"><input type=text><input type=checkbox></form>" "<form action=\"http://cgi.host.com/submit\"></form>" "<form action=\"http://other.com/\"></form>" "<form action=\"query\"></form>" "<form></form></body></html>"; FeatureMap expected_features; expected_features.AddBooleanFeature(features::kPageHasForms); expected_features.AddRealFeature(features::kPageActionOtherDomainFreq, 0.25); expected_features.AddBooleanFeature(features::kPageHasTextInputs); expected_features.AddBooleanFeature(features::kPageHasCheckInputs); FeatureMap features; LoadURL("http://host.com/"); ASSERT_TRUE(ExtractFeatures(&features)); EXPECT_THAT(features.features(), ContainerEq(expected_features.features())); responses_["http://host.com/"] = "<html><head><body>" "<input type=\"radio\"><input type=password></body></html>"; expected_features.Clear(); expected_features.AddBooleanFeature(features::kPageHasRadioInputs); expected_features.AddBooleanFeature(features::kPageHasPswdInputs); features.Clear(); LoadURL("http://host.com/"); ASSERT_TRUE(ExtractFeatures(&features)); EXPECT_THAT(features.features(), ContainerEq(expected_features.features())); responses_["http://host.com/"] = "<html><head><body><input></body></html>"; expected_features.Clear(); expected_features.AddBooleanFeature(features::kPageHasTextInputs); features.Clear(); LoadURL("http://host.com/"); ASSERT_TRUE(ExtractFeatures(&features)); EXPECT_THAT(features.features(), ContainerEq(expected_features.features())); responses_["http://host.com/"] = "<html><head><body><input type=\"invalid\"></body></html>"; expected_features.Clear(); expected_features.AddBooleanFeature(features::kPageHasTextInputs); features.Clear(); LoadURL("http://host.com/"); ASSERT_TRUE(ExtractFeatures(&features)); EXPECT_THAT(features.features(), ContainerEq(expected_features.features())); } TEST_F(PhishingDOMFeatureExtractorTest, LinkFeatures) { // This test doesn't exercise the extraction timing. EXPECT_CALL(clock_, Now()).WillRepeatedly(Return(base::TimeTicks::Now())); responses_["http://www.host.com/"] = "<html><head><body>" "<a href=\"http://www2.host.com/abc\">link</a>" "<a name=page_anchor></a>" "<a href=\"http://www.chromium.org/\">chromium</a>" "</body></html"; FeatureMap expected_features; expected_features.AddRealFeature(features::kPageExternalLinksFreq, 0.5); expected_features.AddRealFeature(features::kPageSecureLinksFreq, 0.0); expected_features.AddBooleanFeature(features::kPageLinkDomain + std::string("chromium.org")); FeatureMap features; LoadURL("http://www.host.com/"); ASSERT_TRUE(ExtractFeatures(&features)); EXPECT_THAT(features.features(), ContainerEq(expected_features.features())); responses_.clear(); responses_["https://www.host.com/"] = "<html><head><body>" "<a href=\"login\">this is secure</a>" "<a href=\"http://host.com\">not secure</a>" "<a href=\"https://www2.host.com/login\">also secure</a>" "<a href=\"http://chromium.org/\">also not secure</a>" "</body></html>"; expected_features.Clear(); expected_features.AddRealFeature(features::kPageExternalLinksFreq, 0.25); expected_features.AddRealFeature(features::kPageSecureLinksFreq, 0.5); expected_features.AddBooleanFeature(features::kPageLinkDomain + std::string("chromium.org")); features.Clear(); LoadURL("https://www.host.com/"); ASSERT_TRUE(ExtractFeatures(&features)); EXPECT_THAT(features.features(), ContainerEq(expected_features.features())); } TEST_F(PhishingDOMFeatureExtractorTest, ScriptAndImageFeatures) { // This test doesn't exercise the extraction timing. EXPECT_CALL(clock_, Now()).WillRepeatedly(Return(base::TimeTicks::Now())); responses_["http://host.com/"] = "<html><head><script></script><script></script></head></html>"; FeatureMap expected_features; expected_features.AddBooleanFeature(features::kPageNumScriptTagsGTOne); FeatureMap features; LoadURL("http://host.com/"); ASSERT_TRUE(ExtractFeatures(&features)); EXPECT_THAT(features.features(), ContainerEq(expected_features.features())); responses_["http://host.com/"] = "<html><head><script></script><script></script><script></script>" "<script></script><script></script><script></script><script></script>" "</head><body><img src=\"blah.gif\">" "<img src=\"http://host2.com/blah.gif\"></body></html>"; expected_features.Clear(); expected_features.AddBooleanFeature(features::kPageNumScriptTagsGTOne); expected_features.AddBooleanFeature(features::kPageNumScriptTagsGTSix); expected_features.AddRealFeature(features::kPageImgOtherDomainFreq, 0.5); features.Clear(); LoadURL("http://host.com/"); ASSERT_TRUE(ExtractFeatures(&features)); EXPECT_THAT(features.features(), ContainerEq(expected_features.features())); } TEST_F(PhishingDOMFeatureExtractorTest, SubFrames) { // This test doesn't exercise the extraction timing. EXPECT_CALL(clock_, Now()).WillRepeatedly(Return(base::TimeTicks::Now())); // Test that features are aggregated across all frames. responses_["http://host.com/"] = "<html><body><input type=text><a href=\"info.html\">link</a>" "<iframe src=\"http://host2.com/\"></iframe>" "<iframe src=\"http://host3.com/\"></iframe>" "</body></html>"; responses_["http://host2.com/"] = "<html><head><script></script><body>" "<form action=\"http://host4.com/\"><input type=checkbox></form>" "<form action=\"http://host2.com/submit\"></form>" "<a href=\"http://www.host2.com/home\">link</a>" "<iframe src=\"nested.html\"></iframe>" "<body></html>"; responses_["http://host2.com/nested.html"] = "<html><body><input type=password>" "<a href=\"https://host4.com/\">link</a>" "<a href=\"relative\">another</a>" "</body></html>"; responses_["http://host3.com/"] = "<html><head><script></script><body>" "<img src=\"http://host.com/123.png\">" "</body></html>"; FeatureMap expected_features; expected_features.AddBooleanFeature(features::kPageHasForms); // Form action domains are compared to the URL of the document they're in, // not the URL of the toplevel page. So http://host2.com/ has two form // actions, one of which is external. expected_features.AddRealFeature(features::kPageActionOtherDomainFreq, 0.5); expected_features.AddBooleanFeature(features::kPageHasTextInputs); expected_features.AddBooleanFeature(features::kPageHasPswdInputs); expected_features.AddBooleanFeature(features::kPageHasCheckInputs); expected_features.AddRealFeature(features::kPageExternalLinksFreq, 0.25); expected_features.AddBooleanFeature(features::kPageLinkDomain + std::string("host4.com")); expected_features.AddRealFeature(features::kPageSecureLinksFreq, 0.25); expected_features.AddBooleanFeature(features::kPageNumScriptTagsGTOne); expected_features.AddRealFeature(features::kPageImgOtherDomainFreq, 1.0); FeatureMap features; LoadURL("http://host.com/"); ASSERT_TRUE(ExtractFeatures(&features)); EXPECT_THAT(features.features(), ContainerEq(expected_features.features())); } TEST_F(PhishingDOMFeatureExtractorTest, Continuation) { // For this test, we'll cause the feature extraction to run multiple // iterations by incrementing the clock. // This page has a total of 50 elements. For the external forms feature to // be computed correctly, the extractor has to examine the whole document. // Note: the empty HEAD is important -- WebKit will synthesize a HEAD if // there isn't one present, which can be confusing for the element counts. std::string response = "<html><head></head><body>" "<form action=\"ondomain\"></form>"; for (int i = 0; i < 45; ++i) { response.append("<p>"); } response.append("<form action=\"http://host2.com/\"></form></body></html>"); responses_["http://host.com/"] = response; // Advance the clock 8 ms every 10 elements processed, 10 ms between chunks. // Note that this assumes kClockCheckGranularity = 10 and // kMaxTimePerChunkMs = 20. base::TimeTicks now = base::TimeTicks::Now(); EXPECT_CALL(clock_, Now()) // Time check at the start of extraction. .WillOnce(Return(now)) // Time check at the start of the first chunk of work. .WillOnce(Return(now)) // Time check after the first 10 elements. .WillOnce(Return(now + base::TimeDelta::FromMilliseconds(8))) // Time check after the next 10 elements. This is over the chunk // time limit, so a continuation task will be posted. .WillOnce(Return(now + base::TimeDelta::FromMilliseconds(16))) // Time check at the start of the second chunk of work. .WillOnce(Return(now + base::TimeDelta::FromMilliseconds(26))) // Time check after resuming iteration for the second chunk. .WillOnce(Return(now + base::TimeDelta::FromMilliseconds(28))) // Time check after the next 10 elements. .WillOnce(Return(now + base::TimeDelta::FromMilliseconds(36))) // Time check after the next 10 elements. This will trigger another // continuation task. .WillOnce(Return(now + base::TimeDelta::FromMilliseconds(44))) // Time check at the start of the third chunk of work. .WillOnce(Return(now + base::TimeDelta::FromMilliseconds(54))) // Time check after resuming iteration for the third chunk. .WillOnce(Return(now + base::TimeDelta::FromMilliseconds(56))) // Time check after the last 10 elements. .WillOnce(Return(now + base::TimeDelta::FromMilliseconds(64))) // A final time check for the histograms. .WillOnce(Return(now + base::TimeDelta::FromMilliseconds(66))); FeatureMap expected_features; expected_features.AddBooleanFeature(features::kPageHasForms); expected_features.AddRealFeature(features::kPageActionOtherDomainFreq, 0.5); FeatureMap features; LoadURL("http://host.com/"); ASSERT_TRUE(ExtractFeatures(&features)); EXPECT_THAT(features.features(), ContainerEq(expected_features.features())); // Make sure none of the mock expectations carry over to the next test. ::testing::Mock::VerifyAndClearExpectations(&clock_); // Now repeat the test with the same page, but advance the clock faster so // that the extraction time exceeds the maximum total time for the feature // extractor. Extraction should fail. Note that this assumes // kMaxTotalTimeMs = 500. EXPECT_CALL(clock_, Now()) // Time check at the start of extraction. .WillOnce(Return(now)) // Time check at the start of the first chunk of work. .WillOnce(Return(now)) // Time check after the first 10 elements. .WillOnce(Return(now + base::TimeDelta::FromMilliseconds(300))) // Time check at the start of the second chunk of work. .WillOnce(Return(now + base::TimeDelta::FromMilliseconds(350))) // Time check after resuming iteration for the second chunk. .WillOnce(Return(now + base::TimeDelta::FromMilliseconds(360))) // Time check after the next 10 elements. This is over the limit. .WillOnce(Return(now + base::TimeDelta::FromMilliseconds(600))) // A final time check for the histograms. .WillOnce(Return(now + base::TimeDelta::FromMilliseconds(620))); features.Clear(); EXPECT_FALSE(ExtractFeatures(&features)); } } // namespace safe_browsing <commit_msg>Fix the clock values in PhishingDOMFeatureExtractorTest.Continuation.<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. // // Note that although this is not a "browser" test, it runs as part of // browser_tests. This is because WebKit does not work properly if it is // shutdown and re-initialized. Since browser_tests runs each test in a // new process, this avoids the problem. #include "chrome/renderer/safe_browsing/phishing_dom_feature_extractor.h" #include "base/callback.h" #include "base/message_loop.h" #include "base/time.h" #include "chrome/renderer/safe_browsing/features.h" #include "chrome/renderer/safe_browsing/mock_feature_extractor_clock.h" #include "chrome/renderer/safe_browsing/render_view_fake_resources_test.h" #include "testing/gmock/include/gmock/gmock.h" using ::testing::ContainerEq; using ::testing::Return; namespace safe_browsing { class PhishingDOMFeatureExtractorTest : public RenderViewFakeResourcesTest { protected: virtual void SetUp() { // Set up WebKit and the RenderView. RenderViewFakeResourcesTest::SetUp(); extractor_.reset(new PhishingDOMFeatureExtractor(view_, &clock_)); } virtual void TearDown() { RenderViewFakeResourcesTest::TearDown(); } // Runs the DOMFeatureExtractor on the RenderView, waiting for the // completion callback. Returns the success boolean from the callback. bool ExtractFeatures(FeatureMap* features) { success_ = false; extractor_->ExtractFeatures( features, NewCallback(this, &PhishingDOMFeatureExtractorTest::ExtractionDone)); message_loop_.Run(); return success_; } // Completion callback for feature extraction. void ExtractionDone(bool success) { success_ = success; message_loop_.Quit(); } MockFeatureExtractorClock clock_; scoped_ptr<PhishingDOMFeatureExtractor> extractor_; bool success_; // holds the success value from ExtractFeatures }; TEST_F(PhishingDOMFeatureExtractorTest, FormFeatures) { // This test doesn't exercise the extraction timing. EXPECT_CALL(clock_, Now()).WillRepeatedly(Return(base::TimeTicks::Now())); responses_["http://host.com/"] = "<html><head><body>" "<form action=\"query\"><input type=text><input type=checkbox></form>" "<form action=\"http://cgi.host.com/submit\"></form>" "<form action=\"http://other.com/\"></form>" "<form action=\"query\"></form>" "<form></form></body></html>"; FeatureMap expected_features; expected_features.AddBooleanFeature(features::kPageHasForms); expected_features.AddRealFeature(features::kPageActionOtherDomainFreq, 0.25); expected_features.AddBooleanFeature(features::kPageHasTextInputs); expected_features.AddBooleanFeature(features::kPageHasCheckInputs); FeatureMap features; LoadURL("http://host.com/"); ASSERT_TRUE(ExtractFeatures(&features)); EXPECT_THAT(features.features(), ContainerEq(expected_features.features())); responses_["http://host.com/"] = "<html><head><body>" "<input type=\"radio\"><input type=password></body></html>"; expected_features.Clear(); expected_features.AddBooleanFeature(features::kPageHasRadioInputs); expected_features.AddBooleanFeature(features::kPageHasPswdInputs); features.Clear(); LoadURL("http://host.com/"); ASSERT_TRUE(ExtractFeatures(&features)); EXPECT_THAT(features.features(), ContainerEq(expected_features.features())); responses_["http://host.com/"] = "<html><head><body><input></body></html>"; expected_features.Clear(); expected_features.AddBooleanFeature(features::kPageHasTextInputs); features.Clear(); LoadURL("http://host.com/"); ASSERT_TRUE(ExtractFeatures(&features)); EXPECT_THAT(features.features(), ContainerEq(expected_features.features())); responses_["http://host.com/"] = "<html><head><body><input type=\"invalid\"></body></html>"; expected_features.Clear(); expected_features.AddBooleanFeature(features::kPageHasTextInputs); features.Clear(); LoadURL("http://host.com/"); ASSERT_TRUE(ExtractFeatures(&features)); EXPECT_THAT(features.features(), ContainerEq(expected_features.features())); } TEST_F(PhishingDOMFeatureExtractorTest, LinkFeatures) { // This test doesn't exercise the extraction timing. EXPECT_CALL(clock_, Now()).WillRepeatedly(Return(base::TimeTicks::Now())); responses_["http://www.host.com/"] = "<html><head><body>" "<a href=\"http://www2.host.com/abc\">link</a>" "<a name=page_anchor></a>" "<a href=\"http://www.chromium.org/\">chromium</a>" "</body></html"; FeatureMap expected_features; expected_features.AddRealFeature(features::kPageExternalLinksFreq, 0.5); expected_features.AddRealFeature(features::kPageSecureLinksFreq, 0.0); expected_features.AddBooleanFeature(features::kPageLinkDomain + std::string("chromium.org")); FeatureMap features; LoadURL("http://www.host.com/"); ASSERT_TRUE(ExtractFeatures(&features)); EXPECT_THAT(features.features(), ContainerEq(expected_features.features())); responses_.clear(); responses_["https://www.host.com/"] = "<html><head><body>" "<a href=\"login\">this is secure</a>" "<a href=\"http://host.com\">not secure</a>" "<a href=\"https://www2.host.com/login\">also secure</a>" "<a href=\"http://chromium.org/\">also not secure</a>" "</body></html>"; expected_features.Clear(); expected_features.AddRealFeature(features::kPageExternalLinksFreq, 0.25); expected_features.AddRealFeature(features::kPageSecureLinksFreq, 0.5); expected_features.AddBooleanFeature(features::kPageLinkDomain + std::string("chromium.org")); features.Clear(); LoadURL("https://www.host.com/"); ASSERT_TRUE(ExtractFeatures(&features)); EXPECT_THAT(features.features(), ContainerEq(expected_features.features())); } TEST_F(PhishingDOMFeatureExtractorTest, ScriptAndImageFeatures) { // This test doesn't exercise the extraction timing. EXPECT_CALL(clock_, Now()).WillRepeatedly(Return(base::TimeTicks::Now())); responses_["http://host.com/"] = "<html><head><script></script><script></script></head></html>"; FeatureMap expected_features; expected_features.AddBooleanFeature(features::kPageNumScriptTagsGTOne); FeatureMap features; LoadURL("http://host.com/"); ASSERT_TRUE(ExtractFeatures(&features)); EXPECT_THAT(features.features(), ContainerEq(expected_features.features())); responses_["http://host.com/"] = "<html><head><script></script><script></script><script></script>" "<script></script><script></script><script></script><script></script>" "</head><body><img src=\"blah.gif\">" "<img src=\"http://host2.com/blah.gif\"></body></html>"; expected_features.Clear(); expected_features.AddBooleanFeature(features::kPageNumScriptTagsGTOne); expected_features.AddBooleanFeature(features::kPageNumScriptTagsGTSix); expected_features.AddRealFeature(features::kPageImgOtherDomainFreq, 0.5); features.Clear(); LoadURL("http://host.com/"); ASSERT_TRUE(ExtractFeatures(&features)); EXPECT_THAT(features.features(), ContainerEq(expected_features.features())); } TEST_F(PhishingDOMFeatureExtractorTest, SubFrames) { // This test doesn't exercise the extraction timing. EXPECT_CALL(clock_, Now()).WillRepeatedly(Return(base::TimeTicks::Now())); // Test that features are aggregated across all frames. responses_["http://host.com/"] = "<html><body><input type=text><a href=\"info.html\">link</a>" "<iframe src=\"http://host2.com/\"></iframe>" "<iframe src=\"http://host3.com/\"></iframe>" "</body></html>"; responses_["http://host2.com/"] = "<html><head><script></script><body>" "<form action=\"http://host4.com/\"><input type=checkbox></form>" "<form action=\"http://host2.com/submit\"></form>" "<a href=\"http://www.host2.com/home\">link</a>" "<iframe src=\"nested.html\"></iframe>" "<body></html>"; responses_["http://host2.com/nested.html"] = "<html><body><input type=password>" "<a href=\"https://host4.com/\">link</a>" "<a href=\"relative\">another</a>" "</body></html>"; responses_["http://host3.com/"] = "<html><head><script></script><body>" "<img src=\"http://host.com/123.png\">" "</body></html>"; FeatureMap expected_features; expected_features.AddBooleanFeature(features::kPageHasForms); // Form action domains are compared to the URL of the document they're in, // not the URL of the toplevel page. So http://host2.com/ has two form // actions, one of which is external. expected_features.AddRealFeature(features::kPageActionOtherDomainFreq, 0.5); expected_features.AddBooleanFeature(features::kPageHasTextInputs); expected_features.AddBooleanFeature(features::kPageHasPswdInputs); expected_features.AddBooleanFeature(features::kPageHasCheckInputs); expected_features.AddRealFeature(features::kPageExternalLinksFreq, 0.25); expected_features.AddBooleanFeature(features::kPageLinkDomain + std::string("host4.com")); expected_features.AddRealFeature(features::kPageSecureLinksFreq, 0.25); expected_features.AddBooleanFeature(features::kPageNumScriptTagsGTOne); expected_features.AddRealFeature(features::kPageImgOtherDomainFreq, 1.0); FeatureMap features; LoadURL("http://host.com/"); ASSERT_TRUE(ExtractFeatures(&features)); EXPECT_THAT(features.features(), ContainerEq(expected_features.features())); } TEST_F(PhishingDOMFeatureExtractorTest, Continuation) { // For this test, we'll cause the feature extraction to run multiple // iterations by incrementing the clock. // This page has a total of 50 elements. For the external forms feature to // be computed correctly, the extractor has to examine the whole document. // Note: the empty HEAD is important -- WebKit will synthesize a HEAD if // there isn't one present, which can be confusing for the element counts. std::string response = "<html><head></head><body>" "<form action=\"ondomain\"></form>"; for (int i = 0; i < 45; ++i) { response.append("<p>"); } response.append("<form action=\"http://host2.com/\"></form></body></html>"); responses_["http://host.com/"] = response; // Advance the clock 12 ms every 10 elements processed, 10 ms between chunks. // Note that this assumes kClockCheckGranularity = 10 and // kMaxTimePerChunkMs = 20. base::TimeTicks now = base::TimeTicks::Now(); EXPECT_CALL(clock_, Now()) // Time check at the start of extraction. .WillOnce(Return(now)) // Time check at the start of the first chunk of work. .WillOnce(Return(now)) // Time check after the first 10 elements. .WillOnce(Return(now + base::TimeDelta::FromMilliseconds(12))) // Time check after the next 10 elements. This is over the chunk // time limit, so a continuation task will be posted. .WillOnce(Return(now + base::TimeDelta::FromMilliseconds(24))) // Time check at the start of the second chunk of work. .WillOnce(Return(now + base::TimeDelta::FromMilliseconds(34))) // Time check after resuming iteration for the second chunk. .WillOnce(Return(now + base::TimeDelta::FromMilliseconds(36))) // Time check after the next 10 elements. .WillOnce(Return(now + base::TimeDelta::FromMilliseconds(48))) // Time check after the next 10 elements. This will trigger another // continuation task. .WillOnce(Return(now + base::TimeDelta::FromMilliseconds(60))) // Time check at the start of the third chunk of work. .WillOnce(Return(now + base::TimeDelta::FromMilliseconds(70))) // Time check after resuming iteration for the third chunk. .WillOnce(Return(now + base::TimeDelta::FromMilliseconds(72))) // Time check after the last 10 elements. .WillOnce(Return(now + base::TimeDelta::FromMilliseconds(84))) // A final time check for the histograms. .WillOnce(Return(now + base::TimeDelta::FromMilliseconds(86))); FeatureMap expected_features; expected_features.AddBooleanFeature(features::kPageHasForms); expected_features.AddRealFeature(features::kPageActionOtherDomainFreq, 0.5); FeatureMap features; LoadURL("http://host.com/"); ASSERT_TRUE(ExtractFeatures(&features)); EXPECT_THAT(features.features(), ContainerEq(expected_features.features())); // Make sure none of the mock expectations carry over to the next test. ::testing::Mock::VerifyAndClearExpectations(&clock_); // Now repeat the test with the same page, but advance the clock faster so // that the extraction time exceeds the maximum total time for the feature // extractor. Extraction should fail. Note that this assumes // kMaxTotalTimeMs = 500. EXPECT_CALL(clock_, Now()) // Time check at the start of extraction. .WillOnce(Return(now)) // Time check at the start of the first chunk of work. .WillOnce(Return(now)) // Time check after the first 10 elements. .WillOnce(Return(now + base::TimeDelta::FromMilliseconds(300))) // Time check at the start of the second chunk of work. .WillOnce(Return(now + base::TimeDelta::FromMilliseconds(350))) // Time check after resuming iteration for the second chunk. .WillOnce(Return(now + base::TimeDelta::FromMilliseconds(360))) // Time check after the next 10 elements. This is over the limit. .WillOnce(Return(now + base::TimeDelta::FromMilliseconds(600))) // A final time check for the histograms. .WillOnce(Return(now + base::TimeDelta::FromMilliseconds(620))); features.Clear(); EXPECT_FALSE(ExtractFeatures(&features)); } } // namespace safe_browsing <|endoftext|>
<commit_before><commit_msg>Added methods for index ptr in python<commit_after><|endoftext|>
<commit_before><commit_msg>ocl: support empty "ptr only" UMat in Kernel::set()<commit_after><|endoftext|>
<commit_before>/****************************************************************************** * Main script for the 2017 RoboFishy Scripps AUV ******************************************************************************/ #include "Mapper.h" // Multithreading #include <pthread.h> #include <sched.h> #include <unistd.h> // Sampling Values #define SAMPLE_RATE 200 // sample rate of main control loop (Hz) #define DT 0.005 // timestep; make sure this is equal to 1/SAMPLE_RATE! // Conversion Factors #define UNITS_KPA 0.1 // converts pressure from mbar to kPa /****************************************************************************** * Controller Gains ******************************************************************************/ // Yaw Controller #define KP_YAW 0.01 #define KI_YAW 0 #define KD_YAW 1 // Depth Controller #define KP_DEPTH 0 #define KI_DEPTH 0 #define KD_DEPTH 0 // Saturation Constants #define YAW_SAT 1 // upper limit of yaw controller #define DEPTH_SAT 1 // upper limit of depth controller #define INT_SAT 10 // upper limit of integral windup #define DINT_SAT 10 // upper limit of depth integral windup // Fluid Densities in kg/m^3 #define DENSITY_FRESHWATER 997 #define DENSITY_SALTWATER 1029 // Acceleration Due to Gravity in m/s^2 #define GRAVITY 9.81 // Depth Start Value #define DEPTH_START 50 // starting depth (mm) // Stop Timer #define STOP_TIME 10 // seconds // Leak Sensor Inpu and Power Pin #define LEAKPIN 27 // connected to GPIO 27 #define LEAKPOWERPIN 17 // providing Vcc to leak board /****************************************************************************** * Declare Threads ******************************************************************************/ void *navigation_thread(void* arg); void *depth_thread(void* arg); void *safety_thread(void* arg); /****************************************************************************** * Global Variables ******************************************************************************/ // Holds the setpoint data structure with current setpoints //setpoint_t setpoint; // Holds the latest pressure value from the MS5837 pressure sensor ms5837_t ms5837; // Holds the latest temperature value from the temperature temperature sensor float temperature; // Holds the constants and latest errors of the yaw pid controller pid_data_t yaw_pid; // Holds the constants and latest errors of the depth pid controller pid_data_t depth_pid; // Motor channels int motor_channels[] = {CHANNEL_1, CHANNEL_2, CHANNEL_3}; // Ignoring sstate float depth = 0; // setmotor intialization float motor_percent = 0; // Start time for stop timer time_t start; /****************************************************************************** * Main Function ******************************************************************************/ int main() { // Set up RasPi GPIO pins through wiringPi wiringPiSetupGpio(); // Check if AUV is initialized correctly if( initialize_sensors() < 0 ) { return -1; } printf("\nAll components are initialized\n"); substate.mode = INITIALIZING; substate.laserarmed = ARMED; printf("Starting Threads\n"); initializeTAttr(); // Thread handles //pthread_t navigationThread; pthread_t depthThread; //pthread_t safetyThread; //pthread_t disarmlaserThread; pthread_t uiThread; // Create threads using modified attributes //pthread_create (&disarmlaserThread, &tattrlow, disarmLaser, NULL); //pthread_create (&safetyThread, &tattrlow, safety_thread, NULL); //pthread_create (&depthThread, &tattrmed, depth_thread, NULL); //pthread_create (&navigationThread, &tattrmed, navigation_thread, NULL); pthread_create (&uiThread, &tattrmed, userInterface, NULL); // Destroy the thread attributes destroyTAttr(); printf("Threads started\n"); // Start timer! start = time(0); // Run main while loop, wait until it's time to stop while(substate.mode != STOPPED) { // Check if we've passed the stop time if(difftime(time(0),start) > STOP_TIME) substate.mode = PAUSED; // Sleep a little auv_usleep(100000); } // Exit cleanly cleanup_auv(); return 0; } /****************************************************************************** * Depth Thread * * For Recording Depth & Determining If AUV is in Water or not ******************************************************************************/ void *depth_thread(void* arg) { printf("Depth Thread Started\n"); while(substate.mode!=STOPPED) { ms5837 = read_pressure_fifo(); printf("\nCurrent Depth:\t %.3f m, Current water temp:\t %.3f C\n", ms5837.depth, ms5837.water_temp); printf("Current battery temp:\t %.2f\n", read_temp_fifo()); // read IMU values from fifo file substate.imu = read_imu_fifo(); // Write IMU data printf("\nYaw: %5.2f Roll: %5.2f Pitch: %5.2f p: %5.2f q: %5.2f r: %5.2f \nSys: %i Gyro: " "%i Accel: %i Mag: %i X_acc: %f Y_acc: %f Z_acc: %f\n ", substate.imu.yaw, substate.imu.roll, substate.imu.pitch, substate.imu.p, substate.imu.q, substate.imu.r, substate.imu.sys, substate.imu.gyro, substate.imu.accel, substate.imu.mag, substate.imu.x_acc, substate.imu.y_acc, substate.imu.z_acc); auv_usleep(1000000); //printf("\nYawPID_perr: %f Motor Percent: %f ", yaw_pid.perr, motor_percent); } pthread_exit(NULL); }//*/ /****************************************************************************** * Navigation Thread * * For yaw control *****************************************************************************/ void *navigation_thread(void* arg) { printf("Nav Thread Started\n"); initialize_motors(motor_channels, HERTZ); float yaw = 0; //Local variable for if statements //////////////////////////////// // Yaw Control Initialization // //////////////////////////////// yaw_pid.old = 0; // Initialize old imu data yaw_pid.setpoint = 0; // Initialize setpoint yaw_pid.derr = 0; yaw_pid.ierr = 0; // Initialize error values yaw_pid.perr = 0; yaw_pid.kp = KP_YAW; yaw_pid.kd = KD_YAW; // Initialize gain values yaw_pid.ki = KI_YAW; yaw_pid.isat = INT_SAT; // Initialize saturation values yaw_pid.sat = YAW_SAT; yaw_pid.dt = DT; // initialize time step ////////////////////////////////// // Depth Control Initialization // ////////////////////////////////// depth_pid.setpoint = 2; // Range-from-bottom setpoint (meters) depth_pid.old = 0; // Initialize old depth depth_pid.dt = DT; // Initialize depth controller time step depth_pid.kp = KP_DEPTH; depth_pid.kd = KD_DEPTH; // Depth controller gain initialization depth_pid.ki = KI_DEPTH; depth_pid.perr = 0; depth_pid.ierr = 0; // Initialize depth controller error values depth_pid.derr = 0; depth_pid.isat = INT_SAT; // Depth controller saturation values depth_pid.sat = DEPTH_SAT; while(substate.mode!=STOPPED) { // read IMU values from fifo file substate.imu = read_imu_fifo(); if (substate.imu.yaw < 180) // AUV pointed right { yaw = substate.imu.yaw; } else // AUV pointed left { yaw =(substate.imu.yaw-360); } // Only tell motors to run if we are RUNNING if( substate.mode == RUNNING) { //calculate yaw controller output motor_percent = marchPID(yaw_pid, yaw); // Set port motor set_motor(0, motor_percent); // Set starboard motor set_motor(1, motor_percent); } // end if RUNNING else if( substate.mode == PAUSED) { // Stop horizontal motors set_motor(0, 0); set_motor(1, 0); // Wipe integral error yaw_pid.ierr = 0; // Sleep a while (we're not doing anything anyways) auv_usleep(100000); } // end if PAUSED // Sleep for 5 ms auv_usleep(DT); } // Turn motors off set_motor(0, 0); set_motor(1, 0); set_motor(2, 0); pthread_exit(NULL); }//*/ /****************************************************************************** * Safety Thread * * Shuts down AUV if vehicle goes belows 10m, temperature gets too high, or * water intrusion is detected *****************************************************************************/ /*void *safety_thread(void* arg) { printf("Safety Thread Started\n"); // Set up WiringPi for use // (not sure if actually needed) wiringPiSetup(); // Leak detection pins pinMode(LEAKPIN, INPUT); // set LEAKPIN as an INPUT pinMode(LEAKPOWERPIN, OUTPUT); // set as output to provide Vcc digitalWrite(LEAKPOWERPIN, HIGH); // write high to provide Vcc // Leak checking variables int leakState; // holds the state (HIGH or LOW) of the LEAKPIN // Test if temp sensor reads anything temperature = read_temp_fifo(); printf("Temperature: %f degC\n", temperature); while( substate.mode != STOPPED ) { // Check if depth threshold has been exceeded if( substate.fdepth > DEPTH_STOP ) { substate.mode = STOPPED; printf("We're too deep! Shutting down...\n"); continue; } else { // We're still good substate.mode = RUNNING; } // Check temperature // Shut down AUV if housing temperature gets too high if( temperature > TEMP_STOP ) { substate.mode = STOPPED; printf("It's too hot! Shutting down...\n"); continue; } else { // We're still good substate.mode = RUNNING; } // Check for leak leakState = digitalRead(LEAKPIN); // check the state of LEAKPIN if( leakState == HIGH ) { substate.mode = STOPPED; printf("LEAK DETECTED! Shutting down...\n"); continue; } else if (leakState == LOW) { // We're still good substate.mode = RUNNING; } // Check IMU accelerometer for collision (1+ g detected) if( (float)fabs(substate.imu.x_acc) > 1.0*GRAVITY || (float)fabs(substate.imu.y_acc) > 1.0*GRAVITY || (float)fabs(substate.imu.z_acc) > 1.0*GRAVITY ) { substate.mode = STOPPED; printf("Collision detected. Shutting down..."); continue; } else { // We're still good substate.mode = RUNNING; } } pthread_exit(NULL); }//*/ /****************************************************************************** * Logging Thread * * Logs the sensor output data into a file *****************************************************************************/ /* PI_THREAD (logging_thread) { while(substate.mode!=STOPPED){ FILE *fd = fopen("log.txt", "a"); char buffer[100] = {0}; // add logging values to the next line sprintf(buffer, "%f %f %f %f %i %i %i %i %f %f %f %f\n",sstate.roll, sstate.pitch[0], sstate.yaw[0], sstate.depth[0],sstate.x[0], sstate.y[0], sstate.radius[0], setpoint.x - sstate.x[0], sstate.esc_out[0], sstate.esc_out[1], sstate.esc_out[2], sstate.esc_out[3]); fputs(buffer, fd); fclose(fd); //sleep for 100 ms usleep(100000); } return 0; } */ /****************************************************************************** * User Interface Thread * void* userInterface(void* arg) * * Interfaces with the user, asks for input *****************************************************************************/ void* userInterface(void* arg) { // Declare local constant variables float _kp, _ki, _kd; // Wait a until everything is initialized before starting while(substate.mode == INITIALIZING) { // Waiting... auv_usleep(100000); } // Prompt user for values continuously until the program exits while(substate.mode != STOPPED) { // Prompt for kp std::cout << "Kp: "; std::cin >> _kp; // Prompt for ki std::cout << "Ki: "; std::cin >> _ki; // Prompt for kd std::cout << "Kd: "; std::cin >> _kp; // Give a newline std::cout << std::endl; // Reset gain values yaw_pid.kp = _kp; yaw_pid.kd = _ki; yaw_pid.ki = _kd; // Clear errors yaw_pid.derr = 0; yaw_pid.ierr = 0; yaw_pid.perr = 0; // Start RUNNING again substate.mode = RUNNING; // Restart timer! start = time(0); } // Exit thread pthread_exit(NULL); }<commit_msg>fixed typos, turned on nav thread<commit_after>/****************************************************************************** * Main script for the 2017 RoboFishy Scripps AUV ******************************************************************************/ #include "Mapper.h" // Multithreading #include <pthread.h> #include <sched.h> #include <unistd.h> // Sampling Values #define SAMPLE_RATE 200 // sample rate of main control loop (Hz) #define DT 0.005 // timestep; make sure this is equal to 1/SAMPLE_RATE! // Conversion Factors #define UNITS_KPA 0.1 // converts pressure from mbar to kPa /****************************************************************************** * Controller Gains ******************************************************************************/ // Yaw Controller #define KP_YAW 0.01 #define KI_YAW 0 #define KD_YAW 1 // Depth Controller #define KP_DEPTH 0 #define KI_DEPTH 0 #define KD_DEPTH 0 // Saturation Constants #define YAW_SAT 1 // upper limit of yaw controller #define DEPTH_SAT 1 // upper limit of depth controller #define INT_SAT 10 // upper limit of integral windup #define DINT_SAT 10 // upper limit of depth integral windup // Fluid Densities in kg/m^3 #define DENSITY_FRESHWATER 997 #define DENSITY_SALTWATER 1029 // Acceleration Due to Gravity in m/s^2 #define GRAVITY 9.81 // Depth Start Value #define DEPTH_START 50 // starting depth (mm) // Stop Timer #define STOP_TIME 10 // seconds // Leak Sensor Inpu and Power Pin #define LEAKPIN 27 // connected to GPIO 27 #define LEAKPOWERPIN 17 // providing Vcc to leak board /****************************************************************************** * Declare Threads ******************************************************************************/ void *navigation_thread(void* arg); void *depth_thread(void* arg); void *safety_thread(void* arg); void *userInterface(void* arg); /****************************************************************************** * Global Variables ******************************************************************************/ // Holds the setpoint data structure with current setpoints //setpoint_t setpoint; // Holds the latest pressure value from the MS5837 pressure sensor ms5837_t ms5837; // Holds the latest temperature value from the temperature temperature sensor float temperature; // Holds the constants and latest errors of the yaw pid controller pid_data_t yaw_pid; // Holds the constants and latest errors of the depth pid controller pid_data_t depth_pid; // Motor channels int motor_channels[] = {CHANNEL_1, CHANNEL_2, CHANNEL_3}; // Ignoring sstate float depth = 0; // setmotor intialization float motor_percent = 0; // Start time for stop timer time_t start; /****************************************************************************** * Main Function ******************************************************************************/ int main() { // Set up RasPi GPIO pins through wiringPi wiringPiSetupGpio(); // Check if AUV is initialized correctly if( initialize_sensors() < 0 ) { return -1; } printf("\nAll components are initialized\n"); substate.mode = INITIALIZING; substate.laserarmed = ARMED; printf("Starting Threads\n"); initializeTAttr(); // Thread handles pthread_t navigationThread; pthread_t depthThread; //pthread_t safetyThread; //pthread_t disarmlaserThread; pthread_t uiThread; // Create threads using modified attributes //pthread_create (&disarmlaserThread, &tattrlow, disarmLaser, NULL); //pthread_create (&safetyThread, &tattrlow, safety_thread, NULL); //pthread_create (&depthThread, &tattrmed, depth_thread, NULL); pthread_create (&navigationThread, &tattrmed, navigation_thread, NULL); pthread_create (&uiThread, &tattrmed, userInterface, NULL); // Destroy the thread attributes destroyTAttr(); printf("Threads started\n"); // Start timer! start = time(0); // Run main while loop, wait until it's time to stop while(substate.mode != STOPPED) { // Check if we've passed the stop time if(difftime(time(0),start) > STOP_TIME) substate.mode = PAUSED; // Sleep a little auv_usleep(100000); } // Exit cleanly cleanup_auv(); return 0; } /****************************************************************************** * Depth Thread * * For Recording Depth & Determining If AUV is in Water or not ******************************************************************************/ void *depth_thread(void* arg) { printf("Depth Thread Started\n"); while(substate.mode!=STOPPED) { ms5837 = read_pressure_fifo(); printf("\nCurrent Depth:\t %.3f m, Current water temp:\t %.3f C\n", ms5837.depth, ms5837.water_temp); printf("Current battery temp:\t %.2f\n", read_temp_fifo()); // read IMU values from fifo file substate.imu = read_imu_fifo(); // Write IMU data printf("\nYaw: %5.2f Roll: %5.2f Pitch: %5.2f p: %5.2f q: %5.2f r: %5.2f \nSys: %i Gyro: " "%i Accel: %i Mag: %i X_acc: %f Y_acc: %f Z_acc: %f\n ", substate.imu.yaw, substate.imu.roll, substate.imu.pitch, substate.imu.p, substate.imu.q, substate.imu.r, substate.imu.sys, substate.imu.gyro, substate.imu.accel, substate.imu.mag, substate.imu.x_acc, substate.imu.y_acc, substate.imu.z_acc); auv_usleep(1000000); //printf("\nYawPID_perr: %f Motor Percent: %f ", yaw_pid.perr, motor_percent); } pthread_exit(NULL); }//*/ /****************************************************************************** * Navigation Thread * * For yaw control *****************************************************************************/ void *navigation_thread(void* arg) { printf("Nav Thread Started\n"); initialize_motors(motor_channels, HERTZ); float yaw = 0; //Local variable for if statements //////////////////////////////// // Yaw Control Initialization // //////////////////////////////// yaw_pid.old = 0; // Initialize old imu data yaw_pid.setpoint = 0; // Initialize setpoint yaw_pid.derr = 0; yaw_pid.ierr = 0; // Initialize error values yaw_pid.perr = 0; yaw_pid.kp = KP_YAW; yaw_pid.kd = KD_YAW; // Initialize gain values yaw_pid.ki = KI_YAW; yaw_pid.isat = INT_SAT; // Initialize saturation values yaw_pid.sat = YAW_SAT; yaw_pid.dt = DT; // initialize time step ////////////////////////////////// // Depth Control Initialization // ////////////////////////////////// depth_pid.setpoint = 2; // Range-from-bottom setpoint (meters) depth_pid.old = 0; // Initialize old depth depth_pid.dt = DT; // Initialize depth controller time step depth_pid.kp = KP_DEPTH; depth_pid.kd = KD_DEPTH; // Depth controller gain initialization depth_pid.ki = KI_DEPTH; depth_pid.perr = 0; depth_pid.ierr = 0; // Initialize depth controller error values depth_pid.derr = 0; depth_pid.isat = INT_SAT; // Depth controller saturation values depth_pid.sat = DEPTH_SAT; while(substate.mode!=STOPPED) { // read IMU values from fifo file substate.imu = read_imu_fifo(); if (substate.imu.yaw < 180) // AUV pointed right { yaw = substate.imu.yaw; } else // AUV pointed left { yaw =(substate.imu.yaw-360); } // Only tell motors to run if we are RUNNING if( substate.mode == RUNNING) { //calculate yaw controller output motor_percent = marchPID(yaw_pid, yaw); // Set port motor set_motor(0, motor_percent); // Set starboard motor set_motor(1, motor_percent); } // end if RUNNING else if( substate.mode == PAUSED) { // Stop horizontal motors set_motor(0, 0); set_motor(1, 0); // Wipe integral error yaw_pid.ierr = 0; // Sleep a while (we're not doing anything anyways) auv_usleep(100000); } // end if PAUSED // Sleep for 5 ms auv_usleep(DT); } // Turn motors off set_motor(0, 0); set_motor(1, 0); set_motor(2, 0); pthread_exit(NULL); }//*/ /****************************************************************************** * Safety Thread * * Shuts down AUV if vehicle goes belows 10m, temperature gets too high, or * water intrusion is detected *****************************************************************************/ /*void *safety_thread(void* arg) { printf("Safety Thread Started\n"); // Set up WiringPi for use // (not sure if actually needed) wiringPiSetup(); // Leak detection pins pinMode(LEAKPIN, INPUT); // set LEAKPIN as an INPUT pinMode(LEAKPOWERPIN, OUTPUT); // set as output to provide Vcc digitalWrite(LEAKPOWERPIN, HIGH); // write high to provide Vcc // Leak checking variables int leakState; // holds the state (HIGH or LOW) of the LEAKPIN // Test if temp sensor reads anything temperature = read_temp_fifo(); printf("Temperature: %f degC\n", temperature); while( substate.mode != STOPPED ) { // Check if depth threshold has been exceeded if( substate.fdepth > DEPTH_STOP ) { substate.mode = STOPPED; printf("We're too deep! Shutting down...\n"); continue; } else { // We're still good substate.mode = RUNNING; } // Check temperature // Shut down AUV if housing temperature gets too high if( temperature > TEMP_STOP ) { substate.mode = STOPPED; printf("It's too hot! Shutting down...\n"); continue; } else { // We're still good substate.mode = RUNNING; } // Check for leak leakState = digitalRead(LEAKPIN); // check the state of LEAKPIN if( leakState == HIGH ) { substate.mode = STOPPED; printf("LEAK DETECTED! Shutting down...\n"); continue; } else if (leakState == LOW) { // We're still good substate.mode = RUNNING; } // Check IMU accelerometer for collision (1+ g detected) if( (float)fabs(substate.imu.x_acc) > 1.0*GRAVITY || (float)fabs(substate.imu.y_acc) > 1.0*GRAVITY || (float)fabs(substate.imu.z_acc) > 1.0*GRAVITY ) { substate.mode = STOPPED; printf("Collision detected. Shutting down..."); continue; } else { // We're still good substate.mode = RUNNING; } } pthread_exit(NULL); }//*/ /****************************************************************************** * Logging Thread * * Logs the sensor output data into a file *****************************************************************************/ /* PI_THREAD (logging_thread) { while(substate.mode!=STOPPED){ FILE *fd = fopen("log.txt", "a"); char buffer[100] = {0}; // add logging values to the next line sprintf(buffer, "%f %f %f %f %i %i %i %i %f %f %f %f\n",sstate.roll, sstate.pitch[0], sstate.yaw[0], sstate.depth[0],sstate.x[0], sstate.y[0], sstate.radius[0], setpoint.x - sstate.x[0], sstate.esc_out[0], sstate.esc_out[1], sstate.esc_out[2], sstate.esc_out[3]); fputs(buffer, fd); fclose(fd); //sleep for 100 ms usleep(100000); } return 0; } */ /****************************************************************************** * User Interface Thread * void* userInterface(void* arg) * * Interfaces with the user, asks for input *****************************************************************************/ void* userInterface(void* arg) { // Declare local constant variables float _kp, _ki, _kd; // Wait a until everything is initialized before starting while(substate.mode == INITIALIZING) { // Waiting... auv_usleep(100000); } // Prompt user for values continuously until the program exits while(substate.mode != STOPPED) { // Prompt for kp std::cout << "Kp: "; std::cin >> _kp; // Prompt for ki std::cout << "Ki: "; std::cin >> _ki; // Prompt for kd std::cout << "Kd: "; std::cin >> _kd; // Give a newline std::cout << std::endl; // Reset gain values yaw_pid.kp = _kp; yaw_pid.ki = _ki; yaw_pid.kd = _kd; // Clear errors yaw_pid.perr = 0; yaw_pid.ierr = 0; yaw_pid.derr = 0; // Start RUNNING again substate.mode = RUNNING; // Restart timer! start = time(0); } // Exit thread pthread_exit(NULL); } <|endoftext|>
<commit_before>#include <mp/wavy.h> #include <mp/functional.h> #include <mp/signal.h> #include <sys/types.h> #include <unistd.h> #include <stdlib.h> #include <iostream> using namespace mp::placeholders; bool signal_handler(int signo, int* count, mp::wavy::loop* lo) { std::cout << "signal" << std::endl; if(++(*count) >= 3) { lo->end(); return false; } return true; } int main(void) { mp::scoped_sigprocmask mask( mp::sigset().add(SIGUSR1)); mp::wavy::loop lo; int count = 0; lo.add_signal(SIGUSR1, mp::bind( &signal_handler, _1, &count, &lo)); lo.start(3); pid_t pid = getpid(); usleep(50*1e3); kill(pid, SIGUSR1); usleep(50*1e3); kill(pid, SIGUSR1); usleep(50*1e3); kill(pid, SIGUSR1); lo.join(); } <commit_msg>fixes test/signal<commit_after>#include <mp/wavy.h> #include <mp/functional.h> #include <sys/types.h> #include <unistd.h> #include <stdlib.h> #include <iostream> using namespace mp::placeholders; bool signal_handler(int signo, int* count, mp::wavy::loop* lo) { std::cout << "signal" << std::endl; if(++(*count) >= 3) { lo->end(); return false; } return true; } int main(void) { signal(SIGUSR1, SIG_IGN); mp::wavy::loop lo; int count = 0; lo.add_signal(SIGUSR1, mp::bind( &signal_handler, _1, &count, &lo)); lo.start(3); pid_t pid = getpid(); usleep(50*1e3); kill(pid, SIGUSR1); usleep(50*1e3); kill(pid, SIGUSR1); usleep(50*1e3); kill(pid, SIGUSR1); lo.join(); } <|endoftext|>
<commit_before>#include "test_macros.hpp" #include <matrix/math.hpp> using namespace matrix; int main() { float data[9] = {0, 2, 3, 4, 5, 6, 7, 8, 10 }; float data_check[6] = { 4, 5, 6, 7, 8, 10 }; SquareMatrix<float, 3> A(data); Matrix<float, 2, 3> B_check(data_check); Matrix<float, 2, 3> B(A.slice<2, 3>(1, 0)); TEST(isEqual(B, B_check)); float data_2[4] = { 11, 12, 13, 14 }; Matrix<float, 2, 2> C(data_2); A.set(C, 1, 1); float data_2_check[9] = { 0, 2, 3, 4, 11, 12, 7, 13, 14 }; Matrix<float, 3, 3> D(data_2_check); TEST(isEqual(A, D)); return 0; } /* vim: set et fenc=utf-8 ff=unix sts=0 sw=4 ts=4 : */ <commit_msg>Add slicing tests that are not pure row slicing<commit_after>#include "test_macros.hpp" #include <matrix/math.hpp> using namespace matrix; int main() { float data[9] = {0, 2, 3, 4, 5, 6, 7, 8, 10 }; SquareMatrix<float, 3> A(data); // Test row slicing Matrix<float, 2, 3> B_rowslice(A.slice<2, 3>(1, 0)); float data_check_rowslice[6] = { 4, 5, 6, 7, 8, 10 }; Matrix<float, 2, 3> B_check_rowslice(data_check_rowslice); TEST(isEqual(B_rowslice, B_check_rowslice)); // Test column slicing Matrix<float, 3, 2> B_colslice(A.slice<3, 2>(0, 1)); float data_check_colslice[6] = { 2, 3, 5, 6, 8, 10 }; Matrix<float, 3, 2> B_check_colslice(data_check_colslice); TEST(isEqual(B_colslice, B_check_colslice)); // Test slicing both Matrix<float, 3, 2> B_bothslice(A.slice<2, 2>(1, 1)); float data_check_bothslice[4] = { 5, 6, 8, 10 }; Matrix<float, 2, 2> B_check_bothslice(data_check_bothslice); TEST(isEqual(B_bothslice, B_check_bothslice)); //Test block writing float data_2[4] = { 11, 12, 13, 14 }; Matrix<float, 2, 2> C(data_2); A.set(C, 1, 1); float data_2_check[9] = { 0, 2, 3, 4, 11, 12, 7, 13, 14 }; Matrix<float, 3, 3> D(data_2_check); TEST(isEqual(A, D)); return 0; } /* vim: set et fenc=utf-8 ff=unix sts=0 sw=4 ts=4 : */ <|endoftext|>
<commit_before>/* This file is part of cpp-ethereum. cpp-ethereum is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. cpp-ethereum 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 cpp-ethereum. If not, see <http://www.gnu.org/licenses/>. */ /** @file state.cpp * @author Christoph Jentzsch <cj@ethdev.com> * @date 2014 * State test functions. */ #include <boost/filesystem/operations.hpp> #include <boost/test/unit_test.hpp> #include "JsonSpiritHeaders.h" #include <libdevcore/CommonIO.h> #include <libethereum/CanonBlockChain.h> #include <libethereum/State.h> #include <libethereum/ExtVM.h> #include <libethereum/Defaults.h> #include <libevm/VM.h> #include "TestHelper.h" using namespace std; using namespace json_spirit; using namespace dev; using namespace dev::eth; namespace dev { namespace test { void doStateTests(json_spirit::mValue& v, bool _fillin) { processCommandLineOptions(); for (auto& i: v.get_obj()) { cerr << i.first << endl; mObject& o = i.second.get_obj(); BOOST_REQUIRE(o.count("env") > 0); BOOST_REQUIRE(o.count("pre") > 0); BOOST_REQUIRE(o.count("transaction") > 0); ImportTest importer(o, _fillin); State theState = importer.m_statePre; bytes tx = importer.m_transaction.rlp(); bytes output; try { theState.execute(lastHashes(importer.m_environment.currentBlock.number), tx, &output); } catch (Exception const& _e) { cnote << "state execution did throw an exception: " << diagnostic_information(_e); } catch (std::exception const& _e) { cnote << "state execution did throw an exception: " << _e.what(); } if (_fillin) importer.exportTest(output, theState); else { BOOST_REQUIRE(o.count("post") > 0); BOOST_REQUIRE(o.count("out") > 0); // check output checkOutput(output, o); // check logs checkLog(theState.pending().size() ? theState.log(0) : LogEntries(), importer.m_environment.sub.logs); // check addresses auto expectedAddrs = importer.m_statePost.addresses(); auto resultAddrs = theState.addresses(); for (auto& expectedPair : expectedAddrs) { auto& expectedAddr = expectedPair.first; auto resultAddrIt = resultAddrs.find(expectedAddr); if (resultAddrIt == resultAddrs.end()) BOOST_ERROR("Missing expected address " << expectedAddr); else { BOOST_CHECK_MESSAGE(importer.m_statePost.balance(expectedAddr) == theState.balance(expectedAddr), expectedAddr << ": incorrect balance " << theState.balance(expectedAddr) << ", expected " << importer.m_statePost.balance(expectedAddr)); BOOST_CHECK_MESSAGE(importer.m_statePost.transactionsFrom(expectedAddr) == theState.transactionsFrom(expectedAddr), expectedAddr << ": incorrect txCount " << theState.transactionsFrom(expectedAddr) << ", expected " << importer.m_statePost.transactionsFrom(expectedAddr)); BOOST_CHECK_MESSAGE(importer.m_statePost.code(expectedAddr) == theState.code(expectedAddr), expectedAddr << ": incorrect code"); checkStorage(importer.m_statePost.storage(expectedAddr), theState.storage(expectedAddr), expectedAddr); } } checkAddresses<map<Address, u256> >(expectedAddrs, resultAddrs); } } } } }// Namespace Close BOOST_AUTO_TEST_SUITE(StateTests) BOOST_AUTO_TEST_CASE(stExample) { dev::test::executeTests("stExample", "/StateTests", dev::test::doStateTests); } BOOST_AUTO_TEST_CASE(stSystemOperationsTest) { dev::test::executeTests("stSystemOperationsTest", "/StateTests", dev::test::doStateTests); } BOOST_AUTO_TEST_CASE(stPreCompiledContracts) { dev::test::executeTests("stPreCompiledContracts", "/StateTests", dev::test::doStateTests); } BOOST_AUTO_TEST_CASE(stLogTests) { dev::test::executeTests("stLogTests", "/StateTests", dev::test::doStateTests); } BOOST_AUTO_TEST_CASE(stRecursiveCreate) { dev::test::executeTests("stRecursiveCreate", "/StateTests", dev::test::doStateTests); } BOOST_AUTO_TEST_CASE(stInitCodeTest) { dev::test::executeTests("stInitCodeTest", "/StateTests", dev::test::doStateTests); } BOOST_AUTO_TEST_CASE(stTransactionTest) { dev::test::executeTests("stTransactionTest", "/StateTests", dev::test::doStateTests); } BOOST_AUTO_TEST_CASE(stSpecialTest) { dev::test::executeTests("stSpecialTest", "/StateTests", dev::test::doStateTests); } BOOST_AUTO_TEST_CASE(stRefundTest) { dev::test::executeTests("stRefundTest", "/StateTests", dev::test::doStateTests); } BOOST_AUTO_TEST_CASE(stBlockHashTest) { dev::test::executeTests("stBlockHashTest", "/StateTests", dev::test::doStateTests); } BOOST_AUTO_TEST_CASE(stSolidityTest) { dev::test::executeTests("stSolidityTest", "/StateTests", dev::test::doStateTests); } BOOST_AUTO_TEST_CASE(stCreateTest) { for (int i = 1; i < boost::unit_test::framework::master_test_suite().argc; ++i) { string arg = boost::unit_test::framework::master_test_suite().argv[i]; if (arg == "--createtest") { if (boost::unit_test::framework::master_test_suite().argc <= i + 2) { cnote << "usage: ./testeth --createtest <PathToConstructor> <PathToDestiny>\n"; return; } try { cnote << "Populating tests..."; json_spirit::mValue v; string s = asString(dev::contents(boost::unit_test::framework::master_test_suite().argv[i + 1])); BOOST_REQUIRE_MESSAGE(s.length() > 0, "Content of " + (string)boost::unit_test::framework::master_test_suite().argv[i + 1] + " is empty."); json_spirit::read_string(s, v); dev::test::doStateTests(v, true); writeFile(boost::unit_test::framework::master_test_suite().argv[i + 2], asBytes(json_spirit::write_string(v, true))); } catch (Exception const& _e) { BOOST_ERROR("Failed state test with Exception: " << diagnostic_information(_e)); } catch (std::exception const& _e) { BOOST_ERROR("Failed state test with Exception: " << _e.what()); } } } } BOOST_AUTO_TEST_CASE(userDefinedFileState) { dev::test::userDefinedTest("--statetest", dev::test::doStateTests); } BOOST_AUTO_TEST_SUITE_END() <commit_msg>only check rootHash of state if FATDB is off<commit_after>/* This file is part of cpp-ethereum. cpp-ethereum is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. cpp-ethereum 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 cpp-ethereum. If not, see <http://www.gnu.org/licenses/>. */ /** @file state.cpp * @author Christoph Jentzsch <cj@ethdev.com> * @date 2014 * State test functions. */ #include <boost/filesystem/operations.hpp> #include <boost/test/unit_test.hpp> #include "JsonSpiritHeaders.h" #include <libdevcore/CommonIO.h> #include <libethereum/CanonBlockChain.h> #include <libethereum/State.h> #include <libethereum/ExtVM.h> #include <libethereum/Defaults.h> #include <libevm/VM.h> #include "TestHelper.h" using namespace std; using namespace json_spirit; using namespace dev; using namespace dev::eth; namespace dev { namespace test { void doStateTests(json_spirit::mValue& v, bool _fillin) { processCommandLineOptions(); for (auto& i: v.get_obj()) { cerr << i.first << endl; mObject& o = i.second.get_obj(); BOOST_REQUIRE(o.count("env") > 0); BOOST_REQUIRE(o.count("pre") > 0); BOOST_REQUIRE(o.count("transaction") > 0); ImportTest importer(o, _fillin); State theState = importer.m_statePre; bytes tx = importer.m_transaction.rlp(); bytes output; try { theState.execute(lastHashes(importer.m_environment.currentBlock.number), tx, &output); } catch (Exception const& _e) { cnote << "state execution did throw an exception: " << diagnostic_information(_e); } catch (std::exception const& _e) { cnote << "state execution did throw an exception: " << _e.what(); } if (_fillin) { #if ETH_FATDB importer.exportTest(output, theState); #else BOOST_THROW_EXCEPTION(Exception() << errinfo_comment("You can not fill tests when FATDB is switched off")); #endif } else { BOOST_REQUIRE(o.count("post") > 0); BOOST_REQUIRE(o.count("out") > 0); // check output checkOutput(output, o); // check logs checkLog(theState.pending().size() ? theState.log(0) : LogEntries(), importer.m_environment.sub.logs); // check addresses #if ETH_FATDB cout << "fatDB is defined\n"; auto expectedAddrs = importer.m_statePost.addresses(); auto resultAddrs = theState.addresses(); for (auto& expectedPair : expectedAddrs) { auto& expectedAddr = expectedPair.first; auto resultAddrIt = resultAddrs.find(expectedAddr); if (resultAddrIt == resultAddrs.end()) BOOST_ERROR("Missing expected address " << expectedAddr); else { BOOST_CHECK_MESSAGE(importer.m_statePost.balance(expectedAddr) == theState.balance(expectedAddr), expectedAddr << ": incorrect balance " << theState.balance(expectedAddr) << ", expected " << importer.m_statePost.balance(expectedAddr)); BOOST_CHECK_MESSAGE(importer.m_statePost.transactionsFrom(expectedAddr) == theState.transactionsFrom(expectedAddr), expectedAddr << ": incorrect txCount " << theState.transactionsFrom(expectedAddr) << ", expected " << importer.m_statePost.transactionsFrom(expectedAddr)); BOOST_CHECK_MESSAGE(importer.m_statePost.code(expectedAddr) == theState.code(expectedAddr), expectedAddr << ": incorrect code"); checkStorage(importer.m_statePost.storage(expectedAddr), theState.storage(expectedAddr), expectedAddr); } } checkAddresses<map<Address, u256> >(expectedAddrs, resultAddrs); #endif BOOST_CHECK_MESSAGE(theState.rootHash() == h256(o["postStateRoot"].get_str()), "wrong post state root"); } } } } }// Namespace Close BOOST_AUTO_TEST_SUITE(StateTests) BOOST_AUTO_TEST_CASE(stExample) { dev::test::executeTests("stExample", "/StateTests", dev::test::doStateTests); } BOOST_AUTO_TEST_CASE(stSystemOperationsTest) { dev::test::executeTests("stSystemOperationsTest", "/StateTests", dev::test::doStateTests); } BOOST_AUTO_TEST_CASE(stPreCompiledContracts) { dev::test::executeTests("stPreCompiledContracts", "/StateTests", dev::test::doStateTests); } BOOST_AUTO_TEST_CASE(stLogTests) { dev::test::executeTests("stLogTests", "/StateTests", dev::test::doStateTests); } BOOST_AUTO_TEST_CASE(stRecursiveCreate) { dev::test::executeTests("stRecursiveCreate", "/StateTests", dev::test::doStateTests); } BOOST_AUTO_TEST_CASE(stInitCodeTest) { dev::test::executeTests("stInitCodeTest", "/StateTests", dev::test::doStateTests); } BOOST_AUTO_TEST_CASE(stTransactionTest) { dev::test::executeTests("stTransactionTest", "/StateTests", dev::test::doStateTests); } BOOST_AUTO_TEST_CASE(stSpecialTest) { dev::test::executeTests("stSpecialTest", "/StateTests", dev::test::doStateTests); } BOOST_AUTO_TEST_CASE(stRefundTest) { dev::test::executeTests("stRefundTest", "/StateTests", dev::test::doStateTests); } BOOST_AUTO_TEST_CASE(stBlockHashTest) { dev::test::executeTests("stBlockHashTest", "/StateTests", dev::test::doStateTests); } BOOST_AUTO_TEST_CASE(stSolidityTest) { dev::test::executeTests("stSolidityTest", "/StateTests", dev::test::doStateTests); } BOOST_AUTO_TEST_CASE(stCreateTest) { for (int i = 1; i < boost::unit_test::framework::master_test_suite().argc; ++i) { string arg = boost::unit_test::framework::master_test_suite().argv[i]; if (arg == "--createtest") { if (boost::unit_test::framework::master_test_suite().argc <= i + 2) { cnote << "usage: ./testeth --createtest <PathToConstructor> <PathToDestiny>\n"; return; } try { cnote << "Populating tests..."; json_spirit::mValue v; string s = asString(dev::contents(boost::unit_test::framework::master_test_suite().argv[i + 1])); BOOST_REQUIRE_MESSAGE(s.length() > 0, "Content of " + (string)boost::unit_test::framework::master_test_suite().argv[i + 1] + " is empty."); json_spirit::read_string(s, v); dev::test::doStateTests(v, true); writeFile(boost::unit_test::framework::master_test_suite().argv[i + 2], asBytes(json_spirit::write_string(v, true))); } catch (Exception const& _e) { BOOST_ERROR("Failed state test with Exception: " << diagnostic_information(_e)); } catch (std::exception const& _e) { BOOST_ERROR("Failed state test with Exception: " << _e.what()); } } } } BOOST_AUTO_TEST_CASE(userDefinedFileState) { dev::test::userDefinedTest("--statetest", dev::test::doStateTests); } BOOST_AUTO_TEST_SUITE_END() <|endoftext|>
<commit_before>#include "MinVRSettings.h" string MinVRSettings::getValueString(string settingName) { map<string, TYPE_ID>::iterator i; i = keyword_to_type.find(settingName); if (i == keyword_to_type.end()) { // translate input into a string string value_column = settingsToValues[settingName]; // save it in the keyword_to_type lookup keyword_to_type[settingName] = STRING; // save it in the settingValues map settingValues[settingName] = value_column; return value_column; } else { // return saved value TYPE_ID t = i->second; if (t == STRING) { return settingValues[settingName]; } else { cout << " getValueString (" << settingName << ") is not a string." << endl; //exit(1); } } return string(); } int MinVRSettings::getValueStringVector(string settingName,vector<string>& stringValues) { // return SUCCESS; } int MinVRSettings::getValueInt(string settingName) { map<string, TYPE_ID>::iterator i; i = keyword_to_type.find(settingName); if (i == keyword_to_type.end()) { // translate input into a string string value_column = settingsToValues[settingName]; // save it in the keyword_to_type lookup keyword_to_type[settingName] = INT; int tmp_int = atoi(value_column.c_str()); // save it in the settingValues map settingIntValues[settingName] = tmp_int; return tmp_int; } else { // return saved value TYPE_ID t = i->second; if (t == INT) { return settingIntValues[settingName]; } else { cout << " getValueInt (" << settingName << ") is not an Int." << endl; //exit(1); } } return FAILURE; } int MinVRSettings::getValueIntVector(string settingName,vector<int>& intValues) { map<string, TYPE_ID>::iterator i; i = keyword_to_type.find(settingName); if (i == keyword_to_type.end()) { // translate input into a string string value_column = settingsToValues[settingName]; // save it in the keyword_to_type lookup keyword_to_type[settingName] = VEC_INT; intValues = string_int_vec(value_column); // save it in the settingValues map settingIntValuesVector[settingName] = intValues; return intValues.size(); } else { // return saved value TYPE_ID t = i->second; if (t == VEC_INT) { intValues = settingIntValuesVector[settingName]; return intValues.size(); } else { cout << " getValueIntVector (" << settingName << ",intValues) is not a vector of integers." << endl; //exit(1); } } return SUCCESS; } vector<int> MinVRSettings::string_int_vec(const string& value_column) { vector<int> i_tmp; char *pch, *dup = strdup(value_column.c_str()); pch = strtok(dup," \t,()"); while(pch != NULL) { i_tmp.push_back(atoi(pch)); pch = strtok(NULL," \t,()"); } return i_tmp; } float MinVRSettings::getValueFloat(string settingName) { map<string, TYPE_ID>::iterator i; i = keyword_to_type.find(settingName); if (i == keyword_to_type.end()) { // translate input into a string string value_column = settingsToValues[settingName]; // save it in the keyword_to_type lookup keyword_to_type[settingName] = FLOAT; float tmp_float = (float)strtod(value_column.c_str(),NULL); // save it in the settingValues map settingFloatValues[settingName] = tmp_float; return tmp_float; } else { // return saved value TYPE_ID t = i->second; if (t == FLOAT) { return settingFloatValues[settingName]; } else { cout << " getValueFloat (" << settingName << ") is not an Float." << endl; //exit(1); } } return FAILURE; } int MinVRSettings::getValueFloatVector(string settingName,vector<float>& floatValues) { map<string, TYPE_ID>::iterator i; i = keyword_to_type.find(settingName); if (i == keyword_to_type.end()) { // translate input into a string string value_column = settingsToValues[settingName]; // save it in the keyword_to_type lookup keyword_to_type[settingName] = VEC_FLOAT; floatValues = string_float_vec(value_column); // save it in the settingValues map settingFloatValuesVector[settingName] = floatValues; return floatValues.size(); } else { // return saved value TYPE_ID t = i->second; if (t == VEC_FLOAT) { floatValues = settingFloatValuesVector[settingName]; return floatValues.size(); } else { cout << " getValueFloatVector (" << settingName << ",floatValues) is not a vector of floats." << endl; //exit(1); } } return SUCCESS; } vector<float> MinVRSettings::string_float_vec(const string& value_column) { vector<float> f_tmp; char *pch, *dup = strdup(value_column.c_str()); pch = strtok(dup," \t,()"); while(pch != NULL) { f_tmp.push_back(static_cast<float>(strtod(pch,NULL))); pch = strtok(NULL," \t,()"); } return f_tmp; } int MinVRSettings::setValueString(string settingName, string settingValue) { settingValues[settingName]=settingValue; keyword_to_type[settingName] = STRING; return SUCCESS; } int MinVRSettings::setValueStringVector(string settingName, const vector<string>& settingValues) { // settingValues[settingName]=settingValue; // keyword_to_type[settingName] = STRING; return SUCCESS; } int MinVRSettings::setValueInt(string settingName, int settingValue) { char str_tmp[128]; sprintf(str_tmp,"%d",settingValue); settingsToValues[settingName]=str_tmp; settingIntValues[settingName]=settingValue; keyword_to_type[settingName] = INT; return SUCCESS; } int MinVRSettings::setValueIntVector(string settingName, const vector<int>& settingValues) { string tmp; char str_tmp[128]; for (int j = 0; j < settingValues.size(); j++) { sprintf(str_tmp,"%d",settingValues[j]); tmp+=str_tmp; } settingsToValues[settingName]=tmp; settingIntValuesVector[settingName]=settingValues; keyword_to_type[settingName] = VEC_INT; return SUCCESS; } int MinVRSettings::setValueFloat(string settingName, float settingValue) { char str_tmp[128]; sprintf(str_tmp,"%f",settingValue); settingsToValues[settingName]=str_tmp; settingFloatValues[settingName]=settingValue; keyword_to_type[settingName] = FLOAT; return SUCCESS; } int MinVRSettings::setValueFloatVector(string settingName, const vector<float>& settingValues) { string tmp; char str_tmp[128]; memset(str_tmp, 0,128); for (int j = 0; j < settingValues.size(); j++) { sprintf(str_tmp,"%f",settingValues[j]); tmp+=str_tmp; } settingsToValues[settingName]=tmp; settingFloatValuesVector[settingName]=settingValues; keyword_to_type[settingName] = VEC_FLOAT; return SUCCESS; } int MinVRSettings::readValues(string settingFileName) { // Read config settings from a file ifstream file(settingFileName.c_str()); int i; char *pch, *str; string line, the_key, the_val; if (file.is_open()) { while (!file.eof()) { getline(file, line); i = line.find("#"); if (i>=0) continue; str=(char*)line.c_str(); pch = strtok (str," \t,()"); if(pch) { the_key = string(pch); pch = strtok (NULL, ""); if(pch) { the_val = string(pch); settingsToValues[the_key] = the_val; } else settingsToValues[the_key] = ""; } } } else { cout << "File " << settingFileName << "cannot be openned" << endl; return FAILURE; } return SUCCESS; } int MinVRSettings::writeValues(string settingFileName) { ofstream m_file; m_file.open(settingFileName.c_str()); if (m_file.is_open()) { map<string, string>::iterator i; for(i=settingsToValues.begin(); i!= settingsToValues.end(); i++) { string tmp = i->second; tmp.erase(tmp.begin(), std::find_if(tmp.begin(), tmp.end(), std::bind1st(std::not_equal_to<char>(), ' '))); m_file << setw(25) << left << i->first << " " << tmp << endl; } m_file.close(); } else { cout << "File " << settingFileName << "cannot be openned for writing." << endl; return FAILURE; } return SUCCESS; } <commit_msg>Inserted space into vector setValue() functions string concats.<commit_after>#include "MinVRSettings.h" string MinVRSettings::getValueString(string settingName) { map<string, TYPE_ID>::iterator i; i = keyword_to_type.find(settingName); if (i == keyword_to_type.end()) { // translate input into a string string value_column = settingsToValues[settingName]; // save it in the keyword_to_type lookup keyword_to_type[settingName] = STRING; // save it in the settingValues map settingValues[settingName] = value_column; return value_column; } else { // return saved value TYPE_ID t = i->second; if (t == STRING) { return settingValues[settingName]; } else { cout << " getValueString (" << settingName << ") is not a string." << endl; //exit(1); } } return string(); } int MinVRSettings::getValueStringVector(string settingName,vector<string>& stringValues) { // return SUCCESS; } int MinVRSettings::getValueInt(string settingName) { map<string, TYPE_ID>::iterator i; i = keyword_to_type.find(settingName); if (i == keyword_to_type.end()) { // translate input into a string string value_column = settingsToValues[settingName]; // save it in the keyword_to_type lookup keyword_to_type[settingName] = INT; int tmp_int = atoi(value_column.c_str()); // save it in the settingValues map settingIntValues[settingName] = tmp_int; return tmp_int; } else { // return saved value TYPE_ID t = i->second; if (t == INT) { return settingIntValues[settingName]; } else { cout << " getValueInt (" << settingName << ") is not an Int." << endl; //exit(1); } } return FAILURE; } int MinVRSettings::getValueIntVector(string settingName,vector<int>& intValues) { map<string, TYPE_ID>::iterator i; i = keyword_to_type.find(settingName); if (i == keyword_to_type.end()) { // translate input into a string string value_column = settingsToValues[settingName]; // save it in the keyword_to_type lookup keyword_to_type[settingName] = VEC_INT; intValues = string_int_vec(value_column); // save it in the settingValues map settingIntValuesVector[settingName] = intValues; return intValues.size(); } else { // return saved value TYPE_ID t = i->second; if (t == VEC_INT) { intValues = settingIntValuesVector[settingName]; return intValues.size(); } else { cout << " getValueIntVector (" << settingName << ",intValues) is not a vector of integers." << endl; //exit(1); } } return SUCCESS; } vector<int> MinVRSettings::string_int_vec(const string& value_column) { vector<int> i_tmp; char *pch, *dup = strdup(value_column.c_str()); pch = strtok(dup," \t,()"); while(pch != NULL) { i_tmp.push_back(atoi(pch)); pch = strtok(NULL," \t,()"); } return i_tmp; } float MinVRSettings::getValueFloat(string settingName) { map<string, TYPE_ID>::iterator i; i = keyword_to_type.find(settingName); if (i == keyword_to_type.end()) { // translate input into a string string value_column = settingsToValues[settingName]; // save it in the keyword_to_type lookup keyword_to_type[settingName] = FLOAT; float tmp_float = (float)strtod(value_column.c_str(),NULL); // save it in the settingValues map settingFloatValues[settingName] = tmp_float; return tmp_float; } else { // return saved value TYPE_ID t = i->second; if (t == FLOAT) { return settingFloatValues[settingName]; } else { cout << " getValueFloat (" << settingName << ") is not an Float." << endl; //exit(1); } } return FAILURE; } int MinVRSettings::getValueFloatVector(string settingName,vector<float>& floatValues) { map<string, TYPE_ID>::iterator i; i = keyword_to_type.find(settingName); if (i == keyword_to_type.end()) { // translate input into a string string value_column = settingsToValues[settingName]; // save it in the keyword_to_type lookup keyword_to_type[settingName] = VEC_FLOAT; floatValues = string_float_vec(value_column); // save it in the settingValues map settingFloatValuesVector[settingName] = floatValues; return floatValues.size(); } else { // return saved value TYPE_ID t = i->second; if (t == VEC_FLOAT) { floatValues = settingFloatValuesVector[settingName]; return floatValues.size(); } else { cout << " getValueFloatVector (" << settingName << ",floatValues) is not a vector of floats." << endl; //exit(1); } } return SUCCESS; } vector<float> MinVRSettings::string_float_vec(const string& value_column) { vector<float> f_tmp; char *pch, *dup = strdup(value_column.c_str()); pch = strtok(dup," \t,()"); while(pch != NULL) { f_tmp.push_back(static_cast<float>(strtod(pch,NULL))); pch = strtok(NULL," \t,()"); } return f_tmp; } int MinVRSettings::setValueString(string settingName, string settingValue) { settingValues[settingName]=settingValue; keyword_to_type[settingName] = STRING; return SUCCESS; } int MinVRSettings::setValueStringVector(string settingName, const vector<string>& settingValues) { // settingValues[settingName]=settingValue; // keyword_to_type[settingName] = STRING; return SUCCESS; } int MinVRSettings::setValueInt(string settingName, int settingValue) { char str_tmp[128]; sprintf(str_tmp,"%d",settingValue); settingsToValues[settingName]=str_tmp; settingIntValues[settingName]=settingValue; keyword_to_type[settingName] = INT; return SUCCESS; } int MinVRSettings::setValueIntVector(string settingName, const vector<int>& settingValues) { string tmp; char str_tmp[128]; for (int j=0; j<settingValues.size(); j++) { sprintf(str_tmp,"%d",settingValues[j]); tmp += str_tmp; tmp += " "; } settingsToValues[settingName]=tmp; settingIntValuesVector[settingName]=settingValues; keyword_to_type[settingName] = VEC_INT; return SUCCESS; } int MinVRSettings::setValueFloat(string settingName, float settingValue) { char str_tmp[128]; sprintf(str_tmp,"%f",settingValue); settingsToValues[settingName]=str_tmp; settingFloatValues[settingName]=settingValue; keyword_to_type[settingName] = FLOAT; return SUCCESS; } int MinVRSettings::setValueFloatVector(string settingName, const vector<float>& settingValues) { string tmp; char str_tmp[128]; for (int j=0; j<settingValues.size(); j++) { sprintf(str_tmp,"%f",settingValues[j]); tmp += str_tmp; tmp += " "; } settingsToValues[settingName]=tmp; settingFloatValuesVector[settingName]=settingValues; keyword_to_type[settingName] = VEC_FLOAT; return SUCCESS; } int MinVRSettings::readValues(string settingFileName) { // Read config settings from a file ifstream file(settingFileName.c_str()); int i; char *pch, *str; string line, the_key, the_val; if (file.is_open()) { while (!file.eof()) { getline(file, line); i = line.find("#"); if (i>=0) continue; str=(char*)line.c_str(); pch = strtok (str," \t,()"); if(pch) { the_key = string(pch); pch = strtok (NULL, ""); if(pch) { the_val = string(pch); settingsToValues[the_key] = the_val; } else settingsToValues[the_key] = ""; } } } else { cout << "File " << settingFileName << "cannot be openned" << endl; return FAILURE; } return SUCCESS; } int MinVRSettings::writeValues(string settingFileName) { ofstream m_file; m_file.open(settingFileName.c_str()); if (m_file.is_open()) { map<string, string>::iterator i; for(i=settingsToValues.begin(); i!= settingsToValues.end(); i++) { string tmp = i->second; tmp.erase(tmp.begin(), std::find_if(tmp.begin(), tmp.end(), std::bind1st(std::not_equal_to<char>(), ' '))); m_file << setw(25) << left << i->first << " " << tmp << endl; } m_file.close(); } else { cout << "File " << settingFileName << "cannot be openned for writing." << endl; return FAILURE; } return SUCCESS; } <|endoftext|>
<commit_before>#include "urtupdater.h" #include "ui_urtupdater.h" UrTUpdater::UrTUpdater(QWidget *parent) : QMainWindow(parent), ui(new Ui::UrTUpdater) { ui->setupUi(this); updaterVersion = "4.0.1"; QMenu *menuFile = menuBar()->addMenu("&File"); QMenu *menuHelp = menuBar()->addMenu("&Help"); QAction *actionDlServer = menuFile->addAction("&Download Server Selection"); connect(actionDlServer, SIGNAL(triggered()), this, SLOT(serverSelection())); QAction *actionChangelog = menuFile->addAction("&Changelog"); //connect(actionChangelog, SIGNAL(triggered()), this, SLOT(openChangelogPage())); QAction *actionAbout = menuHelp->addAction("&About"); //connect(actionAbout, SIGNAL(triggered()), this, SLOT(openAboutPage())); QAction *actionHelp = menuHelp->addAction("&Get help"); //connect(actionHelp, SIGNAL(triggered()), this, SLOT(openHelpPage())); actionHelp->setShortcut(QKeySequence("Ctrl+H")); QAction *actionQuitter = menuFile->addAction("&Quit"); connect(actionQuitter, SIGNAL(triggered()), this, SLOT(quit())); actionQuitter->setShortcut(QKeySequence("Ctrl+Q")); init(); } UrTUpdater::~UrTUpdater() { delete ui; } void UrTUpdater::init(){ updaterPath = getCurrentPath(); // Check if this is the first launch of the updater if(!QFile::exists(updaterPath + URT_GAME_SUBDIR)){ QMessageBox msg; int result; msg.setStandardButtons(QMessageBox::Ok | QMessageBox::Cancel); msg.setIcon(QMessageBox::Information); msg.setText("The game " URT_GAME_NAME " will be installed in this path:\n" + updaterPath + "\n" + "To change the installation path, please click on \"Cancel\" and copy this Updater to where you want it to be installed."); result = msg.exec(); // If we want to quit if(result == QMessageBox::Cancel){ quit(); } // Create the game folder else { if(!QDir().mkdir(updaterPath + URT_GAME_SUBDIR)){ QMessageBox::critical(this, QString(URT_GAME_SUBDIR) + " folder", "Could not create the game folder (" + updaterPath + URT_GAME_SUBDIR + ").\n" + "Please move the updater to a folder where it has sufficient permissions."); quit(); } } } getManifest("versionInfo"); } QString UrTUpdater::getPlatform() { #ifdef Q_OS_MAC return "Mac"; #endif #ifdef Q_OS_LINUX return "Linux"; #endif #ifdef Q_OS_WIN32 return "Windows"; #endif return "Linux"; } QString UrTUpdater::getCurrentPath(){ QDir dir = QDir(QCoreApplication::applicationDirPath()); // If we're on Mac, 'dir' will contain the path to the executable // inside of the Updater's bundle which isn't what we want. // We need to cd ../../.. if(getPlatform() == "Mac"){ dir.cdUp(); dir.cdUp(); dir.cdUp(); } return dir.absolutePath() + "/"; } void UrTUpdater::getManifest(QString query){ QUrl APIUrl(URT_API_LINK); QUrlQuery url; QNetworkRequest apiRequest(APIUrl); QNetworkAccessManager *apiManager = new QNetworkAccessManager(this); qDebug() << "query: " << query << endl; apiRequest.setHeader(QNetworkRequest::ContentTypeHeader,"application/x-www-form-urlencoded;charset=utf-8"); url.addQueryItem("platform", getPlatform()); url.addQueryItem("query", query); apiAnswer = apiManager->post(apiRequest, url.query(QUrl::FullyEncoded).toUtf8()); connect(apiAnswer, SIGNAL(finished()), this, SLOT(parseAPIAnswer())); connect(apiAnswer, SIGNAL(error(QNetworkReply::NetworkError)), this, SLOT(networkError(QNetworkReply::NetworkError))); } void UrTUpdater::parseAPIAnswer(){ QByteArray apiByteAnswer = apiAnswer->readAll(); QString apiData = QString(apiByteAnswer); qDebug() << "apiData: " << apiData << endl; parseDOM(apiData); } void UrTUpdater::parseDOM(QString data){ QDomDocument* dom = new QDomDocument(); dom->setContent(data); QDomNode node = dom->firstChild(); while(!node.isNull()){ if(node.toElement().nodeName() == "Updater"){ QDomNode updater = node.firstChild(); while(!updater.isNull()){ if(updater.toElement().nodeName() == "VersionInfo"){ QDomNode versionInfo = updater.firstChild(); while(!versionInfo.isNull()){ if(versionInfo.nodeName() == "VersionNumber"){ versionNumber = versionInfo.toElement().text(); } if(versionInfo.nodeName() == "ReleaseDate"){ releaseDate = versionInfo.toElement().text(); } versionInfo = versionInfo.nextSibling(); } } else if(updater.toElement().nodeName() == "ServerList"){ QDomNode serverListNode = updater.firstChild(); while(!serverListNode.isNull()){ if(serverListNode.nodeName() == "Server"){ QDomNode serverNode = serverListNode.firstChild(); QString serverURL; QString serverName; QString serverLocation; serverInfo_s si; while(!serverNode.isNull()){ if(serverNode.nodeName() == "ServerName"){ serverName = serverNode.toElement().text(); } if(serverNode.nodeName() == "ServerURL"){ serverURL = serverNode.toElement().text(); } if(serverNode.nodeName() == "ServerLocation"){ serverLocation = serverNode.toElement().text(); } serverNode = serverNode.nextSibling(); } si.serverName = serverName; si.serverURL = serverURL; si.serverLocation = serverLocation; downloadServers.append(si); } serverListNode = serverListNode.nextSibling(); } } else if(updater.toElement().nodeName() == "Files"){ QDomNode files = updater.firstChild(); while(!files.isNull()){ if(files.nodeName() == "File"){ QDomNode fileInfo = files.firstChild(); QString fileDir; QString fileName; QString fileMd5; QString fileSize; bool mustDownload = false; while(!fileInfo.isNull()){ if(fileInfo.nodeName() == "FileDir"){ fileDir = fileInfo.toElement().text(); } if(fileInfo.nodeName() == "FileName"){ fileName = fileInfo.toElement().text(); } if(fileInfo.nodeName() == "FileMD5"){ fileMd5 = fileInfo.toElement().text(); } if(fileInfo.nodeName() == "FileSize"){ fileSize = fileInfo.toElement().text(); } fileInfo = fileInfo.nextSibling(); } QString filePath(updaterPath + fileDir + fileName); QFile* f = new QFile(filePath); // If the file does not exist, it must be downloaded. if(!f->exists()){ mustDownload = true; } // If the md5 string is empty, it means that the API wants // us to delete this file if needed else if(!fileName.isEmpty() && fileMd5.isEmpty()){ QFile::remove(filePath); } // Check the file's md5sum to see if it needs to be updated. else if(!fileName.isEmpty() && !fileMd5.isEmpty()){ if(getMd5Sum(f) != fileMd5){ mustDownload = true; qDebug() << "md5 file: " << getMd5Sum(f) << ", " << fileMd5 << endl; } } qDebug() << "fileDir:" << fileDir << endl; qDebug() << "fileName: " << fileName << endl; qDebug() << "fileMd5: " << fileMd5 << endl; if(mustDownload){ fileInfo_s fi; fi.fileName = fileName; fi.filePath = fileDir; fi.fileMd5 = fileMd5; fi.fileSize = fileSize; filesToDownload.append(fi); } delete f; } files = files.nextSibling(); } } updater = updater.nextSibling(); } } node = node.nextSibling(); } delete dom; } QString UrTUpdater::getMd5Sum(QFile* file) { if (file->exists() && file->open(QIODevice::ReadOnly)) { QByteArray content = file->readAll(); QByteArray hashed = QCryptographicHash::hash(content, QCryptographicHash::Md5); file->close(); return hashed.toHex().data(); } return ""; } void UrTUpdater::networkError(QNetworkReply::NetworkError code){ QString error = ""; bool critical = false; switch(code){ case QNetworkReply::ConnectionRefusedError: error = "Error: the remote server refused the connection. Please try again later."; critical = true; break; case QNetworkReply::RemoteHostClosedError: error = "Error: the remote server closed the connection prematurely. Please try again later."; break; case QNetworkReply::HostNotFoundError: error = "Error: the remote server could not be found. Please check your internet connection!"; critical = true; break; case QNetworkReply::TimeoutError: error = "Error: the connection to the remote server timed out. Please try again."; break; case QNetworkReply::TemporaryNetworkFailureError: error = "Error: the connection to the remote server was broken due to disconnection from the network. Please try again."; break; case QNetworkReply::ContentNotFoundError: error = "Error: the remote content could not be found. Please report this issue on our website: http://www.urbanterror.info"; break; case QNetworkReply::UnknownNetworkError: error = "Error: an unknown network-related error was encountered. Please try again"; break; case QNetworkReply::UnknownContentError: error = "Error: an unknown content-related error was encountered. Please try again"; break; default: case QNetworkReply::NoError: break; } if(!error.isEmpty()){ if(critical == true){ QMessageBox::critical(0, "Download error", error); quit(); } else { QMessageBox::information(0, "Download error", error); } } } void UrTUpdater::serverSelection(){ ServerSelection *serverSel = new ServerSelection(this); serverSel->downloadServers = downloadServers; serverSel->init(); serverSel->exec(); } void UrTUpdater::engineSelection(){ EngineSelection* engineSel = new EngineSelection(this); engineSel->exec(); } void UrTUpdater::quit(){ exit(0); } <commit_msg>When closing the app, force the usage of our quit() function<commit_after>#include "urtupdater.h" #include "ui_urtupdater.h" UrTUpdater::UrTUpdater(QWidget *parent) : QMainWindow(parent), ui(new Ui::UrTUpdater) { ui->setupUi(this); updaterVersion = "4.0.1"; QMenu *menuFile = menuBar()->addMenu("&File"); QMenu *menuHelp = menuBar()->addMenu("&Help"); QAction *actionDlServer = menuFile->addAction("&Download Server Selection"); connect(actionDlServer, SIGNAL(triggered()), this, SLOT(serverSelection())); QAction *actionChangelog = menuFile->addAction("&Changelog"); //connect(actionChangelog, SIGNAL(triggered()), this, SLOT(openChangelogPage())); QAction *actionAbout = menuHelp->addAction("&About"); //connect(actionAbout, SIGNAL(triggered()), this, SLOT(openAboutPage())); QAction *actionHelp = menuHelp->addAction("&Get help"); //connect(actionHelp, SIGNAL(triggered()), this, SLOT(openHelpPage())); actionHelp->setShortcut(QKeySequence("Ctrl+H")); QAction *actionQuitter = menuFile->addAction("&Quit"); connect(actionQuitter, SIGNAL(triggered()), this, SLOT(quit())); actionQuitter->setShortcut(QKeySequence("Ctrl+Q")); connect(qApp, SIGNAL(aboutToQuit()), this, SLOT(quit())); init(); } UrTUpdater::~UrTUpdater() { delete ui; } void UrTUpdater::init(){ updaterPath = getCurrentPath(); // Check if this is the first launch of the updater if(!QFile::exists(updaterPath + URT_GAME_SUBDIR)){ QMessageBox msg; int result; msg.setStandardButtons(QMessageBox::Ok | QMessageBox::Cancel); msg.setIcon(QMessageBox::Information); msg.setText("The game " URT_GAME_NAME " will be installed in this path:\n" + updaterPath + "\n" + "To change the installation path, please click on \"Cancel\" and copy this Updater to where you want it to be installed."); result = msg.exec(); // If we want to quit if(result == QMessageBox::Cancel){ quit(); } // Create the game folder else { if(!QDir().mkdir(updaterPath + URT_GAME_SUBDIR)){ QMessageBox::critical(this, QString(URT_GAME_SUBDIR) + " folder", "Could not create the game folder (" + updaterPath + URT_GAME_SUBDIR + ").\n" + "Please move the updater to a folder where it has sufficient permissions."); quit(); } } } getManifest("versionInfo"); } QString UrTUpdater::getPlatform() { #ifdef Q_OS_MAC return "Mac"; #endif #ifdef Q_OS_LINUX return "Linux"; #endif #ifdef Q_OS_WIN32 return "Windows"; #endif return "Linux"; } QString UrTUpdater::getCurrentPath(){ QDir dir = QDir(QCoreApplication::applicationDirPath()); // If we're on Mac, 'dir' will contain the path to the executable // inside of the Updater's bundle which isn't what we want. // We need to cd ../../.. if(getPlatform() == "Mac"){ dir.cdUp(); dir.cdUp(); dir.cdUp(); } return dir.absolutePath() + "/"; } void UrTUpdater::getManifest(QString query){ QUrl APIUrl(URT_API_LINK); QUrlQuery url; QNetworkRequest apiRequest(APIUrl); QNetworkAccessManager *apiManager = new QNetworkAccessManager(this); qDebug() << "query: " << query << endl; apiRequest.setHeader(QNetworkRequest::ContentTypeHeader,"application/x-www-form-urlencoded;charset=utf-8"); url.addQueryItem("platform", getPlatform()); url.addQueryItem("query", query); apiAnswer = apiManager->post(apiRequest, url.query(QUrl::FullyEncoded).toUtf8()); connect(apiAnswer, SIGNAL(finished()), this, SLOT(parseAPIAnswer())); connect(apiAnswer, SIGNAL(error(QNetworkReply::NetworkError)), this, SLOT(networkError(QNetworkReply::NetworkError))); } void UrTUpdater::parseAPIAnswer(){ QByteArray apiByteAnswer = apiAnswer->readAll(); QString apiData = QString(apiByteAnswer); qDebug() << "apiData: " << apiData << endl; parseDOM(apiData); } void UrTUpdater::parseDOM(QString data){ QDomDocument* dom = new QDomDocument(); dom->setContent(data); QDomNode node = dom->firstChild(); while(!node.isNull()){ if(node.toElement().nodeName() == "Updater"){ QDomNode updater = node.firstChild(); while(!updater.isNull()){ if(updater.toElement().nodeName() == "VersionInfo"){ QDomNode versionInfo = updater.firstChild(); while(!versionInfo.isNull()){ if(versionInfo.nodeName() == "VersionNumber"){ versionNumber = versionInfo.toElement().text(); } if(versionInfo.nodeName() == "ReleaseDate"){ releaseDate = versionInfo.toElement().text(); } versionInfo = versionInfo.nextSibling(); } } else if(updater.toElement().nodeName() == "ServerList"){ QDomNode serverListNode = updater.firstChild(); while(!serverListNode.isNull()){ if(serverListNode.nodeName() == "Server"){ QDomNode serverNode = serverListNode.firstChild(); QString serverURL; QString serverName; QString serverLocation; serverInfo_s si; while(!serverNode.isNull()){ if(serverNode.nodeName() == "ServerName"){ serverName = serverNode.toElement().text(); } if(serverNode.nodeName() == "ServerURL"){ serverURL = serverNode.toElement().text(); } if(serverNode.nodeName() == "ServerLocation"){ serverLocation = serverNode.toElement().text(); } serverNode = serverNode.nextSibling(); } si.serverName = serverName; si.serverURL = serverURL; si.serverLocation = serverLocation; downloadServers.append(si); } serverListNode = serverListNode.nextSibling(); } } else if(updater.toElement().nodeName() == "Files"){ QDomNode files = updater.firstChild(); while(!files.isNull()){ if(files.nodeName() == "File"){ QDomNode fileInfo = files.firstChild(); QString fileDir; QString fileName; QString fileMd5; QString fileSize; bool mustDownload = false; while(!fileInfo.isNull()){ if(fileInfo.nodeName() == "FileDir"){ fileDir = fileInfo.toElement().text(); } if(fileInfo.nodeName() == "FileName"){ fileName = fileInfo.toElement().text(); } if(fileInfo.nodeName() == "FileMD5"){ fileMd5 = fileInfo.toElement().text(); } if(fileInfo.nodeName() == "FileSize"){ fileSize = fileInfo.toElement().text(); } fileInfo = fileInfo.nextSibling(); } QString filePath(updaterPath + fileDir + fileName); QFile* f = new QFile(filePath); // If the file does not exist, it must be downloaded. if(!f->exists()){ mustDownload = true; } // If the md5 string is empty, it means that the API wants // us to delete this file if needed else if(!fileName.isEmpty() && fileMd5.isEmpty()){ QFile::remove(filePath); } // Check the file's md5sum to see if it needs to be updated. else if(!fileName.isEmpty() && !fileMd5.isEmpty()){ if(getMd5Sum(f) != fileMd5){ mustDownload = true; qDebug() << "md5 file: " << getMd5Sum(f) << ", " << fileMd5 << endl; } } qDebug() << "fileDir:" << fileDir << endl; qDebug() << "fileName: " << fileName << endl; qDebug() << "fileMd5: " << fileMd5 << endl; if(mustDownload){ fileInfo_s fi; fi.fileName = fileName; fi.filePath = fileDir; fi.fileMd5 = fileMd5; fi.fileSize = fileSize; filesToDownload.append(fi); } delete f; } files = files.nextSibling(); } } updater = updater.nextSibling(); } } node = node.nextSibling(); } delete dom; } QString UrTUpdater::getMd5Sum(QFile* file) { if (file->exists() && file->open(QIODevice::ReadOnly)) { QByteArray content = file->readAll(); QByteArray hashed = QCryptographicHash::hash(content, QCryptographicHash::Md5); file->close(); return hashed.toHex().data(); } return ""; } void UrTUpdater::networkError(QNetworkReply::NetworkError code){ QString error = ""; bool critical = false; switch(code){ case QNetworkReply::ConnectionRefusedError: error = "Error: the remote server refused the connection. Please try again later."; critical = true; break; case QNetworkReply::RemoteHostClosedError: error = "Error: the remote server closed the connection prematurely. Please try again later."; break; case QNetworkReply::HostNotFoundError: error = "Error: the remote server could not be found. Please check your internet connection!"; critical = true; break; case QNetworkReply::TimeoutError: error = "Error: the connection to the remote server timed out. Please try again."; break; case QNetworkReply::TemporaryNetworkFailureError: error = "Error: the connection to the remote server was broken due to disconnection from the network. Please try again."; break; case QNetworkReply::ContentNotFoundError: error = "Error: the remote content could not be found. Please report this issue on our website: http://www.urbanterror.info"; break; case QNetworkReply::UnknownNetworkError: error = "Error: an unknown network-related error was encountered. Please try again"; break; case QNetworkReply::UnknownContentError: error = "Error: an unknown content-related error was encountered. Please try again"; break; default: case QNetworkReply::NoError: break; } if(!error.isEmpty()){ if(critical == true){ QMessageBox::critical(0, "Download error", error); quit(); } else { QMessageBox::information(0, "Download error", error); } } } void UrTUpdater::serverSelection(){ ServerSelection *serverSel = new ServerSelection(this); serverSel->downloadServers = downloadServers; serverSel->init(); serverSel->exec(); } void UrTUpdater::engineSelection(){ EngineSelection* engineSel = new EngineSelection(this); engineSel->exec(); } void UrTUpdater::quit(){ exit(0); } <|endoftext|>
<commit_before>/* * Copyright (c) 2018, NVIDIA CORPORATION. All rights reserved. * * 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 "ModelImporter.hpp" #include "toposort.hpp" #include "onnx_utils.hpp" #include "onnx2trt_utils.hpp" #include <google/protobuf/io/coded_stream.h> #include <google/protobuf/io/zero_copy_stream_impl.h> #include <google/protobuf/text_format.h> #include <limits> namespace onnx2trt { //Status const& ModelImporter::setInput(const char* name, nvinfer1::ITensor* input) { // _importer_ctx.setUserInput(name, input); // _last_error = Status::success(); // return _last_error; //} // //Status const& ModelImporter::setOutput(const char* name, nvinfer1::ITensor** output) { // _importer_ctx.setUserOutput(name, output); // _last_error = Status::success(); // return _last_error; //} Status importInput(ImporterContext* importer_ctx, ::ONNX_NAMESPACE::ValueInfoProto const& input, nvinfer1::ITensor** tensor) { auto const& onnx_tensor_type = input.type().tensor_type(); nvinfer1::DataType trt_dtype; ASSERT(convert_dtype(onnx_tensor_type.elem_type(), &trt_dtype), ErrorCode::kUNSUPPORTED_NODE); ASSERT(onnx_tensor_type.shape().dim().size() > 0, ErrorCode::kUNSUPPORTED_NODE); auto trt_dims = convert_dims(onnx_tensor_type.shape().dim()); nvinfer1::ITensor* user_input = importer_ctx->getUserInput(input.name().c_str()); if( user_input ) { ASSERT(user_input, ErrorCode::kINVALID_VALUE); // Note: We intentionally don't check dimensions/dtype here so that users // can change the input shape/type if they want to. //ASSERT(trt_dims == user_input->getDimensions(), ErrorCode::kINVALID_VALUE); //ASSERT(trt_dtype == user_input->getType(), ErrorCode::kINVALID_VALUE); *tensor = user_input; return Status::success(); } // WAR for TRT not supporting < 3 input dims for( int i=trt_dims.nbDims; i<3; ++i ) { // Pad with unitary dims ++trt_dims.nbDims; trt_dims.d[i] = 1; trt_dims.type[i] = (i == 0 ? nvinfer1::DimensionType::kCHANNEL : nvinfer1::DimensionType::kSPATIAL); } ASSERT(trt_dims.nbDims <= 3, ErrorCode::kUNSUPPORTED_NODE); ASSERT(*tensor = importer_ctx->network()->addInput( input.name().c_str(), trt_dtype, trt_dims), ErrorCode::kUNSUPPORTED_NODE); return Status::success(); } Status importInputs(ImporterContext* importer_ctx, ::ONNX_NAMESPACE::GraphProto const& graph, string_map<TensorOrWeights>* tensors) { string_map<::ONNX_NAMESPACE::TensorProto const*> initializer_map; for( ::ONNX_NAMESPACE::TensorProto const& initializer : graph.initializer() ) { ASSERT(!initializer_map.count(initializer.name()), ErrorCode::kINVALID_GRAPH); initializer_map.insert({initializer.name(), &initializer}); } for( ::ONNX_NAMESPACE::ValueInfoProto const& input : graph.input() ) { TensorOrWeights tensor; if( initializer_map.count(input.name()) ) { ::ONNX_NAMESPACE::TensorProto const& initializer = *initializer_map.at(input.name()); ShapedWeights weights; ASSERT(convert_onnx_weights(initializer, &weights), ErrorCode::kUNSUPPORTED_NODE); tensor = weights; } else { nvinfer1::ITensor* tensor_ptr; TRT_CHECK(importInput(importer_ctx, input, &tensor_ptr)); tensor = tensor_ptr; } ASSERT(!tensors->count(input.name()), ErrorCode::kINVALID_GRAPH); tensors->insert({input.name(), tensor}); } return Status::success(); } NodeImportResult ModelImporter::importNode(::ONNX_NAMESPACE::NodeProto const& node, std::vector<TensorOrWeights>& inputs) { if( !_op_importers.count(node.op_type()) ) { return MAKE_ERROR("No importer registered for op: " + node.op_type(), ErrorCode::kUNSUPPORTED_NODE); } NodeImporter const& node_importer = _op_importers.at(node.op_type()); std::vector<TensorOrWeights> outputs; GET_VALUE(node_importer(&_importer_ctx, node, inputs), &outputs); ASSERT(outputs.size() <= (size_t)node.output().size(), ErrorCode::kINTERNAL_ERROR); for( size_t i=0; i<outputs.size(); ++i ) { std::string node_output_name = node.output(i); TensorOrWeights& output = outputs.at(i); if( output ) { if( output.is_tensor() ) { output.tensor().setName(node_output_name.c_str()); } //// TODO: Remove when done testing //cout << "Imported " << node.op_type() // << " output tensor '" << node_output_name; //if( output.is_tensor() ) { // cout << "' (" << output.tensor().getType() << ")"; //} //cout << endl; } } return outputs; } Status deserialize_onnx_model(void const* serialized_onnx_model, size_t serialized_onnx_model_size, bool is_serialized_as_text, ::ONNX_NAMESPACE::ModelProto* model) { google::protobuf::io::ArrayInputStream raw_input(serialized_onnx_model, serialized_onnx_model_size); if( is_serialized_as_text ) { ASSERT(google::protobuf::TextFormat::Parse(&raw_input, model), ErrorCode::kMODEL_DESERIALIZE_FAILED); } else { google::protobuf::io::CodedInputStream coded_input(&raw_input); // Note: This WARs the very low default size limit (64MB) coded_input.SetTotalBytesLimit(std::numeric_limits<int>::max(), std::numeric_limits<int>::max() / 4); ASSERT(model->ParseFromCodedStream(&coded_input), ErrorCode::kMODEL_DESERIALIZE_FAILED); } return Status::success(); } Status deserialize_onnx_model(int fd, bool is_serialized_as_text, ::ONNX_NAMESPACE::ModelProto* model) { google::protobuf::io::FileInputStream raw_input(fd); if( is_serialized_as_text ) { ASSERT(google::protobuf::TextFormat::Parse(&raw_input, model), ErrorCode::kMODEL_DESERIALIZE_FAILED); } else { google::protobuf::io::CodedInputStream coded_input(&raw_input); // Note: This WARs the very low default size limit (64MB) coded_input.SetTotalBytesLimit(std::numeric_limits<int>::max(), std::numeric_limits<int>::max()/4); ASSERT(model->ParseFromCodedStream(&coded_input), ErrorCode::kMODEL_DESERIALIZE_FAILED); } return Status::success(); } bool ModelImporter::supportsOperator(const char* op_name) const { return _op_importers.count(op_name); } bool ModelImporter::parse(void const *serialized_onnx_model, size_t serialized_onnx_model_size) { _current_node = -1; // TODO: This function (and its overload below) could do with some cleaning, // particularly wrt error handling. // Note: We store a copy of the model so that weight arrays will persist _onnx_models.emplace_back(); ::ONNX_NAMESPACE::ModelProto& model = _onnx_models.back(); bool is_serialized_as_text = false; Status status = deserialize_onnx_model( serialized_onnx_model, serialized_onnx_model_size, is_serialized_as_text, &model); if( status.is_error() ) { _errors.push_back(status); return false; } status = this->importModel(model); if( status.is_error() ) { status.setNode(_current_node); _errors.push_back(status); return false; } return true; } Status ModelImporter::importModel(::ONNX_NAMESPACE::ModelProto const& model) { // TODO: Remove when done testing //cout << "------Begin model " << model.graph().name() << "-------" << endl; //cout << model << endl; //cout << "------End model-------" << endl; _importer_ctx.clearOpsets(); for( int i=0; i<model.opset_import().size(); ++i ) { std::string domain = model.opset_import(i).domain(); int64_t version = model.opset_import(i).version(); _importer_ctx.addOpset(domain, version); } ::ONNX_NAMESPACE::GraphProto const& graph = model.graph(); string_map<TensorOrWeights> tensors; TRT_CHECK(importInputs(&_importer_ctx, graph, &tensors)); std::vector<size_t> topological_order; ASSERT(toposort(graph.node(), &topological_order), ErrorCode::kINVALID_GRAPH); for( size_t node_idx : topological_order ) { _current_node = node_idx; ::ONNX_NAMESPACE::NodeProto const& node = graph.node(node_idx); std::vector<TensorOrWeights> inputs; for( auto const& input_name : node.input() ) { ASSERT(tensors.count(input_name), ErrorCode::kINVALID_GRAPH); inputs.push_back(tensors.at(input_name)); } std::vector<TensorOrWeights> outputs; GET_VALUE(this->importNode(node, inputs), &outputs); for( size_t i=0; i<outputs.size(); ++i ) { std::string node_output_name = node.output(i); TensorOrWeights& output = outputs.at(i); // Note: This condition is to allow ONNX outputs to be ignored if( output ) { ASSERT(!tensors.count(node_output_name), ErrorCode::kINVALID_GRAPH); tensors.insert({node_output_name, output}); } } if( node.output().size() > 0 ) { std::stringstream ss; ss << node.output(0) << ":" << node.op_type() << " -> " << outputs.at(0).shape(); _importer_ctx.logger().log( nvinfer1::ILogger::Severity::kINFO, ss.str().c_str()); } } _current_node = -1; // Mark outputs defined in the ONNX model (unless tensors are user-requested) for( ::ONNX_NAMESPACE::ValueInfoProto const& output : graph.output() ) { ASSERT(tensors.count(output.name()), ErrorCode::kINVALID_GRAPH); ASSERT(tensors.at(output.name()).is_tensor(), ErrorCode::kUNSUPPORTED_GRAPH); nvinfer1::ITensor* output_tensor_ptr = &tensors.at(output.name()).tensor(); if( output_tensor_ptr->isNetworkInput() ) { // HACK WAR for TRT not allowing input == output // TODO: Does this break things by changing the name of the input tensor? output_tensor_ptr->setName(("__" + output.name()).c_str()); output_tensor_ptr = &identity(&_importer_ctx, output_tensor_ptr).tensor(); ASSERT(output_tensor_ptr, ErrorCode::kUNSUPPORTED_NODE); output_tensor_ptr->setName(output.name().c_str()); } nvinfer1::ITensor** user_output = _importer_ctx.getUserOutput(output.name().c_str()); if( !user_output ) { _importer_ctx.network()->markOutput(*output_tensor_ptr); nvinfer1::DataType trt_dtype; ASSERT(convert_dtype(output.type().tensor_type().elem_type(), &trt_dtype), ErrorCode::kUNSUPPORTED_NODE); // Note: Without this, output type is always float32 output_tensor_ptr->setType(trt_dtype); } } // Return user-requested output tensors for( auto user_output_entry : _importer_ctx.getUserOutputs() ) { std::string user_output_name = user_output_entry.first; nvinfer1::ITensor** user_output_ptr = user_output_entry.second; ASSERT(tensors.count(user_output_name), ErrorCode::kINVALID_VALUE); TensorOrWeights user_output = tensors.at(user_output_name); ASSERT(user_output.is_tensor(), ErrorCode::kINVALID_VALUE); *user_output_ptr = &user_output.tensor(); } return Status::success(); } } // namespace onnx2trt <commit_msg>TRT4: Assert that output type matches INT32 tensor<commit_after>/* * Copyright (c) 2018, NVIDIA CORPORATION. All rights reserved. * * 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 "ModelImporter.hpp" #include "toposort.hpp" #include "onnx_utils.hpp" #include "onnx2trt_utils.hpp" #include <google/protobuf/io/coded_stream.h> #include <google/protobuf/io/zero_copy_stream_impl.h> #include <google/protobuf/text_format.h> #include <limits> namespace onnx2trt { //Status const& ModelImporter::setInput(const char* name, nvinfer1::ITensor* input) { // _importer_ctx.setUserInput(name, input); // _last_error = Status::success(); // return _last_error; //} // //Status const& ModelImporter::setOutput(const char* name, nvinfer1::ITensor** output) { // _importer_ctx.setUserOutput(name, output); // _last_error = Status::success(); // return _last_error; //} Status importInput(ImporterContext* importer_ctx, ::ONNX_NAMESPACE::ValueInfoProto const& input, nvinfer1::ITensor** tensor) { auto const& onnx_tensor_type = input.type().tensor_type(); nvinfer1::DataType trt_dtype; ASSERT(convert_dtype(onnx_tensor_type.elem_type(), &trt_dtype), ErrorCode::kUNSUPPORTED_NODE); ASSERT(onnx_tensor_type.shape().dim().size() > 0, ErrorCode::kUNSUPPORTED_NODE); auto trt_dims = convert_dims(onnx_tensor_type.shape().dim()); nvinfer1::ITensor* user_input = importer_ctx->getUserInput(input.name().c_str()); if( user_input ) { ASSERT(user_input, ErrorCode::kINVALID_VALUE); // Note: We intentionally don't check dimensions/dtype here so that users // can change the input shape/type if they want to. //ASSERT(trt_dims == user_input->getDimensions(), ErrorCode::kINVALID_VALUE); //ASSERT(trt_dtype == user_input->getType(), ErrorCode::kINVALID_VALUE); *tensor = user_input; return Status::success(); } // WAR for TRT not supporting < 3 input dims for( int i=trt_dims.nbDims; i<3; ++i ) { // Pad with unitary dims ++trt_dims.nbDims; trt_dims.d[i] = 1; trt_dims.type[i] = (i == 0 ? nvinfer1::DimensionType::kCHANNEL : nvinfer1::DimensionType::kSPATIAL); } ASSERT(trt_dims.nbDims <= 3, ErrorCode::kUNSUPPORTED_NODE); ASSERT(*tensor = importer_ctx->network()->addInput( input.name().c_str(), trt_dtype, trt_dims), ErrorCode::kUNSUPPORTED_NODE); return Status::success(); } Status importInputs(ImporterContext* importer_ctx, ::ONNX_NAMESPACE::GraphProto const& graph, string_map<TensorOrWeights>* tensors) { string_map<::ONNX_NAMESPACE::TensorProto const*> initializer_map; for( ::ONNX_NAMESPACE::TensorProto const& initializer : graph.initializer() ) { ASSERT(!initializer_map.count(initializer.name()), ErrorCode::kINVALID_GRAPH); initializer_map.insert({initializer.name(), &initializer}); } for( ::ONNX_NAMESPACE::ValueInfoProto const& input : graph.input() ) { TensorOrWeights tensor; if( initializer_map.count(input.name()) ) { ::ONNX_NAMESPACE::TensorProto const& initializer = *initializer_map.at(input.name()); ShapedWeights weights; ASSERT(convert_onnx_weights(initializer, &weights), ErrorCode::kUNSUPPORTED_NODE); tensor = weights; } else { nvinfer1::ITensor* tensor_ptr; TRT_CHECK(importInput(importer_ctx, input, &tensor_ptr)); tensor = tensor_ptr; } ASSERT(!tensors->count(input.name()), ErrorCode::kINVALID_GRAPH); tensors->insert({input.name(), tensor}); } return Status::success(); } NodeImportResult ModelImporter::importNode(::ONNX_NAMESPACE::NodeProto const& node, std::vector<TensorOrWeights>& inputs) { if( !_op_importers.count(node.op_type()) ) { return MAKE_ERROR("No importer registered for op: " + node.op_type(), ErrorCode::kUNSUPPORTED_NODE); } NodeImporter const& node_importer = _op_importers.at(node.op_type()); std::vector<TensorOrWeights> outputs; GET_VALUE(node_importer(&_importer_ctx, node, inputs), &outputs); ASSERT(outputs.size() <= (size_t)node.output().size(), ErrorCode::kINTERNAL_ERROR); for( size_t i=0; i<outputs.size(); ++i ) { std::string node_output_name = node.output(i); TensorOrWeights& output = outputs.at(i); if( output ) { if( output.is_tensor() ) { output.tensor().setName(node_output_name.c_str()); } //// TODO: Remove when done testing //cout << "Imported " << node.op_type() // << " output tensor '" << node_output_name; //if( output.is_tensor() ) { // cout << "' (" << output.tensor().getType() << ")"; //} //cout << endl; } } return outputs; } Status deserialize_onnx_model(void const* serialized_onnx_model, size_t serialized_onnx_model_size, bool is_serialized_as_text, ::ONNX_NAMESPACE::ModelProto* model) { google::protobuf::io::ArrayInputStream raw_input(serialized_onnx_model, serialized_onnx_model_size); if( is_serialized_as_text ) { ASSERT(google::protobuf::TextFormat::Parse(&raw_input, model), ErrorCode::kMODEL_DESERIALIZE_FAILED); } else { google::protobuf::io::CodedInputStream coded_input(&raw_input); // Note: This WARs the very low default size limit (64MB) coded_input.SetTotalBytesLimit(std::numeric_limits<int>::max(), std::numeric_limits<int>::max() / 4); ASSERT(model->ParseFromCodedStream(&coded_input), ErrorCode::kMODEL_DESERIALIZE_FAILED); } return Status::success(); } Status deserialize_onnx_model(int fd, bool is_serialized_as_text, ::ONNX_NAMESPACE::ModelProto* model) { google::protobuf::io::FileInputStream raw_input(fd); if( is_serialized_as_text ) { ASSERT(google::protobuf::TextFormat::Parse(&raw_input, model), ErrorCode::kMODEL_DESERIALIZE_FAILED); } else { google::protobuf::io::CodedInputStream coded_input(&raw_input); // Note: This WARs the very low default size limit (64MB) coded_input.SetTotalBytesLimit(std::numeric_limits<int>::max(), std::numeric_limits<int>::max()/4); ASSERT(model->ParseFromCodedStream(&coded_input), ErrorCode::kMODEL_DESERIALIZE_FAILED); } return Status::success(); } bool ModelImporter::supportsOperator(const char* op_name) const { return _op_importers.count(op_name); } bool ModelImporter::parse(void const *serialized_onnx_model, size_t serialized_onnx_model_size) { _current_node = -1; // TODO: This function (and its overload below) could do with some cleaning, // particularly wrt error handling. // Note: We store a copy of the model so that weight arrays will persist _onnx_models.emplace_back(); ::ONNX_NAMESPACE::ModelProto& model = _onnx_models.back(); bool is_serialized_as_text = false; Status status = deserialize_onnx_model( serialized_onnx_model, serialized_onnx_model_size, is_serialized_as_text, &model); if( status.is_error() ) { _errors.push_back(status); return false; } status = this->importModel(model); if( status.is_error() ) { status.setNode(_current_node); _errors.push_back(status); return false; } return true; } Status ModelImporter::importModel(::ONNX_NAMESPACE::ModelProto const& model) { // TODO: Remove when done testing //cout << "------Begin model " << model.graph().name() << "-------" << endl; //cout << model << endl; //cout << "------End model-------" << endl; _importer_ctx.clearOpsets(); for( int i=0; i<model.opset_import().size(); ++i ) { std::string domain = model.opset_import(i).domain(); int64_t version = model.opset_import(i).version(); _importer_ctx.addOpset(domain, version); } ::ONNX_NAMESPACE::GraphProto const& graph = model.graph(); string_map<TensorOrWeights> tensors; TRT_CHECK(importInputs(&_importer_ctx, graph, &tensors)); std::vector<size_t> topological_order; ASSERT(toposort(graph.node(), &topological_order), ErrorCode::kINVALID_GRAPH); for( size_t node_idx : topological_order ) { _current_node = node_idx; ::ONNX_NAMESPACE::NodeProto const& node = graph.node(node_idx); std::vector<TensorOrWeights> inputs; for( auto const& input_name : node.input() ) { ASSERT(tensors.count(input_name), ErrorCode::kINVALID_GRAPH); inputs.push_back(tensors.at(input_name)); } std::vector<TensorOrWeights> outputs; GET_VALUE(this->importNode(node, inputs), &outputs); for( size_t i=0; i<outputs.size(); ++i ) { std::string node_output_name = node.output(i); TensorOrWeights& output = outputs.at(i); // Note: This condition is to allow ONNX outputs to be ignored if( output ) { ASSERT(!tensors.count(node_output_name), ErrorCode::kINVALID_GRAPH); tensors.insert({node_output_name, output}); } } if( node.output().size() > 0 ) { std::stringstream ss; ss << node.output(0) << ":" << node.op_type() << " -> " << outputs.at(0).shape(); _importer_ctx.logger().log( nvinfer1::ILogger::Severity::kINFO, ss.str().c_str()); } } _current_node = -1; // Mark outputs defined in the ONNX model (unless tensors are user-requested) for( ::ONNX_NAMESPACE::ValueInfoProto const& output : graph.output() ) { ASSERT(tensors.count(output.name()), ErrorCode::kINVALID_GRAPH); ASSERT(tensors.at(output.name()).is_tensor(), ErrorCode::kUNSUPPORTED_GRAPH); nvinfer1::ITensor* output_tensor_ptr = &tensors.at(output.name()).tensor(); if( output_tensor_ptr->isNetworkInput() ) { // HACK WAR for TRT not allowing input == output // TODO: Does this break things by changing the name of the input tensor? output_tensor_ptr->setName(("__" + output.name()).c_str()); output_tensor_ptr = &identity(&_importer_ctx, output_tensor_ptr).tensor(); ASSERT(output_tensor_ptr, ErrorCode::kUNSUPPORTED_NODE); output_tensor_ptr->setName(output.name().c_str()); } nvinfer1::ITensor** user_output = _importer_ctx.getUserOutput(output.name().c_str()); if( !user_output ) { _importer_ctx.network()->markOutput(*output_tensor_ptr); nvinfer1::DataType output_trt_dtype; ASSERT(convert_dtype( output.type().tensor_type().elem_type(), &output_trt_dtype), ErrorCode::kUNSUPPORTED_NODE); #if NV_TENSORRT_MAJOR >= 4 // For INT32 data type, output type must match tensor type ASSERT(output_tensor_ptr->getType() != nvinfer1::DataType::kINT32 || output_trt_dtype == nvinfer1::DataType::kINT32, ErrorCode::kUNSUPPORTED_NODE); #endif // NV_TENSORRT_MAJOR >= 4 // Note: Without this, output type is always float32 output_tensor_ptr->setType(output_trt_dtype); } } // Return user-requested output tensors for( auto user_output_entry : _importer_ctx.getUserOutputs() ) { std::string user_output_name = user_output_entry.first; nvinfer1::ITensor** user_output_ptr = user_output_entry.second; ASSERT(tensors.count(user_output_name), ErrorCode::kINVALID_VALUE); TensorOrWeights user_output = tensors.at(user_output_name); ASSERT(user_output.is_tensor(), ErrorCode::kINVALID_VALUE); *user_output_ptr = &user_output.tensor(); } return Status::success(); } } // namespace onnx2trt <|endoftext|>
<commit_before>/****************************************************************************** * ____ _ _____ * * / ___| / \ | ___| C++ * * | | / _ \ | |_ Actor * * | |___ / ___ \| _| Framework * * \____/_/ \_|_| * * * * Copyright 2011-2018 Dominik Charousset * * * * Distributed under the terms and conditions of the BSD 3-Clause License or * * (at your option) under the terms and conditions of the Boost Software * * License 1.0. See accompanying files LICENSE and LICENSE_ALTERNATIVE. * * * * If you did not receive a copy of the license files, see * * http://opensource.org/licenses/BSD-3-Clause and * * http://www.boost.org/LICENSE_1_0.txt. * ******************************************************************************/ #pragma once #include <cstddef> #include <cstdint> #include <string> #include <vector> #include "caf/actor.hpp" #include "caf/actor_cast.hpp" #include "caf/downstream_manager.hpp" #include "caf/downstream_msg.hpp" #include "caf/fwd.hpp" #include "caf/mailbox_element.hpp" #include "caf/make_message.hpp" #include "caf/message_builder.hpp" #include "caf/ref_counted.hpp" #include "caf/stream.hpp" #include "caf/stream_slot.hpp" #include "caf/upstream_msg.hpp" namespace caf { /// Manages a single stream with any number of in- and outbound paths. class stream_manager : public ref_counted { public: // -- constants -------------------------------------------------------------- /// Configures whether this stream shall remain open even if no in- or /// outbound paths exist. static constexpr int is_continuous_flag = 0x0001; /// Denotes whether the stream is about to stop, only sending already /// buffered elements. static constexpr int is_shutting_down_flag = 0x0002; // -- member types ----------------------------------------------------------- using inbound_paths_list = std::vector<inbound_path*>; stream_manager(scheduled_actor* selfptr, stream_priority prio = stream_priority::normal); ~stream_manager() override; virtual void handle(inbound_path* from, downstream_msg::batch& x); virtual void handle(inbound_path* from, downstream_msg::close& x); virtual void handle(inbound_path* from, downstream_msg::forced_close& x); virtual bool handle(stream_slots, upstream_msg::ack_open& x); virtual void handle(stream_slots slots, upstream_msg::ack_batch& x); virtual void handle(stream_slots slots, upstream_msg::drop& x); virtual void handle(stream_slots slots, upstream_msg::forced_drop& x); /// Closes all output and input paths and sends the final result to the /// client. virtual void stop(error reason = none); /// Mark this stream as shutting down, only allowing flushing all related /// buffers of in- and outbound paths. virtual void shutdown(); /// Tries to advance the stream by generating more credit or by sending /// batches. void advance(); /// Pushes new data to downstream actors by sending batches. The amount of /// pushed data is limited by the available credit. virtual void push(); /// Returns true if the handler is not able to process any further batches /// since it is unable to make progress sending on its own. virtual bool congested() const noexcept; /// Sends a handshake to `dest`. /// @pre `dest != nullptr` virtual void deliver_handshake(response_promise& rp, stream_slot slot, message handshake); // -- implementation hooks for sources --------------------------------------- /// Tries to generate new messages for the stream. This member function does /// nothing on stages and sinks, but can trigger a source to produce more /// messages. virtual bool generate_messages(); // -- pure virtual member functions ------------------------------------------ /// Returns the manager for downstream communication. virtual downstream_manager& out() = 0; /// Returns the manager for downstream communication. const downstream_manager& out() const; /// Returns whether the manager has reached the end and can be discarded /// safely. virtual bool done() const = 0; /// Returns whether the manager cannot make any progress on its own at the /// moment. For example, a source is idle if it has filled its output buffer /// and there isn't any credit left. virtual bool idle() const noexcept = 0; /// Advances time. virtual void cycle_timeout(size_t cycle_nr); // -- input path management -------------------------------------------------- /// Informs the manager that a new input path opens. /// @note The lifetime of inbound paths is managed by the downstream queue. /// This function is called from the constructor of `inbound_path`. virtual void register_input_path(inbound_path* x); /// Informs the manager that an input path closes. /// @note The lifetime of inbound paths is managed by the downstream queue. /// This function is called from the destructor of `inbound_path`. virtual void deregister_input_path(inbound_path* x) noexcept; /// Removes an input path virtual void remove_input_path(stream_slot slot, error reason, bool silent); // -- properties ------------------------------------------------------------- /// Returns whether this stream is shutting down. bool shutting_down() const noexcept { return getf(is_shutting_down_flag); } /// Returns whether this stream remains open even if no in- or outbound paths /// exist. The default is `false`. Does not keep a source alive past the /// point where its driver returns `done() == true`. inline bool continuous() const noexcept { return getf(is_continuous_flag); } /// Sets whether this stream remains open even if no in- or outbound paths /// exist. inline void continuous(bool x) noexcept { if (!shutting_down()) { if (x) setf(is_continuous_flag); else unsetf(is_continuous_flag); } } /// Returns the list of inbound paths. inline const inbound_paths_list& inbound_paths() const noexcept{ return inbound_paths_; } /// Returns the inbound paths at slot `x`. inbound_path* get_inbound_path(stream_slot x) const noexcept; /// Queries whether all inbound paths are up-to-date and have non-zero /// credit. A sink is idle if this function returns `true`. bool inbound_paths_idle() const noexcept; /// Returns the parent actor. inline scheduled_actor* self() { return self_; } /// Acquires credit on an inbound path. The calculated credit to fill our /// queue fro two cycles is `desired`, but the manager is allowed to return /// any non-negative value. virtual int32_t acquire_credit(inbound_path* path, int32_t desired); /// Creates an outbound path to the current sender without any type checking. /// @pre `out().terminal() == false` /// @private template <class Out> outbound_stream_slot<Out> add_unchecked_outbound_path() { auto handshake = make_message(stream<Out>{}); return add_unchecked_outbound_path_impl(std::move(handshake)); } /// Creates an outbound path to the current sender without any type checking. /// @pre `out().terminal() == false` /// @private template <class Out, class... Ts> outbound_stream_slot<Out, detail::strip_and_convert_t<Ts>...> add_unchecked_outbound_path(std::tuple<Ts...> xs) { auto tk = std::make_tuple(stream<Out>{}); auto handshake = make_message_from_tuple(std::tuple_cat(tk, std::move(xs))); return add_unchecked_outbound_path_impl(std::move(handshake)); } /// Creates an outbound path to `next`, only checking whether the interface /// of `next` allows handshakes of type `Out`. /// @pre `next != nullptr` /// @pre `self()->pending_stream_managers_[slot] == this` /// @pre `out().terminal() == false` /// @private template <class Out, class Handle> outbound_stream_slot<Out> add_unchecked_outbound_path(Handle next) { // TODO: type-check whether `next` accepts our handshake auto handshake = make_message(stream<Out>{}); auto hdl = actor_cast<strong_actor_ptr>(std::move(next)); return add_unchecked_outbound_path_impl(std::move(hdl), std::move(handshake)); } /// Creates an outbound path to `next`, only checking whether the interface /// of `next` allows handshakes of type `Out` with arguments `Ts...`. /// @pre `next != nullptr` /// @pre `self()->pending_stream_managers_[slot] == this` /// @pre `out().terminal() == false` /// @private template <class Out, class Handle, class... Ts> outbound_stream_slot<Out, detail::strip_and_convert_t<Ts>...> add_unchecked_outbound_path(const Handle& next, std::tuple<Ts...> xs) { // TODO: type-check whether `next` accepts our handshake auto tk = std::make_tuple(stream<Out>{}); auto handshake = make_message_from_tuple(std::tuple_cat(tk, std::move(xs))); auto hdl = actor_cast<strong_actor_ptr>(std::move(next)); return add_unchecked_outbound_path_impl(std::move(hdl), std::move(handshake)); } /// Creates an inbound path to the current sender without any type checking. /// @pre `current_sender() != nullptr` /// @pre `out().terminal() == false` /// @private template <class In> stream_slot add_unchecked_inbound_path(const stream<In>&) { return add_unchecked_inbound_path_impl(make_rtti_pair<In>()); } /// Adds a new outbound path to `rp.next()`. /// @private stream_slot add_unchecked_outbound_path_impl(response_promise& rp, message handshake); /// Adds a new outbound path to `next`. /// @private stream_slot add_unchecked_outbound_path_impl(strong_actor_ptr next, message handshake); /// Adds a new outbound path to the current sender. /// @private stream_slot add_unchecked_outbound_path_impl(message handshake); /// Adds the current sender as an inbound path. /// @pre Current message is an `open_stream_msg`. stream_slot add_unchecked_inbound_path_impl(rtti_pair rtti); protected: // -- modifiers for self ----------------------------------------------------- stream_slot assign_next_slot(); stream_slot assign_next_pending_slot(); // -- implementation hooks --------------------------------------------------- virtual void finalize(const error& reason); // -- implementation hooks for sinks ----------------------------------------- /// Called when `in().closed()` changes to `true`. The default /// implementation does nothing. virtual void input_closed(error reason); // -- implementation hooks for sources --------------------------------------- /// Called whenever new credit becomes available. The default implementation /// logs an error (sources are expected to override this hook). virtual void downstream_demand(outbound_path* ptr, long demand); /// Called when `out().closed()` changes to `true`. The default /// implementation does nothing. virtual void output_closed(error reason); // -- member variables ------------------------------------------------------- /// Points to the parent actor. scheduled_actor* self_; /// Stores non-owning pointers to all input paths. inbound_paths_list inbound_paths_; /// Keeps track of pending handshakes. long pending_handshakes_; /// Configures the importance of outgoing traffic. stream_priority priority_; /// Stores individual flags, for continuous streaming or when shutting down. int flags_; private: void setf(int flag) noexcept { auto x = flags_; flags_ = x | flag; } void unsetf(int flag) noexcept { auto x = flags_; flags_ = x & ~flag; } bool getf(int flag) const noexcept { return (flags_ & flag) != 0; } }; /// A reference counting pointer to a `stream_manager`. /// @relates stream_manager using stream_manager_ptr = intrusive_ptr<stream_manager>; } // namespace caf <commit_msg>Add is_stopped_flag and fix formatting<commit_after>/****************************************************************************** * ____ _ _____ * * / ___| / \ | ___| C++ * * | | / _ \ | |_ Actor * * | |___ / ___ \| _| Framework * * \____/_/ \_|_| * * * * Copyright 2011-2018 Dominik Charousset * * * * Distributed under the terms and conditions of the BSD 3-Clause License or * * (at your option) under the terms and conditions of the Boost Software * * License 1.0. See accompanying files LICENSE and LICENSE_ALTERNATIVE. * * * * If you did not receive a copy of the license files, see * * http://opensource.org/licenses/BSD-3-Clause and * * http://www.boost.org/LICENSE_1_0.txt. * ******************************************************************************/ #pragma once #include <cstddef> #include <cstdint> #include <string> #include <vector> #include "caf/actor.hpp" #include "caf/actor_cast.hpp" #include "caf/downstream_manager.hpp" #include "caf/downstream_msg.hpp" #include "caf/fwd.hpp" #include "caf/mailbox_element.hpp" #include "caf/make_message.hpp" #include "caf/message_builder.hpp" #include "caf/ref_counted.hpp" #include "caf/stream.hpp" #include "caf/stream_slot.hpp" #include "caf/upstream_msg.hpp" namespace caf { /// Manages a single stream with any number of in- and outbound paths. class stream_manager : public ref_counted { public: // -- constants -------------------------------------------------------------- /// Configures whether this stream shall remain open even if no in- or /// outbound paths exist. static constexpr int is_continuous_flag = 0x0001; /// Denotes whether the stream is about to stop, only sending already /// buffered elements. static constexpr int is_shutting_down_flag = 0x0002; /// Denotes whether the manager has already stopped. Calling member functions /// such as stop() or abort() on it no longer has any effect. static constexpr int is_stopped_flag = 0x0004; // -- member types ----------------------------------------------------------- using inbound_paths_list = std::vector<inbound_path*>; stream_manager(scheduled_actor* selfptr, stream_priority prio = stream_priority::normal); ~stream_manager() override; virtual void handle(inbound_path* from, downstream_msg::batch& x); virtual void handle(inbound_path* from, downstream_msg::close& x); virtual void handle(inbound_path* from, downstream_msg::forced_close& x); virtual bool handle(stream_slots, upstream_msg::ack_open& x); virtual void handle(stream_slots slots, upstream_msg::ack_batch& x); virtual void handle(stream_slots slots, upstream_msg::drop& x); virtual void handle(stream_slots slots, upstream_msg::forced_drop& x); /// Closes all output and input paths and sends the final result to the /// client. virtual void stop(error reason = none); /// Mark this stream as shutting down, only allowing flushing all related /// buffers of in- and outbound paths. virtual void shutdown(); /// Tries to advance the stream by generating more credit or by sending /// batches. void advance(); /// Pushes new data to downstream actors by sending batches. The amount of /// pushed data is limited by the available credit. virtual void push(); /// Returns true if the handler is not able to process any further batches /// since it is unable to make progress sending on its own. virtual bool congested() const noexcept; /// Sends a handshake to `dest`. /// @pre `dest != nullptr` virtual void deliver_handshake(response_promise& rp, stream_slot slot, message handshake); // -- implementation hooks for sources --------------------------------------- /// Tries to generate new messages for the stream. This member function does /// nothing on stages and sinks, but can trigger a source to produce more /// messages. virtual bool generate_messages(); // -- pure virtual member functions ------------------------------------------ /// Returns the manager for downstream communication. virtual downstream_manager& out() = 0; /// Returns the manager for downstream communication. const downstream_manager& out() const; /// Returns whether the manager has reached the end and can be discarded /// safely. virtual bool done() const = 0; /// Returns whether the manager cannot make any progress on its own at the /// moment. For example, a source is idle if it has filled its output buffer /// and there isn't any credit left. virtual bool idle() const noexcept = 0; /// Advances time. virtual void cycle_timeout(size_t cycle_nr); // -- input path management -------------------------------------------------- /// Informs the manager that a new input path opens. /// @note The lifetime of inbound paths is managed by the downstream queue. /// This function is called from the constructor of `inbound_path`. virtual void register_input_path(inbound_path* x); /// Informs the manager that an input path closes. /// @note The lifetime of inbound paths is managed by the downstream queue. /// This function is called from the destructor of `inbound_path`. virtual void deregister_input_path(inbound_path* x) noexcept; /// Removes an input path virtual void remove_input_path(stream_slot slot, error reason, bool silent); // -- properties ------------------------------------------------------------- /// Returns whether this stream is shutting down. bool shutting_down() const noexcept { return getf(is_shutting_down_flag); } /// Returns whether this manager has already stopped. bool stopped() const noexcept { return getf(is_stopped_flag); } /// Returns whether this stream remains open even if no in- or outbound paths /// exist. The default is `false`. Does not keep a source alive past the /// point where its driver returns `done() == true`. bool continuous() const noexcept { return getf(is_continuous_flag); } /// Sets whether this stream remains open even if no in- or outbound paths /// exist. void continuous(bool x) noexcept { if (!shutting_down()) { if (x) setf(is_continuous_flag); else unsetf(is_continuous_flag); } } /// Returns the list of inbound paths. const inbound_paths_list& inbound_paths() const noexcept { return inbound_paths_; } /// Returns the inbound paths at slot `x`. inbound_path* get_inbound_path(stream_slot x) const noexcept; /// Queries whether all inbound paths are up-to-date and have non-zero /// credit. A sink is idle if this function returns `true`. bool inbound_paths_idle() const noexcept; /// Returns the parent actor. scheduled_actor* self() { return self_; } /// Acquires credit on an inbound path. The calculated credit to fill our /// queue fro two cycles is `desired`, but the manager is allowed to return /// any non-negative value. virtual int32_t acquire_credit(inbound_path* path, int32_t desired); /// Creates an outbound path to the current sender without any type checking. /// @pre `out().terminal() == false` /// @private template <class Out> outbound_stream_slot<Out> add_unchecked_outbound_path() { auto handshake = make_message(stream<Out>{}); return add_unchecked_outbound_path_impl(std::move(handshake)); } /// Creates an outbound path to the current sender without any type checking. /// @pre `out().terminal() == false` /// @private template <class Out, class... Ts> outbound_stream_slot<Out, detail::strip_and_convert_t<Ts>...> add_unchecked_outbound_path(std::tuple<Ts...> xs) { auto tk = std::make_tuple(stream<Out>{}); auto handshake = make_message_from_tuple(std::tuple_cat(tk, std::move(xs))); return add_unchecked_outbound_path_impl(std::move(handshake)); } /// Creates an outbound path to `next`, only checking whether the interface /// of `next` allows handshakes of type `Out`. /// @pre `next != nullptr` /// @pre `self()->pending_stream_managers_[slot] == this` /// @pre `out().terminal() == false` /// @private template <class Out, class Handle> outbound_stream_slot<Out> add_unchecked_outbound_path(Handle next) { // TODO: type-check whether `next` accepts our handshake auto handshake = make_message(stream<Out>{}); auto hdl = actor_cast<strong_actor_ptr>(std::move(next)); return add_unchecked_outbound_path_impl(std::move(hdl), std::move(handshake)); } /// Creates an outbound path to `next`, only checking whether the interface /// of `next` allows handshakes of type `Out` with arguments `Ts...`. /// @pre `next != nullptr` /// @pre `self()->pending_stream_managers_[slot] == this` /// @pre `out().terminal() == false` /// @private template <class Out, class Handle, class... Ts> outbound_stream_slot<Out, detail::strip_and_convert_t<Ts>...> add_unchecked_outbound_path(const Handle& next, std::tuple<Ts...> xs) { // TODO: type-check whether `next` accepts our handshake auto tk = std::make_tuple(stream<Out>{}); auto handshake = make_message_from_tuple(std::tuple_cat(tk, std::move(xs))); auto hdl = actor_cast<strong_actor_ptr>(std::move(next)); return add_unchecked_outbound_path_impl(std::move(hdl), std::move(handshake)); } /// Creates an inbound path to the current sender without any type checking. /// @pre `current_sender() != nullptr` /// @pre `out().terminal() == false` /// @private template <class In> stream_slot add_unchecked_inbound_path(const stream<In>&) { return add_unchecked_inbound_path_impl(make_rtti_pair<In>()); } /// Adds a new outbound path to `rp.next()`. /// @private stream_slot add_unchecked_outbound_path_impl(response_promise& rp, message handshake); /// Adds a new outbound path to `next`. /// @private stream_slot add_unchecked_outbound_path_impl(strong_actor_ptr next, message handshake); /// Adds a new outbound path to the current sender. /// @private stream_slot add_unchecked_outbound_path_impl(message handshake); /// Adds the current sender as an inbound path. /// @pre Current message is an `open_stream_msg`. stream_slot add_unchecked_inbound_path_impl(rtti_pair rtti); protected: // -- modifiers for self ----------------------------------------------------- stream_slot assign_next_slot(); stream_slot assign_next_pending_slot(); // -- implementation hooks --------------------------------------------------- virtual void finalize(const error& reason); // -- implementation hooks for sinks ----------------------------------------- /// Called when `in().closed()` changes to `true`. The default /// implementation does nothing. virtual void input_closed(error reason); // -- implementation hooks for sources --------------------------------------- /// Called whenever new credit becomes available. The default implementation /// logs an error (sources are expected to override this hook). virtual void downstream_demand(outbound_path* ptr, long demand); /// Called when `out().closed()` changes to `true`. The default /// implementation does nothing. virtual void output_closed(error reason); // -- member variables ------------------------------------------------------- /// Points to the parent actor. scheduled_actor* self_; /// Stores non-owning pointers to all input paths. inbound_paths_list inbound_paths_; /// Keeps track of pending handshakes. long pending_handshakes_; /// Configures the importance of outgoing traffic. stream_priority priority_; /// Stores individual flags, for continuous streaming or when shutting down. int flags_; private: void setf(int flag) noexcept { auto x = flags_; flags_ = x | flag; } void unsetf(int flag) noexcept { auto x = flags_; flags_ = x & ~flag; } bool getf(int flag) const noexcept { return (flags_ & flag) != 0; } }; /// A reference counting pointer to a `stream_manager`. /// @relates stream_manager using stream_manager_ptr = intrusive_ptr<stream_manager>; } // namespace caf <|endoftext|>
<commit_before>// Copyright 2015-2019 Elviss Strazdins. All rights reserved. #ifndef OUZEL_MATH_MATHUTILS_HPP #define OUZEL_MATH_MATHUTILS_HPP #include <cstdint> #include <cmath> #include <limits> #include <type_traits> #if defined(__ANDROID__) # include <cpu-features.h> #endif namespace ouzel { #if defined(__ARM_NEON__) # if defined(__ANDROID__) && defined(__arm__) // NEON support must be checked at runtime on 32-bit Android class AnrdoidNeonChecker final { public: AnrdoidNeonChecker() noexcept: neonAvailable(android_getCpuFamily() == ANDROID_CPU_FAMILY_ARM && (android_getCpuFeatures() & ANDROID_CPU_ARM_FEATURE_NEON) != 0) { } operator bool() const noexcept { return neonAvailable; } private: bool neonAvailable; }; extern const AnrdoidNeonChecker isSimdAvailable; # else constexpr auto isSimdAvailable = true; # endif #elif defined(__SSE__) constexpr auto isSimdAvailable = true; #else constexpr auto isSimdAvailable = false; #endif template <typename T> constexpr T lerp(const T v0, const T v1, const T t) noexcept { return (T(1) - t) * v0 + t * v1; } template <typename T> constexpr T smoothStep(const T a, const T b, const T t) noexcept { return lerp(a, b, t * t * (T(3) - T(2) * t)); } template <typename T, typename std::enable_if<std::is_unsigned<T>::value>::type* = nullptr> constexpr auto isPowerOfTwo(const T x) noexcept { return (x != T(0)) && (((x - T(1)) & x) == 0); } template <typename T, typename std::enable_if<std::is_unsigned<T>::value>::type* = nullptr> inline T nextPowerOfTwo(const T x) noexcept { if (x != 0) { --x; for (uint32_t shift = 1; shift < sizeof(T) * 8; shift *= 2) x |= (x >> shift); } return ++x; } template <typename T> constexpr T degToRad(const T x) noexcept { return x * T(0.01745329251994329576); } template <typename T> constexpr T radToDeg(const T x) noexcept { return x * T(57.2957795130823208767); } template <typename T> constexpr T clamp(const T x, const T lo, const T hi) noexcept { return (x < lo) ? lo : ((x > hi) ? hi : x); } template <typename T> constexpr auto isNearlyEqual(const T a, const T b, const T tolerance = std::numeric_limits<T>::min()) noexcept { return (a - b) <= tolerance && (a - b) >= -tolerance; } } #endif // OUZEL_MATH_MATHUTILS_HPP <commit_msg>Split math function declarations into multiple lines<commit_after>// Copyright 2015-2019 Elviss Strazdins. All rights reserved. #ifndef OUZEL_MATH_MATHUTILS_HPP #define OUZEL_MATH_MATHUTILS_HPP #include <cstdint> #include <cmath> #include <limits> #include <type_traits> #if defined(__ANDROID__) # include <cpu-features.h> #endif namespace ouzel { #if defined(__ARM_NEON__) # if defined(__ANDROID__) && defined(__arm__) // NEON support must be checked at runtime on 32-bit Android class AnrdoidNeonChecker final { public: AnrdoidNeonChecker() noexcept: neonAvailable(android_getCpuFamily() == ANDROID_CPU_FAMILY_ARM && (android_getCpuFeatures() & ANDROID_CPU_ARM_FEATURE_NEON) != 0) { } operator bool() const noexcept { return neonAvailable; } private: bool neonAvailable; }; extern const AnrdoidNeonChecker isSimdAvailable; # else constexpr auto isSimdAvailable = true; # endif #elif defined(__SSE__) constexpr auto isSimdAvailable = true; #else constexpr auto isSimdAvailable = false; #endif template <typename T> constexpr T lerp(const T v0, const T v1, const T t) noexcept { return (T(1) - t) * v0 + t * v1; } template <typename T> constexpr T smoothStep(const T a, const T b, const T t) noexcept { return lerp(a, b, t * t * (T(3) - T(2) * t)); } template <typename T, typename std::enable_if<std::is_unsigned<T>::value>::type* = nullptr> constexpr auto isPowerOfTwo(const T x) noexcept { return (x != T(0)) && (((x - T(1)) & x) == 0); } template <typename T, typename std::enable_if<std::is_unsigned<T>::value>::type* = nullptr> inline T nextPowerOfTwo(const T x) noexcept { if (x != 0) { --x; for (uint32_t shift = 1; shift < sizeof(T) * 8; shift *= 2) x |= (x >> shift); } return ++x; } template <typename T> constexpr T degToRad(const T x) noexcept { return x * T(0.01745329251994329576); } template <typename T> constexpr T radToDeg(const T x) noexcept { return x * T(57.2957795130823208767); } template <typename T> constexpr T clamp(const T x, const T lo, const T hi) noexcept { return (x < lo) ? lo : ((x > hi) ? hi : x); } template <typename T> constexpr auto isNearlyEqual(const T a, const T b, const T tolerance = std::numeric_limits<T>::min()) noexcept { return (a - b) <= tolerance && (a - b) >= -tolerance; } } #endif // OUZEL_MATH_MATHUTILS_HPP <|endoftext|>
<commit_before>/********************************************************************* * NAN - Native Abstractions for Node.js * * Copyright (c) 2018 NAN contributors * * MIT License <https://github.com/nodejs/nan/blob/master/LICENSE.md> ********************************************************************/ #include <nan.h> #include <cstring> using namespace Nan; // NOLINT(build/namespaces) class NamedInterceptor : public ObjectWrap { char buf[256]; public: NamedInterceptor() { std::strncpy(this->buf, "foo", sizeof (this->buf)); } static NAN_MODULE_INIT(Init); static v8::Local<v8::Value> NewInstance (); static NAN_METHOD(New); static NAN_PROPERTY_GETTER(PropertyGetter); static NAN_PROPERTY_SETTER(PropertySetter); static NAN_PROPERTY_ENUMERATOR(PropertyEnumerator); static NAN_PROPERTY_DELETER(PropertyDeleter); static NAN_PROPERTY_QUERY(PropertyQuery); }; static Persistent<v8::FunctionTemplate> namedinterceptors_constructor; NAN_METHOD(CreateNew) { info.GetReturnValue().Set(NamedInterceptor::NewInstance()); } NAN_MODULE_INIT(NamedInterceptor::Init) { v8::Local<v8::FunctionTemplate> tpl = Nan::New<v8::FunctionTemplate>(NamedInterceptor::New); namedinterceptors_constructor.Reset(tpl); tpl->SetClassName(Nan::New("NamedInterceptor").ToLocalChecked()); tpl->InstanceTemplate()->SetInternalFieldCount(1); v8::Local<v8::ObjectTemplate> inst = tpl->InstanceTemplate(); SetNamedPropertyHandler( inst , NamedInterceptor::PropertyGetter , NamedInterceptor::PropertySetter , NamedInterceptor::PropertyQuery , NamedInterceptor::PropertyDeleter , NamedInterceptor::PropertyEnumerator); v8::Local<v8::Function> createnew = Nan::New<v8::FunctionTemplate>(CreateNew)->GetFunction(); Set(target, Nan::New("create").ToLocalChecked(), createnew); } v8::Local<v8::Value> NamedInterceptor::NewInstance () { EscapableHandleScope scope; v8::Local<v8::FunctionTemplate> constructorHandle = Nan::New(namedinterceptors_constructor); v8::Local<v8::Object> instance = Nan::NewInstance(constructorHandle->GetFunction()).ToLocalChecked(); return scope.Escape(instance); } NAN_METHOD(NamedInterceptor::New) { NamedInterceptor* interceptor = new NamedInterceptor(); interceptor->Wrap(info.This()); info.GetReturnValue().Set(info.This()); } NAN_PROPERTY_GETTER(NamedInterceptor::PropertyGetter) { NamedInterceptor* interceptor = ObjectWrap::Unwrap<NamedInterceptor>(info.Holder()); if (!std::strcmp(*Nan::Utf8String(property), "prop")) { info.GetReturnValue().Set(Nan::New(interceptor->buf).ToLocalChecked()); } else { info.GetReturnValue().Set(Nan::New("bar").ToLocalChecked()); } } NAN_PROPERTY_SETTER(NamedInterceptor::PropertySetter) { NamedInterceptor* interceptor = ObjectWrap::Unwrap<NamedInterceptor>(info.Holder()); if (!std::strcmp(*Nan::Utf8String(property), "prop")) { std::strncpy( interceptor->buf , *Nan::Utf8String(value) , sizeof (interceptor->buf)); info.GetReturnValue().Set(info.This()); } else { info.GetReturnValue().Set(info.This()); } } NAN_PROPERTY_ENUMERATOR(NamedInterceptor::PropertyEnumerator) { v8::Local<v8::Array> arr = Nan::New<v8::Array>(); Set(arr, 0, Nan::New("value").ToLocalChecked()); info.GetReturnValue().Set(arr); } NAN_PROPERTY_DELETER(NamedInterceptor::PropertyDeleter) { NamedInterceptor* interceptor = ObjectWrap::Unwrap<NamedInterceptor>(info.Holder()); std::strncpy(interceptor->buf, "goober", sizeof (interceptor->buf)); info.GetReturnValue().Set(True()); } NAN_PROPERTY_QUERY(NamedInterceptor::PropertyQuery) { if (!std::strcmp(*Nan::Utf8String(property), "thing")) { info.GetReturnValue().Set(Nan::New<v8::Integer>(v8::DontEnum)); } } NODE_MODULE(namedinterceptors, NamedInterceptor::Init) <commit_msg>Fix bugs in named interceptor test.<commit_after>/********************************************************************* * NAN - Native Abstractions for Node.js * * Copyright (c) 2018 NAN contributors * * MIT License <https://github.com/nodejs/nan/blob/master/LICENSE.md> ********************************************************************/ #include <nan.h> #include <cstring> using namespace Nan; // NOLINT(build/namespaces) class NamedInterceptor : public ObjectWrap { char buf[256]; public: NamedInterceptor() { std::strncpy(this->buf, "foo", sizeof (this->buf)); } static NAN_MODULE_INIT(Init); static v8::Local<v8::Value> NewInstance (); static NAN_METHOD(New); static NAN_PROPERTY_GETTER(PropertyGetter); static NAN_PROPERTY_SETTER(PropertySetter); static NAN_PROPERTY_ENUMERATOR(PropertyEnumerator); static NAN_PROPERTY_DELETER(PropertyDeleter); static NAN_PROPERTY_QUERY(PropertyQuery); }; static Persistent<v8::FunctionTemplate> namedinterceptors_constructor; NAN_METHOD(CreateNew) { info.GetReturnValue().Set(NamedInterceptor::NewInstance()); } NAN_MODULE_INIT(NamedInterceptor::Init) { v8::Local<v8::FunctionTemplate> tpl = Nan::New<v8::FunctionTemplate>(NamedInterceptor::New); namedinterceptors_constructor.Reset(tpl); tpl->SetClassName(Nan::New("NamedInterceptor").ToLocalChecked()); tpl->InstanceTemplate()->SetInternalFieldCount(1); v8::Local<v8::ObjectTemplate> inst = tpl->InstanceTemplate(); SetNamedPropertyHandler( inst , NamedInterceptor::PropertyGetter , NamedInterceptor::PropertySetter , NamedInterceptor::PropertyQuery , NamedInterceptor::PropertyDeleter , NamedInterceptor::PropertyEnumerator); v8::Local<v8::Function> createnew = Nan::New<v8::FunctionTemplate>(CreateNew)->GetFunction(); Set(target, Nan::New("create").ToLocalChecked(), createnew); } v8::Local<v8::Value> NamedInterceptor::NewInstance () { EscapableHandleScope scope; v8::Local<v8::FunctionTemplate> constructorHandle = Nan::New(namedinterceptors_constructor); v8::Local<v8::Object> instance = Nan::NewInstance(constructorHandle->GetFunction()).ToLocalChecked(); return scope.Escape(instance); } NAN_METHOD(NamedInterceptor::New) { NamedInterceptor* interceptor = new NamedInterceptor(); interceptor->Wrap(info.This()); info.GetReturnValue().Set(info.This()); } NAN_PROPERTY_GETTER(NamedInterceptor::PropertyGetter) { NamedInterceptor* interceptor = ObjectWrap::Unwrap<NamedInterceptor>(info.Holder()); if (!std::strcmp(*Nan::Utf8String(property), "prop")) { info.GetReturnValue().Set(Nan::New(interceptor->buf).ToLocalChecked()); } else { info.GetReturnValue().Set(Nan::New("bar").ToLocalChecked()); } } NAN_PROPERTY_SETTER(NamedInterceptor::PropertySetter) { NamedInterceptor* interceptor = ObjectWrap::Unwrap<NamedInterceptor>(info.Holder()); if (!std::strcmp(*Nan::Utf8String(property), "prop")) { std::strncpy( interceptor->buf , *Nan::Utf8String(value) , sizeof (interceptor->buf)); info.GetReturnValue().Set(info.This()); } else { info.GetReturnValue().Set(info.This()); } } NAN_PROPERTY_ENUMERATOR(NamedInterceptor::PropertyEnumerator) { v8::Local<v8::Array> arr = Nan::New<v8::Array>(); Set(arr, 0, Nan::New("value").ToLocalChecked()); info.GetReturnValue().Set(arr); } NAN_PROPERTY_DELETER(NamedInterceptor::PropertyDeleter) { NamedInterceptor* interceptor = ObjectWrap::Unwrap<NamedInterceptor>(info.Holder()); std::strncpy(interceptor->buf, "goober", sizeof (interceptor->buf)); info.GetReturnValue().Set(True()); } NAN_PROPERTY_QUERY(NamedInterceptor::PropertyQuery) { Nan::Utf8String s(property); if (!std::strcmp(*s, "thing")) { return info.GetReturnValue().Set(Nan::New<v8::Integer>(v8::DontEnum)); } if (!std::strcmp(*s, "value")) { return info.GetReturnValue().Set(Nan::New(0)); } } NODE_MODULE(namedinterceptors, NamedInterceptor::Init) <|endoftext|>
<commit_before>// Copyright Yangqing Jia 2013 // pycaffe provides a wrapper of the caffe::Net class as well as some // caffe::Caffe functions so that one could easily call it from Python. // Note that for python, we will simply use float as the data type. #define NPY_NO_DEPRECATED_API NPY_1_7_API_VERSION #include <boost/python.hpp> #include <boost/python/suite/indexing/vector_indexing_suite.hpp> #include <numpy/arrayobject.h> #include "caffe/caffe.hpp" // Temporary solution for numpy < 1.7 versions: old macro. #ifndef NPY_ARRAY_C_CONTIGUOUS #define NPY_ARRAY_C_CONTIGUOUS NPY_C_CONTIGUOUS #endif using namespace caffe; using boost::python::extract; using boost::python::len; using boost::python::list; using boost::python::object; using boost::python::handle; using boost::python::vector_indexing_suite; // wrap shared_ptr<Blob<float> > in a class that we construct in C++ and pass // to Python class CaffeBlob { public: CaffeBlob(const shared_ptr<Blob<float> > &blob) : blob_(blob) {} CaffeBlob() {} int num() const { return blob_->num(); } int channels() const { return blob_->channels(); } int height() const { return blob_->height(); } int width() const { return blob_->width(); } int count() const { return blob_->count(); } bool operator == (const CaffeBlob &other) { return this->blob_ == other.blob_; } protected: shared_ptr<Blob<float> > blob_; }; // we need another wrapper (used as boost::python's HeldType) that receives a // self PyObject * which we can use as ndarray.base, so that data/diff memory // is not freed while still being used in Python class CaffeBlobWrap : public CaffeBlob { public: CaffeBlobWrap(PyObject *p, shared_ptr<Blob<float> > &blob) : CaffeBlob(blob), self_(p) {} CaffeBlobWrap(PyObject *p, const CaffeBlob &blob) : CaffeBlob(blob), self_(p) {} object get_data() { npy_intp dims[] = {num(), channels(), height(), width()}; PyObject *obj = PyArray_SimpleNewFromData(4, dims, NPY_FLOAT32, blob_->mutable_cpu_data()); PyArray_SetBaseObject(reinterpret_cast<PyArrayObject *>(obj), self_); Py_INCREF(self_); handle<> h(obj); return object(h); } object get_diff() { npy_intp dims[] = {num(), channels(), height(), width()}; PyObject *obj = PyArray_SimpleNewFromData(4, dims, NPY_FLOAT32, blob_->mutable_cpu_diff()); PyArray_SetBaseObject(reinterpret_cast<PyArrayObject *>(obj), self_); Py_INCREF(self_); handle<> h(obj); return object(h); } private: PyObject *self_; }; // A simple wrapper over CaffeNet that runs the forward process. struct CaffeNet { CaffeNet(string param_file, string pretrained_param_file) { net_.reset(new Net<float>(param_file)); net_->CopyTrainedLayersFrom(pretrained_param_file); } virtual ~CaffeNet() {} inline void check_array_against_blob( PyArrayObject* arr, Blob<float>* blob) { CHECK(PyArray_FLAGS(arr) & NPY_ARRAY_C_CONTIGUOUS); CHECK_EQ(PyArray_NDIM(arr), 4); CHECK_EQ(PyArray_ITEMSIZE(arr), 4); npy_intp* dims = PyArray_DIMS(arr); CHECK_EQ(dims[0], blob->num()); CHECK_EQ(dims[1], blob->channels()); CHECK_EQ(dims[2], blob->height()); CHECK_EQ(dims[3], blob->width()); } // The actual forward function. It takes in a python list of numpy arrays as // input and a python list of numpy arrays as output. The input and output // should all have correct shapes, are single-precisionabcdnt- and c contiguous. void Forward(list bottom, list top) { vector<Blob<float>*>& input_blobs = net_->input_blobs(); CHECK_EQ(len(bottom), input_blobs.size()); CHECK_EQ(len(top), net_->num_outputs()); // First, copy the input for (int i = 0; i < input_blobs.size(); ++i) { object elem = bottom[i]; PyArrayObject* arr = reinterpret_cast<PyArrayObject*>(elem.ptr()); check_array_against_blob(arr, input_blobs[i]); switch (Caffe::mode()) { case Caffe::CPU: memcpy(input_blobs[i]->mutable_cpu_data(), PyArray_DATA(arr), sizeof(float) * input_blobs[i]->count()); break; case Caffe::GPU: cudaMemcpy(input_blobs[i]->mutable_gpu_data(), PyArray_DATA(arr), sizeof(float) * input_blobs[i]->count(), cudaMemcpyHostToDevice); break; default: LOG(FATAL) << "Unknown Caffe mode."; } // switch (Caffe::mode()) } //LOG(INFO) << "Start"; const vector<Blob<float>*>& output_blobs = net_->ForwardPrefilled(); //LOG(INFO) << "End"; for (int i = 0; i < output_blobs.size(); ++i) { object elem = top[i]; PyArrayObject* arr = reinterpret_cast<PyArrayObject*>(elem.ptr()); check_array_against_blob(arr, output_blobs[i]); switch (Caffe::mode()) { case Caffe::CPU: memcpy(PyArray_DATA(arr), output_blobs[i]->cpu_data(), sizeof(float) * output_blobs[i]->count()); break; case Caffe::GPU: cudaMemcpy(PyArray_DATA(arr), output_blobs[i]->gpu_data(), sizeof(float) * output_blobs[i]->count(), cudaMemcpyDeviceToHost); break; default: LOG(FATAL) << "Unknown Caffe mode."; } // switch (Caffe::mode()) } } void Backward(list top_diff, list bottom_diff) { vector<Blob<float>*>& output_blobs = net_->output_blobs(); vector<Blob<float>*>& input_blobs = net_->input_blobs(); CHECK_EQ(len(bottom_diff), input_blobs.size()); CHECK_EQ(len(top_diff), output_blobs.size()); // First, copy the output diff for (int i = 0; i < output_blobs.size(); ++i) { object elem = top_diff[i]; PyArrayObject* arr = reinterpret_cast<PyArrayObject*>(elem.ptr()); check_array_against_blob(arr, output_blobs[i]); switch (Caffe::mode()) { case Caffe::CPU: memcpy(output_blobs[i]->mutable_cpu_diff(), PyArray_DATA(arr), sizeof(float) * output_blobs[i]->count()); break; case Caffe::GPU: cudaMemcpy(output_blobs[i]->mutable_gpu_diff(), PyArray_DATA(arr), sizeof(float) * output_blobs[i]->count(), cudaMemcpyHostToDevice); break; default: LOG(FATAL) << "Unknown Caffe mode."; } // switch (Caffe::mode()) } //LOG(INFO) << "Start"; net_->Backward(); //LOG(INFO) << "End"; for (int i = 0; i < input_blobs.size(); ++i) { object elem = bottom_diff[i]; PyArrayObject* arr = reinterpret_cast<PyArrayObject*>(elem.ptr()); check_array_against_blob(arr, input_blobs[i]); switch (Caffe::mode()) { case Caffe::CPU: memcpy(PyArray_DATA(arr), input_blobs[i]->cpu_diff(), sizeof(float) * input_blobs[i]->count()); break; case Caffe::GPU: cudaMemcpy(PyArray_DATA(arr), input_blobs[i]->gpu_diff(), sizeof(float) * input_blobs[i]->count(), cudaMemcpyDeviceToHost); break; default: LOG(FATAL) << "Unknown Caffe mode."; } // switch (Caffe::mode()) } } // The caffe::Caffe utility functions. void set_mode_cpu() { Caffe::set_mode(Caffe::CPU); } void set_mode_gpu() { Caffe::set_mode(Caffe::GPU); } void set_phase_train() { Caffe::set_phase(Caffe::TRAIN); } void set_phase_test() { Caffe::set_phase(Caffe::TEST); } void set_device(int device_id) { Caffe::SetDevice(device_id); } vector<CaffeBlob> blobs() { return vector<CaffeBlob>(net_->blobs().begin(), net_->blobs().end()); } } // The pointer to the internal caffe::Net instant. shared_ptr<Net<float> > net_; }; // The boost python module definition. BOOST_PYTHON_MODULE(pycaffe) { boost::python::class_<CaffeNet>( "CaffeNet", boost::python::init<string, string>()) .def("Forward", &CaffeNet::Forward) .def("Backward", &CaffeNet::Backward) .def("set_mode_cpu", &CaffeNet::set_mode_cpu) .def("set_mode_gpu", &CaffeNet::set_mode_gpu) .def("set_phase_train", &CaffeNet::set_phase_train) .def("set_phase_test", &CaffeNet::set_phase_test) .def("set_device", &CaffeNet::set_device) .def("blobs", &CaffeNet::blobs) ; boost::python::class_<CaffeBlob, CaffeBlobWrap>( "CaffeBlob", boost::python::no_init) .add_property("num", &CaffeBlob::num) .add_property("channels", &CaffeBlob::channels) .add_property("height", &CaffeBlob::height) .add_property("width", &CaffeBlob::width) .add_property("count", &CaffeBlob::count) .add_property("data", &CaffeBlobWrap::get_data) .add_property("diff", &CaffeBlobWrap::get_diff) ; boost::python::class_<vector<CaffeBlob> >("BlobVec") .def(vector_indexing_suite<vector<CaffeBlob>, true>()); import_array(); } <commit_msg>Expose params in Python interface<commit_after>// Copyright Yangqing Jia 2013 // pycaffe provides a wrapper of the caffe::Net class as well as some // caffe::Caffe functions so that one could easily call it from Python. // Note that for python, we will simply use float as the data type. #define NPY_NO_DEPRECATED_API NPY_1_7_API_VERSION #include <boost/python.hpp> #include <boost/python/suite/indexing/vector_indexing_suite.hpp> #include <numpy/arrayobject.h> #include "caffe/caffe.hpp" // Temporary solution for numpy < 1.7 versions: old macro. #ifndef NPY_ARRAY_C_CONTIGUOUS #define NPY_ARRAY_C_CONTIGUOUS NPY_C_CONTIGUOUS #endif using namespace caffe; using boost::python::extract; using boost::python::len; using boost::python::list; using boost::python::object; using boost::python::handle; using boost::python::vector_indexing_suite; // wrap shared_ptr<Blob<float> > in a class that we construct in C++ and pass // to Python class CaffeBlob { public: CaffeBlob(const shared_ptr<Blob<float> > &blob) : blob_(blob) {} CaffeBlob() {} int num() const { return blob_->num(); } int channels() const { return blob_->channels(); } int height() const { return blob_->height(); } int width() const { return blob_->width(); } int count() const { return blob_->count(); } bool operator == (const CaffeBlob &other) { return this->blob_ == other.blob_; } protected: shared_ptr<Blob<float> > blob_; }; // we need another wrapper (used as boost::python's HeldType) that receives a // self PyObject * which we can use as ndarray.base, so that data/diff memory // is not freed while still being used in Python class CaffeBlobWrap : public CaffeBlob { public: CaffeBlobWrap(PyObject *p, shared_ptr<Blob<float> > &blob) : CaffeBlob(blob), self_(p) {} CaffeBlobWrap(PyObject *p, const CaffeBlob &blob) : CaffeBlob(blob), self_(p) {} object get_data() { npy_intp dims[] = {num(), channels(), height(), width()}; PyObject *obj = PyArray_SimpleNewFromData(4, dims, NPY_FLOAT32, blob_->mutable_cpu_data()); PyArray_SetBaseObject(reinterpret_cast<PyArrayObject *>(obj), self_); Py_INCREF(self_); handle<> h(obj); return object(h); } object get_diff() { npy_intp dims[] = {num(), channels(), height(), width()}; PyObject *obj = PyArray_SimpleNewFromData(4, dims, NPY_FLOAT32, blob_->mutable_cpu_diff()); PyArray_SetBaseObject(reinterpret_cast<PyArrayObject *>(obj), self_); Py_INCREF(self_); handle<> h(obj); return object(h); } private: PyObject *self_; }; // A simple wrapper over CaffeNet that runs the forward process. struct CaffeNet { CaffeNet(string param_file, string pretrained_param_file) { net_.reset(new Net<float>(param_file)); net_->CopyTrainedLayersFrom(pretrained_param_file); } virtual ~CaffeNet() {} inline void check_array_against_blob( PyArrayObject* arr, Blob<float>* blob) { CHECK(PyArray_FLAGS(arr) & NPY_ARRAY_C_CONTIGUOUS); CHECK_EQ(PyArray_NDIM(arr), 4); CHECK_EQ(PyArray_ITEMSIZE(arr), 4); npy_intp* dims = PyArray_DIMS(arr); CHECK_EQ(dims[0], blob->num()); CHECK_EQ(dims[1], blob->channels()); CHECK_EQ(dims[2], blob->height()); CHECK_EQ(dims[3], blob->width()); } // The actual forward function. It takes in a python list of numpy arrays as // input and a python list of numpy arrays as output. The input and output // should all have correct shapes, are single-precisionabcdnt- and c contiguous. void Forward(list bottom, list top) { vector<Blob<float>*>& input_blobs = net_->input_blobs(); CHECK_EQ(len(bottom), input_blobs.size()); CHECK_EQ(len(top), net_->num_outputs()); // First, copy the input for (int i = 0; i < input_blobs.size(); ++i) { object elem = bottom[i]; PyArrayObject* arr = reinterpret_cast<PyArrayObject*>(elem.ptr()); check_array_against_blob(arr, input_blobs[i]); switch (Caffe::mode()) { case Caffe::CPU: memcpy(input_blobs[i]->mutable_cpu_data(), PyArray_DATA(arr), sizeof(float) * input_blobs[i]->count()); break; case Caffe::GPU: cudaMemcpy(input_blobs[i]->mutable_gpu_data(), PyArray_DATA(arr), sizeof(float) * input_blobs[i]->count(), cudaMemcpyHostToDevice); break; default: LOG(FATAL) << "Unknown Caffe mode."; } // switch (Caffe::mode()) } //LOG(INFO) << "Start"; const vector<Blob<float>*>& output_blobs = net_->ForwardPrefilled(); //LOG(INFO) << "End"; for (int i = 0; i < output_blobs.size(); ++i) { object elem = top[i]; PyArrayObject* arr = reinterpret_cast<PyArrayObject*>(elem.ptr()); check_array_against_blob(arr, output_blobs[i]); switch (Caffe::mode()) { case Caffe::CPU: memcpy(PyArray_DATA(arr), output_blobs[i]->cpu_data(), sizeof(float) * output_blobs[i]->count()); break; case Caffe::GPU: cudaMemcpy(PyArray_DATA(arr), output_blobs[i]->gpu_data(), sizeof(float) * output_blobs[i]->count(), cudaMemcpyDeviceToHost); break; default: LOG(FATAL) << "Unknown Caffe mode."; } // switch (Caffe::mode()) } } void Backward(list top_diff, list bottom_diff) { vector<Blob<float>*>& output_blobs = net_->output_blobs(); vector<Blob<float>*>& input_blobs = net_->input_blobs(); CHECK_EQ(len(bottom_diff), input_blobs.size()); CHECK_EQ(len(top_diff), output_blobs.size()); // First, copy the output diff for (int i = 0; i < output_blobs.size(); ++i) { object elem = top_diff[i]; PyArrayObject* arr = reinterpret_cast<PyArrayObject*>(elem.ptr()); check_array_against_blob(arr, output_blobs[i]); switch (Caffe::mode()) { case Caffe::CPU: memcpy(output_blobs[i]->mutable_cpu_diff(), PyArray_DATA(arr), sizeof(float) * output_blobs[i]->count()); break; case Caffe::GPU: cudaMemcpy(output_blobs[i]->mutable_gpu_diff(), PyArray_DATA(arr), sizeof(float) * output_blobs[i]->count(), cudaMemcpyHostToDevice); break; default: LOG(FATAL) << "Unknown Caffe mode."; } // switch (Caffe::mode()) } //LOG(INFO) << "Start"; net_->Backward(); //LOG(INFO) << "End"; for (int i = 0; i < input_blobs.size(); ++i) { object elem = bottom_diff[i]; PyArrayObject* arr = reinterpret_cast<PyArrayObject*>(elem.ptr()); check_array_against_blob(arr, input_blobs[i]); switch (Caffe::mode()) { case Caffe::CPU: memcpy(PyArray_DATA(arr), input_blobs[i]->cpu_diff(), sizeof(float) * input_blobs[i]->count()); break; case Caffe::GPU: cudaMemcpy(PyArray_DATA(arr), input_blobs[i]->gpu_diff(), sizeof(float) * input_blobs[i]->count(), cudaMemcpyDeviceToHost); break; default: LOG(FATAL) << "Unknown Caffe mode."; } // switch (Caffe::mode()) } } // The caffe::Caffe utility functions. void set_mode_cpu() { Caffe::set_mode(Caffe::CPU); } void set_mode_gpu() { Caffe::set_mode(Caffe::GPU); } void set_phase_train() { Caffe::set_phase(Caffe::TRAIN); } void set_phase_test() { Caffe::set_phase(Caffe::TEST); } void set_device(int device_id) { Caffe::SetDevice(device_id); } vector<CaffeBlob> blobs() { return vector<CaffeBlob>(net_->blobs().begin(), net_->blobs().end()); } vector<CaffeBlob> params() { return vector<CaffeBlob>(net_->params().begin(), net_->params().end()); } // The pointer to the internal caffe::Net instant. shared_ptr<Net<float> > net_; }; // The boost python module definition. BOOST_PYTHON_MODULE(pycaffe) { boost::python::class_<CaffeNet>( "CaffeNet", boost::python::init<string, string>()) .def("Forward", &CaffeNet::Forward) .def("Backward", &CaffeNet::Backward) .def("set_mode_cpu", &CaffeNet::set_mode_cpu) .def("set_mode_gpu", &CaffeNet::set_mode_gpu) .def("set_phase_train", &CaffeNet::set_phase_train) .def("set_phase_test", &CaffeNet::set_phase_test) .def("set_device", &CaffeNet::set_device) .def("blobs", &CaffeNet::blobs) .def("params", &CaffeNet::params) ; boost::python::class_<CaffeBlob, CaffeBlobWrap>( "CaffeBlob", boost::python::no_init) .add_property("num", &CaffeBlob::num) .add_property("channels", &CaffeBlob::channels) .add_property("height", &CaffeBlob::height) .add_property("width", &CaffeBlob::width) .add_property("count", &CaffeBlob::count) .add_property("data", &CaffeBlobWrap::get_data) .add_property("diff", &CaffeBlobWrap::get_diff) ; boost::python::class_<vector<CaffeBlob> >("BlobVec") .def(vector_indexing_suite<vector<CaffeBlob>, true>()); import_array(); } <|endoftext|>
<commit_before> AliAnalysisTaskJetCluster *AddTaskJetCluster(char* bRec = "AOD",char* bGen = "",UInt_t filterMask = 16, UInt_t iPhysicsSelectionFlag = AliVEvent::kMB,Char_t *jf = "KT", Float_t radius = 0.4,Int_t nSkip = 0,Int_t kWriteAOD = kFALSE,char* deltaFile = "",Float_t ptTrackCut = 0.15); Int_t kBackgroundMode = 0; Float_t kPtTrackCut = 0.15; Float_t kTrackEtaCut = 0.8; AliAnalysisTaskJetCluster *AddTaskJetClusterDelta(UInt_t filterMask = 16,Bool_t kUseAODMC = kFALSE,UInt_t iPhysicsSelectionFlag = AliVEvent::kMB,Char_t *jf = "KT", UInt_t iFlag){ AliAnalysisTaskJetCluster *js = 0; if(kUseAODMC&&false){// do not use the MC info yet if(iFlag&(1<<0))js = AddTaskJetCluster("AOD","AODMC",filterMask,iPhysicsSelectionFlag,jf,0.00001); if(iFlag&(1<<1))js = AddTaskJetCluster("AOD","AODMC",filterMask,iPhysicsSelectionFlag,jf,0.1); if(iFlag&(1<<2))js = AddTaskJetCluster("AOD","AODMC",filterMask,iPhysicsSelectionFlag,jf,0.2); if(iFlag&(1<<4))js = AddTaskJetCluster("AOD","AODMC",filterMask,iPhysicsSelectionFlag,jf,0.4); if(iFlag&(1<<6))js = AddTaskJetCluster("AOD","AODMC",filterMask,iPhysicsSelectionFlag,jf,0.6); if(iFlag&(1<<8))js = AddTaskJetCluster("AOD","AODMC",filterMask,iPhysicsSelectionFlag,jf,0.8); if(iFlag&(1<<10))js = AddTaskJetCluster("AOD","AODMC",filterMask,iPhysicsSelectionFlag,jf,1.0); } else{ if(iFlag&(1<<0))js = AddTaskJetCluster("AOD","",filterMask,iPhysicsSelectionFlag,jf,0.00001); if(iFlag&(1<<1))js = AddTaskJetCluster("AOD","",filterMask,iPhysicsSelectionFlag,jf,0.1); if(iFlag&(1<<2))js = AddTaskJetCluster("AOD","",filterMask,iPhysicsSelectionFlag,jf,0.2); if(iFlag&(1<<4))js = AddTaskJetCluster("AOD","",filterMask,iPhysicsSelectionFlag,jf,0.4); if(iFlag&(1<<6))js = AddTaskJetCluster("AOD","",filterMask,iPhysicsSelectionFlag,jf,0.6); if(iFlag&(1<<8))js = AddTaskJetCluster("AOD","",filterMask,iPhysicsSelectionFlag,jf,0.8); if(iFlag&(1<<10))js = AddTaskJetCluster("AOD","",filterMask,iPhysicsSelectionFlag,jf,1.0); } return js; } AliAnalysisTaskJetCluster *AddTaskJetCluster(char* bRec,char* bGen ,UInt_t filterMask,UInt_t iPhysicsSelectionFlag,Char_t *jf,Float_t radius,Int_t nSkip,Int_t kWriteAOD,char *deltaFile,Float_t ptTrackCut) { // Creates a jet fider task, configures it and adds it to the analysis manager. kPtTrackCut = ptTrackCut; TString outputFile(deltaFile); // Get the pointer to the existing analysis manager via the static access method. //============================================================================== AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager(); if (!mgr) { ::Error("AddTaskJetCluster", "No analysis manager to connect to."); return NULL; } // Check the analysis type using the event handlers connected to the analysis manager. //============================================================================== if (!mgr->GetInputEventHandler()) { ::Error("AddTaskJetCluster", "This task requires an input event handler"); return NULL; } TString type = mgr->GetInputEventHandler()->GetDataType(); TString typeRec(bRec); TString typeGen(bGen); if(!typeRec.Contains("AODextra")) { typeGen.ToUpper(); typeRec.ToUpper(); } cout << "typeRec: " << typeRec << endl; // Create the task and configure it. //=========================================================================== TString cAdd = ""; cAdd += Form("%02d_",(int)((radius+0.01)*10.)); cAdd += Form("B%d",(int)kBackgroundMode); cAdd += Form("_Filter%05d",filterMask); cAdd += Form("_Cut%05d",(int)(1000.*kPtTrackCut)); cAdd += Form("_Skip%02d",nSkip); Printf("%s %E",cAdd.Data(),kPtTrackCut); AliAnalysisTaskJetCluster* pwg4spec = new AliAnalysisTaskJetCluster(Form("JetCluster%s_%s%s",bRec,jf,cAdd.Data())); // or a config file // pwg4spec->SetAnalysisType(AliAnalysisTaskJetCluster::kAnaMC); // if(iAODanalysis)pwg4spec->SetAODInput(kTRUE); // pwg4spec->SetDebugLevel(11); pwg4spec->SetFilterMask(filterMask); // pwg4spec->SetUseGlobalSelection(kTRUE); if(type == "AOD"){ // Assume all jet are produced already pwg4spec->SetAODTrackInput(kTRUE); pwg4spec->SetAODMCInput(kTRUE); } if(typeRec.Contains("AODMC2b")){// work down from the top AODMC2b -> AODMC2 -> AODMC -> AOD pwg4spec->SetTrackTypeRec(AliAnalysisTaskJetCluster::kTrackAODMCChargedAcceptance); pwg4spec->SetTrackPtCut(kTrackEtaCut); } else if (typeRec.Contains("AODMC2")){ pwg4spec->SetTrackTypeRec(AliAnalysisTaskJetCluster::kTrackAODMCCharged); pwg4spec->SetTrackPtCut(5); } else if (typeRec.Contains("AODMC")){ pwg4spec->SetTrackTypeRec(AliAnalysisTaskJetCluster::kTrackAODMCAll); pwg4spec->SetTrackPtCut(5); } else if (typeRec.Contains("AODextraonly")) { pwg4spec->SetTrackTypeRec(AliAnalysisTaskJetCluster::kTrackAODextraonly); pwg4spec->SetTrackPtCut(kPtTrackCut); pwg4spec->SetTrackPtCut(kTrackEtaCut); } else if (typeRec.Contains("AODextra")) { cout << "AliAnalysisTaskJetCluster::kTrackAODextra: " << AliAnalysisTaskJetCluster::kTrackAODextra << endl; pwg4spec->SetTrackTypeRec(AliAnalysisTaskJetCluster::kTrackAODextra); pwg4spec->SetTrackPtCut(kPtTrackCut); pwg4spec->SetTrackPtCut(kTrackEtaCut); } else if (typeRec.Contains("AOD")) { pwg4spec->SetTrackTypeRec(AliAnalysisTaskJetCluster::kTrackAOD); pwg4spec->SetTrackPtCut(kPtTrackCut); pwg4spec->SetTrackPtCut(kTrackEtaCut); } pwg4spec->SetRparam(radius); switch (jf) { case "ANTIKT": pwg4spec->SetAlgorithm(2); // antikt from fastjet/JetDefinition.hh break; case "CA": pwg4spec->SetAlgorithm(1); // CA from fastjet/JetDefinition.hh break; case "KT": pwg4spec->SetAlgorithm(0); // kt from fastjet/JetDefinition.hh break; default: ::Error("AddTaskJetCluster", "Wrong jet finder selected\n"); return 0; } if(kWriteAOD){ if(outputFile.Length())pwg4spec->SetJetOutputFile(outputFile); pwg4spec->SetJetOutputBranch(Form("clusters%s_%s%s",bRec,jf,cAdd.Data())); pwg4spec->SetJetOutputMinPt(0); // store only jets / clusters above a certain threshold } pwg4spec->SetNSkipLeadingRan(nSkip); if(iPhysicsSelectionFlag)pwg4spec->SelectCollisionCandidates(iPhysicsSelectionFlag); mgr->AddTask(pwg4spec); // Create ONLY the output containers for the data produced by the task. // Get and connect other common input/output containers via the manager as below //============================================================================== AliAnalysisDataContainer *coutput1_Spec = mgr->CreateContainer(Form("pwg4cluster_%s_%s_%s%s",bRec,bGen,jf,cAdd.Data()), TList::Class(),AliAnalysisManager::kOutputContainer,Form("%s:PWG4_cluster_%s_%s_%s%s",AliAnalysisManager::GetCommonFileName(),bRec,bGen,jf,cAdd.Data())); mgr->ConnectInput (pwg4spec, 0, mgr->GetCommonInputContainer()); mgr->ConnectOutput (pwg4spec, 0, mgr->GetCommonOutputContainer()); mgr->ConnectOutput (pwg4spec, 1, coutput1_Spec ); return pwg4spec; } <commit_msg>fixed seeting of eta cut<commit_after> AliAnalysisTaskJetCluster *AddTaskJetCluster(char* bRec = "AOD",char* bGen = "",UInt_t filterMask = 16, UInt_t iPhysicsSelectionFlag = AliVEvent::kMB,Char_t *jf = "KT", Float_t radius = 0.4,Int_t nSkip = 0,Int_t kWriteAOD = kFALSE,char* deltaFile = "",Float_t ptTrackCut = 0.15); Int_t kBackgroundMode = 0; Float_t kPtTrackCut = 0.15; Float_t kTrackEtaCut = 0.8; AliAnalysisTaskJetCluster *AddTaskJetClusterDelta(UInt_t filterMask = 16,Bool_t kUseAODMC = kFALSE,UInt_t iPhysicsSelectionFlag = AliVEvent::kMB,Char_t *jf = "KT", UInt_t iFlag){ AliAnalysisTaskJetCluster *js = 0; if(kUseAODMC&&false){// do not use the MC info yet if(iFlag&(1<<0))js = AddTaskJetCluster("AOD","AODMC",filterMask,iPhysicsSelectionFlag,jf,0.00001); if(iFlag&(1<<1))js = AddTaskJetCluster("AOD","AODMC",filterMask,iPhysicsSelectionFlag,jf,0.1); if(iFlag&(1<<2))js = AddTaskJetCluster("AOD","AODMC",filterMask,iPhysicsSelectionFlag,jf,0.2); if(iFlag&(1<<4))js = AddTaskJetCluster("AOD","AODMC",filterMask,iPhysicsSelectionFlag,jf,0.4); if(iFlag&(1<<6))js = AddTaskJetCluster("AOD","AODMC",filterMask,iPhysicsSelectionFlag,jf,0.6); if(iFlag&(1<<8))js = AddTaskJetCluster("AOD","AODMC",filterMask,iPhysicsSelectionFlag,jf,0.8); if(iFlag&(1<<10))js = AddTaskJetCluster("AOD","AODMC",filterMask,iPhysicsSelectionFlag,jf,1.0); } else{ if(iFlag&(1<<0))js = AddTaskJetCluster("AOD","",filterMask,iPhysicsSelectionFlag,jf,0.00001); if(iFlag&(1<<1))js = AddTaskJetCluster("AOD","",filterMask,iPhysicsSelectionFlag,jf,0.1); if(iFlag&(1<<2))js = AddTaskJetCluster("AOD","",filterMask,iPhysicsSelectionFlag,jf,0.2); if(iFlag&(1<<4))js = AddTaskJetCluster("AOD","",filterMask,iPhysicsSelectionFlag,jf,0.4); if(iFlag&(1<<6))js = AddTaskJetCluster("AOD","",filterMask,iPhysicsSelectionFlag,jf,0.6); if(iFlag&(1<<8))js = AddTaskJetCluster("AOD","",filterMask,iPhysicsSelectionFlag,jf,0.8); if(iFlag&(1<<10))js = AddTaskJetCluster("AOD","",filterMask,iPhysicsSelectionFlag,jf,1.0); } return js; } AliAnalysisTaskJetCluster *AddTaskJetCluster(char* bRec,char* bGen ,UInt_t filterMask,UInt_t iPhysicsSelectionFlag,Char_t *jf,Float_t radius,Int_t nSkip,Int_t kWriteAOD,char *deltaFile,Float_t ptTrackCut) { // Creates a jet fider task, configures it and adds it to the analysis manager. kPtTrackCut = ptTrackCut; TString outputFile(deltaFile); // Get the pointer to the existing analysis manager via the static access method. //============================================================================== AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager(); if (!mgr) { ::Error("AddTaskJetCluster", "No analysis manager to connect to."); return NULL; } // Check the analysis type using the event handlers connected to the analysis manager. //============================================================================== if (!mgr->GetInputEventHandler()) { ::Error("AddTaskJetCluster", "This task requires an input event handler"); return NULL; } TString type = mgr->GetInputEventHandler()->GetDataType(); TString typeRec(bRec); TString typeGen(bGen); if(!typeRec.Contains("AODextra")) { typeGen.ToUpper(); typeRec.ToUpper(); } cout << "typeRec: " << typeRec << endl; // Create the task and configure it. //=========================================================================== TString cAdd = ""; cAdd += Form("%02d_",(int)((radius+0.01)*10.)); cAdd += Form("B%d",(int)kBackgroundMode); cAdd += Form("_Filter%05d",filterMask); cAdd += Form("_Cut%05d",(int)(1000.*kPtTrackCut)); cAdd += Form("_Skip%02d",nSkip); Printf("%s %E",cAdd.Data(),kPtTrackCut); AliAnalysisTaskJetCluster* pwg4spec = new AliAnalysisTaskJetCluster(Form("JetCluster%s_%s%s",bRec,jf,cAdd.Data())); // or a config file // pwg4spec->SetAnalysisType(AliAnalysisTaskJetCluster::kAnaMC); // if(iAODanalysis)pwg4spec->SetAODInput(kTRUE); // pwg4spec->SetDebugLevel(11); pwg4spec->SetFilterMask(filterMask); // pwg4spec->SetUseGlobalSelection(kTRUE); if(type == "AOD"){ // Assume all jet are produced already pwg4spec->SetAODTrackInput(kTRUE); pwg4spec->SetAODMCInput(kTRUE); } if(typeRec.Contains("AODMC2b")){// work down from the top AODMC2b -> AODMC2 -> AODMC -> AOD pwg4spec->SetTrackTypeRec(AliAnalysisTaskJetCluster::kTrackAODMCChargedAcceptance); pwg4spec->SetTrackPtCut(kPtTrackCut); pwg4spec->SetTrackEtaCut(kTrackEtaCut); } else if (typeRec.Contains("AODMC2")){ pwg4spec->SetTrackTypeRec(AliAnalysisTaskJetCluster::kTrackAODMCCharged); pwg4spec->SetTrackPtCut(kPtTrackCut); pwg4spec->SetTrackEtaCut(5); } else if (typeRec.Contains("AODMC")){ pwg4spec->SetTrackTypeRec(AliAnalysisTaskJetCluster::kTrackAODMCAll); pwg4spec->SetTrackPtCut(kPtTrackCut); pwg4spec->SetTrackEtaCut(5); } else if (typeRec.Contains("AODextraonly")) { pwg4spec->SetTrackTypeRec(AliAnalysisTaskJetCluster::kTrackAODextraonly); pwg4spec->SetTrackPtCut(kPtTrackCut); pwg4spec->SetTrackEtaCut(kTrackEtaCut); } else if (typeRec.Contains("AODextra")) { cout << "AliAnalysisTaskJetCluster::kTrackAODextra: " << AliAnalysisTaskJetCluster::kTrackAODextra << endl; pwg4spec->SetTrackTypeRec(AliAnalysisTaskJetCluster::kTrackAODextra); pwg4spec->SetTrackPtCut(kPtTrackCut); pwg4spec->SetTrackEtaCut(kTrackEtaCut); } else if (typeRec.Contains("AOD")) { pwg4spec->SetTrackTypeRec(AliAnalysisTaskJetCluster::kTrackAOD); pwg4spec->SetTrackPtCut(kPtTrackCut); pwg4spec->SetTrackEtaCut(kTrackEtaCut); } pwg4spec->SetRparam(radius); switch (jf) { case "ANTIKT": pwg4spec->SetAlgorithm(2); // antikt from fastjet/JetDefinition.hh break; case "CA": pwg4spec->SetAlgorithm(1); // CA from fastjet/JetDefinition.hh break; case "KT": pwg4spec->SetAlgorithm(0); // kt from fastjet/JetDefinition.hh break; default: ::Error("AddTaskJetCluster", "Wrong jet finder selected\n"); return 0; } if(kWriteAOD){ if(outputFile.Length())pwg4spec->SetJetOutputFile(outputFile); pwg4spec->SetJetOutputBranch(Form("clusters%s_%s%s",bRec,jf,cAdd.Data())); pwg4spec->SetJetOutputMinPt(0); // store only jets / clusters above a certain threshold } pwg4spec->SetNSkipLeadingRan(nSkip); if(iPhysicsSelectionFlag)pwg4spec->SelectCollisionCandidates(iPhysicsSelectionFlag); mgr->AddTask(pwg4spec); // Create ONLY the output containers for the data produced by the task. // Get and connect other common input/output containers via the manager as below //============================================================================== AliAnalysisDataContainer *coutput1_Spec = mgr->CreateContainer(Form("pwg4cluster_%s_%s_%s%s",bRec,bGen,jf,cAdd.Data()), TList::Class(),AliAnalysisManager::kOutputContainer,Form("%s:PWG4_cluster_%s_%s_%s%s",AliAnalysisManager::GetCommonFileName(),bRec,bGen,jf,cAdd.Data())); mgr->ConnectInput (pwg4spec, 0, mgr->GetCommonInputContainer()); mgr->ConnectOutput (pwg4spec, 0, mgr->GetCommonOutputContainer()); mgr->ConnectOutput (pwg4spec, 1, coutput1_Spec ); return pwg4spec; } <|endoftext|>
<commit_before>/*------------------------------------------------------------------------- * * FILE * pqxx/isolation.hxx * * DESCRIPTION * definitions of transaction isolation levels * Policies and traits describing SQL transaction isolation levels * DO NOT INCLUDE THIS FILE DIRECTLY; include pqxx/isolation instead. * * Copyright (c) 2003, Jeroen T. Vermeulen <jtv@xs4all.nl> * * See COPYING for copyright license. If you did not receive a file called * COPYING with this source code, please notify the distributor of this mistake, * or contact the author. * *------------------------------------------------------------------------- */ #include "pqxx/util" namespace pqxx { /// Transaction isolation levels; PostgreSQL doesn't implement all SQL levels /** The only levels implemented in postgres are read_committed and serializable; * SQL also defines read_uncommitted and repeatable_read. Unless you're bent on * using nasty tricks to communicate between ongoing transactions and such, you * won't really need isolation levels for anything except performance * optimization. In that case, you can safely emulate read_uncommitted by using * read_committed and repeatable_read by using serializable. In general, * serializable is the safest choice. */ enum PQXX_LIBEXPORT isolation_level { // read_uncommitted, read_committed, // repeatable_read, serializable }; /// Traits class to describe an isolation level; primarly for libpqxx's own use template<isolation_level LEVEL> struct isolation_traits { static isolation_level level() throw () { return LEVEL; } static const char *name() throw (); /// Only defined for implemented levels; nonexistant levels yield link errors static void implemented() throw (); }; template<> inline void isolation_traits<read_committed>::implemented() throw(){} template<> inline void isolation_traits<serializable>::implemented() throw(){} template<> inline const char *isolation_traits<read_committed>::name() throw () { return "READ COMMITTED"; } template<> inline const char *isolation_traits<serializable>::name() throw () { return "SERIALIZABLE"; } } <commit_msg>Removed unused stuff<commit_after>/*------------------------------------------------------------------------- * * FILE * pqxx/isolation.hxx * * DESCRIPTION * definitions of transaction isolation levels * Policies and traits describing SQL transaction isolation levels * DO NOT INCLUDE THIS FILE DIRECTLY; include pqxx/isolation instead. * * Copyright (c) 2003-2004, Jeroen T. Vermeulen <jtv@xs4all.nl> * * See COPYING for copyright license. If you did not receive a file called * COPYING with this source code, please notify the distributor of this mistake, * or contact the author. * *------------------------------------------------------------------------- */ #include "pqxx/util" namespace pqxx { /// Transaction isolation levels; PostgreSQL doesn't implement all SQL levels /** The only levels implemented in postgres are read_committed and serializable; * SQL also defines read_uncommitted and repeatable_read. Unless you're bent on * using nasty tricks to communicate between ongoing transactions and such, you * won't really need isolation levels for anything except performance * optimization. In that case, you can safely emulate read_uncommitted by using * read_committed and repeatable_read by using serializable. In general, * serializable is the safest choice. */ enum PQXX_LIBEXPORT isolation_level { // read_uncommitted, read_committed, // repeatable_read, serializable }; /// Traits class to describe an isolation level; primarly for libpqxx's own use template<isolation_level LEVEL> struct isolation_traits { static isolation_level level() throw () { return LEVEL; } static const char *name() throw (); }; template<> inline const char *isolation_traits<read_committed>::name() throw () { return "READ COMMITTED"; } template<> inline const char *isolation_traits<serializable>::name() throw () { return "SERIALIZABLE"; } } <|endoftext|>
<commit_before>#pragma once #include <PluginFactory/details/NullPluginService.hpp> #include <PluginFactory/details/PluginHandle.hpp> #include <PluginFactory/details/PolicyHolder.hpp> #include <PluginFactory/details/PluginLoader.hpp> #include <PluginFactory/details/PolicyProperties.hpp> #include <PluginFactory/Exceptions.hpp> #include <boost/filesystem/path.hpp> #include <boost/filesystem/operations.hpp> #include <memory> #include <string> #include <unordered_map> #include <vector> namespace PluginFactory { // A tag type to indicate we want to create a shared_ptr to struct AsSharedTagType {}; // <PluginInterface> is the abstract interface of the plugin object itself. You'll need // a PluginFactory for each different type of plugin you wish to support. // // <PluginServiceInterface> is the interface given to the plugin to allow it to make // modifications to the main program. This is to encourage plugin developers not to // engage in crazy behavior like calling willy-nilly into the base process's code. // // NOTE: lifetime management using plugins can be difficult. It is essential // the PluginFactory stays in scope longer than any instanced plugin. Failure // to do so will most likely end in the process crashing. template<class PluginInterface, class PluginServiceInterface = details::NullPluginService, class PolicyOwnershipProperty = details::PolicyIsInternal> class PluginFactory : public details::PolicyHolder<PluginServiceInterface, PolicyOwnershipProperty> { public: static AsSharedTagType create_shared; // @pluginDirectory is the directory path to load plugins from. template<typename... Args> PluginFactory(const boost::filesystem::path& pluginDirectory, Args&&... args); void load(); // load all found plugins void load(const boost::filesystem::path& pluginPath); // load a specific plugin (@pluginPath) void unload(); // unload all loaded plugins void unload(const boost::filesystem::path& pluginPath); // unload a specific plugin (@pluginPath) std::unique_ptr<PluginInterface> instance(const std::string& plugin); std::shared_ptr<PluginInterface> instance(const std::string& pluginName, AsSharedTagType /*create_shared*/); std::vector<std::string> availablePlugins() const; private: using PluginPath = std::string; using PluginInstanceMethod = std::function<PluginInterface* (PluginServiceInterface&)>; std::unordered_map<PluginPath, PluginHandle<PluginInterface, PluginServiceInterface>> plugins_; boost::filesystem::path pluginDirectory_; std::string pluginVersion_; std::string compilerToken_; std::string serviceVersion_; }; template<class PluginInterface, class PluginServiceInterface, class PolicyOwnershipProperty> template<typename... Args> PluginFactory<PluginInterface, PluginServiceInterface, PolicyOwnershipProperty>::PluginFactory(const boost::filesystem::path& pluginDirectory, Args&&... args) : details::PolicyHolder<PluginServiceInterface, PolicyOwnershipProperty>(std::forward<Args>(args)...) , pluginDirectory_(pluginDirectory) { if(!boost::filesystem::exists(pluginDirectory_)) { throw PluginPathDoesntExist(pluginDirectory_); } if(!boost::filesystem::is_directory(pluginDirectory_)) { throw PluginPathIsntDirectory(pluginDirectory_); } } template<class PluginInterface, class PluginServiceInterface, class PolicyOwnershipProperty> void PluginFactory<PluginInterface, PluginServiceInterface, PolicyOwnershipProperty>::load() { for(boost::filesystem::directory_iterator iter(pluginDirectory_), end; iter != end; ++iter) { // TODO: check each regular file's extension to see if it is the correct // extension for a shared lib on this platform. } } template<class PluginInterface, class PluginServiceInterface, class PolicyOwnershipProperty> void PluginFactory<PluginInterface, PluginServiceInterface, PolicyOwnershipProperty>::load(const boost::filesystem::path& pluginPath) { try { details::PluginLoader loader(pluginPath); loader.validateCompiler(compilerToken_); loader.validatePluginVersion(pluginVersion_); loader.validatePluginServiceVersion(serviceVersion_); auto pluginHandle = loader.getPluginHandle<PluginInterface, PluginServiceInterface>(); plugins_.emplace(pluginPath.string(), pluginHandle); } // TODO: make this exception more specific, we don't want to catch all of // e catch(const std::exception& e) { } } template<class PluginInterface, class PluginServiceInterface, class PolicyOwnershipProperty> void PluginFactory<PluginInterface, PluginServiceInterface, PolicyOwnershipProperty>::unload() { plugins_.clear(); } template<class PluginInterface, class PluginServiceInterface, class PolicyOwnershipProperty> void PluginFactory<PluginInterface, PluginServiceInterface, PolicyOwnershipProperty>::unload(const boost::filesystem::path& pluginPath) { auto iter = plugins_.find(pluginPath.string()); if(iter != plugins_.end()) { plugins_.erase(iter); } } template<class PluginInterface, class PluginServiceInterface, class PolicyOwnershipProperty> std::unique_ptr<PluginInterface> PluginFactory<PluginInterface, PluginServiceInterface, PolicyOwnershipProperty>::instance(const std::string& pluginName) { std::unique_ptr<PluginInterface> p; auto iter = plugins_.find(pluginName); if(iter != plugins_.end()) { auto& createPlugin = iter->second; p.reset(createPlugin(this->policy_)); } return p; } template<class PluginInterface, class PluginServiceInterface, class PolicyOwnershipProperty> std::shared_ptr<PluginInterface> PluginFactory<PluginInterface, PluginServiceInterface, PolicyOwnershipProperty>::instance(const std::string& pluginName, AsSharedTagType) { std::shared_ptr<PluginInterface> p; auto iter = plugins_.find(pluginName); if(iter != plugins_.end()) { auto& createPlugin = iter->second; p.reset(createPlugin(this->policy_)); } return p; } template<class PluginInterface, class PluginServiceInterface, class PolicyOwnershipProperty> std::vector<std::string> PluginFactory<PluginInterface, PluginServiceInterface, PolicyOwnershipProperty>::availablePlugins() const { std::vector<std::string> plugins; plugins.reserve(plugins_.size()); for(const auto& info : plugins_) { const auto& key = info.first; plugins.push_back(key); } return plugins; } } <commit_msg>comment: improving comments.<commit_after>#pragma once #include <PluginFactory/details/NullPluginService.hpp> #include <PluginFactory/details/PluginHandle.hpp> #include <PluginFactory/details/PolicyHolder.hpp> #include <PluginFactory/details/PluginLoader.hpp> #include <PluginFactory/details/PolicyProperties.hpp> #include <PluginFactory/Exceptions.hpp> #include <boost/filesystem/path.hpp> #include <boost/filesystem/operations.hpp> #include <memory> #include <string> #include <unordered_map> #include <vector> namespace PluginFactory { // A tag type to indicate we want to create a std::shared_ptr of the plugin // rather than std::unique_ptr struct AsSharedTagType {}; // <PluginInterface> is the abstract interface of the plugin object itself. You'll need // a PluginFactory for each different type of plugin you wish to support. // // <PluginServiceInterface> is the interface given to the plugin to allow it to make // modifications to the main program. This is to encourage plugin developers not to // engage in crazy behavior like calling willy-nilly into the base process's code. // // NOTE: lifetime management using plugins can be difficult. It is essential // the PluginFactory stays in scope longer than any instanced plugin. Failure // to do so will most likely end in the process crashing. template<class PluginInterface, class PluginServiceInterface = details::NullPluginService, class PolicyOwnershipProperty = details::PolicyIsInternal> class PluginFactory : public details::PolicyHolder<PluginServiceInterface, PolicyOwnershipProperty> { public: static AsSharedTagType create_shared; // @pluginDirectory is the directory path to load plugins from. template<typename... Args> PluginFactory(const boost::filesystem::path& pluginDirectory, Args&&... args); void load(); // load all found plugins void load(const boost::filesystem::path& pluginPath); // load a specific plugin (@pluginPath) void unload(); // unload all loaded plugins void unload(const boost::filesystem::path& pluginPath); // unload a specific plugin (@pluginPath) std::unique_ptr<PluginInterface> instance(const std::string& plugin); std::shared_ptr<PluginInterface> instance(const std::string& pluginName, AsSharedTagType /*create_shared*/); std::vector<std::string> availablePlugins() const; private: using PluginPath = std::string; using PluginInstanceMethod = std::function<PluginInterface* (PluginServiceInterface&)>; std::unordered_map<PluginPath, PluginHandle<PluginInterface, PluginServiceInterface>> plugins_; boost::filesystem::path pluginDirectory_; std::string pluginVersion_; std::string compilerToken_; std::string serviceVersion_; }; template<class PluginInterface, class PluginServiceInterface, class PolicyOwnershipProperty> template<typename... Args> PluginFactory<PluginInterface, PluginServiceInterface, PolicyOwnershipProperty>::PluginFactory(const boost::filesystem::path& pluginDirectory, Args&&... args) : details::PolicyHolder<PluginServiceInterface, PolicyOwnershipProperty>(std::forward<Args>(args)...) , pluginDirectory_(pluginDirectory) { if(!boost::filesystem::exists(pluginDirectory_)) { throw PluginPathDoesntExist(pluginDirectory_); } if(!boost::filesystem::is_directory(pluginDirectory_)) { throw PluginPathIsntDirectory(pluginDirectory_); } } template<class PluginInterface, class PluginServiceInterface, class PolicyOwnershipProperty> void PluginFactory<PluginInterface, PluginServiceInterface, PolicyOwnershipProperty>::load() { for(boost::filesystem::directory_iterator iter(pluginDirectory_), end; iter != end; ++iter) { // TODO: check each regular file's extension to see if it is the correct // extension for a shared lib on this platform. } } template<class PluginInterface, class PluginServiceInterface, class PolicyOwnershipProperty> void PluginFactory<PluginInterface, PluginServiceInterface, PolicyOwnershipProperty>::load(const boost::filesystem::path& pluginPath) { try { details::PluginLoader loader(pluginPath); loader.validateCompiler(compilerToken_); loader.validatePluginVersion(pluginVersion_); loader.validatePluginServiceVersion(serviceVersion_); auto pluginHandle = loader.getPluginHandle<PluginInterface, PluginServiceInterface>(); plugins_.emplace(pluginPath.string(), pluginHandle); } // TODO: make this exception more specific, we don't want to catch all of // e catch(const std::exception& e) { } } template<class PluginInterface, class PluginServiceInterface, class PolicyOwnershipProperty> void PluginFactory<PluginInterface, PluginServiceInterface, PolicyOwnershipProperty>::unload() { plugins_.clear(); } template<class PluginInterface, class PluginServiceInterface, class PolicyOwnershipProperty> void PluginFactory<PluginInterface, PluginServiceInterface, PolicyOwnershipProperty>::unload(const boost::filesystem::path& pluginPath) { auto iter = plugins_.find(pluginPath.string()); if(iter != plugins_.end()) { plugins_.erase(iter); } } template<class PluginInterface, class PluginServiceInterface, class PolicyOwnershipProperty> std::unique_ptr<PluginInterface> PluginFactory<PluginInterface, PluginServiceInterface, PolicyOwnershipProperty>::instance(const std::string& pluginName) { std::unique_ptr<PluginInterface> p; auto iter = plugins_.find(pluginName); if(iter != plugins_.end()) { auto& createPlugin = iter->second; p.reset(createPlugin(this->policy_)); } return p; } template<class PluginInterface, class PluginServiceInterface, class PolicyOwnershipProperty> std::shared_ptr<PluginInterface> PluginFactory<PluginInterface, PluginServiceInterface, PolicyOwnershipProperty>::instance(const std::string& pluginName, AsSharedTagType) { std::shared_ptr<PluginInterface> p; auto iter = plugins_.find(pluginName); if(iter != plugins_.end()) { auto& createPlugin = iter->second; p.reset(createPlugin(this->policy_)); } return p; } template<class PluginInterface, class PluginServiceInterface, class PolicyOwnershipProperty> std::vector<std::string> PluginFactory<PluginInterface, PluginServiceInterface, PolicyOwnershipProperty>::availablePlugins() const { std::vector<std::string> plugins; plugins.reserve(plugins_.size()); for(const auto& info : plugins_) { const auto& key = info.first; plugins.push_back(key); } return plugins; } } <|endoftext|>
<commit_before>/* * Copyright (c) 2015 Cryptonomex, 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. */ #include <graphene/witness/witness.hpp> #include <graphene/chain/database.hpp> #include <graphene/chain/witness_object.hpp> #include <graphene/utilities/key_conversion.hpp> #include <fc/thread/thread.hpp> #include <iostream> using namespace graphene::witness_plugin; using std::string; using std::vector; namespace bpo = boost::program_options; void new_chain_banner( const graphene::chain::database& db ) { ilog("\n" "********************************\n" "* *\n" "* ------- NEW CHAIN ------ *\n" "* - Welcome to Graphene! - *\n" "* ------------------------ *\n" "* *\n" "********************************\n" "\n"); if( db.get_slot_at_time( fc::time_point::now() ) > 200 ) { wlog("Your genesis seems to have an old timestamp"); wlog("Please consider using the --genesis-timestamp option to give your genesis a recent timestamp"); } } void witness_plugin::plugin_set_program_options( boost::program_options::options_description& command_line_options, boost::program_options::options_description& config_file_options) { auto default_priv_key = fc::ecc::private_key::regenerate(fc::sha256::hash(std::string("nathan"))); string witness_id_example = fc::json::to_string(chain::witness_id_type(5)); command_line_options.add_options() ("enable-stale-production", bpo::bool_switch()->notifier([this](bool e){_production_enabled = e;}), "Enable block production, even if the chain is stale.") ("required-participation", bpo::value<uint32_t>()->default_value(33), "Percent of witnesses (0-100) that must be participating in order to produce blocks") ("witness-id,w", bpo::value<vector<string>>()->composing()->multitoken(), ("ID of witness controlled by this node (e.g. " + witness_id_example + ", quotes are required, may specify multiple times)").c_str()) ("private-key", bpo::value<vector<string>>()->composing()->multitoken()-> DEFAULT_VALUE_VECTOR(std::make_pair(chain::public_key_type(default_priv_key.get_public_key()), graphene::utilities::key_to_wif(default_priv_key))), "Tuple of [PublicKey, WIF private key] (may specify multiple times)") ; config_file_options.add(command_line_options); } std::string witness_plugin::plugin_name()const { return "witness"; } void witness_plugin::plugin_initialize(const boost::program_options::variables_map& options) { try { ilog("witness plugin: plugin_initialize() begin"); _options = &options; LOAD_VALUE_SET(options, "witness-id", _witnesses, chain::witness_id_type) if( options.count("private-key") ) { const std::vector<std::string> key_id_to_wif_pair_strings = options["private-key"].as<std::vector<std::string>>(); for (const std::string& key_id_to_wif_pair_string : key_id_to_wif_pair_strings) { auto key_id_to_wif_pair = graphene::app::dejsonify<std::pair<chain::public_key_type, std::string> >(key_id_to_wif_pair_string, 5); ilog("Public Key: ${public}", ("public", key_id_to_wif_pair.first)); fc::optional<fc::ecc::private_key> private_key = graphene::utilities::wif_to_key(key_id_to_wif_pair.second); if (!private_key) { // the key isn't in WIF format; see if they are still passing the old native private key format. This is // just here to ease the transition, can be removed soon try { private_key = fc::variant(key_id_to_wif_pair.second, 2).as<fc::ecc::private_key>(1); } catch (const fc::exception&) { FC_THROW("Invalid WIF-format private key ${key_string}", ("key_string", key_id_to_wif_pair.second)); } } _private_keys[key_id_to_wif_pair.first] = *private_key; } } if(options.count("required-participation")) { auto required_participation = options["required-participation"].as<uint32_t>(); FC_ASSERT(required_participation <= 100); _required_witness_participation = options["required-participation"].as<uint32_t>()*GRAPHENE_1_PERCENT; if(required_participation < 10) wlog("witness plugin: Warning - Low required participation of ${rp}% found", ("rp", required_participation)); else if(required_participation > 90) wlog("witness plugin: Warning - High required participation of ${rp}% found", ("rp", required_participation)); } ilog("witness plugin: plugin_initialize() end"); } FC_LOG_AND_RETHROW() } void witness_plugin::plugin_startup() { try { ilog("witness plugin: plugin_startup() begin"); chain::database& d = database(); if( !_witnesses.empty() ) { ilog("Launching block production for ${n} witnesses.", ("n", _witnesses.size())); app().set_block_production(true); if( _production_enabled ) { if( d.head_block_num() == 0 ) new_chain_banner(d); _production_skip_flags |= graphene::chain::database::skip_undo_history_check; } refresh_witness_key_cache(); d.applied_block.connect( [this]( const chain::signed_block& b ) { refresh_witness_key_cache(); }); schedule_production_loop(); } else { ilog("No witness configured."); } ilog("witness plugin: plugin_startup() end"); } FC_CAPTURE_AND_RETHROW() } void witness_plugin::plugin_shutdown() { stop_block_production(); } void witness_plugin::stop_block_production() { _shutting_down = true; try { if( _block_production_task.valid() ) _block_production_task.cancel_and_wait(__FUNCTION__); } catch(fc::canceled_exception&) { //Expected exception. Move along. } catch(fc::exception& e) { edump((e.to_detail_string())); } } void witness_plugin::refresh_witness_key_cache() { const auto& db = database(); for( const chain::witness_id_type wit_id : _witnesses ) { const chain::witness_object* wit_obj = db.find( wit_id ); if( wit_obj ) _witness_key_cache[wit_id] = wit_obj->signing_key; else _witness_key_cache[wit_id] = fc::optional<chain::public_key_type>(); } } void witness_plugin::schedule_production_loop() { if (_shutting_down) return; //Schedule for the next second's tick regardless of chain state // If we would wait less than 50ms, wait for the whole second. fc::time_point now = fc::time_point::now(); int64_t time_to_next_second = 1000000 - (now.time_since_epoch().count() % 1000000); if( time_to_next_second < 50000 ) // we must sleep for at least 50ms time_to_next_second += 1000000; fc::time_point next_wakeup( now + fc::microseconds( time_to_next_second ) ); _block_production_task = fc::schedule([this]{block_production_loop();}, next_wakeup, "Witness Block Production"); } block_production_condition::block_production_condition_enum witness_plugin::block_production_loop() { block_production_condition::block_production_condition_enum result; fc::limited_mutable_variant_object capture( GRAPHENE_MAX_NESTED_OBJECTS ); if (_shutting_down) { result = block_production_condition::shutdown; } else { try { result = maybe_produce_block(capture); } catch( const fc::canceled_exception& ) { //We're trying to exit. Go ahead and let this one out. throw; } catch( const fc::exception& e ) { elog("Got exception while generating block:\n${e}", ("e", e.to_detail_string())); result = block_production_condition::exception_producing_block; } } switch( result ) { case block_production_condition::produced: ilog("Generated block #${n} with ${x} transaction(s) and timestamp ${t} at time ${c}", (capture)); break; case block_production_condition::not_synced: ilog("Not producing block because production is disabled until we receive a recent block (see: --enable-stale-production)"); break; case block_production_condition::not_my_turn: break; case block_production_condition::not_time_yet: break; case block_production_condition::no_private_key: ilog("Not producing block because I don't have the private key for ${scheduled_key}", (capture) ); break; case block_production_condition::low_participation: elog("Not producing block because node appears to be on a minority fork with only ${pct}% witness participation", (capture) ); break; case block_production_condition::lag: elog("Not producing block because node didn't wake up within 2500ms of the slot time."); break; case block_production_condition::exception_producing_block: elog( "exception producing block" ); break; case block_production_condition::shutdown: ilog( "shutdown producing block" ); return result; default: elog( "unknown condition ${result} while producing block", ("result", (unsigned char)result) ); break; } schedule_production_loop(); return result; } block_production_condition::block_production_condition_enum witness_plugin::maybe_produce_block( fc::limited_mutable_variant_object& capture ) { chain::database& db = database(); fc::time_point now_fine = fc::time_point::now(); fc::time_point_sec now = now_fine + fc::microseconds( 500000 ); // If the next block production opportunity is in the present or future, we're synced. if( !_production_enabled ) { if( db.get_slot_time(1) >= now ) _production_enabled = true; else return block_production_condition::not_synced; } // is anyone scheduled to produce now or one second in the future? uint32_t slot = db.get_slot_at_time( now ); if( slot == 0 ) { capture("next_time", db.get_slot_time(1)); return block_production_condition::not_time_yet; } // // this assert should not fail, because now <= db.head_block_time() // should have resulted in slot == 0. // // if this assert triggers, there is a serious bug in get_slot_at_time() // which would result in allowing a later block to have a timestamp // less than or equal to the previous block // assert( now > db.head_block_time() ); graphene::chain::witness_id_type scheduled_witness = db.get_scheduled_witness( slot ); // we must control the witness scheduled to produce the next block. if( _witnesses.find( scheduled_witness ) == _witnesses.end() ) { capture("scheduled_witness", scheduled_witness); return block_production_condition::not_my_turn; } fc::time_point_sec scheduled_time = db.get_slot_time( slot ); graphene::chain::public_key_type scheduled_key = *_witness_key_cache[scheduled_witness]; // should be valid auto private_key_itr = _private_keys.find( scheduled_key ); if( private_key_itr == _private_keys.end() ) { capture("scheduled_key", scheduled_key); return block_production_condition::no_private_key; } uint32_t prate = db.witness_participation_rate(); if( prate < _required_witness_participation ) { capture("pct", uint32_t(100*uint64_t(prate) / GRAPHENE_1_PERCENT)); return block_production_condition::low_participation; } if( llabs((scheduled_time - now).count()) > fc::milliseconds( 2500 ).count() ) { capture("scheduled_time", scheduled_time)("now", now); return block_production_condition::lag; } auto block = db.generate_block( scheduled_time, scheduled_witness, private_key_itr->second, _production_skip_flags ); capture("n", block.block_num())("t", block.timestamp)("c", now)("x", block.transactions.size()); fc::async( [this,block](){ p2p_node().broadcast(net::block_message(block)); } ); return block_production_condition::produced; } <commit_msg>wrap long lines in witness.cpp file<commit_after>/* * Copyright (c) 2015 Cryptonomex, 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. */ #include <graphene/witness/witness.hpp> #include <graphene/chain/database.hpp> #include <graphene/chain/witness_object.hpp> #include <graphene/utilities/key_conversion.hpp> #include <fc/thread/thread.hpp> #include <iostream> using namespace graphene::witness_plugin; using std::string; using std::vector; namespace bpo = boost::program_options; void new_chain_banner( const graphene::chain::database& db ) { ilog("\n" "********************************\n" "* *\n" "* ------- NEW CHAIN ------ *\n" "* - Welcome to Graphene! - *\n" "* ------------------------ *\n" "* *\n" "********************************\n" "\n"); if( db.get_slot_at_time( fc::time_point::now() ) > 200 ) { wlog("Your genesis seems to have an old timestamp"); wlog("Please consider using the --genesis-timestamp option to give your genesis a recent timestamp"); } } void witness_plugin::plugin_set_program_options( boost::program_options::options_description& command_line_options, boost::program_options::options_description& config_file_options) { auto default_priv_key = fc::ecc::private_key::regenerate(fc::sha256::hash(std::string("nathan"))); string witness_id_example = fc::json::to_string(chain::witness_id_type(5)); command_line_options.add_options() ("enable-stale-production", bpo::bool_switch()->notifier([this](bool e){_production_enabled = e;}), "Enable block production, even if the chain is stale.") ("required-participation", bpo::value<uint32_t>()->default_value(33), "Percent of witnesses (0-100) that must be participating in order to produce blocks") ("witness-id,w", bpo::value<vector<string>>()->composing()->multitoken(), ("ID of witness controlled by this node (e.g. " + witness_id_example + ", quotes are required, may specify multiple times)").c_str()) ("private-key", bpo::value<vector<string>>()->composing()->multitoken()-> DEFAULT_VALUE_VECTOR(std::make_pair(chain::public_key_type(default_priv_key.get_public_key()), graphene::utilities::key_to_wif(default_priv_key))), "Tuple of [PublicKey, WIF private key] (may specify multiple times)") ; config_file_options.add(command_line_options); } std::string witness_plugin::plugin_name()const { return "witness"; } void witness_plugin::plugin_initialize(const boost::program_options::variables_map& options) { try { ilog("witness plugin: plugin_initialize() begin"); _options = &options; LOAD_VALUE_SET(options, "witness-id", _witnesses, chain::witness_id_type) if( options.count("private-key") ) { const std::vector<std::string> key_id_to_wif_pair_strings = options["private-key"].as<std::vector<std::string>>(); for (const std::string& key_id_to_wif_pair_string : key_id_to_wif_pair_strings) { auto key_id_to_wif_pair = graphene::app::dejsonify<std::pair<chain::public_key_type, std::string> > (key_id_to_wif_pair_string, 5); ilog("Public Key: ${public}", ("public", key_id_to_wif_pair.first)); fc::optional<fc::ecc::private_key> private_key = graphene::utilities::wif_to_key(key_id_to_wif_pair.second); if (!private_key) { // the key isn't in WIF format; see if they are still passing the old native private key format. This is // just here to ease the transition, can be removed soon try { private_key = fc::variant(key_id_to_wif_pair.second, 2).as<fc::ecc::private_key>(1); } catch (const fc::exception&) { FC_THROW("Invalid WIF-format private key ${key_string}", ("key_string", key_id_to_wif_pair.second)); } } _private_keys[key_id_to_wif_pair.first] = *private_key; } } if(options.count("required-participation")) { auto required_participation = options["required-participation"].as<uint32_t>(); FC_ASSERT(required_participation <= 100); _required_witness_participation = options["required-participation"].as<uint32_t>()*GRAPHENE_1_PERCENT; if(required_participation < 10) wlog("witness plugin: Warning - Low required participation of ${rp}% found", ("rp", required_participation)); else if(required_participation > 90) wlog("witness plugin: Warning - High required participation of ${rp}% found", ("rp", required_participation)); } ilog("witness plugin: plugin_initialize() end"); } FC_LOG_AND_RETHROW() } void witness_plugin::plugin_startup() { try { ilog("witness plugin: plugin_startup() begin"); chain::database& d = database(); if( !_witnesses.empty() ) { ilog("Launching block production for ${n} witnesses.", ("n", _witnesses.size())); app().set_block_production(true); if( _production_enabled ) { if( d.head_block_num() == 0 ) new_chain_banner(d); _production_skip_flags |= graphene::chain::database::skip_undo_history_check; } refresh_witness_key_cache(); d.applied_block.connect( [this]( const chain::signed_block& b ) { refresh_witness_key_cache(); }); schedule_production_loop(); } else { ilog("No witness configured."); } ilog("witness plugin: plugin_startup() end"); } FC_CAPTURE_AND_RETHROW() } void witness_plugin::plugin_shutdown() { stop_block_production(); } void witness_plugin::stop_block_production() { _shutting_down = true; try { if( _block_production_task.valid() ) _block_production_task.cancel_and_wait(__FUNCTION__); } catch(fc::canceled_exception&) { //Expected exception. Move along. } catch(fc::exception& e) { edump((e.to_detail_string())); } } void witness_plugin::refresh_witness_key_cache() { const auto& db = database(); for( const chain::witness_id_type wit_id : _witnesses ) { const chain::witness_object* wit_obj = db.find( wit_id ); if( wit_obj ) _witness_key_cache[wit_id] = wit_obj->signing_key; else _witness_key_cache[wit_id] = fc::optional<chain::public_key_type>(); } } void witness_plugin::schedule_production_loop() { if (_shutting_down) return; //Schedule for the next second's tick regardless of chain state // If we would wait less than 50ms, wait for the whole second. fc::time_point now = fc::time_point::now(); int64_t time_to_next_second = 1000000 - (now.time_since_epoch().count() % 1000000); if( time_to_next_second < 50000 ) // we must sleep for at least 50ms time_to_next_second += 1000000; fc::time_point next_wakeup( now + fc::microseconds( time_to_next_second ) ); _block_production_task = fc::schedule([this]{block_production_loop();}, next_wakeup, "Witness Block Production"); } block_production_condition::block_production_condition_enum witness_plugin::block_production_loop() { block_production_condition::block_production_condition_enum result; fc::limited_mutable_variant_object capture( GRAPHENE_MAX_NESTED_OBJECTS ); if (_shutting_down) { result = block_production_condition::shutdown; } else { try { result = maybe_produce_block(capture); } catch( const fc::canceled_exception& ) { //We're trying to exit. Go ahead and let this one out. throw; } catch( const fc::exception& e ) { elog("Got exception while generating block:\n${e}", ("e", e.to_detail_string())); result = block_production_condition::exception_producing_block; } } switch( result ) { case block_production_condition::produced: ilog("Generated block #${n} with ${x} transaction(s) and timestamp ${t} at time ${c}", (capture)); break; case block_production_condition::not_synced: ilog("Not producing block because production is disabled until we receive a recent block " "(see: --enable-stale-production)"); break; case block_production_condition::not_my_turn: break; case block_production_condition::not_time_yet: break; case block_production_condition::no_private_key: ilog("Not producing block because I don't have the private key for ${scheduled_key}", (capture) ); break; case block_production_condition::low_participation: elog("Not producing block because node appears to be on a minority fork with only ${pct}% witness participation", (capture) ); break; case block_production_condition::lag: elog("Not producing block because node didn't wake up within 2500ms of the slot time."); break; case block_production_condition::exception_producing_block: elog( "exception producing block" ); break; case block_production_condition::shutdown: ilog( "shutdown producing block" ); return result; default: elog( "unknown condition ${result} while producing block", ("result", (unsigned char)result) ); break; } schedule_production_loop(); return result; } block_production_condition::block_production_condition_enum witness_plugin::maybe_produce_block( fc::limited_mutable_variant_object& capture ) { chain::database& db = database(); fc::time_point now_fine = fc::time_point::now(); fc::time_point_sec now = now_fine + fc::microseconds( 500000 ); // If the next block production opportunity is in the present or future, we're synced. if( !_production_enabled ) { if( db.get_slot_time(1) >= now ) _production_enabled = true; else return block_production_condition::not_synced; } // is anyone scheduled to produce now or one second in the future? uint32_t slot = db.get_slot_at_time( now ); if( slot == 0 ) { capture("next_time", db.get_slot_time(1)); return block_production_condition::not_time_yet; } // // this assert should not fail, because now <= db.head_block_time() // should have resulted in slot == 0. // // if this assert triggers, there is a serious bug in get_slot_at_time() // which would result in allowing a later block to have a timestamp // less than or equal to the previous block // assert( now > db.head_block_time() ); graphene::chain::witness_id_type scheduled_witness = db.get_scheduled_witness( slot ); // we must control the witness scheduled to produce the next block. if( _witnesses.find( scheduled_witness ) == _witnesses.end() ) { capture("scheduled_witness", scheduled_witness); return block_production_condition::not_my_turn; } fc::time_point_sec scheduled_time = db.get_slot_time( slot ); graphene::chain::public_key_type scheduled_key = *_witness_key_cache[scheduled_witness]; // should be valid auto private_key_itr = _private_keys.find( scheduled_key ); if( private_key_itr == _private_keys.end() ) { capture("scheduled_key", scheduled_key); return block_production_condition::no_private_key; } uint32_t prate = db.witness_participation_rate(); if( prate < _required_witness_participation ) { capture("pct", uint32_t(100*uint64_t(prate) / GRAPHENE_1_PERCENT)); return block_production_condition::low_participation; } if( llabs((scheduled_time - now).count()) > fc::milliseconds( 2500 ).count() ) { capture("scheduled_time", scheduled_time)("now", now); return block_production_condition::lag; } auto block = db.generate_block( scheduled_time, scheduled_witness, private_key_itr->second, _production_skip_flags ); capture("n", block.block_num())("t", block.timestamp)("c", now)("x", block.transactions.size()); fc::async( [this,block](){ p2p_node().broadcast(net::block_message(block)); } ); return block_production_condition::produced; } <|endoftext|>